text
stringlengths 54
60.6k
|
---|
<commit_before>// Copyright 2016 Chirstopher Torres (Raven), L3nn0x
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http ://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "ccharclient.h"
#include "ccharisc.h"
#include "ccharserver.h"
#include "connection.h"
#include "connectionpool.h"
#include "config.h"
#include "dataconsts.h"
#include "srv_channel_list_reply.h"
#include "srv_char_list_reply.h"
#include "srv_create_char_reply.h"
#include "srv_delete_char_reply.h"
#include "srv_join_server_reply.h"
#include "srv_switch_server.h"
using namespace RoseCommon;
const auto now = ::sqlpp::chrono::floor<::std::chrono::seconds>(std::chrono::system_clock::now());
namespace {
constexpr size_t convertSlot(uint8_t slot) {
using namespace Packet;
switch (static_cast<RoseCommon::EquippedPosition>(slot)) {
case RoseCommon::EquippedPosition::GOGGLES:
return SrvCharListReply::GOOGLES;
case RoseCommon::EquippedPosition::HELMET:
return SrvCharListReply::HELMET;
case RoseCommon::EquippedPosition::ARMOR:
return SrvCharListReply::ARMOR;
case RoseCommon::EquippedPosition::BACKPACK:
return SrvCharListReply::BACKPACK;
case RoseCommon::EquippedPosition::GAUNTLET:
return SrvCharListReply::GAUNTLET;
case RoseCommon::EquippedPosition::BOOTS:
return SrvCharListReply::BOOTS;
case RoseCommon::EquippedPosition::WEAPON_R:
return SrvCharListReply::WEAPON_R;
case RoseCommon::EquippedPosition::WEAPON_L:
return SrvCharListReply::WEAPON_L;
default:
break;
}
return SrvCharListReply::WEAPON_R;
}
}
CCharClient::CCharClient()
: CRoseClient(), accessRights_(0), loginState_(eSTATE::DEFAULT), sessionId_(0), userId_(0), channelId_(0), server_(nullptr) {}
CCharClient::CCharClient(CCharServer *server, std::unique_ptr<Core::INetwork> _sock)
: CRoseClient(std::move(_sock)),
accessRights_(0),
loginState_(eSTATE::DEFAULT),
sessionId_(0),
userId_(0),
channelId_(0),
server_(server) {}
bool CCharClient::handlePacket(uint8_t *_buffer) {
switch (CRosePacket::type(_buffer)) {
case ePacketType::PAKCS_JOIN_SERVER_REQ:
return joinServerReply(Packet::CliJoinServerReq::create(_buffer)); // Allow client to connect
case ePacketType::PAKCS_CHAR_LIST_REQ:
return sendCharListReply();
case ePacketType::PAKCS_CREATE_CHAR_REQ:
return sendCharCreateReply(Packet::CliCreateCharReq::create(_buffer));
case ePacketType::PAKCS_DELETE_CHAR_REQ:
return sendCharDeleteReply(Packet::CliDeleteCharReq::create(_buffer));
case ePacketType::PAKCS_SELECT_CHAR_REQ:
return sendCharSelectReply(Packet::CliSelectCharReq::create(_buffer));
case ePacketType::PAKCS_ALIVE:
if (loginState_ != eSTATE::LOGGEDIN) {
logger_->warn("Client {} is attempting to execute an action before loggin in.", userId_);
return true;
}
updateSession();
[[fallthrough]];
default:
CRoseClient::handlePacket(_buffer);
}
return true;
}
void CCharClient::updateSession() {
using namespace std::chrono_literals;
static std::chrono::steady_clock::time_point time{};
if (Core::Time::GetTickCount() - time < 2min) return;
time = Core::Time::GetTickCount();
logger_->trace("CCharClient::updateSession()");
Core::SessionTable session{};
auto conn = Core::connectionPool.getConnection<Core::Osirose>();
conn(sqlpp::update(session).set(session.time = std::chrono::system_clock::now()).where(session.userid == userId_));
}
bool CCharClient::joinServerReply(RoseCommon::Packet::CliJoinServerReq&& P) {
logger_->trace("CCharClient::joinServerReply");
if (loginState_ != eSTATE::DEFAULT) {
logger_->warn("Client {} is attempting to login when already logged in.", get_id());
return true;
}
uint32_t sessionID = P.get_sessionId();
std::string password = Core::escapeData(P.get_password());
auto conn = Core::connectionPool.getConnection<Core::Osirose>();
Core::AccountTable accounts{};
Core::SessionTable sessions{};
try {
const auto res = conn(
sqlpp::select(sessions.userid, sessions.channelid)
.from(sessions.join(accounts).on(sessions.userid == accounts.id))
.where(sessions.id == sessionID and accounts.password == sqlpp::verbatim<sqlpp::varchar>(fmt::format(
"SHA2(CONCAT('{}', salt), 256)", password))));
if (!res.empty()) {
loginState_ = eSTATE::LOGGEDIN;
const auto &row = res.front();
userId_ = row.userid;
channelId_ = row.channelid;
sessionId_ = sessionID;
logger_->debug("Client {} accepted with sessionid {}.", get_id(), sessionId_);
auto packet = Packet::SrvJoinServerReply::create(Packet::SrvJoinServerReply::OK, std::time(nullptr));
send(packet);
} else {
logger_->debug("Client {} failed the session check.", get_id());
auto packet = Packet::SrvJoinServerReply::create(Packet::SrvJoinServerReply::INVALID_PASSWORD, 0);
send(packet);
}
} catch (const sqlpp::exception &e) {
logger_->error("Error while accessing the database: {}", e.what());
auto packet = Packet::SrvJoinServerReply::create(Packet::SrvJoinServerReply::FAILED, 0);
send(packet);
}
return true;
}
bool CCharClient::sendCharListReply() {
logger_->trace("CCharClient::sendCharListReply");
if (loginState_ == eSTATE::DEFAULT) {
logger_->warn("Client {} is attempting to get the char list before logging in.", get_id());
return true;
}
auto conn = Core::connectionPool.getConnection<Core::Osirose>();
Core::CharacterTable table{};
auto packet = Packet::SrvCharListReply::create();
std::time_t now_c = std::chrono::system_clock::to_time_t(std::chrono::system_clock::now());
characterRealId_.clear();
for (const auto &row : conn(sqlpp::select(sqlpp::all_of(table)).from(table).where(table.userid == userId_))) {
Packet::SrvCharListReply::CharInfo charInfo;
charInfo.set_name(row.name);
charInfo.set_race(row.race);
charInfo.set_level(row.level);
charInfo.set_job(row.job);
charInfo.set_face(row.face);
charInfo.set_hair(row.hair);
auto _remaining_time = 0; // Get time in seconds until delete
if(row.deleteDate.is_null() == false)
_remaining_time = std::difftime(std::chrono::system_clock::to_time_t(row.deleteDate.value()), now_c);
charInfo.set_remainSecsUntilDelete(_remaining_time);
characterRealId_.push_back(row.id);
Core::InventoryTable inv{};
for (const auto &iv : conn(sqlpp::select(inv.slot, inv.itemid).from(inv).where(inv.charId == row.id and inv.slot < 10))) {
Packet::SrvCharListReply::EquippedItem item;
item.set_id(iv.itemid);
item.set_gem_opt(0);
item.set_socket(0);
item.set_grade(0);
charInfo.set_items(item, convertSlot(iv.slot));
}
packet.add_characters(charInfo);
}
send(packet);
return true;
}
bool CCharClient::sendCharCreateReply(RoseCommon::Packet::CliCreateCharReq&& P) {
logger_->trace("CCharClient::sendCharCreateReply");
if (loginState_ == eSTATE::DEFAULT) {
logger_->warn("Client {} is attempting to get the create a char before logging in.", get_id());
return true;
}
std::string query = fmt::format("CALL create_char('{}', {}, {}, {}, {}, {});", Core::escapeData(P.get_name().c_str()),
userId_, P.get_race(), P.get_face(), P.get_hair(), P.get_stone());
auto conn = Core::connectionPool.getConnection<Core::Osirose>();
auto res = Packet::SrvCreateCharReply::OK;
try {
conn->execute(query);
} catch (sqlpp::exception &) {
res = Packet::SrvCreateCharReply::NAME_TAKEN;
}
auto packet = Packet::SrvCreateCharReply::create(res);
send(packet);
return true;
}
bool CCharClient::sendCharDeleteReply(RoseCommon::Packet::CliDeleteCharReq&& P) {
logger_->trace("CCharClient::sendCharDeleteReply");
if (loginState_ == eSTATE::DEFAULT) {
logger_->warn("Client {} is attempting to delete a char before logging in.", get_id());
return true;
}
//TODO: change this to be variable
if (P.get_charId() > 6) return false;
uint8_t delete_type = (uint8_t)P.get_isDelete();
uint32_t time = 0;
if (P.get_isDelete()) {
//TODO: if the character is a guild leader, time = -1 and don't delete character
// we need to delete the char
Core::Config& config = Core::Config::getInstance();
if(config.charServer().instantCharDelete == false) {
//TODO: allow the server owner to set the time. This will also require the ability to change the time in sql
time = 60*60*24; // The default is one day from now
} else {
time = 0;
delete_type = 2;
}
}
std::string query = fmt::format("CALL delete_character({}, '{}', {});", userId_, Core::escapeData(P.get_name().c_str()), delete_type);
auto conn = Core::connectionPool.getConnection<Core::Osirose>();
conn->execute(query);
// if time == -1, delete failed
auto packet = Packet::SrvDeleteCharReply::create(time, P.get_name());
send(packet);
return true;
}
void CCharClient::onDisconnected() {
logger_->trace("CCharClient::onDisconnected()");
Core::SessionTable session{};
Core::AccountTable table{};
auto conn = Core::connectionPool.getConnection<Core::Osirose>();
const auto res = conn(sqlpp::select(table.online).from(table).where(table.id == userId_));
if (!res.empty())
if (res.front().online) conn(sqlpp::remove_from(session).where(session.userid == userId_));
conn(sqlpp::update(table).set(table.online = 0).where(table.id == userId_));
}
bool CCharClient::sendCharSelectReply(RoseCommon::Packet::CliSelectCharReq&& P) {
logger_->trace("CCharClient::sendCharSelectReply");
if (loginState_ == eSTATE::DEFAULT) {
logger_->warn("Client {} is attempting to select a char before logging in.", get_id());
return true;
}
uint8_t selected_id = P.get_charId();
if (selected_id > characterRealId_.size()) {
logger_->warn("Client {} is attempting to select a invalid character.", get_id());
return false;
}
// if (characterRealId_[selected_id]) {
// logger_->warn("Client {} is attempting to select a character that is being deleted.", get_id());
// return false;
// }
//loginState_ = eSTATE::TRANSFERING;
std::string query =
fmt::format("CALL update_session_with_character({}, '{}');", sessionId_, characterRealId_[selected_id]);
auto conn = Core::connectionPool.getConnection<Core::Osirose>();
conn->execute(query);
Core::CharacterTable table{};
auto charRes = conn(sqlpp::select(table.map).from(table).where(table.id == characterRealId_[selected_id]));
uint16_t map_id = charRes.front().map;
server_->load_user(characterRealId_[selected_id]);
std::lock_guard<std::mutex> lock(server_->GetISCListMutex());
for (auto &server : server_->GetISCList()) {
if (server->get_type() == Isc::ServerType::MAP_MASTER && server->get_id() == channelId_) {
auto packet = Packet::SrvSwitchServer::create(
server->get_port() + map_id, sessionId_, 0,
server->get_address()); // this should be set to the map server's encryption seed
send(packet);
}
}
return true;
}
<commit_msg>Update ccharclient.cpp<commit_after>// Copyright 2016 Chirstopher Torres (Raven), L3nn0x
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http ://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "ccharclient.h"
#include "ccharisc.h"
#include "ccharserver.h"
#include "connection.h"
#include "connectionpool.h"
#include "config.h"
#include "dataconsts.h"
#include "srv_channel_list_reply.h"
#include "srv_char_list_reply.h"
#include "srv_create_char_reply.h"
#include "srv_delete_char_reply.h"
#include "srv_join_server_reply.h"
#include "srv_switch_server.h"
using namespace RoseCommon;
const auto now = ::sqlpp::chrono::floor<::std::chrono::seconds>(std::chrono::system_clock::now());
namespace {
constexpr size_t convertSlot(uint8_t slot) {
using namespace Packet;
switch (static_cast<RoseCommon::EquippedPosition>(slot)) {
case RoseCommon::EquippedPosition::GOGGLES:
return SrvCharListReply::GOOGLES;
case RoseCommon::EquippedPosition::HELMET:
return SrvCharListReply::HELMET;
case RoseCommon::EquippedPosition::ARMOR:
return SrvCharListReply::ARMOR;
case RoseCommon::EquippedPosition::BACKPACK:
return SrvCharListReply::BACKPACK;
case RoseCommon::EquippedPosition::GAUNTLET:
return SrvCharListReply::GAUNTLET;
case RoseCommon::EquippedPosition::BOOTS:
return SrvCharListReply::BOOTS;
case RoseCommon::EquippedPosition::WEAPON_R:
return SrvCharListReply::WEAPON_R;
case RoseCommon::EquippedPosition::WEAPON_L:
return SrvCharListReply::WEAPON_L;
default:
break;
}
return SrvCharListReply::WEAPON_R;
}
}
CCharClient::CCharClient()
: CRoseClient(), accessRights_(0), loginState_(eSTATE::DEFAULT), sessionId_(0), userId_(0), channelId_(0), server_(nullptr) {}
CCharClient::CCharClient(CCharServer *server, std::unique_ptr<Core::INetwork> _sock)
: CRoseClient(std::move(_sock)),
accessRights_(0),
loginState_(eSTATE::DEFAULT),
sessionId_(0),
userId_(0),
channelId_(0),
server_(server) {}
bool CCharClient::handlePacket(uint8_t *_buffer) {
switch (CRosePacket::type(_buffer)) {
case ePacketType::PAKCS_JOIN_SERVER_REQ:
return joinServerReply(Packet::CliJoinServerReq::create(_buffer)); // Allow client to connect
case ePacketType::PAKCS_CHAR_LIST_REQ:
return sendCharListReply();
case ePacketType::PAKCS_CREATE_CHAR_REQ:
return sendCharCreateReply(Packet::CliCreateCharReq::create(_buffer));
case ePacketType::PAKCS_DELETE_CHAR_REQ:
return sendCharDeleteReply(Packet::CliDeleteCharReq::create(_buffer));
case ePacketType::PAKCS_SELECT_CHAR_REQ:
return sendCharSelectReply(Packet::CliSelectCharReq::create(_buffer));
case ePacketType::PAKCS_ALIVE:
if (loginState_ != eSTATE::LOGGEDIN) {
logger_->warn("Client {} is attempting to execute an action before loggin in.", userId_);
return true;
}
updateSession();
[[fallthrough]];
default:
CRoseClient::handlePacket(_buffer);
}
return true;
}
void CCharClient::updateSession() {
using namespace std::chrono_literals;
static std::chrono::steady_clock::time_point time{};
if (Core::Time::GetTickCount() - time < 2min) return;
time = Core::Time::GetTickCount();
logger_->trace("CCharClient::updateSession()");
Core::SessionTable session{};
auto conn = Core::connectionPool.getConnection<Core::Osirose>();
conn(sqlpp::update(session).set(session.time = std::chrono::system_clock::now()).where(session.userid == userId_));
}
bool CCharClient::joinServerReply(RoseCommon::Packet::CliJoinServerReq&& P) {
logger_->trace("CCharClient::joinServerReply");
if (loginState_ != eSTATE::DEFAULT) {
logger_->warn("Client {} is attempting to login when already logged in.", get_id());
return true;
}
uint32_t sessionID = P.get_sessionId();
std::string password = Core::escapeData(P.get_password());
auto conn = Core::connectionPool.getConnection<Core::Osirose>();
Core::AccountTable accounts{};
Core::SessionTable sessions{};
try {
const auto res = conn(
sqlpp::select(sessions.userid, sessions.channelid)
.from(sessions.join(accounts).on(sessions.userid == accounts.id))
.where(sessions.id == sessionID and accounts.password == sqlpp::verbatim<sqlpp::varchar>(fmt::format(
"SHA2(CONCAT('{}', salt), 256)", password))));
if (!res.empty()) {
loginState_ = eSTATE::LOGGEDIN;
const auto &row = res.front();
userId_ = row.userid;
channelId_ = row.channelid;
sessionId_ = sessionID;
logger_->debug("Client {} accepted with sessionid {}.", get_id(), sessionId_);
auto packet = Packet::SrvJoinServerReply::create(Packet::SrvJoinServerReply::OK, std::time(nullptr));
send(packet);
} else {
logger_->debug("Client {} failed the session check.", get_id());
auto packet = Packet::SrvJoinServerReply::create(Packet::SrvJoinServerReply::INVALID_PASSWORD, 0);
send(packet);
}
} catch (const sqlpp::exception &e) {
logger_->error("Error while accessing the database: {}", e.what());
auto packet = Packet::SrvJoinServerReply::create(Packet::SrvJoinServerReply::FAILED, 0);
send(packet);
}
return true;
}
bool CCharClient::sendCharListReply() {
logger_->trace("CCharClient::sendCharListReply");
if (loginState_ == eSTATE::DEFAULT) {
logger_->warn("Client {} is attempting to get the char list before logging in.", get_id());
return true;
}
auto conn = Core::connectionPool.getConnection<Core::Osirose>();
Core::CharacterTable table{};
auto packet = Packet::SrvCharListReply::create();
std::time_t now_c = std::chrono::system_clock::to_time_t(std::chrono::system_clock::now());
characterRealId_.clear();
for (const auto &row : conn(sqlpp::select(sqlpp::all_of(table)).from(table).where(table.userid == userId_))) {
Packet::SrvCharListReply::CharInfo charInfo;
charInfo.set_name(row.name);
charInfo.set_race(row.race);
charInfo.set_level(row.level);
charInfo.set_job(row.job);
charInfo.set_face(row.face);
charInfo.set_hair(row.hair);
auto _remaining_time = 0; // Get time in seconds until delete
if(row.deleteDate.is_null() == false)
_remaining_time = std::difftime(std::chrono::system_clock::to_time_t(row.deleteDate.value()), now_c);
charInfo.set_remainSecsUntilDelete(_remaining_time);
characterRealId_.push_back(row.id);
Core::InventoryTable inv{};
for (const auto &iv : conn(sqlpp::select(inv.slot, inv.itemid).from(inv).where(inv.charId == row.id and inv.slot < 10))) {
Packet::SrvCharListReply::EquippedItem item;
item.set_id(iv.itemid);
item.set_gem_opt(0);
item.set_socket(0);
item.set_grade(0);
charInfo.set_items(item, convertSlot(iv.slot));
}
packet.add_characters(charInfo);
}
send(packet);
return true;
}
bool CCharClient::sendCharCreateReply(RoseCommon::Packet::CliCreateCharReq&& P) {
logger_->trace("CCharClient::sendCharCreateReply");
if (loginState_ == eSTATE::DEFAULT) {
logger_->warn("Client {} is attempting to get the create a char before logging in.", get_id());
return true;
}
std::string query = fmt::format("CALL create_char('{}', {}, {}, {}, {}, {});", Core::escapeData(P.get_name().c_str()),
userId_, P.get_race(), P.get_face(), P.get_hair(), P.get_stone());
auto conn = Core::connectionPool.getConnection<Core::Osirose>();
auto res = Packet::SrvCreateCharReply::OK;
try {
conn->execute(query);
} catch (sqlpp::exception &) {
res = Packet::SrvCreateCharReply::NAME_TAKEN;
}
auto packet = Packet::SrvCreateCharReply::create(res);
send(packet);
return true;
}
bool CCharClient::sendCharDeleteReply(RoseCommon::Packet::CliDeleteCharReq&& P) {
logger_->trace("CCharClient::sendCharDeleteReply");
if (loginState_ == eSTATE::DEFAULT) {
logger_->warn("Client {} is attempting to delete a char before logging in.", get_id());
return true;
}
//TODO: change this to be variable
if (P.get_charId() > 6) return false;
uint8_t delete_type = (uint8_t)P.get_isDelete();
uint32_t time = 0;
if (P.get_isDelete()) {
//TODO: if the character is a guild leader, time = -1 and don't delete character
// we need to delete the char
Core::Config& config = Core::Config::getInstance();
if(config.charServer().instantCharDelete == false) {
//TODO: allow the server owner to set the time. This will also require the ability to change the time in sql
time = 60*60*24; // The default is one day from now
} else {
time = 0;
delete_type = 2;
}
}
std::string query = fmt::format("CALL delete_character({}, '{}', {});", userId_, Core::escapeData(P.get_name().c_str()), delete_type);
auto conn = Core::connectionPool.getConnection<Core::Osirose>();
conn->execute(query);
// if time == -1, delete failed
auto packet = Packet::SrvDeleteCharReply::create(time, P.get_name());
send(packet);
return true;
}
void CCharClient::onDisconnected() {
logger_->trace("CCharClient::onDisconnected()");
Core::SessionTable session{};
Core::AccountTable table{};
auto conn = Core::connectionPool.getConnection<Core::Osirose>();
const auto res = conn(sqlpp::select(table.online).from(table).where(table.id == userId_));
if (!res.empty())
if (res.front().online) conn(sqlpp::remove_from(session).where(session.userid == userId_));
conn(sqlpp::update(table).set(table.online = 0).where(table.id == userId_));
}
bool CCharClient::sendCharSelectReply(RoseCommon::Packet::CliSelectCharReq&& P) {
logger_->trace("CCharClient::sendCharSelectReply");
if (loginState_ == eSTATE::DEFAULT) {
logger_->warn("Client {} is attempting to select a char before logging in.", get_id());
return true;
}
uint8_t selected_id = P.get_charId();
if (selected_id > characterRealId_.size()) {
logger_->warn("Client {} is attempting to select a invalid character.", get_id());
return false;
}
// if (characterRealId_[selected_id]) {
// logger_->warn("Client {} is attempting to select a character that is being deleted.", get_id());
// return false;
// }
//loginState_ = eSTATE::TRANSFERING;
std::string query =
fmt::format("CALL update_session_with_character({}, '{}');", sessionId_, characterRealId_[selected_id]);
auto conn = Core::connectionPool.getConnection<Core::Osirose>();
conn->execute(query);
Core::CharacterTable table{};
auto charRes = conn(sqlpp::select(table.map).from(table).where(table.id == characterRealId_[selected_id]));
uint16_t map_id = charRes.front().map;
server_->load_user(weak_from_this(), characterRealId_[selected_id]);
std::lock_guard<std::mutex> lock(server_->GetISCListMutex());
for (auto &server : server_->GetISCList()) {
if (server->get_type() == Isc::ServerType::MAP_MASTER && server->get_id() == channelId_) {
auto packet = Packet::SrvSwitchServer::create(
server->get_port() + map_id, sessionId_, 0,
server->get_address()); // this should be set to the map server's encryption seed
send(packet);
}
}
return true;
}
<|endoftext|> |
<commit_before>/* This file is part of the KDE libraries
Copyright (C) 2003-2005 Hamish Rodda <[email protected]>
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public
License version 2 as published by the Free Software Foundation.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Library General Public License for more details.
You should have received a copy of the GNU Library General Public License
along with this library; see the file COPYING.LIB. If not, write to
the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
Boston, MA 02110-1301, USA.
*/
#include "rangefeedback.h"
using namespace KTextEditor;
SmartRangeWatcher::~ SmartRangeWatcher( )
{
}
SmartRangeNotifier::SmartRangeNotifier( )
: m_wantDirectChanges(true)
{
}
bool SmartRangeNotifier::wantsDirectChanges( ) const
{
return m_wantDirectChanges;
}
void SmartRangeNotifier::setWantsDirectChanges( bool wantsDirectChanges )
{
m_wantDirectChanges = wantsDirectChanges;
}
SmartRangeWatcher::SmartRangeWatcher( )
: m_wantDirectChanges(true)
{
}
bool SmartRangeWatcher::wantsDirectChanges( ) const
{
return m_wantDirectChanges;
}
void SmartRangeWatcher::setWantsDirectChanges( bool wantsDirectChanges )
{
m_wantDirectChanges = wantsDirectChanges;
}
void SmartRangeWatcher::rangePositionChanged( SmartRange* )
{
}
void SmartRangeWatcher::rangeContentsChanged( SmartRange* )
{
}
void SmartRangeWatcher::rangeContentsChanged( SmartRange*, SmartRange* )
{
}
void SmartRangeWatcher::mouseEnteredRange( SmartRange*, View* )
{
}
void SmartRangeWatcher::mouseExitedRange( SmartRange*, View* )
{
}
void SmartRangeWatcher::caretEnteredRange( SmartRange*, View* )
{
}
void SmartRangeWatcher::caretExitedRange( SmartRange*, View* )
{
}
void SmartRangeWatcher::rangeEliminated( SmartRange* )
{
}
void SmartRangeWatcher::rangeDeleted( SmartRange* )
{
}
void SmartRangeWatcher::childRangeInserted( SmartRange*, SmartRange* )
{
}
void SmartRangeWatcher::childRangeRemoved( SmartRange*, SmartRange* )
{
}
void SmartRangeWatcher::rangeAttributeChanged( SmartRange*, Attribute::Ptr, Attribute::Ptr )
{
}
void SmartRangeWatcher::parentRangeChanged( SmartRange *, SmartRange *, SmartRange * )
{
}
#include "smartrangenotifier.moc"
// kate: space-indent on; indent-width 2; replace-tabs on;
<commit_msg>- lgplv2+: goutte ( 2 LOC): 485351<commit_after>/* This file is part of the KDE libraries
* Copyright (C) 2003-2005 Hamish Rodda <[email protected]>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public License
* along with this library; see the file COPYING.LIB. If not, write to
* the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301, USA.*/
#include "rangefeedback.h"
using namespace KTextEditor;
SmartRangeWatcher::~ SmartRangeWatcher( )
{
}
SmartRangeNotifier::SmartRangeNotifier( )
: m_wantDirectChanges(true)
{
}
bool SmartRangeNotifier::wantsDirectChanges( ) const
{
return m_wantDirectChanges;
}
void SmartRangeNotifier::setWantsDirectChanges( bool wantsDirectChanges )
{
m_wantDirectChanges = wantsDirectChanges;
}
SmartRangeWatcher::SmartRangeWatcher( )
: m_wantDirectChanges(true)
{
}
bool SmartRangeWatcher::wantsDirectChanges( ) const
{
return m_wantDirectChanges;
}
void SmartRangeWatcher::setWantsDirectChanges( bool wantsDirectChanges )
{
m_wantDirectChanges = wantsDirectChanges;
}
void SmartRangeWatcher::rangePositionChanged( SmartRange* )
{
}
void SmartRangeWatcher::rangeContentsChanged( SmartRange* )
{
}
void SmartRangeWatcher::rangeContentsChanged( SmartRange*, SmartRange* )
{
}
void SmartRangeWatcher::mouseEnteredRange( SmartRange*, View* )
{
}
void SmartRangeWatcher::mouseExitedRange( SmartRange*, View* )
{
}
void SmartRangeWatcher::caretEnteredRange( SmartRange*, View* )
{
}
void SmartRangeWatcher::caretExitedRange( SmartRange*, View* )
{
}
void SmartRangeWatcher::rangeEliminated( SmartRange* )
{
}
void SmartRangeWatcher::rangeDeleted( SmartRange* )
{
}
void SmartRangeWatcher::childRangeInserted( SmartRange*, SmartRange* )
{
}
void SmartRangeWatcher::childRangeRemoved( SmartRange*, SmartRange* )
{
}
void SmartRangeWatcher::rangeAttributeChanged( SmartRange*, Attribute::Ptr, Attribute::Ptr )
{
}
void SmartRangeWatcher::parentRangeChanged( SmartRange *, SmartRange *, SmartRange * )
{
}
#include "smartrangenotifier.moc"
// kate: space-indent on; indent-width 2; replace-tabs on;
<|endoftext|> |
<commit_before>#include "multiplemonthcal.h"
#include "MultipleMonthCalCtrl.h"
IMPLEMENT_DYNAMIC(CMultipleMonthCalCtrl, CMonthCalCtrl)
CMultipleMonthCalCtrl::CMultipleMonthCalCtrl()
{
}
CMultipleMonthCalCtrl::~CMultipleMonthCalCtrl()
{
}
void CMultipleMonthCalCtrl::RegisterControl()
{
MONTHCAL_Register();
}
void CMultipleMonthCalCtrl::UnregisterControl()
{
MONTHCAL_Unregister();
}
void CMultipleMonthCalCtrl::SetOriginalColors()
{
//SetWindowTheme(m_hWnd, L" ", L" ");
COLORREF black = RGB(0, 0, 0);
COLORREF gray = RGB(211, 211, 211);
COLORREF white = RGB(255, 255, 255);
COLORREF monthTitleColor = RGB(219, 238, 244);
COLORREF monthTitleTextColor = RGB(87, 108, 113);
COLORREF selectBgColor = RGB(152, 194, 206);
COLORREF selectTextColor = RGB(10, 65, 122);
SetColor(MCSC_BACKGROUND, white);
SetColor(MCSC_TEXT, black);
SetColor(MCSC_TITLEBK, monthTitleColor);
SetColor(MCSC_TITLETEXT, monthTitleTextColor);
SetColor(MCSC_MONTHBK, white);
SetColor(MCSC_TRAILINGTEXT, white);
SetColor(MCSC_SELECTEDTEXT, selectTextColor);
SetColor(MCSC_SELECTEDBK, selectBgColor);
SetColor(MCSC_ABBREVIATIONSTEXT, black);
SetColor(MCSC_ABBREVIATIONSBK, white);
SetColor(MCSC_ABBREVIATIONSLINE, gray);
}
void CMultipleMonthCalCtrl::EnableMultiselect(int maxSelectCount)
{
SetMaxSelCount(maxSelectCount);
}
void CMultipleMonthCalCtrl::DisableMultiselect()
{
EnableMultiselect(1);
}
std::vector<SYSTEMTIME>
CMultipleMonthCalCtrl::GetSelection() const
{
ASSERT(m_hWnd != NULL);
SELECTION_INFO info;
BOOL ret = (BOOL)::SendMessage(m_hWnd, MCM_GETCURSEL, 0, (LPARAM)&info);
std::vector<SYSTEMTIME> dates;
if (ret != FALSE)
{
LPSELECTION_ITEM item = info.first;
while (item)
{
dates.push_back(item->date);
item = item->next;
}
}
return dates;
}
void CMultipleMonthCalCtrl::SelectDate(const SYSTEMTIME & date)
{
::SendMessage(m_hWnd, MCM_SETCURSEL, 0, (LPARAM)&date);
}
void CMultipleMonthCalCtrl::SelectDates(const std::vector<SYSTEMTIME>& dates)
{
for (size_t i = 0; i < dates.size(); ++i)
{
SelectDate(dates[i]);
}
}
void CMultipleMonthCalCtrl::UnselectAll()
{
::SendMessage(m_hWnd, MCM_SETCURSEL, 0, 0);
}
BEGIN_MESSAGE_MAP(CMultipleMonthCalCtrl, CMonthCalCtrl)
END_MESSAGE_MAP()
<commit_msg>Added comment for code.<commit_after>#include "multiplemonthcal.h"
#include "MultipleMonthCalCtrl.h"
IMPLEMENT_DYNAMIC(CMultipleMonthCalCtrl, CMonthCalCtrl)
CMultipleMonthCalCtrl::CMultipleMonthCalCtrl()
{
}
CMultipleMonthCalCtrl::~CMultipleMonthCalCtrl()
{
}
void CMultipleMonthCalCtrl::RegisterControl()
{
MONTHCAL_Register();
}
void CMultipleMonthCalCtrl::UnregisterControl()
{
MONTHCAL_Unregister();
}
void CMultipleMonthCalCtrl::SetOriginalColors()
{
//SetWindowTheme(m_hWnd, L" ", L" ");
COLORREF black = RGB(0, 0, 0);
COLORREF gray = RGB(211, 211, 211);
COLORREF white = RGB(255, 255, 255);
COLORREF monthTitleColor = RGB(219, 238, 244);
COLORREF monthTitleTextColor = RGB(87, 108, 113);
COLORREF selectBgColor = RGB(152, 194, 206);
COLORREF selectTextColor = RGB(10, 65, 122);
SetColor(MCSC_BACKGROUND, white);
SetColor(MCSC_TEXT, black);
SetColor(MCSC_TITLEBK, monthTitleColor);
SetColor(MCSC_TITLETEXT, monthTitleTextColor);
SetColor(MCSC_MONTHBK, white);
SetColor(MCSC_SELECTEDTEXT, selectTextColor);
SetColor(MCSC_SELECTEDBK, selectBgColor);
SetColor(MCSC_ABBREVIATIONSTEXT, black);
SetColor(MCSC_ABBREVIATIONSBK, white);
SetColor(MCSC_ABBREVIATIONSLINE, gray);
//Hide trailing dates
SetColor(MCSC_TRAILINGTEXT, white);
}
void CMultipleMonthCalCtrl::EnableMultiselect(int maxSelectCount)
{
SetMaxSelCount(maxSelectCount);
}
void CMultipleMonthCalCtrl::DisableMultiselect()
{
EnableMultiselect(1);
}
std::vector<SYSTEMTIME>
CMultipleMonthCalCtrl::GetSelection() const
{
ASSERT(m_hWnd != NULL);
SELECTION_INFO info;
BOOL ret = (BOOL)::SendMessage(m_hWnd, MCM_GETCURSEL, 0, (LPARAM)&info);
std::vector<SYSTEMTIME> dates;
if (ret != FALSE)
{
LPSELECTION_ITEM item = info.first;
while (item)
{
dates.push_back(item->date);
item = item->next;
}
}
return dates;
}
void CMultipleMonthCalCtrl::SelectDate(const SYSTEMTIME & date)
{
::SendMessage(m_hWnd, MCM_SETCURSEL, 0, (LPARAM)&date);
}
void CMultipleMonthCalCtrl::SelectDates(const std::vector<SYSTEMTIME>& dates)
{
for (size_t i = 0; i < dates.size(); ++i)
{
SelectDate(dates[i]);
}
}
void CMultipleMonthCalCtrl::UnselectAll()
{
::SendMessage(m_hWnd, MCM_SETCURSEL, 0, 0);
}
BEGIN_MESSAGE_MAP(CMultipleMonthCalCtrl, CMonthCalCtrl)
END_MESSAGE_MAP()
<|endoftext|> |
<commit_before>/*=========================================================================
Program: Visualization Toolkit
Module: vtkPairwiseExtractHistogram2D.cxx
Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
All rights reserved.
See Copyright.txt or http://www.kitware.com/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notice for more information.
=========================================================================*/
/*-------------------------------------------------------------------------
Copyright 2009 Sandia Corporation.
Under the terms of Contract DE-AC04-94AL85000 with Sandia Corporation,
the U.S. Government retains certain rights in this software.
-------------------------------------------------------------------------*/
#include "vtkPairwiseExtractHistogram2D.h"
//------------------------------------------------------------------------------
#include "vtkArrayData.h"
#include "vtkArrayIteratorIncludes.h"
#include "vtkStatisticsAlgorithmPrivate.h"
#include "vtkCollection.h"
#include "vtkExtractHistogram2D.h"
#include "vtkIdTypeArray.h"
#include "vtkImageData.h"
#include "vtkImageMedian3D.h"
#include "vtkInformation.h"
#include "vtkMultiBlockDataSet.h"
#include "vtkObjectFactory.h"
#include "vtkPointData.h"
#include "vtkStdString.h"
#include "vtkTable.h"
#include "vtkTimerLog.h"
#include "vtkUnsignedIntArray.h"
#define VTK_CREATE(type, name) \
vtkSmartPointer<type> name = vtkSmartPointer<type>::New()
//------------------------------------------------------------------------------
#include <vtkstd/set>
#include <vtkstd/vector>
#include <vtkstd/string>
#include <vtkstd/map>
//------------------------------------------------------------------------------
vtkCxxRevisionMacro(vtkPairwiseExtractHistogram2D, "1.4");
vtkStandardNewMacro(vtkPairwiseExtractHistogram2D);
//------------------------------------------------------------------------------
class vtkPairwiseExtractHistogram2D::Internals
{
public:
vtkstd::vector< vtkstd::pair< vtkStdString,vtkStdString > > ColumnPairs;
vtkstd::map< vtkstd::string,bool > ColumnUsesCustomExtents;
vtkstd::map< vtkstd::string,vtkstd::vector<double> > ColumnExtents;
};
//------------------------------------------------------------------------------
vtkPairwiseExtractHistogram2D::vtkPairwiseExtractHistogram2D()
{
this->Implementation = new Internals;
this->SetNumberOfOutputPorts(4);
this->NumberOfBins[0] = 0;
this->NumberOfBins[1] = 0;
this->CustomColumnRangeIndex = -1;
this->ScalarType = VTK_UNSIGNED_INT;
this->HistogramFilters = vtkSmartPointer<vtkCollection>::New();
this->BuildTime.Modified();
}
//------------------------------------------------------------------------------
vtkPairwiseExtractHistogram2D::~vtkPairwiseExtractHistogram2D()
{
delete this->Implementation;
}
//------------------------------------------------------------------------------
void vtkPairwiseExtractHistogram2D::PrintSelf(ostream& os, vtkIndent indent)
{
this->Superclass::PrintSelf(os,indent);
os << "NumberOfBins: " << this->NumberOfBins[0] << ", " << this->NumberOfBins[1] << endl;
os << "CustomColumnRangeIndex: " << this->CustomColumnRangeIndex << endl;
os << "ScalarType: " << this->ScalarType << endl;
}
//------------------------------------------------------------------------------
void vtkPairwiseExtractHistogram2D::Learn(vtkTable *inData,
vtkTable* vtkNotUsed(inParameters),
vtkDataObject *outMetaDO)
{
vtkTable* outMeta = vtkTable::SafeDownCast( outMetaDO );
if ( ! outMeta )
{
return;
}
if (this->NumberOfBins[0] == 0 || this->NumberOfBins[1] == 0)
{
vtkErrorMacro(<<"Error: histogram dimensions not set (use SetNumberOfBins).");
return;
}
// if the number of columns in the input has changed, we'll need to do
// some reinitializing
int numHistograms = inData->GetNumberOfColumns()-1;
if (numHistograms != this->HistogramFilters->GetNumberOfItems())
{
// clear out the list of histogram filters
for (int i=0; i<this->HistogramFilters->GetNumberOfItems(); i++)
{
this->HistogramFilters->GetItemAsObject(i)->Delete();
}
// clear out the internals
this->HistogramFilters->RemoveAllItems();
this->Implementation->ColumnPairs.clear();
this->Implementation->ColumnUsesCustomExtents.clear();
this->Implementation->ColumnExtents.clear();
// Make a shallow copy of the input to be safely passed to internal
// histogram filters.
VTK_CREATE(vtkTable, inDataCopy);
inDataCopy->ShallowCopy(inData);
// fill it up with new histogram filters
for (int i=0; i<numHistograms; i++)
{
vtkDataArray* col1 = vtkDataArray::SafeDownCast(inData->GetColumn(i));
vtkDataArray* col2 = vtkDataArray::SafeDownCast(inData->GetColumn(i+1));
if (!col1 || !col2)
{
vtkErrorMacro("All inputs must be numeric arrays.");
return;
}
// create a new histogram filter
vtkSmartPointer<vtkExtractHistogram2D> f;
f.TakeReference(this->NewHistogramFilter());
f->SetInput(inDataCopy);
f->SetNumberOfBins(this->NumberOfBins);
vtkstd::pair<vtkStdString,vtkStdString> colpair(inData->GetColumn(i)->GetName(),inData->GetColumn(i+1)->GetName());
f->AddColumnPair(colpair.first.c_str(),colpair.second.c_str());
f->SetSwapColumns(strcmp(colpair.first.c_str(),colpair.second.c_str())>=0);
this->HistogramFilters->AddItem(f);
// update the internals accordingly
this->Implementation->ColumnPairs.push_back(colpair);
this->Implementation->ColumnUsesCustomExtents[colpair.first.c_str()] = false;
// compute the range of the the new columns, and update the internals
double r[2] = {0,0};
if (i == 0)
{
col1->GetRange(r,0);
this->Implementation->ColumnExtents[colpair.first.c_str()].clear();
this->Implementation->ColumnExtents[colpair.first.c_str()].push_back(r[0]);
this->Implementation->ColumnExtents[colpair.first.c_str()].push_back(r[1]);
}
col2->GetRange(r,0);
this->Implementation->ColumnExtents[colpair.second.c_str()].clear();
this->Implementation->ColumnExtents[colpair.second.c_str()].push_back(r[0]);
this->Implementation->ColumnExtents[colpair.second.c_str()].push_back(r[1]);
}
}
// check the filters one by one and update them if necessary
if (this->BuildTime < inData->GetMTime() ||
this->BuildTime < this->GetMTime())
{
for (int i=0; i<numHistograms; i++)
{
vtkExtractHistogram2D* f = this->GetHistogramFilter(i);
// if the column names have changed, that means we need to update
vtkstd::pair<vtkStdString,vtkStdString> cols = this->Implementation->ColumnPairs[i];
if (inData->GetColumn(i)->GetName() != cols.first ||
inData->GetColumn(i+1)->GetName() != cols.second)
{
vtkstd::pair<vtkStdString,vtkStdString> newCols(inData->GetColumn(i)->GetName(),inData->GetColumn(i+1)->GetName());
f->ResetRequests();
f->AddColumnPair(newCols.first.c_str(),newCols.second.c_str());
f->SetSwapColumns(strcmp(newCols.first.c_str(),newCols.second.c_str()) >= 0);
f->Modified();
this->Implementation->ColumnPairs[i] = newCols;
}
// if the filter extents have changed, that means we need to update
vtkstd::pair<vtkStdString,vtkStdString> newCols(inData->GetColumn(i)->GetName(),inData->GetColumn(i+1)->GetName());
if (this->Implementation->ColumnUsesCustomExtents[newCols.first.c_str()] ||
this->Implementation->ColumnUsesCustomExtents[newCols.second.c_str()])
{
f->UseCustomHistogramExtentsOn();
double *ext = f->GetCustomHistogramExtents();
if (ext[0] != this->Implementation->ColumnExtents[newCols.first.c_str()][0] ||
ext[1] != this->Implementation->ColumnExtents[newCols.first.c_str()][1] ||
ext[2] != this->Implementation->ColumnExtents[newCols.second.c_str()][0] ||
ext[3] != this->Implementation->ColumnExtents[newCols.second.c_str()][1])
{
f->SetCustomHistogramExtents(this->Implementation->ColumnExtents[newCols.first.c_str()][0],
this->Implementation->ColumnExtents[newCols.first.c_str()][1],
this->Implementation->ColumnExtents[newCols.second.c_str()][0],
this->Implementation->ColumnExtents[newCols.second.c_str()][1]);
}
}
else
{
f->UseCustomHistogramExtentsOff();
}
// if the number of bins has changed, that definitely means we need to update
int* nbins = f->GetNumberOfBins();
if (nbins[0] != this->NumberOfBins[0] ||
nbins[1] != this->NumberOfBins[1])
{
f->SetNumberOfBins(this->NumberOfBins);
}
}
}
// update the filters as necessary
for (int i=0; i<numHistograms; i++)
{
vtkExtractHistogram2D* f = this->GetHistogramFilter(i);
if (f && (f->GetMTime() > this->BuildTime ||
inData->GetColumn(i)->GetMTime() > this->BuildTime ||
inData->GetColumn(i+1)->GetMTime() > this->BuildTime))
{
f->Update();
}
}
// build the composite image data set
vtkMultiBlockDataSet* outImages = vtkMultiBlockDataSet::SafeDownCast(
this->GetOutputDataObject(vtkPairwiseExtractHistogram2D::HISTOGRAM_IMAGE));
if (outImages)
{
outImages->SetNumberOfBlocks(numHistograms);
for (int i=0; i<numHistograms; i++)
{
vtkExtractHistogram2D* f = this->GetHistogramFilter(i);
if (f)
{
outImages->SetBlock(i,f->GetOutputHistogramImage());
}
}
}
// build the output table
outMeta->Initialize();
for (int i=0; i<this->HistogramFilters->GetNumberOfItems(); i++)
{
vtkExtractHistogram2D* f = this->GetHistogramFilter(i);
if (f)
{
if (f->GetMTime() > this->BuildTime)
f->Update();
outMeta->AddColumn(f->GetOutput()->GetColumn(0));
}
}
// build the reordered output table
/*
vtkTable* outReorderedTable = vtkTable::SafeDownCast(
this->GetOutputDataObject(vtkPairwiseExtractHistogram2D::REORDERED_INPUT));
if (outReorderedTable && this->Implementation->ColumnPairs.size())
{
outReorderedTable->Initialize();
outReorderedTable->AddColumn(inData->GetColumnByName(this->Implementation->ColumnPairs[0].first));
for (int i=0; i<(int)this->Implementation->ColumnPairs.size(); i++)
{
outReorderedTable->AddColumn(inData->GetColumnByName(this->Implementation->ColumnPairs[i].second));
}
}
*/
this->BuildTime.Modified();
}
//------------------------------------------------------------------------------
void vtkPairwiseExtractHistogram2D::SetCustomColumnRangeByIndex(double rmin, double rmax)
{
this->SetCustomColumnRange(this->CustomColumnRangeIndex,rmin,rmax);
}
//------------------------------------------------------------------------------
void vtkPairwiseExtractHistogram2D::SetCustomColumnRange(int column, double rmin, double rmax)
{
vtkTable* t = vtkTable::SafeDownCast(this->GetInputDataObject(0,0));
if (t)
{
vtkAbstractArray* a = t->GetColumn(column);
if (a)
{
this->Implementation->ColumnUsesCustomExtents[a->GetName()] = true;
this->Implementation->ColumnExtents[a->GetName()][0] = rmin;
this->Implementation->ColumnExtents[a->GetName()][1] = rmax;
this->Modified();
}
}
}
//------------------------------------------------------------------------------
void vtkPairwiseExtractHistogram2D::SetCustomColumnRange(int column, double range[2])
{
this->SetCustomColumnRange(column,range[0],range[1]);
}
//------------------------------------------------------------------------------
int vtkPairwiseExtractHistogram2D::GetBinRange(int idx, vtkIdType binX, vtkIdType binY, double range[4])
{
vtkExtractHistogram2D* f = this->GetHistogramFilter(idx);
if (f)
{
return f->GetBinRange(binX,binY,range);
}
else
{
return 0;
}
}
int vtkPairwiseExtractHistogram2D::GetBinRange(int idx, vtkIdType bin, double range[4])
{
vtkExtractHistogram2D* f = this->GetHistogramFilter(idx);
if (f)
{
return f->GetBinRange(bin,range);
}
else
{
return 0;
}
}
//------------------------------------------------------------------------------
vtkExtractHistogram2D* vtkPairwiseExtractHistogram2D::GetHistogramFilter(int idx)
{
return vtkExtractHistogram2D::SafeDownCast(this->HistogramFilters->GetItemAsObject(idx));
}
//------------------------------------------------------------------------------
vtkImageData* vtkPairwiseExtractHistogram2D::GetOutputHistogramImage(int idx)
{
if (this->BuildTime < this->GetMTime() ||
this->BuildTime < this->GetInputDataObject(0,0)->GetMTime())
this->Update();
vtkMultiBlockDataSet* mbds = vtkMultiBlockDataSet::SafeDownCast(
this->GetOutputDataObject(vtkPairwiseExtractHistogram2D::HISTOGRAM_IMAGE));
if (mbds)
{
return vtkImageData::SafeDownCast(mbds->GetBlock(idx));
}
return NULL;
}
//------------------------------------------------------------------------------
void vtkPairwiseExtractHistogram2D::GetBinWidth(int idx,double bw[2])
{
vtkExtractHistogram2D* f = this->GetHistogramFilter(idx);
if (f)
{
f->GetBinWidth(bw);
}
}
//------------------------------------------------------------------------------
double* vtkPairwiseExtractHistogram2D::GetHistogramExtents(int idx)
{
vtkExtractHistogram2D* f = this->GetHistogramFilter(idx);
if (f)
{
return f->GetHistogramExtents();
}
else
{
return NULL;
}
}
//------------------------------------------------------------------------------
vtkExtractHistogram2D* vtkPairwiseExtractHistogram2D::NewHistogramFilter()
{
return vtkExtractHistogram2D::New();
}
//------------------------------------------------------------------------------
int vtkPairwiseExtractHistogram2D::GetMaximumBinCount(int idx)
{
vtkExtractHistogram2D* f = this->GetHistogramFilter(idx);
if (f)
{
return f->GetMaximumBinCount();
}
return -1;
}
//------------------------------------------------------------------------------
int vtkPairwiseExtractHistogram2D::GetMaximumBinCount()
{
if( !this->GetInputDataObject(0,0) )
return -1;
if (this->BuildTime < this->GetMTime() ||
this->BuildTime < this->GetInputDataObject(0,0)->GetMTime())
this->Update();
int maxcount = -1;
for (int i=0; i<this->HistogramFilters->GetNumberOfItems(); i++)
{
vtkExtractHistogram2D* f = this->GetHistogramFilter(i);
if (f)
{
maxcount = vtkstd::max((int)f->GetMaximumBinCount(),maxcount);
}
}
return maxcount;
}
//------------------------------------------------------------------------------
int vtkPairwiseExtractHistogram2D::FillOutputPortInformation( int port, vtkInformation* info )
{
if ( port == vtkPairwiseExtractHistogram2D::HISTOGRAM_IMAGE )
{
info->Set( vtkDataObject::DATA_TYPE_NAME(), "vtkMultiBlockDataSet" );
return 1;
}
else
{
return this->Superclass::FillOutputPortInformation(port,info);
}
}
<commit_msg>BUG: fixed crashing due to resizing custom ranges before histogram computation<commit_after>/*=========================================================================
Program: Visualization Toolkit
Module: vtkPairwiseExtractHistogram2D.cxx
Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
All rights reserved.
See Copyright.txt or http://www.kitware.com/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notice for more information.
=========================================================================*/
/*-------------------------------------------------------------------------
Copyright 2009 Sandia Corporation.
Under the terms of Contract DE-AC04-94AL85000 with Sandia Corporation,
the U.S. Government retains certain rights in this software.
-------------------------------------------------------------------------*/
#include "vtkPairwiseExtractHistogram2D.h"
//------------------------------------------------------------------------------
#include "vtkArrayData.h"
#include "vtkArrayIteratorIncludes.h"
#include "vtkStatisticsAlgorithmPrivate.h"
#include "vtkCollection.h"
#include "vtkExtractHistogram2D.h"
#include "vtkIdTypeArray.h"
#include "vtkImageData.h"
#include "vtkImageMedian3D.h"
#include "vtkInformation.h"
#include "vtkMultiBlockDataSet.h"
#include "vtkObjectFactory.h"
#include "vtkPointData.h"
#include "vtkStdString.h"
#include "vtkTable.h"
#include "vtkTimerLog.h"
#include "vtkUnsignedIntArray.h"
#define VTK_CREATE(type, name) \
vtkSmartPointer<type> name = vtkSmartPointer<type>::New()
//------------------------------------------------------------------------------
#include <vtkstd/set>
#include <vtkstd/vector>
#include <vtkstd/string>
#include <vtkstd/map>
//------------------------------------------------------------------------------
vtkCxxRevisionMacro(vtkPairwiseExtractHistogram2D, "1.5");
vtkStandardNewMacro(vtkPairwiseExtractHistogram2D);
//------------------------------------------------------------------------------
class vtkPairwiseExtractHistogram2D::Internals
{
public:
vtkstd::vector< vtkstd::pair< vtkStdString,vtkStdString > > ColumnPairs;
vtkstd::map< vtkstd::string,bool > ColumnUsesCustomExtents;
vtkstd::map< vtkstd::string,vtkstd::vector<double> > ColumnExtents;
};
//------------------------------------------------------------------------------
vtkPairwiseExtractHistogram2D::vtkPairwiseExtractHistogram2D()
{
this->Implementation = new Internals;
this->SetNumberOfOutputPorts(4);
this->NumberOfBins[0] = 0;
this->NumberOfBins[1] = 0;
this->CustomColumnRangeIndex = -1;
this->ScalarType = VTK_UNSIGNED_INT;
this->HistogramFilters = vtkSmartPointer<vtkCollection>::New();
this->BuildTime.Modified();
}
//------------------------------------------------------------------------------
vtkPairwiseExtractHistogram2D::~vtkPairwiseExtractHistogram2D()
{
delete this->Implementation;
}
//------------------------------------------------------------------------------
void vtkPairwiseExtractHistogram2D::PrintSelf(ostream& os, vtkIndent indent)
{
this->Superclass::PrintSelf(os,indent);
os << "NumberOfBins: " << this->NumberOfBins[0] << ", " << this->NumberOfBins[1] << endl;
os << "CustomColumnRangeIndex: " << this->CustomColumnRangeIndex << endl;
os << "ScalarType: " << this->ScalarType << endl;
}
//------------------------------------------------------------------------------
void vtkPairwiseExtractHistogram2D::Learn(vtkTable *inData,
vtkTable* vtkNotUsed(inParameters),
vtkDataObject *outMetaDO)
{
vtkTable* outMeta = vtkTable::SafeDownCast( outMetaDO );
if ( ! outMeta )
{
return;
}
if (this->NumberOfBins[0] == 0 || this->NumberOfBins[1] == 0)
{
vtkErrorMacro(<<"Error: histogram dimensions not set (use SetNumberOfBins).");
return;
}
// if the number of columns in the input has changed, we'll need to do
// some reinitializing
int numHistograms = inData->GetNumberOfColumns()-1;
if (numHistograms != this->HistogramFilters->GetNumberOfItems())
{
// clear out the list of histogram filters
for (int i=0; i<this->HistogramFilters->GetNumberOfItems(); i++)
{
this->HistogramFilters->GetItemAsObject(i)->Delete();
}
// clear out the internals
this->HistogramFilters->RemoveAllItems();
this->Implementation->ColumnPairs.clear();
this->Implementation->ColumnUsesCustomExtents.clear();
this->Implementation->ColumnExtents.clear();
// Make a shallow copy of the input to be safely passed to internal
// histogram filters.
VTK_CREATE(vtkTable, inDataCopy);
inDataCopy->ShallowCopy(inData);
// fill it up with new histogram filters
for (int i=0; i<numHistograms; i++)
{
vtkDataArray* col1 = vtkDataArray::SafeDownCast(inData->GetColumn(i));
vtkDataArray* col2 = vtkDataArray::SafeDownCast(inData->GetColumn(i+1));
if (!col1 || !col2)
{
vtkErrorMacro("All inputs must be numeric arrays.");
return;
}
// create a new histogram filter
vtkSmartPointer<vtkExtractHistogram2D> f;
f.TakeReference(this->NewHistogramFilter());
f->SetInput(inDataCopy);
f->SetNumberOfBins(this->NumberOfBins);
vtkstd::pair<vtkStdString,vtkStdString> colpair(inData->GetColumn(i)->GetName(),inData->GetColumn(i+1)->GetName());
f->AddColumnPair(colpair.first.c_str(),colpair.second.c_str());
f->SetSwapColumns(strcmp(colpair.first.c_str(),colpair.second.c_str())>=0);
this->HistogramFilters->AddItem(f);
// update the internals accordingly
this->Implementation->ColumnPairs.push_back(colpair);
this->Implementation->ColumnUsesCustomExtents[colpair.first.c_str()] = false;
// compute the range of the the new columns, and update the internals
double r[2] = {0,0};
if (i == 0)
{
col1->GetRange(r,0);
this->Implementation->ColumnExtents[colpair.first.c_str()].clear();
this->Implementation->ColumnExtents[colpair.first.c_str()].push_back(r[0]);
this->Implementation->ColumnExtents[colpair.first.c_str()].push_back(r[1]);
}
col2->GetRange(r,0);
this->Implementation->ColumnExtents[colpair.second.c_str()].clear();
this->Implementation->ColumnExtents[colpair.second.c_str()].push_back(r[0]);
this->Implementation->ColumnExtents[colpair.second.c_str()].push_back(r[1]);
}
}
// check the filters one by one and update them if necessary
if (this->BuildTime < inData->GetMTime() ||
this->BuildTime < this->GetMTime())
{
for (int i=0; i<numHistograms; i++)
{
vtkExtractHistogram2D* f = this->GetHistogramFilter(i);
// if the column names have changed, that means we need to update
vtkstd::pair<vtkStdString,vtkStdString> cols = this->Implementation->ColumnPairs[i];
if (inData->GetColumn(i)->GetName() != cols.first ||
inData->GetColumn(i+1)->GetName() != cols.second)
{
vtkstd::pair<vtkStdString,vtkStdString> newCols(inData->GetColumn(i)->GetName(),inData->GetColumn(i+1)->GetName());
f->ResetRequests();
f->AddColumnPair(newCols.first.c_str(),newCols.second.c_str());
f->SetSwapColumns(strcmp(newCols.first.c_str(),newCols.second.c_str()) >= 0);
f->Modified();
this->Implementation->ColumnPairs[i] = newCols;
}
// if the filter extents have changed, that means we need to update
vtkstd::pair<vtkStdString,vtkStdString> newCols(inData->GetColumn(i)->GetName(),inData->GetColumn(i+1)->GetName());
if (this->Implementation->ColumnUsesCustomExtents[newCols.first.c_str()] ||
this->Implementation->ColumnUsesCustomExtents[newCols.second.c_str()])
{
f->UseCustomHistogramExtentsOn();
double *ext = f->GetCustomHistogramExtents();
if (ext[0] != this->Implementation->ColumnExtents[newCols.first.c_str()][0] ||
ext[1] != this->Implementation->ColumnExtents[newCols.first.c_str()][1] ||
ext[2] != this->Implementation->ColumnExtents[newCols.second.c_str()][0] ||
ext[3] != this->Implementation->ColumnExtents[newCols.second.c_str()][1])
{
f->SetCustomHistogramExtents(this->Implementation->ColumnExtents[newCols.first.c_str()][0],
this->Implementation->ColumnExtents[newCols.first.c_str()][1],
this->Implementation->ColumnExtents[newCols.second.c_str()][0],
this->Implementation->ColumnExtents[newCols.second.c_str()][1]);
}
}
else
{
f->UseCustomHistogramExtentsOff();
}
// if the number of bins has changed, that definitely means we need to update
int* nbins = f->GetNumberOfBins();
if (nbins[0] != this->NumberOfBins[0] ||
nbins[1] != this->NumberOfBins[1])
{
f->SetNumberOfBins(this->NumberOfBins);
}
}
}
// update the filters as necessary
for (int i=0; i<numHistograms; i++)
{
vtkExtractHistogram2D* f = this->GetHistogramFilter(i);
if (f && (f->GetMTime() > this->BuildTime ||
inData->GetColumn(i)->GetMTime() > this->BuildTime ||
inData->GetColumn(i+1)->GetMTime() > this->BuildTime))
{
f->Update();
}
}
// build the composite image data set
vtkMultiBlockDataSet* outImages = vtkMultiBlockDataSet::SafeDownCast(
this->GetOutputDataObject(vtkPairwiseExtractHistogram2D::HISTOGRAM_IMAGE));
if (outImages)
{
outImages->SetNumberOfBlocks(numHistograms);
for (int i=0; i<numHistograms; i++)
{
vtkExtractHistogram2D* f = this->GetHistogramFilter(i);
if (f)
{
outImages->SetBlock(i,f->GetOutputHistogramImage());
}
}
}
// build the output table
outMeta->Initialize();
for (int i=0; i<this->HistogramFilters->GetNumberOfItems(); i++)
{
vtkExtractHistogram2D* f = this->GetHistogramFilter(i);
if (f)
{
if (f->GetMTime() > this->BuildTime)
f->Update();
outMeta->AddColumn(f->GetOutput()->GetColumn(0));
}
}
// build the reordered output table
/*
vtkTable* outReorderedTable = vtkTable::SafeDownCast(
this->GetOutputDataObject(vtkPairwiseExtractHistogram2D::REORDERED_INPUT));
if (outReorderedTable && this->Implementation->ColumnPairs.size())
{
outReorderedTable->Initialize();
outReorderedTable->AddColumn(inData->GetColumnByName(this->Implementation->ColumnPairs[0].first));
for (int i=0; i<(int)this->Implementation->ColumnPairs.size(); i++)
{
outReorderedTable->AddColumn(inData->GetColumnByName(this->Implementation->ColumnPairs[i].second));
}
}
*/
this->BuildTime.Modified();
}
//------------------------------------------------------------------------------
void vtkPairwiseExtractHistogram2D::SetCustomColumnRangeByIndex(double rmin, double rmax)
{
this->SetCustomColumnRange(this->CustomColumnRangeIndex,rmin,rmax);
}
//------------------------------------------------------------------------------
void vtkPairwiseExtractHistogram2D::SetCustomColumnRange(int column, double rmin, double rmax)
{
vtkTable* t = vtkTable::SafeDownCast(this->GetInputDataObject(0,0));
if (t)
{
vtkAbstractArray* a = t->GetColumn(column);
if (a)
{
this->Implementation->ColumnUsesCustomExtents[a->GetName()] = true;
if (this->Implementation->ColumnExtents[a->GetName()].size() == 0)
{
this->Implementation->ColumnExtents[a->GetName()].push_back(rmin);
this->Implementation->ColumnExtents[a->GetName()].push_back(rmax);
}
else
{
this->Implementation->ColumnExtents[a->GetName()][0] = rmin;
this->Implementation->ColumnExtents[a->GetName()][1] = rmax;
}
this->Modified();
}
}
}
//------------------------------------------------------------------------------
void vtkPairwiseExtractHistogram2D::SetCustomColumnRange(int column, double range[2])
{
this->SetCustomColumnRange(column,range[0],range[1]);
}
//------------------------------------------------------------------------------
int vtkPairwiseExtractHistogram2D::GetBinRange(int idx, vtkIdType binX, vtkIdType binY, double range[4])
{
vtkExtractHistogram2D* f = this->GetHistogramFilter(idx);
if (f)
{
return f->GetBinRange(binX,binY,range);
}
else
{
return 0;
}
}
int vtkPairwiseExtractHistogram2D::GetBinRange(int idx, vtkIdType bin, double range[4])
{
vtkExtractHistogram2D* f = this->GetHistogramFilter(idx);
if (f)
{
return f->GetBinRange(bin,range);
}
else
{
return 0;
}
}
//------------------------------------------------------------------------------
vtkExtractHistogram2D* vtkPairwiseExtractHistogram2D::GetHistogramFilter(int idx)
{
return vtkExtractHistogram2D::SafeDownCast(this->HistogramFilters->GetItemAsObject(idx));
}
//------------------------------------------------------------------------------
vtkImageData* vtkPairwiseExtractHistogram2D::GetOutputHistogramImage(int idx)
{
if (this->BuildTime < this->GetMTime() ||
this->BuildTime < this->GetInputDataObject(0,0)->GetMTime())
this->Update();
vtkMultiBlockDataSet* mbds = vtkMultiBlockDataSet::SafeDownCast(
this->GetOutputDataObject(vtkPairwiseExtractHistogram2D::HISTOGRAM_IMAGE));
if (mbds)
{
return vtkImageData::SafeDownCast(mbds->GetBlock(idx));
}
return NULL;
}
//------------------------------------------------------------------------------
void vtkPairwiseExtractHistogram2D::GetBinWidth(int idx,double bw[2])
{
vtkExtractHistogram2D* f = this->GetHistogramFilter(idx);
if (f)
{
f->GetBinWidth(bw);
}
}
//------------------------------------------------------------------------------
double* vtkPairwiseExtractHistogram2D::GetHistogramExtents(int idx)
{
vtkExtractHistogram2D* f = this->GetHistogramFilter(idx);
if (f)
{
return f->GetHistogramExtents();
}
else
{
return NULL;
}
}
//------------------------------------------------------------------------------
vtkExtractHistogram2D* vtkPairwiseExtractHistogram2D::NewHistogramFilter()
{
return vtkExtractHistogram2D::New();
}
//------------------------------------------------------------------------------
int vtkPairwiseExtractHistogram2D::GetMaximumBinCount(int idx)
{
vtkExtractHistogram2D* f = this->GetHistogramFilter(idx);
if (f)
{
return f->GetMaximumBinCount();
}
return -1;
}
//------------------------------------------------------------------------------
int vtkPairwiseExtractHistogram2D::GetMaximumBinCount()
{
if( !this->GetInputDataObject(0,0) )
return -1;
if (this->BuildTime < this->GetMTime() ||
this->BuildTime < this->GetInputDataObject(0,0)->GetMTime())
this->Update();
int maxcount = -1;
for (int i=0; i<this->HistogramFilters->GetNumberOfItems(); i++)
{
vtkExtractHistogram2D* f = this->GetHistogramFilter(i);
if (f)
{
maxcount = vtkstd::max((int)f->GetMaximumBinCount(),maxcount);
}
}
return maxcount;
}
//------------------------------------------------------------------------------
int vtkPairwiseExtractHistogram2D::FillOutputPortInformation( int port, vtkInformation* info )
{
if ( port == vtkPairwiseExtractHistogram2D::HISTOGRAM_IMAGE )
{
info->Set( vtkDataObject::DATA_TYPE_NAME(), "vtkMultiBlockDataSet" );
return 1;
}
else
{
return this->Superclass::FillOutputPortInformation(port,info);
}
}
<|endoftext|> |
<commit_before>/*
This file is part of CanFestival, a library implementing CanOpen Stack.
CanFestival Copyright (C): Edouard TISSERANT and Francis DUPIN
CanFestival Win32 port Copyright (C) 2007 Leonid Tochinski, ChattenAssociates, Inc.
See COPYING file for copyrights details.
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
*/
// pragma based message
// http://www.codeproject.com/macro/location_pragma.asp
#define __STR2__(x) #x
#define __STR1__(x) __STR2__(x)
#define __LOC2__ __FILE__ "("__STR1__(__LINE__)") : "
#pragma message("*********************************************************************************")
#pragma message(" NOTE: IXXAT Win32 drivers and API should be installed in order to build this project!")
#pragma message(__LOC2__ "See IXXAT.Cpp header for details.")
#pragma message("*********************************************************************************")
// IXXAT adapter driver for CanFestival-3 Win32 port
//
// Notes
//--------------------------------------------
// For building of this project you will need
// the following IXXAT API files
// Vci2.h
// Vci11un6.lib
//
// IXXAT Win32 drivers and API can be downloaded from
// http://www.ixxat.com/download_vci_en,7547,5873.html
//
// Copy Vci2.h & Vci11un6.lib files to can_ixxat_win32 folder of add path to them in Project settings.
#include <stdio.h>
extern "C" {
#include "applicfg.h"
#include "can_driver.h"
#include "def.h"
}
#include "VCI2.h"
#include "async_access_que.h"
#pragma warning(disable:4996)
#define CAN_NUM 0
class IXXAT
{
public:
class error
{
};
IXXAT(s_BOARD *board);
~IXXAT();
bool send(const Message *m);
bool receive(Message *m);
private:
bool open(const char* board_name, int board_number, const char* baud_rate);
bool close();
void receive_queuedata(UINT16 que_hdl, UINT16 count, VCI_CAN_OBJ* p_obj);
// VCI2 handler
static void VCI_CALLBACKATTR message_handler(char *msg_str);
static void VCI_CALLBACKATTR receive_queuedata_handler(UINT16 que_hdl, UINT16 count, VCI_CAN_OBJ* p_obj);
static void VCI_CALLBACKATTR exception_handler(VCI_FUNC_NUM func_num, INT32 err_code, UINT16 ext_err, char* err_str);
private:
UINT16 m_BoardHdl;
UINT16 m_TxQueHdl;
UINT16 m_RxQueHdl;
async_access_que<VCI_CAN_OBJ> m_RX_Que;
static IXXAT* m_callbackPtr;
};
IXXAT *IXXAT::m_callbackPtr = NULL;
IXXAT::IXXAT(s_BOARD *board) : m_BoardHdl(0xFFFF),
m_TxQueHdl(0xFFFF),
m_RxQueHdl(0xFFFF)
{
char busname[100];
::strcpy(busname,board->busname);
char board_name[100];
long board_number = 0;
char *ptr = ::strrchr(busname,':');
if (ptr != 0)
{
*ptr = 0;
::strcpy(board_name,busname);
if (++ptr - busname < (int)::strlen(board->busname))
board_number = ::atoi(ptr);
}
if (!open(board_name,board_number,board->baudrate))
{
close();
throw error();
}
m_callbackPtr = this;
}
IXXAT::~IXXAT()
{
close();
m_callbackPtr = 0;
}
bool IXXAT::send(const Message *m)
{
if (m_BoardHdl == 0xFFFF)
return true; // true -> NOT OK
long res = VCI_ERR;
if (m->rtr == NOT_A_REQUEST)
res = VCI_TransmitObj(m_BoardHdl, m_TxQueHdl, m->cob_id, m->len, const_cast<unsigned char*>(m->data));
else
res = VCI_RequestObj(m_BoardHdl, m_TxQueHdl, m->cob_id, m->len);
return (res == false); // false -> OK
}
bool IXXAT::receive(Message *m)
{
if (m_BoardHdl == 0xFFFF)
return false;
VCI_CAN_OBJ obj;
if (m_RX_Que.extract_top(obj))
{
m->cob_id = obj.id;
m->len = obj.len;
m->rtr = (obj.rtr == VCI_RX_BUF) ? NOT_A_REQUEST : REQUEST;
if (m->rtr == NOT_A_REQUEST)
::memcpy(m->data, obj.a_data, m->len);
return true;
}
return false;
}
bool IXXAT::open(const char* board_name, int board_number, const char* baud_rate)
{
// check, if baudrate is supported
struct IXXAT_baud_rate_param
{
UINT8 bt0;
UINT8 bt1;
};
struct IXXAT_look_up_table
{
char baud_rate[20];
IXXAT_baud_rate_param bt;
};
static const IXXAT_look_up_table br_lut[] = {
{"10K",{VCI_10KB}},
{"20K",{VCI_20KB}},
{"50K",{VCI_50KB}},
{"100K",{VCI_100KB}},
{"125K",{VCI_125KB}},
{"250K",{VCI_250KB}},
{"500K",{VCI_500KB}},
{"800K",{VCI_800KB}},
{"1M",{VCI_1000KB}}
};
static const long br_lut_size = sizeof (br_lut)/sizeof(IXXAT_look_up_table);
int index;
for (index = 0; index < br_lut_size; ++index)
{
if (::strcmp(br_lut[index].baud_rate,baud_rate)==0)
break;
}
if (index == br_lut_size)
return false;
// close existing board
close();
// init IXXAT board
unsigned long board_type = VCI_GetBrdTypeByName(const_cast<char*>(board_name));
long res = VCI2_PrepareBoard( board_type, // board type
board_number, // unique board index
NULL, // pointer to buffer for additional info
0, // length of additional info buffer
message_handler, // pointer to msg-callbackhandler
receive_queuedata_handler, // pointer to receive-callbackhandler
exception_handler); // pointer to exception-callbackhandler
if (res < 0)
return false;
m_BoardHdl = (UINT16)res;
VCI_ResetBoard(m_BoardHdl);
// init CAN parameters
// initialize CAN-Controller
res = VCI_InitCan(m_BoardHdl, CAN_NUM, br_lut[index].bt.bt0,br_lut[index].bt.bt1, VCI_11B);
// definition of Acceptance-Mask (define to receive all IDs)
res = VCI_SetAccMask(m_BoardHdl, CAN_NUM, 0x0UL, 0x0UL);
// definition of Transmit Queue
res = VCI_ConfigQueue(m_BoardHdl, CAN_NUM, VCI_TX_QUE, 100 , 0, 0, 0, &m_TxQueHdl);
// definition of Receive Queue (interrupt mode)
res = VCI_ConfigQueue(m_BoardHdl, CAN_NUM, VCI_RX_QUE, 50, 1, 0, 100, &m_RxQueHdl);
// assign the all IDs to the Receive Queue
res = VCI_AssignRxQueObj(m_BoardHdl, m_RxQueHdl ,VCI_ACCEPT, 0, 0) ;
// And now start the CAN
res = VCI_StartCan(m_BoardHdl, CAN_NUM);
return true;
}
bool IXXAT::close()
{
if (m_BoardHdl == 0xFFFF)
return true;
VCI_ResetBoard(m_BoardHdl);
VCI_CancelBoard(m_BoardHdl);
m_BoardHdl =
m_TxQueHdl =
m_RxQueHdl = 0xFFFF;
return true;
}
void IXXAT::receive_queuedata(UINT16 que_hdl, UINT16 count, VCI_CAN_OBJ *p_obj)
{
for (int i = 0; i < count; ++i)
m_RX_Que.append(p_obj[i]); // can packet
}
void VCI_CALLBACKATTR IXXAT::receive_queuedata_handler(UINT16 que_hdl, UINT16 count, VCI_CAN_OBJ *p_obj)
{
if (m_callbackPtr != NULL)
m_callbackPtr->receive_queuedata(que_hdl, count, p_obj);
}
void VCI_CALLBACKATTR IXXAT::message_handler(char *msg_str)
{
char buf[200];
::sprintf(buf,"IXXAT Message: [%s]\n", msg_str);
::OutputDebugString(buf);
}
void VCI_CALLBACKATTR IXXAT::exception_handler(VCI_FUNC_NUM func_num, INT32 err_code, UINT16 ext_err, char* err_str)
{
static const char* Num2Function[] =
{
"VCI_Init",
"VCI_Searchboard",
"VCI_Prepareboard",
"VCI_Cancel_board",
"VCI_Testboard",
"VCI_ReadBoardInfo",
"VCI_ReadBoardStatus",
"VCI_Resetboard",
"VCI_ReadCANInfo",
"VCI_ReadCANStatus",
"VCI_InitCAN",
"VCI_SetAccMask",
"VCI_ResetCAN",
"VCI_StartCAN",
"VCI_ResetTimeStamps",
"VCI_ConfigQueue",
"VCI_AssignRxQueObj",
"VCI_ConfigBuffer",
"VCI_ReconfigBuffer",
"VCI_ConfigTimer",
"VCI_ReadQueStatus",
"VCI_ReadQueObj",
"VCI_ReadBufStatus",
"VCI_ReadBufData",
"VCI_TransmitObj",
"VCI_RequestObj",
"VCI_UpdateBufObj",
"VCI_CciReqData"
};
char buf[200];
::sprintf(buf, "IXXAT Exception: %s (%i / %u) [%s]\n", Num2Function[func_num], err_code, ext_err, err_str);
::OutputDebugString(buf);
}
//------------------------------------------------------------------------
extern "C"
UNS8 __stdcall canReceive_driver(CAN_HANDLE inst, Message *m)
{
return (UNS8)reinterpret_cast<IXXAT*>(inst)->receive(m);
}
extern "C"
UNS8 __stdcall canSend_driver(CAN_HANDLE inst, Message const *m)
{
return (UNS8)reinterpret_cast<IXXAT*>(inst)->send(m);
}
extern "C"
CAN_HANDLE __stdcall canOpen_driver(s_BOARD *board)
{
try
{
return new IXXAT(board);
}
catch (IXXAT::error&)
{
return 0;
}
}
extern "C"
int __stdcall canClose_driver(CAN_HANDLE inst)
{
delete reinterpret_cast<IXXAT*>(inst);
return 1;
}
extern "C"
UNS8 __stdcall canChangeBaudRate_driver( CAN_HANDLE fd, char* baud)
{
//printf("canChangeBaudRate not yet supported by this driver\n");
return 0;
}
<commit_msg>CHANGED: - added explicit cast to remove compiler warning<commit_after>/*
This file is part of CanFestival, a library implementing CanOpen Stack.
CanFestival Copyright (C): Edouard TISSERANT and Francis DUPIN
CanFestival Win32 port Copyright (C) 2007 Leonid Tochinski, ChattenAssociates, Inc.
See COPYING file for copyrights details.
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
*/
// pragma based message
// http://www.codeproject.com/macro/location_pragma.asp
#define __STR2__(x) #x
#define __STR1__(x) __STR2__(x)
#define __LOC2__ __FILE__ "("__STR1__(__LINE__)") : "
#pragma message("*********************************************************************************")
#pragma message(" NOTE: IXXAT Win32 drivers and API should be installed in order to build this project!")
#pragma message(__LOC2__ "See IXXAT.Cpp header for details.")
#pragma message("*********************************************************************************")
// IXXAT adapter driver for CanFestival-3 Win32 port
//
// Notes
//--------------------------------------------
// For building of this project you will need
// the following IXXAT API files
// Vci2.h
// Vci11un6.lib
//
// IXXAT Win32 drivers and API can be downloaded from
// http://www.ixxat.com/download_vci_en,7547,5873.html
//
// Copy Vci2.h & Vci11un6.lib files to can_ixxat_win32 folder of add path to them in Project settings.
#include <stdio.h>
extern "C" {
#include "applicfg.h"
#include "can_driver.h"
#include "def.h"
}
#include "VCI2.h"
#include "async_access_que.h"
#pragma warning(disable:4996)
#define CAN_NUM 0
class IXXAT
{
public:
class error
{
};
IXXAT(s_BOARD *board);
~IXXAT();
bool send(const Message *m);
bool receive(Message *m);
private:
bool open(const char* board_name, int board_number, const char* baud_rate);
bool close();
void receive_queuedata(UINT16 que_hdl, UINT16 count, VCI_CAN_OBJ* p_obj);
// VCI2 handler
static void VCI_CALLBACKATTR message_handler(char *msg_str);
static void VCI_CALLBACKATTR receive_queuedata_handler(UINT16 que_hdl, UINT16 count, VCI_CAN_OBJ* p_obj);
static void VCI_CALLBACKATTR exception_handler(VCI_FUNC_NUM func_num, INT32 err_code, UINT16 ext_err, char* err_str);
private:
UINT16 m_BoardHdl;
UINT16 m_TxQueHdl;
UINT16 m_RxQueHdl;
async_access_que<VCI_CAN_OBJ> m_RX_Que;
static IXXAT* m_callbackPtr;
};
IXXAT *IXXAT::m_callbackPtr = NULL;
IXXAT::IXXAT(s_BOARD *board) : m_BoardHdl(0xFFFF),
m_TxQueHdl(0xFFFF),
m_RxQueHdl(0xFFFF)
{
char busname[100];
::strcpy(busname,board->busname);
char board_name[100];
long board_number = 0;
char *ptr = ::strrchr(busname,':');
if (ptr != 0)
{
*ptr = 0;
::strcpy(board_name,busname);
if (++ptr - busname < (int)::strlen(board->busname))
board_number = ::atoi(ptr);
}
if (!open(board_name,board_number,board->baudrate))
{
close();
throw error();
}
m_callbackPtr = this;
}
IXXAT::~IXXAT()
{
close();
m_callbackPtr = 0;
}
bool IXXAT::send(const Message *m)
{
if (m_BoardHdl == 0xFFFF)
return true; // true -> NOT OK
long res = VCI_ERR;
if (m->rtr == NOT_A_REQUEST)
res = VCI_TransmitObj(m_BoardHdl, m_TxQueHdl, m->cob_id, m->len, const_cast<unsigned char*>(m->data));
else
res = VCI_RequestObj(m_BoardHdl, m_TxQueHdl, m->cob_id, m->len);
return (res == false); // false -> OK
}
bool IXXAT::receive(Message *m)
{
if (m_BoardHdl == 0xFFFF)
return false;
VCI_CAN_OBJ obj;
if (m_RX_Que.extract_top(obj))
{
m->cob_id = static_cast<UNS16>(obj.id); //valid for 11Bit ids
m->len = obj.len;
m->rtr = (obj.rtr == VCI_RX_BUF) ? NOT_A_REQUEST : REQUEST;
if (m->rtr == NOT_A_REQUEST)
::memcpy(m->data, obj.a_data, m->len);
return true;
}
return false;
}
bool IXXAT::open(const char* board_name, int board_number, const char* baud_rate)
{
// check, if baudrate is supported
struct IXXAT_baud_rate_param
{
UINT8 bt0;
UINT8 bt1;
};
struct IXXAT_look_up_table
{
char baud_rate[20];
IXXAT_baud_rate_param bt;
};
static const IXXAT_look_up_table br_lut[] = {
{"10K",{VCI_10KB}},
{"20K",{VCI_20KB}},
{"50K",{VCI_50KB}},
{"100K",{VCI_100KB}},
{"125K",{VCI_125KB}},
{"250K",{VCI_250KB}},
{"500K",{VCI_500KB}},
{"800K",{VCI_800KB}},
{"1M",{VCI_1000KB}}
};
static const long br_lut_size = sizeof (br_lut)/sizeof(IXXAT_look_up_table);
int index;
for (index = 0; index < br_lut_size; ++index)
{
if (::strcmp(br_lut[index].baud_rate,baud_rate)==0)
break;
}
if (index == br_lut_size)
return false;
// close existing board
close();
// init IXXAT board
unsigned long board_type = VCI_GetBrdTypeByName(const_cast<char*>(board_name));
long res = VCI2_PrepareBoard( board_type, // board type
board_number, // unique board index
NULL, // pointer to buffer for additional info
0, // length of additional info buffer
message_handler, // pointer to msg-callbackhandler
receive_queuedata_handler, // pointer to receive-callbackhandler
exception_handler); // pointer to exception-callbackhandler
if (res < 0)
return false;
m_BoardHdl = (UINT16)res;
VCI_ResetBoard(m_BoardHdl);
// init CAN parameters
// initialize CAN-Controller
res = VCI_InitCan(m_BoardHdl, CAN_NUM, br_lut[index].bt.bt0,br_lut[index].bt.bt1, VCI_11B);
// definition of Acceptance-Mask (define to receive all IDs)
res = VCI_SetAccMask(m_BoardHdl, CAN_NUM, 0x0UL, 0x0UL);
// definition of Transmit Queue
res = VCI_ConfigQueue(m_BoardHdl, CAN_NUM, VCI_TX_QUE, 100 , 0, 0, 0, &m_TxQueHdl);
// definition of Receive Queue (interrupt mode)
res = VCI_ConfigQueue(m_BoardHdl, CAN_NUM, VCI_RX_QUE, 50, 1, 0, 100, &m_RxQueHdl);
// assign the all IDs to the Receive Queue
res = VCI_AssignRxQueObj(m_BoardHdl, m_RxQueHdl ,VCI_ACCEPT, 0, 0) ;
// And now start the CAN
res = VCI_StartCan(m_BoardHdl, CAN_NUM);
return true;
}
bool IXXAT::close()
{
if (m_BoardHdl == 0xFFFF)
return true;
VCI_ResetBoard(m_BoardHdl);
VCI_CancelBoard(m_BoardHdl);
m_BoardHdl =
m_TxQueHdl =
m_RxQueHdl = 0xFFFF;
return true;
}
void IXXAT::receive_queuedata(UINT16 que_hdl, UINT16 count, VCI_CAN_OBJ *p_obj)
{
for (int i = 0; i < count; ++i)
m_RX_Que.append(p_obj[i]); // can packet
}
void VCI_CALLBACKATTR IXXAT::receive_queuedata_handler(UINT16 que_hdl, UINT16 count, VCI_CAN_OBJ *p_obj)
{
if (m_callbackPtr != NULL)
m_callbackPtr->receive_queuedata(que_hdl, count, p_obj);
}
void VCI_CALLBACKATTR IXXAT::message_handler(char *msg_str)
{
char buf[200];
::sprintf(buf,"IXXAT Message: [%s]\n", msg_str);
::OutputDebugString(buf);
}
void VCI_CALLBACKATTR IXXAT::exception_handler(VCI_FUNC_NUM func_num, INT32 err_code, UINT16 ext_err, char* err_str)
{
static const char* Num2Function[] =
{
"VCI_Init",
"VCI_Searchboard",
"VCI_Prepareboard",
"VCI_Cancel_board",
"VCI_Testboard",
"VCI_ReadBoardInfo",
"VCI_ReadBoardStatus",
"VCI_Resetboard",
"VCI_ReadCANInfo",
"VCI_ReadCANStatus",
"VCI_InitCAN",
"VCI_SetAccMask",
"VCI_ResetCAN",
"VCI_StartCAN",
"VCI_ResetTimeStamps",
"VCI_ConfigQueue",
"VCI_AssignRxQueObj",
"VCI_ConfigBuffer",
"VCI_ReconfigBuffer",
"VCI_ConfigTimer",
"VCI_ReadQueStatus",
"VCI_ReadQueObj",
"VCI_ReadBufStatus",
"VCI_ReadBufData",
"VCI_TransmitObj",
"VCI_RequestObj",
"VCI_UpdateBufObj",
"VCI_CciReqData"
};
char buf[200];
::sprintf(buf, "IXXAT Exception: %s (%i / %u) [%s]\n", Num2Function[func_num], err_code, ext_err, err_str);
::OutputDebugString(buf);
}
//------------------------------------------------------------------------
extern "C"
UNS8 __stdcall canReceive_driver(CAN_HANDLE inst, Message *m)
{
return (UNS8)reinterpret_cast<IXXAT*>(inst)->receive(m);
}
extern "C"
UNS8 __stdcall canSend_driver(CAN_HANDLE inst, Message const *m)
{
return (UNS8)reinterpret_cast<IXXAT*>(inst)->send(m);
}
extern "C"
CAN_HANDLE __stdcall canOpen_driver(s_BOARD *board)
{
try
{
return new IXXAT(board);
}
catch (IXXAT::error&)
{
return 0;
}
}
extern "C"
int __stdcall canClose_driver(CAN_HANDLE inst)
{
delete reinterpret_cast<IXXAT*>(inst);
return 1;
}
extern "C"
UNS8 __stdcall canChangeBaudRate_driver( CAN_HANDLE fd, char* baud)
{
//printf("canChangeBaudRate not yet supported by this driver\n");
return 0;
}
<|endoftext|> |
<commit_before>/* This file is part of the KDE libraries
* Copyright (C) 2008-2009 Erlend Hamberg <[email protected]>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) version 3.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public License
* along with this library; see the file COPYING.LIB. If not, write to
* the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301, USA.
*/
#include "kateviglobal.h"
#include "katevikeyparser.h"
#include "kconfiggroup.h"
#include "kdebug.h"
#include <QApplication>
#include <QClipboard>
KateViGlobal::KateViGlobal()
{
m_numberedRegisters = new QList<QString>;
m_registers = new QMap<QChar, QString>;
}
KateViGlobal::~KateViGlobal()
{
delete m_numberedRegisters;
delete m_registers;
}
void KateViGlobal::writeConfig( KConfigGroup &config ) const
{
config.writeEntry( "Normal Mode Mapping Keys", getMappings( NormalMode, true ) );
QStringList l;
foreach( const QString &s, getMappings( NormalMode ) ) {
l << KateViKeyParser::getInstance()->decodeKeySequence( getMapping( NormalMode, s ) );
}
config.writeEntry( "Normal Mode Mappings", l );
}
void KateViGlobal::readConfig( const KConfigGroup &config )
{
QStringList keys = config.readEntry( "Normal Mode Mapping Keys", QStringList() );
QStringList mappings = config.readEntry( "Normal Mode Mappings", QStringList() );
// sanity check
if ( keys.length() == mappings.length() ) {
for ( int i = 0; i < keys.length(); i++ ) {
addMapping( NormalMode, keys.at( i ), mappings.at( i ) );
kDebug( 13070 ) << "Mapping " << keys.at( i ) << " -> " << mappings.at( i );
}
} else {
kDebug( 13070 ) << "Error when reading mappings from config: number of keys != number of values";
}
}
QString KateViGlobal::getRegisterContent( const QChar ® ) const
{
QString regContent;
QChar _reg = ( reg != '"' ? reg : m_defaultRegister );
if ( _reg >= '1' && _reg <= '9' ) { // numbered register
int index = QString( _reg ).toInt()-1;
if ( m_numberedRegisters->size() > index) {
regContent = m_numberedRegisters->at( index );
} else {
regContent = QString();
}
} else if ( _reg == '+' ) { // system clipboard register
regContent = QApplication::clipboard()->text( QClipboard::Clipboard );
} else if ( _reg == '*' ) { // system selection register
regContent = QApplication::clipboard()->text( QClipboard::Selection );
} else { // regular, named register
if ( m_registers->contains( _reg ) ) {
regContent = m_registers->value( _reg );
}
}
return regContent;
}
void KateViGlobal::addToNumberedRegister( const QString &text )
{
if ( m_numberedRegisters->size() == 9 ) {
m_numberedRegisters->removeLast();
}
// register 0 is used for the last yank command, so insert at position 1
m_numberedRegisters->prepend( text );
kDebug( 13070 ) << "Register 1-9:";
for ( int i = 0; i < m_numberedRegisters->size(); i++ ) {
kDebug( 13070 ) << "\t Register " << i+1 << ": " << m_numberedRegisters->at( i );
}
}
void KateViGlobal::fillRegister( const QChar ®, const QString &text )
{
// the specified register is the "black hole register", don't do anything
if ( reg == '_' ) {
return;
}
if ( reg >= '1' && reg <= '9' ) { // "kill ring" registers
addToNumberedRegister( text );
} else if ( reg == '+' ) { // system clipboard register
QApplication::clipboard()->setText( text, QClipboard::Clipboard );
} else if ( reg == '*' ) { // system selection register
QApplication::clipboard()->setText( text, QClipboard::Selection );
} else {
m_registers->insert( reg, text );
}
kDebug( 13070 ) << "Register " << reg << " set to " << getRegisterContent( reg );
if ( reg == '0' || reg == '1' || reg == '-' ) {
m_defaultRegister = reg;
kDebug( 13070 ) << "Register " << '"' << " set to point to \"" << reg;
}
}
void KateViGlobal::addMapping( ViMode mode, const QString &from, const QString &to )
{
if ( !from.isEmpty() ) {
switch ( mode ) {
case NormalMode:
m_normalModeMappings[ KateViKeyParser::getInstance()->encodeKeySequence( from ) ]
= KateViKeyParser::getInstance()->encodeKeySequence( to );
break;
default:
kDebug( 13070 ) << "Mapping not supported for given mode";
}
}
}
const QString KateViGlobal::getMapping( ViMode mode, const QString &from, bool decode ) const
{
QString ret;
switch ( mode ) {
case NormalMode:
ret = m_normalModeMappings.value( from );
break;
default:
kDebug( 13070 ) << "Mapping not supported for given mode";
}
if ( decode ) {
return KateViKeyParser::getInstance()->decodeKeySequence( ret );
}
return ret;
}
const QStringList KateViGlobal::getMappings( ViMode mode, bool decode ) const
{
QStringList l;
switch (mode ) {
case NormalMode:
foreach ( const QString &str, m_normalModeMappings.keys() ) {
if ( decode ) {
l << KateViKeyParser::getInstance()->decodeKeySequence( str );
} else {
l << str;
}
}
break;
default:
kDebug( 13070 ) << "Mapping not supported for given mode";
}
return l;
}
void KateViGlobal::clearMappings( ViMode mode )
{
switch (mode ) {
case NormalMode:
m_normalModeMappings.clear();
break;
default:
kDebug( 13070 ) << "Mapping not supported for given mode";
}
}
<commit_msg>fix krazy warning<commit_after>/* This file is part of the KDE libraries
* Copyright (C) 2008-2009 Erlend Hamberg <[email protected]>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) version 3.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public License
* along with this library; see the file COPYING.LIB. If not, write to
* the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301, USA.
*/
#include "kateviglobal.h"
#include "katevikeyparser.h"
#include "kconfiggroup.h"
#include "kdebug.h"
#include <QApplication>
#include <QClipboard>
KateViGlobal::KateViGlobal()
{
m_numberedRegisters = new QList<QString>;
m_registers = new QMap<QChar, QString>;
}
KateViGlobal::~KateViGlobal()
{
delete m_numberedRegisters;
delete m_registers;
}
void KateViGlobal::writeConfig( KConfigGroup &config ) const
{
config.writeEntry( "Normal Mode Mapping Keys", getMappings( NormalMode, true ) );
QStringList l;
foreach( const QString &s, getMappings( NormalMode ) ) {
l << KateViKeyParser::getInstance()->decodeKeySequence( getMapping( NormalMode, s ) );
}
config.writeEntry( "Normal Mode Mappings", l );
}
void KateViGlobal::readConfig( const KConfigGroup &config )
{
QStringList keys = config.readEntry( "Normal Mode Mapping Keys", QStringList() );
QStringList mappings = config.readEntry( "Normal Mode Mappings", QStringList() );
// sanity check
if ( keys.length() == mappings.length() ) {
for ( int i = 0; i < keys.length(); i++ ) {
addMapping( NormalMode, keys.at( i ), mappings.at( i ) );
kDebug( 13070 ) << "Mapping " << keys.at( i ) << " -> " << mappings.at( i );
}
} else {
kDebug( 13070 ) << "Error when reading mappings from config: number of keys != number of values";
}
}
QString KateViGlobal::getRegisterContent( const QChar ® ) const
{
QString regContent;
QChar _reg = ( reg != '"' ? reg : m_defaultRegister );
if ( _reg >= '1' && _reg <= '9' ) { // numbered register
int index = QString( _reg ).toInt()-1;
if ( m_numberedRegisters->size() > index) {
regContent = m_numberedRegisters->at( index );
}
} else if ( _reg == '+' ) { // system clipboard register
regContent = QApplication::clipboard()->text( QClipboard::Clipboard );
} else if ( _reg == '*' ) { // system selection register
regContent = QApplication::clipboard()->text( QClipboard::Selection );
} else { // regular, named register
if ( m_registers->contains( _reg ) ) {
regContent = m_registers->value( _reg );
}
}
return regContent;
}
void KateViGlobal::addToNumberedRegister( const QString &text )
{
if ( m_numberedRegisters->size() == 9 ) {
m_numberedRegisters->removeLast();
}
// register 0 is used for the last yank command, so insert at position 1
m_numberedRegisters->prepend( text );
kDebug( 13070 ) << "Register 1-9:";
for ( int i = 0; i < m_numberedRegisters->size(); i++ ) {
kDebug( 13070 ) << "\t Register " << i+1 << ": " << m_numberedRegisters->at( i );
}
}
void KateViGlobal::fillRegister( const QChar ®, const QString &text )
{
// the specified register is the "black hole register", don't do anything
if ( reg == '_' ) {
return;
}
if ( reg >= '1' && reg <= '9' ) { // "kill ring" registers
addToNumberedRegister( text );
} else if ( reg == '+' ) { // system clipboard register
QApplication::clipboard()->setText( text, QClipboard::Clipboard );
} else if ( reg == '*' ) { // system selection register
QApplication::clipboard()->setText( text, QClipboard::Selection );
} else {
m_registers->insert( reg, text );
}
kDebug( 13070 ) << "Register " << reg << " set to " << getRegisterContent( reg );
if ( reg == '0' || reg == '1' || reg == '-' ) {
m_defaultRegister = reg;
kDebug( 13070 ) << "Register " << '"' << " set to point to \"" << reg;
}
}
void KateViGlobal::addMapping( ViMode mode, const QString &from, const QString &to )
{
if ( !from.isEmpty() ) {
switch ( mode ) {
case NormalMode:
m_normalModeMappings[ KateViKeyParser::getInstance()->encodeKeySequence( from ) ]
= KateViKeyParser::getInstance()->encodeKeySequence( to );
break;
default:
kDebug( 13070 ) << "Mapping not supported for given mode";
}
}
}
const QString KateViGlobal::getMapping( ViMode mode, const QString &from, bool decode ) const
{
QString ret;
switch ( mode ) {
case NormalMode:
ret = m_normalModeMappings.value( from );
break;
default:
kDebug( 13070 ) << "Mapping not supported for given mode";
}
if ( decode ) {
return KateViKeyParser::getInstance()->decodeKeySequence( ret );
}
return ret;
}
const QStringList KateViGlobal::getMappings( ViMode mode, bool decode ) const
{
QStringList l;
switch (mode ) {
case NormalMode:
foreach ( const QString &str, m_normalModeMappings.keys() ) {
if ( decode ) {
l << KateViKeyParser::getInstance()->decodeKeySequence( str );
} else {
l << str;
}
}
break;
default:
kDebug( 13070 ) << "Mapping not supported for given mode";
}
return l;
}
void KateViGlobal::clearMappings( ViMode mode )
{
switch (mode ) {
case NormalMode:
m_normalModeMappings.clear();
break;
default:
kDebug( 13070 ) << "Mapping not supported for given mode";
}
}
<|endoftext|> |
<commit_before>/*************************************************************************/
/* spdlog - an extremely fast and easy to use c++11 logging library. */
/* Copyright (c) 2014 Gabi Melman. */
/* */
/* 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. */
/*************************************************************************/
//
// spdlog usage example
//
#include <iostream>
#include "spdlog/spdlog.h"
int main(int, char* [])
{
namespace spd = spdlog;
try
{
// Set log level to all loggers to DEBUG and above
spd::set_level(spd::level::debug);
//Create console, multithreaded logger
auto console = spd::stdout_logger_mt("console");
console->info("Welcome to spdlog!") ;
console->info("An info message example {}..", 1);
console->info() << "Streams are supported too " << 1;
console->info("Easy padding in numbers like {:08d}", 12);
console->info("Support for int: {0:d}; hex: {0:x}; oct: {0:o}; bin: {0:b}", 42);
console->info("Support for floats {:03.2f}", 1.23456);
console->info("Positional args are {1} {0}..", "too", "supported");
console->info("{:<30}", "left aligned");
console->info("{:>30}", "right aligned");
console->info("{:^30}", "centered");
//Create a file rotating logger with 5mb size max and 3 rotated files
auto file_logger = spd::rotating_logger_mt("file_logger", "logs/mylogfile", 1048576 * 5, 3);
file_logger->set_level(spd::level::info);
for(int i = 0; i < 10; ++i)
file_logger->info("{} * {} equals {:>10}", i, i, i*i);
//Customize msg format for all messages
spd::set_pattern("*** [%H:%M:%S %z] [thread %t] %v ***");
file_logger->info("This is another message with custom format");
spd::get("console")->info("loggers can be retrieved from a global registry using the spdlog::get(logger_name) function");
SPDLOG_TRACE(console, "Enabled only #ifdef SPDLOG_TRACE_ON..{} ,{}", 1, 3.23);
SPDLOG_DEBUG(console, "Enabled only #ifdef SPDLOG_DEBUG_ON.. {} ,{}", 1, 3.23);
//
// Asynchronous logging is very fast..
// Just call spdlog::set_async_mode(q_size) and all created loggers from now on will be asynchronous..
//
size_t q_size = 1048576; //queue size must be power of 2
spdlog::set_async_mode(q_size);
auto async_file= spd::daily_logger_st("async_file_logger", "logs/async_log.txt");
async_file->info() << "This is async log.." << "Should be very fast!";
#ifdef __linux__
// syslog example. linux only..
std::string ident = "spdlog-example";
auto syslog_logger = spd::syslog_logger("syslog", ident, LOG_PID);
syslog_logger->warn("This is warning that will end up in syslog. This is Linux only!");
#endif
}
catch (const spd::spdlog_ex& ex)
{
std::cout << "Log failed: " << ex.what() << std::endl;
}
}
<commit_msg>updated example<commit_after>/*************************************************************************/
/* spdlog - an extremely fast and easy to use c++11 logging library. */
/* Copyright (c) 2014 Gabi Melman. */
/* */
/* 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. */
/*************************************************************************/
//
// spdlog usage example
//
#include <iostream>
#include "spdlog/spdlog.h"
int main(int, char* [])
{
namespace spd = spdlog;
try
{
// Set log level to all loggers to debug and above
spd::set_level(spd::level::debug);
// Create console, multithreaded logger
auto console = spd::stdout_logger_mt("console");
console->info("Welcome to spdlog!") ;
console->info("An info message example {}..", 1);
console->info() << "Streams are supported too " << 1;
console->info("Easy padding in numbers like {:08d}", 12);
console->info("Support for int: {0:d}; hex: {0:x}; oct: {0:o}; bin: {0:b}", 42);
console->info("Support for floats {:03.2f}", 1.23456);
console->info("Positional args are {1} {0}..", "too", "supported");
console->info("{:<30}", "left aligned");
console->info("{:>30}", "right aligned");
console->info("{:^30}", "centered");
// Create a file rotating logger with 5mb size max and 3 rotated files
auto file_logger = spd::rotating_logger_mt("file_logger", "logs/mylogfile", 1048576 * 5, 3);
file_logger->set_level(spd::level::info);
for(int i = 0; i < 10; ++i)
file_logger->info("{} * {} equals {:>10}", i, i, i*i);
// Customize msg format for all messages
spd::set_pattern("*** [%H:%M:%S %z] [thread %t] %v ***");
file_logger->info("This is another message with custom format");
spd::get("console")->info("loggers can be retrieved from a global registry using the spdlog::get(logger_name) function");
SPDLOG_TRACE(console, "Enabled only #ifdef SPDLOG_TRACE_ON..{} ,{}", 1, 3.23);
SPDLOG_DEBUG(console, "Enabled only #ifdef SPDLOG_DEBUG_ON.. {} ,{}", 1, 3.23);
//
// Asynchronous logging is very fast..
// Just call spdlog::set_async_mode(q_size) and all created loggers from now on will be asynchronous..
//
size_t q_size = 1048576; //queue size must be power of 2
spdlog::set_async_mode(q_size);
auto async_file= spd::daily_logger_st("async_file_logger", "logs/async_log.txt");
async_file->info() << "This is async log.." << "Should be very fast!";
// syslog example. linux only..
#ifdef __linux__
std::string ident = "spdlog-example";
auto syslog_logger = spd::syslog_logger("syslog", ident, LOG_PID);
syslog_logger->warn("This is warning that will end up in syslog. This is Linux only!");
#endif
}
catch (const spd::spdlog_ex& ex)
{
std::cout << "Log failed: " << ex.what() << std::endl;
}
}
<|endoftext|> |
<commit_before>/**
* Copyright (c) 2013 Egor Pushkin. 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 "Common/Common.h"
// Server object model.
#include "../../Server/Client.h"
#include "../../Server/IClientHandler.h"
#include "../../Server/Services/Services.h"
#include "../../Server/IServerControl.h"
#include "../../Server/Config.h"
#include "ScreenshotSpreader.h"
// Hardware subsystem.
#include "Hardware/Hardware.h"
// Interaction protocol tool.
#include "Messages/ScreenshotMessage.h"
// QT is responsible for image capturing and resizing.
#include <QtGui/QtGui>
#include <QDesktopWidget>
#include <QApplication>
namespace RemotePC
{
void ScreenshotSpreader::Handle(const Client& client, mc::IProtocolRef protocol, IServerControlRef /* server */)
{
if ( !client.IsScreenCaptureEnabled() )
return;
// Acquire mouse cursor position.
RemotePC::ScreenPoint position = RemotePC::HardwareProvider::Instance().GetMouseControl()->GetPosition();
// Calculate bounding box around current mouse position.
float blockSize = 256.0f;
float zoomLevel = client.GetZoomLevel();
int imageSize = (int)( blockSize * zoomLevel );
int leftX = position.x_ - imageSize / 2;
int topY = position.y_ - imageSize / 2;
int rightX = leftX + imageSize;
int bottomY = topY + imageSize;
// Find screen to which cursor currently belongs.
QDesktopWidget* desktop = QApplication::desktop();
int screenNumber = desktop->screenNumber(QPoint(position.x_, position.y_));
QWidget* screen = desktop->screen(screenNumber);
QRect geometry = screen->geometry();
// Cut areas beyond the surface of the screen.
int leftdX = ( leftX < geometry.left() ) ? ( geometry.left() - leftX ) : 0;
int topdY = ( topY < geometry.top() ) ? ( geometry.top() - topY ) : 0;
int rightdX = ( rightX > geometry.right() ) ? ( rightX - geometry.right() ) : 0;
int bottomdY = ( bottomY >= geometry.bottom() ) ? ( bottomY - geometry.bottom() ) : 0;
leftX += leftdX;
topY += topdY;
rightX += rightdX;
bottomY += bottomdY;
int fragmentWidth = imageSize - leftdX - rightdX;
int fragmentHeight = imageSize - topdY - bottomdY;
bool isBoundary = ( leftdX > 0 ) || ( topdY > 0 ) || ( rightdX > 0 ) || ( bottomdY > 0 );
// Grab part of the screen.
QPixmap fragment = QApplication::primaryScreen()->grabWindow(
QApplication::desktop()->winId(),
leftX, topY, fragmentWidth, fragmentHeight);
// Check to see if anything was actually grabbed.
fragmentWidth = fragment.width();
fragmentHeight = fragment.height();
if ( fragmentWidth <= 0 || fragmentHeight <= 0 )
{
return;
}
if ( isBoundary )
{
// Image was grabbed right next to one of screen edges.
QPixmap temp(blockSize, blockSize);
QPainter painter(&temp);
painter.fillRect(0, 0, blockSize, blockSize, QColor(Qt::black));
QRect source(0, 0, fragmentWidth, fragmentHeight);
QRect target(
leftdX * blockSize / imageSize, topdY * blockSize / imageSize,
fragmentWidth * blockSize / imageSize, fragmentHeight * blockSize / imageSize);
painter.drawPixmap(target, fragment, source);
fragment = temp;
}
else
{
if ( imageSize != (int)blockSize )
{
// Image was grabbed from within the screen.
fragment = fragment.scaled(
QSize(blockSize, blockSize),
Qt::KeepAspectRatio,
Qt::SmoothTransformation);
}
}
// Construct screenshot message from QT image.
QByteArray imageBytes;
QBuffer imageBuffer(&imageBytes);
imageBuffer.open(QIODevice::WriteOnly);
#if !defined(IREMOTE_NO_QT_PLUGINS)
fragment.save(&imageBuffer, "JPG", Config::Instance().GetSFBCompression());
#else
fragment.save(&imageBuffer, "PNG", Config::Instance().GetSFBCompression());
#endif
mc::IMessagePtr message(
mc::Class< RemotePC::ScreenshotMessage >::Create(
imageBytes.size(), imageBytes.constData() ) );
// Send image to the client.
protocol->Send( message );
}
}
<commit_msg>RPC. Image quality is preserved better when scaling this way.<commit_after>/**
* Copyright (c) 2013 Egor Pushkin. 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 "Common/Common.h"
// Server object model.
#include "../../Server/Client.h"
#include "../../Server/IClientHandler.h"
#include "../../Server/Services/Services.h"
#include "../../Server/IServerControl.h"
#include "../../Server/Config.h"
#include "ScreenshotSpreader.h"
// Hardware subsystem.
#include "Hardware/Hardware.h"
// Interaction protocol tool.
#include "Messages/ScreenshotMessage.h"
// QT is responsible for image capturing and resizing.
#include <QtGui/QtGui>
#include <QDesktopWidget>
#include <QApplication>
namespace RemotePC
{
void ScreenshotSpreader::Handle(const Client& client, mc::IProtocolRef protocol, IServerControlRef /* server */)
{
if ( !client.IsScreenCaptureEnabled() )
return;
// Acquire mouse cursor position.
RemotePC::ScreenPoint position = RemotePC::HardwareProvider::Instance().GetMouseControl()->GetPosition();
// Calculate bounding box around current mouse position.
float blockSize = 256.0f;
float zoomLevel = client.GetZoomLevel();
int imageSize = (int)( blockSize * zoomLevel );
int leftX = position.x_ - imageSize / 2;
int topY = position.y_ - imageSize / 2;
int rightX = leftX + imageSize;
int bottomY = topY + imageSize;
// Find screen to which cursor currently belongs.
QDesktopWidget* desktop = QApplication::desktop();
int screenNumber = desktop->screenNumber(QPoint(position.x_, position.y_));
QWidget* screen = desktop->screen(screenNumber);
QRect geometry = screen->geometry();
// Cut areas beyond the surface of the screen.
int leftdX = ( leftX < geometry.left() ) ? ( geometry.left() - leftX ) : 0;
int topdY = ( topY < geometry.top() ) ? ( geometry.top() - topY ) : 0;
int rightdX = ( rightX > geometry.right() ) ? ( rightX - geometry.right() ) : 0;
int bottomdY = ( bottomY >= geometry.bottom() ) ? ( bottomY - geometry.bottom() ) : 0;
leftX += leftdX;
topY += topdY;
rightX += rightdX;
bottomY += bottomdY;
int fragmentWidth = imageSize - leftdX - rightdX;
int fragmentHeight = imageSize - topdY - bottomdY;
bool isBoundary = ( leftdX > 0 ) || ( topdY > 0 ) || ( rightdX > 0 ) || ( bottomdY > 0 );
// Grab part of the screen.
QPixmap fragment = QApplication::primaryScreen()->grabWindow(
QApplication::desktop()->winId(),
leftX, topY, fragmentWidth, fragmentHeight);
// Check to see if anything was actually grabbed.
fragmentWidth = fragment.width();
fragmentHeight = fragment.height();
if ( fragmentWidth <= 0 || fragmentHeight <= 0 )
{
return;
}
if ( isBoundary )
{
// Image was grabbed right next to one of screen edges.
// Scale image first. QPainter's scaling does not always work even with QPainter::SmoothPixmapTransform.
fragment = fragment.scaled(
QSize(fragmentWidth * blockSize / imageSize, fragmentHeight * blockSize / imageSize),
Qt::KeepAspectRatio,
Qt::SmoothTransformation);
// Locate grabbed fragment appropriately in the resulting image.
QPixmap temp(blockSize, blockSize);
QPainter painter(&temp);
painter.fillRect(0, 0, blockSize, blockSize, QColor(Qt::black));
painter.drawPixmap(QPoint(leftdX * blockSize / imageSize, topdY * blockSize / imageSize), fragment);
fragment = temp;
}
else
{
if ( imageSize != (int)blockSize )
{
// Image was grabbed from within the screen.
fragment = fragment.scaled(
QSize(blockSize, blockSize),
Qt::KeepAspectRatio,
Qt::SmoothTransformation);
}
}
// Construct screenshot message from QT image.
QByteArray imageBytes;
QBuffer imageBuffer(&imageBytes);
imageBuffer.open(QIODevice::WriteOnly);
#if !defined(IREMOTE_NO_QT_PLUGINS)
fragment.save(&imageBuffer, "JPG", Config::Instance().GetSFBCompression());
#else
fragment.save(&imageBuffer, "PNG", Config::Instance().GetSFBCompression());
#endif
// Construct message object.
mc::IMessagePtr message(
mc::Class< RemotePC::ScreenshotMessage >::Create(
imageBytes.size(), imageBytes.constData() ) );
// Send image to the client.
protocol->Send( message );
}
}
<|endoftext|> |
<commit_before>/*
Copyright (c) 2010, The Barbarian Group
All rights reserved.
Redistribution and use in source and binary forms, with or without modification, are permitted provided that
the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this list of conditions and
the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice, this list of conditions and
the following disclaimer in the documentation and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED
WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
#include "cinder/app/App.h"
#include "cinder/params/Params.h"
#include "AntTweakBar.h"
using namespace std;
namespace cinder { namespace params {
namespace {
bool mouseDown( app::MouseEvent event )
{
TwMouseButtonID button;
if( event.isLeft() )
button = TW_MOUSE_LEFT;
else if( event.isRight() )
button = TW_MOUSE_RIGHT;
else
button = TW_MOUSE_MIDDLE;
return TwMouseButton( TW_MOUSE_PRESSED, button ) != 0;
}
bool mouseUp( app::MouseEvent event )
{
TwMouseButtonID button;
if( event.isLeft() )
button = TW_MOUSE_LEFT;
else if( event.isRight() )
button = TW_MOUSE_RIGHT;
else
button = TW_MOUSE_MIDDLE;
return TwMouseButton( TW_MOUSE_RELEASED, button ) != 0;
}
bool mouseWheel( app::MouseEvent event )
{
static float sWheelPos = 0;
sWheelPos += event.getWheelIncrement();
return TwMouseWheel( (int)(sWheelPos) ) != 0;
}
bool mouseMove( app::MouseEvent event )
{
return TwMouseMotion( event.getX(), event.getY() ) != 0;
}
bool keyDown( app::KeyEvent event )
{
int kmod = 0;
if( event.isShiftDown() )
kmod |= TW_KMOD_SHIFT;
if( event.isControlDown() )
kmod |= TW_KMOD_CTRL;
if( event.isAltDown() )
kmod |= TW_KMOD_ALT;
return TwKeyPressed( event.getChar(), kmod ) != 0;
}
bool resize( app::ResizeEvent event )
{
TwWindowSize( event.getWidth(), event.getHeight() );
return false;
}
void TW_CALL implStdStringToClient( std::string& destinationClientString, const std::string& sourceLibraryString )
{
// copy strings from the library to the client app
destinationClientString = sourceLibraryString;
}
class AntMgr {
public:
AntMgr() {
if( ! TwInit( TW_OPENGL, NULL ) ) {
throw Exception();
}
app::App::get()->registerMouseDown( mouseDown );
app::App::get()->registerMouseUp( mouseUp );
app::App::get()->registerMouseWheel( mouseWheel );
app::App::get()->registerMouseMove( mouseMove );
app::App::get()->registerMouseDrag( mouseMove );
app::App::get()->registerKeyDown( keyDown );
app::App::get()->registerResize( resize );
}
~AntMgr() {
TwTerminate();
}
};
} // anonymous namespace
void initAntGl()
{
static std::shared_ptr<AntMgr> mgr;
if( ! mgr )
mgr = std::shared_ptr<AntMgr>( new AntMgr );
}
InterfaceGl::InterfaceGl( const std::string &title, const Vec2i &size, const ColorA color )
{
initAntGl();
mBar = std::shared_ptr<TwBar>( TwNewBar( title.c_str() ), TwDeleteBar );
char optionsStr[1024];
sprintf( optionsStr, "`%s` size='%d %d' color='%d %d %d' alpha=%d", title.c_str(), size.x, size.y, (int)(color.r * 255), (int)(color.g * 255), (int)(color.b * 255), (int)(color.a * 255) );
TwDefine( optionsStr );
TwCopyStdStringToClientFunc( implStdStringToClient );
}
void InterfaceGl::draw()
{
TwDraw();
}
void InterfaceGl::show( bool visible )
{
int32_t visibleInt = ( visible ) ? 1 : 0;
TwSetParam( mBar.get(), NULL, "visible", TW_PARAM_INT32, 1, &visibleInt );
}
void InterfaceGl::hide()
{
int32_t visibleInt = 0;
TwSetParam( mBar.get(), NULL, "visible", TW_PARAM_INT32, 1, &visibleInt );
}
bool InterfaceGl::isVisible() const
{
int32_t visibleInt;
TwGetParam( mBar.get(), NULL, "visible", TW_PARAM_INT32, 1, &visibleInt );
return visibleInt != 0;
}
void InterfaceGl::implAddParam( const std::string &name, void *param, int type, const std::string &optionsStr, bool readOnly )
{
if( readOnly )
TwAddVarRO( mBar.get(), name.c_str(), (TwType)type, param, optionsStr.c_str() );
else
TwAddVarRW( mBar.get(), name.c_str(), (TwType)type, param, optionsStr.c_str() );
}
void InterfaceGl::addParam( const std::string &name, bool *param, const std::string &optionsStr, bool readOnly )
{
implAddParam( name, param, TW_TYPE_BOOLCPP, optionsStr, readOnly );
}
void InterfaceGl::addParam( const std::string &name, float *param, const std::string &optionsStr, bool readOnly )
{
implAddParam( name, param, TW_TYPE_FLOAT, optionsStr, readOnly );
}
void InterfaceGl::addParam( const std::string &name, int32_t *param, const std::string &optionsStr, bool readOnly )
{
implAddParam( name, param, TW_TYPE_INT32, optionsStr, readOnly );
}
void InterfaceGl::addParam( const std::string &name, Vec3f *param, const std::string &optionsStr, bool readOnly )
{
implAddParam( name, param, TW_TYPE_DIR3F, optionsStr, readOnly );
}
void InterfaceGl::addParam( const std::string &name, Quatf *param, const std::string &optionsStr, bool readOnly )
{
implAddParam( name, param, TW_TYPE_QUAT4F, optionsStr, readOnly );
}
void InterfaceGl::addParam( const std::string &name, Color *param, const std::string &optionsStr, bool readOnly )
{
implAddParam( name, param, TW_TYPE_COLOR3F, optionsStr, readOnly );
}
void InterfaceGl::addParam( const std::string &name, ColorA *param, const std::string &optionsStr, bool readOnly )
{
implAddParam( name, param, TW_TYPE_COLOR4F, optionsStr, readOnly );
}
void InterfaceGl::addParam( const std::string &name, std::string *param, const std::string &optionsStr, bool readOnly )
{
implAddParam( name, param, TW_TYPE_STDSTRING, optionsStr, readOnly );
}
void InterfaceGl::addParam( const std::string &name, const std::vector<std::string> &enumNames, int *param, const std::string &optionsStr, bool readOnly )
{
TwEnumVal *ev = new TwEnumVal[enumNames.size()];
for( size_t v = 0; v < enumNames.size(); ++v ) {
ev[v].Value = v;
ev[v].Label = const_cast<char*>( enumNames[v].c_str() );
}
TwType evType = TwDefineEnum( (name + "EnumType").c_str(), ev, enumNames.size() );
if( readOnly )
TwAddVarRO( mBar.get(), name.c_str(), evType, param, optionsStr.c_str() );
else
TwAddVarRW( mBar.get(), name.c_str(), evType, param, optionsStr.c_str() );
delete [] ev;
}
void InterfaceGl::addSeparator( const std::string &name, const std::string &optionsStr )
{
TwAddSeparator( mBar.get(), name.c_str(), optionsStr.c_str() );
}
void InterfaceGl::addText( const std::string &name, const std::string &optionsStr )
{
TwAddButton( mBar.get(), name.c_str(), NULL, NULL, optionsStr.c_str() );
}
namespace { // anonymous namespace
void TW_CALL implButtonCallback( void *clientData )
{
std::function<void ()> *fn = reinterpret_cast<std::function<void ()>*>( clientData );
(*fn)();
}
} // anonymous namespace
void InterfaceGl::addButton( const std::string &name, const std::function<void ()> &callback, const std::string &optionsStr )
{
std::shared_ptr<std::function<void ()> > callbackPtr( new std::function<void ()>( callback ) );
mButtonCallbacks.push_back( callbackPtr );
TwAddButton( mBar.get(), name.c_str(), implButtonCallback, (void*)callbackPtr.get(), optionsStr.c_str() );
}
void InterfaceGl::setOptions( const std::string &name, const std::string &optionsStr )
{
std::string target = "`" + (std::string)TwGetBarName( mBar.get() ) + "`";
if( !( name.empty() ) )
target += "/`" + name + "`";
TwDefine( ( target + " " + optionsStr ).c_str() );
}
} } // namespace cinder::params
<commit_msg>translate special keys to AntTweakBar<commit_after>/*
Copyright (c) 2010, The Barbarian Group
All rights reserved.
Redistribution and use in source and binary forms, with or without modification, are permitted provided that
the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this list of conditions and
the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice, this list of conditions and
the following disclaimer in the documentation and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED
WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
#include "cinder/app/App.h"
#include "cinder/params/Params.h"
#include "AntTweakBar.h"
#include <boost/assign/list_of.hpp>
using namespace std;
namespace cinder { namespace params {
namespace {
#define SYNONYM(ck,ak) ((int)cinder::app::KeyEvent::KEY_ ## ck, TW_KEY_ ## ak)
#define HOMONYM(k) SYNONYM(k,k)
std::map<int,TwKeySpecial> specialKeys = boost::assign::map_list_of
HOMONYM(RIGHT)
HOMONYM(LEFT)
HOMONYM(BACKSPACE)
HOMONYM(DELETE)
HOMONYM(TAB)
HOMONYM(F1)
HOMONYM(F2)
HOMONYM(F3)
HOMONYM(F4)
HOMONYM(F5)
HOMONYM(F6)
HOMONYM(F7)
HOMONYM(F8)
HOMONYM(F9)
HOMONYM(F10)
HOMONYM(F11)
HOMONYM(F12)
HOMONYM(F13)
HOMONYM(F14)
HOMONYM(F15)
HOMONYM(HOME)
HOMONYM(END)
SYNONYM(PAGEUP,PAGE_UP)
SYNONYM(PAGEDOWN,PAGE_DOWN)
;
#undef SYNONYM
#undef HOMONYM
bool mouseDown( app::MouseEvent event )
{
TwMouseButtonID button;
if( event.isLeft() )
button = TW_MOUSE_LEFT;
else if( event.isRight() )
button = TW_MOUSE_RIGHT;
else
button = TW_MOUSE_MIDDLE;
return TwMouseButton( TW_MOUSE_PRESSED, button ) != 0;
}
bool mouseUp( app::MouseEvent event )
{
TwMouseButtonID button;
if( event.isLeft() )
button = TW_MOUSE_LEFT;
else if( event.isRight() )
button = TW_MOUSE_RIGHT;
else
button = TW_MOUSE_MIDDLE;
return TwMouseButton( TW_MOUSE_RELEASED, button ) != 0;
}
bool mouseWheel( app::MouseEvent event )
{
static float sWheelPos = 0;
sWheelPos += event.getWheelIncrement();
return TwMouseWheel( (int)(sWheelPos) ) != 0;
}
bool mouseMove( app::MouseEvent event )
{
return TwMouseMotion( event.getX(), event.getY() ) != 0;
}
bool keyDown( app::KeyEvent event )
{
int kmod = 0;
if( event.isShiftDown() )
kmod |= TW_KMOD_SHIFT;
if( event.isControlDown() )
kmod |= TW_KMOD_CTRL;
if( event.isAltDown() )
kmod |= TW_KMOD_ALT;
return TwKeyPressed(
(specialKeys.count( event.getCode() ) > 0)
? specialKeys[event.getCode()]
: event.getChar(),
kmod ) != 0;
}
bool resize( app::ResizeEvent event )
{
TwWindowSize( event.getWidth(), event.getHeight() );
return false;
}
void TW_CALL implStdStringToClient( std::string& destinationClientString, const std::string& sourceLibraryString )
{
// copy strings from the library to the client app
destinationClientString = sourceLibraryString;
}
class AntMgr {
public:
AntMgr() {
if( ! TwInit( TW_OPENGL, NULL ) ) {
throw Exception();
}
app::App::get()->registerMouseDown( mouseDown );
app::App::get()->registerMouseUp( mouseUp );
app::App::get()->registerMouseWheel( mouseWheel );
app::App::get()->registerMouseMove( mouseMove );
app::App::get()->registerMouseDrag( mouseMove );
app::App::get()->registerKeyDown( keyDown );
app::App::get()->registerResize( resize );
}
~AntMgr() {
TwTerminate();
}
};
} // anonymous namespace
void initAntGl()
{
static std::shared_ptr<AntMgr> mgr;
if( ! mgr )
mgr = std::shared_ptr<AntMgr>( new AntMgr );
}
InterfaceGl::InterfaceGl( const std::string &title, const Vec2i &size, const ColorA color )
{
initAntGl();
mBar = std::shared_ptr<TwBar>( TwNewBar( title.c_str() ), TwDeleteBar );
char optionsStr[1024];
sprintf( optionsStr, "`%s` size='%d %d' color='%d %d %d' alpha=%d", title.c_str(), size.x, size.y, (int)(color.r * 255), (int)(color.g * 255), (int)(color.b * 255), (int)(color.a * 255) );
TwDefine( optionsStr );
TwCopyStdStringToClientFunc( implStdStringToClient );
}
void InterfaceGl::draw()
{
TwDraw();
}
void InterfaceGl::show( bool visible )
{
int32_t visibleInt = ( visible ) ? 1 : 0;
TwSetParam( mBar.get(), NULL, "visible", TW_PARAM_INT32, 1, &visibleInt );
}
void InterfaceGl::hide()
{
int32_t visibleInt = 0;
TwSetParam( mBar.get(), NULL, "visible", TW_PARAM_INT32, 1, &visibleInt );
}
bool InterfaceGl::isVisible() const
{
int32_t visibleInt;
TwGetParam( mBar.get(), NULL, "visible", TW_PARAM_INT32, 1, &visibleInt );
return visibleInt != 0;
}
void InterfaceGl::implAddParam( const std::string &name, void *param, int type, const std::string &optionsStr, bool readOnly )
{
if( readOnly )
TwAddVarRO( mBar.get(), name.c_str(), (TwType)type, param, optionsStr.c_str() );
else
TwAddVarRW( mBar.get(), name.c_str(), (TwType)type, param, optionsStr.c_str() );
}
void InterfaceGl::addParam( const std::string &name, bool *param, const std::string &optionsStr, bool readOnly )
{
implAddParam( name, param, TW_TYPE_BOOLCPP, optionsStr, readOnly );
}
void InterfaceGl::addParam( const std::string &name, float *param, const std::string &optionsStr, bool readOnly )
{
implAddParam( name, param, TW_TYPE_FLOAT, optionsStr, readOnly );
}
void InterfaceGl::addParam( const std::string &name, int32_t *param, const std::string &optionsStr, bool readOnly )
{
implAddParam( name, param, TW_TYPE_INT32, optionsStr, readOnly );
}
void InterfaceGl::addParam( const std::string &name, Vec3f *param, const std::string &optionsStr, bool readOnly )
{
implAddParam( name, param, TW_TYPE_DIR3F, optionsStr, readOnly );
}
void InterfaceGl::addParam( const std::string &name, Quatf *param, const std::string &optionsStr, bool readOnly )
{
implAddParam( name, param, TW_TYPE_QUAT4F, optionsStr, readOnly );
}
void InterfaceGl::addParam( const std::string &name, Color *param, const std::string &optionsStr, bool readOnly )
{
implAddParam( name, param, TW_TYPE_COLOR3F, optionsStr, readOnly );
}
void InterfaceGl::addParam( const std::string &name, ColorA *param, const std::string &optionsStr, bool readOnly )
{
implAddParam( name, param, TW_TYPE_COLOR4F, optionsStr, readOnly );
}
void InterfaceGl::addParam( const std::string &name, std::string *param, const std::string &optionsStr, bool readOnly )
{
implAddParam( name, param, TW_TYPE_STDSTRING, optionsStr, readOnly );
}
void InterfaceGl::addParam( const std::string &name, const std::vector<std::string> &enumNames, int *param, const std::string &optionsStr, bool readOnly )
{
TwEnumVal *ev = new TwEnumVal[enumNames.size()];
for( size_t v = 0; v < enumNames.size(); ++v ) {
ev[v].Value = v;
ev[v].Label = const_cast<char*>( enumNames[v].c_str() );
}
TwType evType = TwDefineEnum( (name + "EnumType").c_str(), ev, enumNames.size() );
if( readOnly )
TwAddVarRO( mBar.get(), name.c_str(), evType, param, optionsStr.c_str() );
else
TwAddVarRW( mBar.get(), name.c_str(), evType, param, optionsStr.c_str() );
delete [] ev;
}
void InterfaceGl::addSeparator( const std::string &name, const std::string &optionsStr )
{
TwAddSeparator( mBar.get(), name.c_str(), optionsStr.c_str() );
}
void InterfaceGl::addText( const std::string &name, const std::string &optionsStr )
{
TwAddButton( mBar.get(), name.c_str(), NULL, NULL, optionsStr.c_str() );
}
namespace { // anonymous namespace
void TW_CALL implButtonCallback( void *clientData )
{
std::function<void ()> *fn = reinterpret_cast<std::function<void ()>*>( clientData );
(*fn)();
}
} // anonymous namespace
void InterfaceGl::addButton( const std::string &name, const std::function<void ()> &callback, const std::string &optionsStr )
{
std::shared_ptr<std::function<void ()> > callbackPtr( new std::function<void ()>( callback ) );
mButtonCallbacks.push_back( callbackPtr );
TwAddButton( mBar.get(), name.c_str(), implButtonCallback, (void*)callbackPtr.get(), optionsStr.c_str() );
}
void InterfaceGl::setOptions( const std::string &name, const std::string &optionsStr )
{
std::string target = "`" + (std::string)TwGetBarName( mBar.get() ) + "`";
if( !( name.empty() ) )
target += "/`" + name + "`";
TwDefine( ( target + " " + optionsStr ).c_str() );
}
} } // namespace cinder::params
<|endoftext|> |
<commit_before>#pragma once
/* Liveness analysis */
//#include <crab/cfg/basic_block_traits.hpp>
#include <crab/domains/discrete_domains.hpp>
#include <crab/iterators/killgen_fixpoint_iterator.hpp>
#include <crab/support/debug.hpp>
#include <crab/support/stats.hpp>
#include <boost/range/iterator_range.hpp>
#include <unordered_map>
namespace crab {
namespace analyzer {
template <typename V>
using varset_domain = ikos::discrete_domain<V>;
/**
* Define the main operations for the liveness variable analysis:
* compute for each basic block the set of live variables, i.e.,
* variables that might be used in the future
**/
template <class CFG>
class liveness_analysis_operations
: public crab::iterators::killgen_operations_api<
CFG, varset_domain<typename CFG::variable_t>> {
public:
using varset_domain_t = varset_domain<typename CFG::variable_t>;
using basic_block_label_t = typename CFG::basic_block_label_t;
private:
using parent_type =
crab::iterators::killgen_operations_api<CFG, varset_domain_t>;
using binding_t = std::pair<varset_domain_t, varset_domain_t>;
using liveness_map_t = std::unordered_map<basic_block_label_t, binding_t>;
liveness_map_t m_liveness_map;
public:
liveness_analysis_operations(CFG cfg) : parent_type(cfg) {}
virtual bool is_forward() { return false; }
virtual varset_domain_t entry() {
varset_domain_t res = varset_domain_t::bottom();
if (this->m_cfg.has_func_decl()) {
auto fdecl = this->m_cfg.get_func_decl();
for (unsigned i = 0, e = fdecl.get_num_outputs(); i < e; ++i) {
res += fdecl.get_output_name(i);
}
}
return res;
}
virtual varset_domain_t merge(varset_domain_t d1, varset_domain_t d2) {
return d1 | d2;
}
virtual void init_fixpoint() {
for (auto &b :
boost::make_iterator_range(this->m_cfg.begin(), this->m_cfg.end())) {
varset_domain_t kill, gen;
for (auto &s : boost::make_iterator_range(b.rbegin(), b.rend())) {
auto const &live = s.get_live();
for (auto d :
boost::make_iterator_range(live.defs_begin(), live.defs_end())) {
kill += d;
gen -= d;
}
for (auto u :
boost::make_iterator_range(live.uses_begin(), live.uses_end())) {
gen += u;
}
}
m_liveness_map.insert(std::make_pair(b.label(), binding_t(kill, gen)));
}
}
virtual varset_domain_t analyze(const basic_block_label_t &bb_id,
varset_domain_t in) {
auto it = m_liveness_map.find(bb_id);
assert(it != m_liveness_map.end());
in -= it->second.first;
in += it->second.second;
return in;
}
virtual std::string name() { return "Liveness"; }
};
/** Live variable analysis **/
template <typename CFG>
class liveness_analysis : public crab::iterators::killgen_fixpoint_iterator<
CFG, liveness_analysis_operations<CFG>> {
using liveness_analysis_operations_t = liveness_analysis_operations<CFG>;
using killgen_fixpoint_iterator_t =
crab::iterators::killgen_fixpoint_iterator<
CFG, liveness_analysis_operations_t>;
liveness_analysis(const liveness_analysis<CFG> &other) = delete;
liveness_analysis<CFG> &
operator=(const liveness_analysis<CFG> &other) = delete;
using basic_block_t = typename CFG::basic_block_t;
public:
using basic_block_label_t = typename CFG::basic_block_label_t;
using statement_t = typename CFG::statement_t;
using varname_t = typename CFG::varname_t;
typedef
typename liveness_analysis_operations_t::varset_domain_t varset_domain_t;
private:
bool m_release_in;
public:
liveness_analysis(CFG cfg, bool release_in = true)
: killgen_fixpoint_iterator_t(cfg), m_release_in(release_in) {}
void exec() {
this->run();
CRAB_LOG("liveness-live", for (auto p
: boost::make_iterator_range(
this->out_begin(), this->out_end())) {
crab::outs() << basic_block_traits<basic_block_t>::to_string(p.first)
<< " live variables=" << p.second << "\n";
;
});
if (m_release_in) {
this->m_in_map.clear();
}
}
varset_domain_t get(const basic_block_label_t &bb) const {
auto it = this->m_out_map.find(bb);
if (it != this->m_out_map.end()) {
return it->second;
} else {
return varset_domain_t::bottom();
}
}
void write(crab_os &o) const {
o << "TODO: print liveness analysis results\n";
}
};
template <typename CFG>
inline crab_os &operator<<(crab_os &o, const liveness_analysis<CFG> &l) {
l.write(o);
return o;
}
/**
* Live and Dead variable analysis.
**/
template <typename CFG> class live_and_dead_analysis {
public:
using basic_block_label_t = typename CFG::basic_block_label_t;
using basic_block_t = typename CFG::basic_block_t;
using statement_t = typename CFG::statement_t;
using varname_t = typename CFG::varname_t;
using variable_t = typename CFG::variable_t;
using varset_domain_t = varset_domain<variable_t>;
private:
using liveness_analysis_t = liveness_analysis<CFG>;
// the cfg
CFG m_cfg;
// liveness analysis
std::unique_ptr<liveness_analysis_t> m_live;
// precompute dead variables might be expensive so user can choose.
bool m_ignore_dead;
// map basic blocks to set of dead variables at the end of the
// blocks
std::unordered_map<basic_block_label_t, varset_domain_t> m_dead_map;
// statistics
unsigned m_max_live;
unsigned m_total_live;
unsigned m_total_blocks;
public:
// for backward compatibility
// XXX: maybe unused already
using set_t = varset_domain_t;
// If ignore_dead is true then dead symbols are not computed.
live_and_dead_analysis(CFG cfg, bool ignore_dead = false)
: m_cfg(cfg), m_live(new liveness_analysis_t(m_cfg)),
m_ignore_dead(ignore_dead), m_max_live(0), m_total_live(0),
m_total_blocks(0) {}
live_and_dead_analysis(const live_and_dead_analysis &other) = delete;
live_and_dead_analysis &
operator=(const live_and_dead_analysis &other) = delete;
void exec() {
m_live->exec();
if (!m_ignore_dead) {
crab::ScopedCrabStats __st__("Liveness.precompute_dead_variables");
/** Remove dead variables locally **/
for (auto &bb : boost::make_iterator_range(m_cfg.begin(), m_cfg.end())) {
varset_domain_t live_set = m_live->get(bb.label());
if (live_set.is_bottom())
continue;
varset_domain_t dead_set = m_cfg.get_node(bb.label()).live();
// dead variables = (USE(bb) U DEF(bb)) \ live_out(bb)
dead_set -= live_set;
CRAB_LOG("liveness",
crab::outs()
<< basic_block_traits<basic_block_t>::to_string(bb.label())
<< " dead variables=" << dead_set << "\n";);
m_dead_map.insert(std::make_pair(bb.label(), std::move(dead_set)));
// update statistics
m_total_live += live_set.size();
if (live_set.size() > m_max_live) {
m_max_live = live_set.size();
}
m_total_blocks++;
}
}
}
// Return the set of live variables at the exit of block bb
varset_domain_t get(const basic_block_label_t &bb) const {
return m_live->get(bb);
}
// Return the set of dead variables at the exit of block bb
varset_domain_t dead_exit(const basic_block_label_t &bb) const {
if (m_ignore_dead) {
CRAB_WARN("Dead variables were not precomputed during liveness analysis");
}
auto it = m_dead_map.find(bb);
if (it == m_dead_map.end()) {
return varset_domain_t();
} else {
return it->second;
}
}
void get_stats(unsigned &total_live, unsigned &max_live_per_blk,
unsigned &avg_live_per_blk) const {
total_live = m_total_live;
max_live_per_blk = m_max_live;
avg_live_per_blk =
(m_total_blocks == 0 ? 0 : (int)m_total_live / m_total_blocks);
}
void write(crab_os &o) const {
o << "TODO: printing dead variable analysis results\n";
}
};
template <typename CFG>
inline crab_os &operator<<(crab_os &o, const live_and_dead_analysis<CFG> &l) {
l.write(o);
return o;
}
} // end namespace analyzer
} // end namespace crab
<commit_msg>refactor(liveness): improve precision is block is unreachable<commit_after>#pragma once
/* Liveness analysis */
//#include <crab/cfg/basic_block_traits.hpp>
#include <crab/domains/discrete_domains.hpp>
#include <crab/iterators/killgen_fixpoint_iterator.hpp>
#include <crab/support/debug.hpp>
#include <crab/support/stats.hpp>
#include <boost/range/iterator_range.hpp>
#include <unordered_map>
namespace crab {
namespace analyzer {
template <typename V>
using varset_domain = ikos::discrete_domain<V>;
/**
* Define the main operations for the liveness variable analysis:
* compute for each basic block the set of live variables, i.e.,
* variables that might be used in the future
**/
template <class CFG>
class liveness_analysis_operations
: public crab::iterators::killgen_operations_api<
CFG, varset_domain<typename CFG::variable_t>> {
public:
using varset_domain_t = varset_domain<typename CFG::variable_t>;
using basic_block_label_t = typename CFG::basic_block_label_t;
private:
using parent_type =
crab::iterators::killgen_operations_api<CFG, varset_domain_t>;
using binding_t = std::pair<varset_domain_t, varset_domain_t>;
using liveness_map_t = std::unordered_map<basic_block_label_t, binding_t>;
liveness_map_t m_liveness_map;
public:
liveness_analysis_operations(CFG cfg) : parent_type(cfg) {}
virtual bool is_forward() { return false; }
virtual varset_domain_t entry() {
varset_domain_t res = varset_domain_t::bottom();
if (this->m_cfg.has_func_decl()) {
auto fdecl = this->m_cfg.get_func_decl();
for (unsigned i = 0, e = fdecl.get_num_outputs(); i < e; ++i) {
res += fdecl.get_output_name(i);
}
}
return res;
}
virtual varset_domain_t merge(varset_domain_t d1, varset_domain_t d2) {
return d1 | d2;
}
virtual void init_fixpoint() {
for (auto &b :
boost::make_iterator_range(this->m_cfg.begin(), this->m_cfg.end())) {
bool is_unreachable_block = false;
varset_domain_t kill, gen;
for (auto &s : boost::make_iterator_range(b.rbegin(), b.rend())) {
if (s.is_unreachable()) {
is_unreachable_block = true;
break;
}
auto const &live = s.get_live();
for (auto d :
boost::make_iterator_range(live.defs_begin(), live.defs_end())) {
kill += d;
gen -= d;
}
for (auto u :
boost::make_iterator_range(live.uses_begin(), live.uses_end())) {
gen += u;
}
} // end for
if (!is_unreachable_block) {
m_liveness_map.insert(std::make_pair(b.label(), binding_t(kill, gen)));
}
} // end for
}
virtual varset_domain_t analyze(const basic_block_label_t &bb_id,
varset_domain_t in) {
auto it = m_liveness_map.find(bb_id);
if (it != m_liveness_map.end()) {
in -= it->second.first;
in += it->second.second;
} else {
// bb_id is unreachable
in = varset_domain_t::bottom(); // empty set (i.e., no live variables)
}
return in;
}
virtual std::string name() { return "Liveness"; }
};
/** Live variable analysis **/
template <typename CFG>
class liveness_analysis : public crab::iterators::killgen_fixpoint_iterator<
CFG, liveness_analysis_operations<CFG>> {
using liveness_analysis_operations_t = liveness_analysis_operations<CFG>;
using killgen_fixpoint_iterator_t =
crab::iterators::killgen_fixpoint_iterator<
CFG, liveness_analysis_operations_t>;
liveness_analysis(const liveness_analysis<CFG> &other) = delete;
liveness_analysis<CFG> &
operator=(const liveness_analysis<CFG> &other) = delete;
using basic_block_t = typename CFG::basic_block_t;
public:
using basic_block_label_t = typename CFG::basic_block_label_t;
using statement_t = typename CFG::statement_t;
using varname_t = typename CFG::varname_t;
typedef
typename liveness_analysis_operations_t::varset_domain_t varset_domain_t;
private:
bool m_release_in;
public:
liveness_analysis(CFG cfg, bool release_in = true)
: killgen_fixpoint_iterator_t(cfg), m_release_in(release_in) {}
void exec() {
this->run();
CRAB_LOG("liveness-live", for (auto p
: boost::make_iterator_range(
this->out_begin(), this->out_end())) {
crab::outs() << basic_block_traits<basic_block_t>::to_string(p.first)
<< " OUT live variables=" << p.second << "\n";
;
});
if (m_release_in) {
this->m_in_map.clear();
}
}
varset_domain_t get(const basic_block_label_t &bb) const {
auto it = this->m_out_map.find(bb);
if (it != this->m_out_map.end()) {
return it->second;
} else {
return varset_domain_t::bottom();
}
}
void write(crab_os &o) const {
o << "TODO: print liveness analysis results\n";
}
};
template <typename CFG>
inline crab_os &operator<<(crab_os &o, const liveness_analysis<CFG> &l) {
l.write(o);
return o;
}
/**
* Live and Dead variable analysis.
**/
template <typename CFG> class live_and_dead_analysis {
public:
using basic_block_label_t = typename CFG::basic_block_label_t;
using basic_block_t = typename CFG::basic_block_t;
using statement_t = typename CFG::statement_t;
using varname_t = typename CFG::varname_t;
using variable_t = typename CFG::variable_t;
using varset_domain_t = varset_domain<variable_t>;
private:
using liveness_analysis_t = liveness_analysis<CFG>;
// the cfg
CFG m_cfg;
// liveness analysis
std::unique_ptr<liveness_analysis_t> m_live;
// precompute dead variables might be expensive so user can choose.
bool m_ignore_dead;
// map basic blocks to set of dead variables at the end of the
// blocks
std::unordered_map<basic_block_label_t, varset_domain_t> m_dead_map;
// statistics
unsigned m_max_live;
unsigned m_total_live;
unsigned m_total_blocks;
public:
// for backward compatibility
// XXX: maybe unused already
using set_t = varset_domain_t;
// If ignore_dead is true then dead symbols are not computed.
live_and_dead_analysis(CFG cfg, bool ignore_dead = false)
: m_cfg(cfg), m_live(new liveness_analysis_t(m_cfg)),
m_ignore_dead(ignore_dead), m_max_live(0), m_total_live(0),
m_total_blocks(0) {}
live_and_dead_analysis(const live_and_dead_analysis &other) = delete;
live_and_dead_analysis &
operator=(const live_and_dead_analysis &other) = delete;
void exec() {
m_live->exec();
if (!m_ignore_dead) {
crab::ScopedCrabStats __st__("Liveness.precompute_dead_variables");
/** Remove dead variables locally **/
for (auto &bb : boost::make_iterator_range(m_cfg.begin(), m_cfg.end())) {
varset_domain_t live_set = m_live->get(bb.label());
if (live_set.is_bottom())
continue;
varset_domain_t dead_set = m_cfg.get_node(bb.label()).live();
// dead variables = (USE(bb) U DEF(bb)) \ live_out(bb)
dead_set -= live_set;
CRAB_LOG("liveness",
crab::outs()
<< basic_block_traits<basic_block_t>::to_string(bb.label())
<< " dead variables=" << dead_set << "\n";);
m_dead_map.insert(std::make_pair(bb.label(), std::move(dead_set)));
// update statistics
m_total_live += live_set.size();
if (live_set.size() > m_max_live) {
m_max_live = live_set.size();
}
m_total_blocks++;
}
}
}
// Return the set of live variables at the exit of block bb
varset_domain_t get(const basic_block_label_t &bb) const {
return m_live->get(bb);
}
// Return the set of dead variables at the exit of block bb
varset_domain_t dead_exit(const basic_block_label_t &bb) const {
if (m_ignore_dead) {
CRAB_WARN("Dead variables were not precomputed during liveness analysis");
}
auto it = m_dead_map.find(bb);
if (it == m_dead_map.end()) {
return varset_domain_t();
} else {
return it->second;
}
}
void get_stats(unsigned &total_live, unsigned &max_live_per_blk,
unsigned &avg_live_per_blk) const {
total_live = m_total_live;
max_live_per_blk = m_max_live;
avg_live_per_blk =
(m_total_blocks == 0 ? 0 : (int)m_total_live / m_total_blocks);
}
void write(crab_os &o) const {
o << "TODO: printing dead variable analysis results\n";
}
};
template <typename CFG>
inline crab_os &operator<<(crab_os &o, const live_and_dead_analysis<CFG> &l) {
l.write(o);
return o;
}
} // end namespace analyzer
} // end namespace crab
<|endoftext|> |
<commit_before>//
// Copyright (c) 2014 CNRS
// Authors: Florent Lamiraux
//
// This file is part of hpp-core
// hpp-core is free software: you can redistribute it
// and/or modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation, either version
// 3 of the License, or (at your option) any later version.
//
// hpp-core 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 Lesser Public License for more details. You should have
// received a copy of the GNU Lesser General Public License along with
// hpp-core If not, see
// <http://www.gnu.org/licenses/>.
#ifndef HPP_CORE_DIFFERENTIABLE_FUNCTION_HH
# define HPP_CORE_DIFFERENTIABLE_FUNCTION_HH
# include <boost/algorithm/string/replace.hpp>
# include <roboptim/core/indent.hh>
# include <hpp/core/fwd.hh>
namespace hpp {
namespace core {
/// Differentiable function of the robot configuration
class DifferentiableFunction
{
public:
virtual ~DifferentiableFunction () {}
/// Evaluate the function at a given parameter.
///
/// \note parameters should be of the correct size.
void operator () (vectorOut_t result,
ConfigurationIn_t argument) const
{
assert (result.size () == outputSize ());
assert (argument.size () == inputSize ());
impl_compute (result, argument);
}
/// Computes the jacobian.
///
/// \retval jacobian jacobian will be stored in this argument
/// \param argument point at which the jacobian will be computed
void jacobian (matrixOut_t jacobian, ConfigurationIn_t argument) const
{
assert (argument.size () == inputSize ());
assert (jacobian.rows () == outputSize ());
assert (jacobian.cols () == inputDerivativeSize ());
impl_jacobian (jacobian, argument);
}
/// Get dimension of input vector
size_type inputSize () const
{
return inputSize_;
}
/// Get dimension of input derivative vector
///
/// The dimension of configuration vectors might differ from the dimension
/// of velocity vectors since some joints are represented by non minimal
/// size vectors: e.g. quaternion for SO(3)
size_type inputDerivativeSize () const
{
return inputDerivativeSize_;
}
/// Get dimension of output vector
size_type outputSize () const
{
return outputSize_;
}
/// \brief Get function name.
///
/// \return Function name.
const std::string& name () const
{
return name_;
}
/// Display object in a stream
virtual std::ostream& print (std::ostream& o) const
{
if (this->name ().empty ())
return o << "Differentiable function";
std::stringstream ss;
ss << std::endl;
char fill = o.fill (' ');
ss << std::setw ((int)roboptim::indent (o))
<< ""
<< std::setfill (fill);
std::string name = this->name ();
boost::algorithm::replace_all (name, "\n", ss.str ());
return o << name << " (differentiable function)";
}
/// Check whether this function is parametric.
/// \return True if parametric.
bool isParametric () const
{
return isParametric_;
}
/// Make the function parametric or non-parametric.
/// \param value True if you want a parametric projector.
/// \note When change from true to false, the level set parameters of any
/// ConfigProjector containing the function should be recomputed using
/// ConfigProjector::offset.
void isParametric (const bool& value)
{
isParametric_ = value;
}
protected:
/// \brief Concrete class constructor should call this constructor.
///
/// \param inputSize function arity
/// \param outputSize result size
/// \param name function's name
DifferentiableFunction (size_type inputSize,
size_type inputDerivativeSize,
size_type outputSize,
std::string name = std::string ()) :
inputSize_ (inputSize), inputDerivativeSize_ (inputDerivativeSize),
outputSize_ (outputSize), isParametric_ (false), name_ (name)
{
}
/// User implementation of function evaluation
virtual void impl_compute (vectorOut_t result,
ConfigurationIn_t argument) const = 0;
virtual void impl_jacobian (matrixOut_t jacobian,
ConfigurationIn_t arg) const = 0;
private:
/// Dimension of input vector.
size_type inputSize_;
/// Dimension of input derivative
size_type inputDerivativeSize_;
/// Dimension of output vector
size_type outputSize_;
/// Whether this function is parametric
bool isParametric_;
std::string name_;
}; // class DifferentiableFunction
inline std::ostream&
operator<< (std::ostream& os, const DifferentiableFunction& f)
{
return f.print (os);
}
} // namespace core
} // namespace hpp
#endif // HPP_CORE_DIFFERENTIABLE_FUNCTION_HH
<commit_msg>Add passive dofs to DifferentiableFunction.<commit_after>//
// Copyright (c) 2014 CNRS
// Authors: Florent Lamiraux
//
// This file is part of hpp-core
// hpp-core is free software: you can redistribute it
// and/or modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation, either version
// 3 of the License, or (at your option) any later version.
//
// hpp-core 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 Lesser Public License for more details. You should have
// received a copy of the GNU Lesser General Public License along with
// hpp-core If not, see
// <http://www.gnu.org/licenses/>.
#ifndef HPP_CORE_DIFFERENTIABLE_FUNCTION_HH
# define HPP_CORE_DIFFERENTIABLE_FUNCTION_HH
# include <boost/algorithm/string/replace.hpp>
# include <boost/assign/list_of.hpp>
# include <roboptim/core/indent.hh>
# include <hpp/core/fwd.hh>
# include <algorithm>
namespace hpp {
namespace core {
/// Differentiable function of the robot configuration
class DifferentiableFunction
{
public:
typedef std::pair <size_type, size_type> Interval_t;
typedef std::vector <Interval_t> Intervals_t;
virtual ~DifferentiableFunction () {}
/// Evaluate the function at a given parameter.
///
/// \note parameters should be of the correct size.
void operator () (vectorOut_t result,
ConfigurationIn_t argument) const
{
assert (result.size () == outputSize ());
assert (argument.size () == inputSize ());
impl_compute (result, argument);
}
/// Computes the jacobian.
///
/// \retval jacobian jacobian will be stored in this argument
/// \param argument point at which the jacobian will be computed
void jacobian (matrixOut_t jacobian, ConfigurationIn_t argument) const
{
assert (argument.size () == inputSize ());
assert (jacobian.rows () == outputSize ());
assert (jacobian.cols () == inputDerivativeSize ());
impl_jacobian (jacobian, argument);
for (size_t i = 0; i < passiveDofs_.size(); i++)
jacobian.middleCols (passiveDofs_[i].first, passiveDofs_[i].second).setZero ();
}
/// Get dimension of input vector
size_type inputSize () const
{
return inputSize_;
}
/// Get dimension of input derivative vector
///
/// The dimension of configuration vectors might differ from the dimension
/// of velocity vectors since some joints are represented by non minimal
/// size vectors: e.g. quaternion for SO(3)
size_type inputDerivativeSize () const
{
return inputDerivativeSize_;
}
/// Get dimension of output vector
size_type outputSize () const
{
return outputSize_;
}
/// \brief Get function name.
///
/// \return Function name.
const std::string& name () const
{
return name_;
}
/// Display object in a stream
virtual std::ostream& print (std::ostream& o) const
{
if (this->name ().empty ())
return o << "Differentiable function";
std::stringstream ss;
ss << std::endl;
char fill = o.fill (' ');
ss << std::setw ((int)roboptim::indent (o))
<< ""
<< std::setfill (fill);
std::string name = this->name ();
boost::algorithm::replace_all (name, "\n", ss.str ());
return o << name << " (differentiable function)";
}
/// Check whether this function is parametric.
/// \return True if parametric.
bool isParametric () const
{
return isParametric_;
}
/// Make the function parametric or non-parametric.
/// \param value True if you want a parametric projector.
/// \note When change from true to false, the level set parameters of any
/// ConfigProjector containing the function should be recomputed using
/// ConfigProjector::offset.
void isParametric (const bool& value)
{
isParametric_ = value;
}
/// Set passive DOFs. Passive DOF cannot be modified by this function.
/// Corresponding columns of the jacobian are set to zero.
const Intervals_t& passiveDofs (std::vector <size_type> dofs)
{
passiveDofs_.clear ();
if (dofs.size () == 0) return passiveDofs_;
std::sort (dofs.begin (), dofs.end ());
std::vector <size_type>::iterator it =
std::unique (dofs.begin (), dofs.end ());
dofs.resize (std::distance (dofs.begin (), it));
dofs.push_back (inputDerivativeSize_ + 1);
size_type intStart = dofs[0], intEnd = dofs[0];
for (size_t i = 1; i < dofs.size (); i++) {
intEnd ++;
if (intEnd == dofs[i]) {
continue;
} else {
passiveDofs_.push_back (Interval_t (intStart, intEnd - intStart));
intStart = intEnd = dofs[i];
}
}
return passiveDofs_;
}
protected:
/// \brief Concrete class constructor should call this constructor.
///
/// \param inputSize function arity
/// \param outputSize result size
/// \param name function's name
DifferentiableFunction (size_type inputSize,
size_type inputDerivativeSize,
size_type outputSize,
std::string name = std::string ()) :
inputSize_ (inputSize), inputDerivativeSize_ (inputDerivativeSize),
outputSize_ (outputSize), isParametric_ (false),
passiveDofs_ (), name_ (name)
{
}
/// User implementation of function evaluation
virtual void impl_compute (vectorOut_t result,
ConfigurationIn_t argument) const = 0;
virtual void impl_jacobian (matrixOut_t jacobian,
ConfigurationIn_t arg) const = 0;
private:
/// Dimension of input vector.
size_type inputSize_;
/// Dimension of input derivative
size_type inputDerivativeSize_;
/// Dimension of output vector
size_type outputSize_;
/// Whether this function is parametric
bool isParametric_;
/// Intervals of passive dofs
Intervals_t passiveDofs_;
std::string name_;
}; // class DifferentiableFunction
inline std::ostream&
operator<< (std::ostream& os, const DifferentiableFunction& f)
{
return f.print (os);
}
} // namespace core
} // namespace hpp
#endif // HPP_CORE_DIFFERENTIABLE_FUNCTION_HH
<|endoftext|> |
<commit_before>/*
* Copyright (c) 2003-2011 Rony Shapiro <[email protected]>.
* All rights reserved. Use of the code is allowed under the
* Artistic License 2.0 terms, as specified in the LICENSE file
* distributed with this code, or available from
* http://www.opensource.org/licenses/artistic-license-2.0.php
*/
/*
* xsendstring - send a bunch of keystrokes to the app having current input focus
*
* Calls X library functions defined in Xt and Xtst
*
* +. Initialize all the params of XKeyEvent
* + More escape sequences from http://msdn.microsoft.com/en-us/library/h21280bw%28VS.80%29.aspx
* + XGetErrorText and sprintf overflow
*/
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <ctype.h>
#include <string.h>
#include <time.h>
#include <vector>
#include <errno.h>
#include <limits.h>
#include <X11/Intrinsic.h> // in libxt-dev
#include <X11/keysym.h>
#include <X11/extensions/XTest.h> // in libxtst-dev
#include "./xsendstring.h"
#include "../sleep.h"
#include "../../core/PwsPlatform.h" // for NumberOf()
#include "../../core/StringX.h"
namespace { // anonymous namespace for hiding
// local variables and functions
typedef struct _KeyPress {
KeyCode code;
unsigned int state;
} KeyPressInfo;
struct AutotypeGlobals
{
Boolean error_detected;
char errorString[1024];
KeyCode lshiftCode;
pws_os::AutotypeMethod method;
Boolean LiteralKeysymsInitialized;
} atGlobals = { False, {0}, 0, pws_os::ATMETHOD_AUTO, False };
class autotype_exception: public std::exception
{
public:
virtual const char* what() const throw() {
return atGlobals.errorString;
}
};
/*
* ErrorHandler will be called when X detects an error. This function
* just sets a global flag and saves the error message text
*/
int ErrorHandler(Display *my_dpy, XErrorEvent *event)
{
char xmsg[512] = {0};
atGlobals.error_detected = TRUE;
XGetErrorText(my_dpy, event->error_code, xmsg, NumberOf(xmsg) - 1);
snprintf(atGlobals.errorString, NumberOf(atGlobals.errorString)-1, "X error (%d): %s\n", event->request_code, xmsg);
return 0;
}
/*
* - characters which need to be manually converted to KeySyms
*/
static struct {
char ch;
const char* keystr;
KeySym sym;
} LiteralKeysyms[] =
{
{ ' ', "space", NoSymbol },
{ '\t', "Tab", NoSymbol },
{ '\n', "Linefeed", NoSymbol },
{ '\r', "Return", NoSymbol },
{ '\010', "BackSpace", NoSymbol }, /* \b doesn't work */
{ '\177', "Delete", NoSymbol },
{ '\033', "Escape", NoSymbol }, /* \e doesn't work and \e is non-iso escape sequence*/
{ '!', "exclam", NoSymbol },
{ '#', "numbersign", NoSymbol },
{ '%', "percent", NoSymbol },
{ '$', "dollar", NoSymbol },
{ '&', "ampersand", NoSymbol },
{ '"', "quotedbl", NoSymbol },
{ '\'', "apostrophe", NoSymbol },
{ '(', "parenleft", NoSymbol },
{ ')', "parenright", NoSymbol },
{ '*', "asterisk", NoSymbol },
{ '=', "equal", NoSymbol },
{ '+', "plus", NoSymbol },
{ ',', "comma", NoSymbol },
{ '-', "minus", NoSymbol },
{ '.', "period", NoSymbol },
{ '/', "slash", NoSymbol },
{ ':', "colon", NoSymbol },
{ ';', "semicolon", NoSymbol },
{ '<', "less", 44 }, /* I don't understand why we get '>' instead of '<' unless we hardcode this */
{ '>', "greater", NoSymbol },
{ '?', "question", NoSymbol },
{ '@', "at", NoSymbol },
{ '[', "bracketleft", NoSymbol },
{ ']', "bracketright", NoSymbol },
{ '\\', "backslash", NoSymbol },
{ '^', "asciicircum", NoSymbol },
{ '_', "underscore", NoSymbol },
{ '`', "grave", NoSymbol },
{ '{', "braceleft", NoSymbol },
{ '|', "bar", NoSymbol },
{ '}', "braceright", NoSymbol },
{ '~', "asciitilde", NoSymbol },
};
void InitLiteralKeysyms(void)
{
size_t idx;
for (idx = 0; idx < NumberOf(LiteralKeysyms); ++idx)
if (LiteralKeysyms[idx].sym == NoSymbol)
LiteralKeysyms[idx].sym = XStringToKeysym(LiteralKeysyms[idx].keystr);
atGlobals.lshiftCode = XKeysymToKeycode(XOpenDisplay(NULL), XK_Shift_L);
}
KeySym GetLiteralKeysym(char* keystring)
{
size_t idx;
for (idx = 0; idx < NumberOf(LiteralKeysyms); ++idx)
if (keystring[0] == LiteralKeysyms[idx].ch )
return LiteralKeysyms[idx].sym;
return NoSymbol;
}
void XTest_SendEvent(XKeyEvent *event)
{
XTestFakeKeyEvent(event->display, event->keycode, event->type == KeyPress, 0);
}
void XSendKeys_SendEvent(XKeyEvent *event)
{
XSendEvent(event->display, event->window, TRUE, KeyPressMask, reinterpret_cast<XEvent *>(event));
}
void XSendKeys_SendKeyEvent(XKeyEvent* event)
{
event->type = KeyPress;
XSendKeys_SendEvent(event);
event->type = KeyRelease;
XSendKeys_SendEvent(event);
XFlush(event->display);
}
void XTest_SendKeyEvent(XKeyEvent* event)
{
XKeyEvent shiftEvent;
/* must simulate the shift-press for CAPS and shifted keypresses manually */
if (event->state & ShiftMask) {
memcpy(&shiftEvent, event, sizeof(shiftEvent));
shiftEvent.keycode = atGlobals.lshiftCode;
shiftEvent.type = KeyPress;
XTest_SendEvent(&shiftEvent);
}
event->type = KeyPress;
XTest_SendEvent(event);
event->type = KeyRelease;
XTest_SendEvent(event);
if (event->state & ShiftMask) {
shiftEvent.type = KeyRelease;
XTest_SendEvent(&shiftEvent);
}
XFlush(event->display);
}
Bool UseXTest(void)
{
int major_opcode, first_event, first_error;
static Bool useXTest;
static int checked = 0;
if (!checked) {
useXTest = XQueryExtension(XOpenDisplay(0), "XTEST", &major_opcode, &first_event, &first_error);
checked = 1;
}
return useXTest;
}
void InitKeyEvent(XKeyEvent* event)
{
int revert_to;
event->display = XOpenDisplay(NULL);
XGetInputFocus(event->display, &event->window, &revert_to);
event->subwindow = None;
event->x = event->y = event->x_root = event->y_root = 1;
event->same_screen = TRUE;
}
int FindModifierMask(Display* disp, KeySym sym)
{
int modmask = 0;
XModifierKeymap* modmap = XGetModifierMapping(disp);
if (modmap) {
const int last = 8*modmap->max_keypermod;
//begin at 4th row, where Mod1 starts
for (int i = 3*modmap->max_keypermod && !modmask; i < last; i++) {
//
const KeyCode kc = modmap->modifiermap[i];
if (!kc)
continue;
int keysyms_per_keycode = 0;
// For each keycode attached to this modifier, get a list of all keysyms
// attached with this keycode. If any of those keysyms is what we are looking
// for, then this is the modifier to use
KeySym* symlist = XGetKeyboardMapping(disp, kc, 1, &keysyms_per_keycode);
if ( symlist) {
for (int j = 0; j < keysyms_per_keycode; j++) {
if (sym == symlist[j]) {
modmask = (i / modmap->max_keypermod);
break;
}
}
}
}
XFreeModifiermap(modmap);
}
assert( modmask >= 3 && modmask <= 7);
return 1 << modmask;
}
int CalcModifiersForKeysym(KeyCode code, KeySym sym, Display* disp)
{
int keysyms_per_keycode = 0;
const KeySym* symlist = XGetKeyboardMapping(disp, code, 1, &keysyms_per_keycode);
if (symlist != NULL && keysyms_per_keycode > 0) {
const int ModeSwitchMask = FindModifierMask(disp, XK_Mode_switch);
const int Level3ShiftMask = FindModifierMask(disp, XK_ISO_Level3_Shift);
int mods[] = {
0, //none
ShiftMask,
ModeSwitchMask,
ShiftMask | ModeSwitchMask,
// beyond this, its all guesswork since there's no documentation, but see this:
//
// http://superuser.com/questions/189869/xmodmap-six-characters-to-one-key
//
// Also, if you install mulitple keyboard layouts the number of keysyms-per-keycode
// will keep increasing to a max of 16 (up to 4 layouts can be installed together
// in Ubuntu 11.04). For some keycodes, you will actually have non-NoSymbol
// keysyms beyond the first four
//
// We probably shouldn't go here if Mode_switch and ISO_Level3_Shift are assigned to
// the same modifier mask
Level3ShiftMask,
ShiftMask | Level3ShiftMask,
ModeSwitchMask | Level3ShiftMask,
ShiftMask | ModeSwitchMask | Level3ShiftMask,
};
const int max_keysym_index = std::min(int(NumberOf(mods)), keysyms_per_keycode);
for (int idx = 0; idx < max_keysym_index; ++idx) {
if (symlist[idx] == sym)
return mods[idx];
}
}
// we should at least find the keysym without any mods (index 0)
assert(0);
return 0;
}
/*
* DoSendString - actually sends a string to the X Window having input focus
*
* The main task of this function is to convert the ascii char values
* into X KeyCodes. But they need to be converted to X KeySyms first
* and then to the keycodes. The KeyCodes can have any random values
* and are not contiguous like the ascii values are.
*
* Some escape sequences can be converted to the appropriate KeyCodes
* by this function. See the code below for details
*/
void DoSendString(const StringX& str, pws_os::AutotypeMethod method, unsigned delayMS)
{
if (!atGlobals.LiteralKeysymsInitialized) {
InitLiteralKeysyms();
atGlobals.LiteralKeysymsInitialized = True;
}
XKeyEvent event;
InitKeyEvent(&event);
// convert all the chars into keycodes and required shift states first
// Abort if any of the characters cannot be converted
typedef std::vector<KeyPressInfo> KeyPressInfoVector;
KeyPressInfoVector keypresses;
for (StringX::const_iterator srcIter = str.begin(); srcIter != str.end(); ++srcIter) {
//throw away 'vertical tab' chars which are only used on Windows to send a shift+tab
//as a workaround for some issues with IE
if (*srcIter == _T('\v'))
continue;
//This array holds the multibyte representation of the current (wide) char, plus NULL
char keystring[MB_LEN_MAX + 1] = {0};
mbstate_t state = mbstate_t();//using init throw constructor because of missing initializer warning
size_t ret = wcrtomb(keystring, *srcIter, &state);
if (ret == static_cast<size_t>(-1)) {
snprintf(atGlobals.errorString, NumberOf(atGlobals.errorString),
"char at index(%u), value(%d) couldn't be converted to keycode. %s\n",
static_cast<unsigned int>(std::distance(str.begin(), srcIter)), static_cast<int>(*srcIter), strerror(errno));
atGlobals.error_detected = True;
return;
}
ASSERT(ret < (NumberOf(keystring)-1));
//Try a regular conversion first
KeySym sym = XStringToKeysym(keystring);
//Failing which, use our hard-coded special names for certain keys
if (NoSymbol != sym || (sym = GetLiteralKeysym(keystring)) != NoSymbol) {
KeyPressInfo keypress = {0, 0};
if ((keypress.code = XKeysymToKeycode(event.display, sym)) != 0) {
//non-zero return value implies sym -> code was successful
keypress.state |= CalcModifiersForKeysym(keypress.code, sym, event.display);
keypresses.push_back(keypress);
}
else {
const char* symStr = XKeysymToString(sym);
snprintf(atGlobals.errorString, NumberOf(atGlobals.errorString),
"Could not get keycode for key char(%s) - sym(%d) - str(%s). Aborting autotype\n",
keystring, static_cast<int>(sym), symStr ? symStr : "NULL");
atGlobals.error_detected = True;
return;
}
}
else {
snprintf(atGlobals.errorString, NumberOf(atGlobals.errorString),
"Cannot convert '%s' to keysym. Aborting autotype\n", keystring);
atGlobals.error_detected = True;
return;
}
}
XSetErrorHandler(ErrorHandler);
atGlobals.error_detected = False;
bool useXTEST = (UseXTest() && method != pws_os::ATMETHOD_XSENDKEYS);
void (*KeySendFunction)(XKeyEvent*);
if ( useXTEST) {
KeySendFunction = XTest_SendKeyEvent;
XTestGrabControl(event.display, True);
}
else {
KeySendFunction = XSendKeys_SendKeyEvent;
}
for (KeyPressInfoVector::const_iterator itr = keypresses.begin(); itr != keypresses.end()
&& !atGlobals.error_detected; ++itr) {
event.keycode = itr->code;
event.state = itr->state;
event.time = CurrentTime;
KeySendFunction(&event);
pws_os::sleep_ms(delayMS);
}
if (useXTEST) {
XTestGrabControl(event.display, False);
}
else {
XSync(event.display, False);
}
XSetErrorHandler(NULL);
}
} // anonymous namespace
/*
* SendString - The interface method for CKeySend
*
* The actual work is done by DoSendString above. This function just
* just throws an exception if DoSendString encounters an error.
*
*/
void pws_os::SendString(const StringX& str, AutotypeMethod method, unsigned delayMS)
{
atGlobals.error_detected = false;
atGlobals.errorString[0] = 0;
DoSendString(str, method, delayMS);
if (atGlobals.error_detected)
throw autotype_exception();
}
<commit_msg>We only need to track keysyms for wchar_t values less than 0x20<commit_after>/*
* Copyright (c) 2003-2011 Rony Shapiro <[email protected]>.
* All rights reserved. Use of the code is allowed under the
* Artistic License 2.0 terms, as specified in the LICENSE file
* distributed with this code, or available from
* http://www.opensource.org/licenses/artistic-license-2.0.php
*/
/*
* xsendstring - send a bunch of keystrokes to the app having current input focus
*
* Calls X library functions defined in Xt and Xtst
*
* +. Initialize all the params of XKeyEvent
* + More escape sequences from http://msdn.microsoft.com/en-us/library/h21280bw%28VS.80%29.aspx
* + XGetErrorText and sprintf overflow
*/
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <ctype.h>
#include <string.h>
#include <time.h>
#include <vector>
#include <errno.h>
#include <limits.h>
#include <X11/Intrinsic.h> // in libxt-dev
#include <X11/keysym.h>
#include <X11/extensions/XTest.h> // in libxtst-dev
#include "./xsendstring.h"
#include "../sleep.h"
#include "../../core/PwsPlatform.h" // for NumberOf()
#include "../../core/StringX.h"
namespace { // anonymous namespace for hiding
// local variables and functions
typedef struct _KeyPress {
KeyCode code;
unsigned int state;
} KeyPressInfo;
struct AutotypeGlobals
{
Boolean error_detected;
char errorString[1024];
KeyCode lshiftCode;
pws_os::AutotypeMethod method;
Boolean LiteralKeysymsInitialized;
} atGlobals = { False, {0}, 0, pws_os::ATMETHOD_AUTO, False };
class autotype_exception: public std::exception
{
public:
virtual const char* what() const throw() {
return atGlobals.errorString;
}
};
/*
* ErrorHandler will be called when X detects an error. This function
* just sets a global flag and saves the error message text
*/
int ErrorHandler(Display *my_dpy, XErrorEvent *event)
{
char xmsg[512] = {0};
atGlobals.error_detected = TRUE;
XGetErrorText(my_dpy, event->error_code, xmsg, NumberOf(xmsg) - 1);
snprintf(atGlobals.errorString, NumberOf(atGlobals.errorString)-1, "X error (%d): %s", event->request_code, xmsg);
return 0;
}
void InitLiteralKeysyms(void)
{
atGlobals.lshiftCode = XKeysymToKeycode(XOpenDisplay(NULL), XK_Shift_L);
}
void XTest_SendEvent(XKeyEvent *event)
{
XTestFakeKeyEvent(event->display, event->keycode, event->type == KeyPress, 0);
}
void XSendKeys_SendEvent(XKeyEvent *event)
{
XSendEvent(event->display, event->window, TRUE, KeyPressMask, reinterpret_cast<XEvent *>(event));
}
void XSendKeys_SendKeyEvent(XKeyEvent* event)
{
event->type = KeyPress;
XSendKeys_SendEvent(event);
event->type = KeyRelease;
XSendKeys_SendEvent(event);
XFlush(event->display);
}
void XTest_SendKeyEvent(XKeyEvent* event)
{
XKeyEvent shiftEvent;
/* must simulate the shift-press for CAPS and shifted keypresses manually */
if (event->state & ShiftMask) {
memcpy(&shiftEvent, event, sizeof(shiftEvent));
shiftEvent.keycode = atGlobals.lshiftCode;
shiftEvent.type = KeyPress;
XTest_SendEvent(&shiftEvent);
}
event->type = KeyPress;
XTest_SendEvent(event);
event->type = KeyRelease;
XTest_SendEvent(event);
if (event->state & ShiftMask) {
shiftEvent.type = KeyRelease;
XTest_SendEvent(&shiftEvent);
}
XFlush(event->display);
}
Bool UseXTest(void)
{
int major_opcode, first_event, first_error;
static Bool useXTest;
static int checked = 0;
if (!checked) {
useXTest = XQueryExtension(XOpenDisplay(0), "XTEST", &major_opcode, &first_event, &first_error);
checked = 1;
}
return useXTest;
}
void InitKeyEvent(XKeyEvent* event)
{
int revert_to;
event->display = XOpenDisplay(NULL);
XGetInputFocus(event->display, &event->window, &revert_to);
event->subwindow = None;
event->x = event->y = event->x_root = event->y_root = 1;
event->same_screen = TRUE;
}
int FindModifierMask(Display* disp, KeySym sym)
{
int modmask = 0;
XModifierKeymap* modmap = XGetModifierMapping(disp);
if (modmap) {
const int last = 8*modmap->max_keypermod;
//begin at 4th row, where Mod1 starts
for (int i = 3*modmap->max_keypermod && !modmask; i < last; i++) {
//
const KeyCode kc = modmap->modifiermap[i];
if (!kc)
continue;
int keysyms_per_keycode = 0;
// For each keycode attached to this modifier, get a list of all keysyms
// attached with this keycode. If any of those keysyms is what we are looking
// for, then this is the modifier to use
KeySym* symlist = XGetKeyboardMapping(disp, kc, 1, &keysyms_per_keycode);
if ( symlist) {
for (int j = 0; j < keysyms_per_keycode; j++) {
if (sym == symlist[j]) {
modmask = (i / modmap->max_keypermod);
break;
}
}
}
}
XFreeModifiermap(modmap);
}
assert( modmask >= 3 && modmask <= 7);
return 1 << modmask;
}
int CalcModifiersForKeysym(KeyCode code, KeySym sym, Display* disp)
{
int keysyms_per_keycode = 0;
const KeySym* symlist = XGetKeyboardMapping(disp, code, 1, &keysyms_per_keycode);
if (symlist != NULL && keysyms_per_keycode > 0) {
const int ModeSwitchMask = FindModifierMask(disp, XK_Mode_switch);
const int Level3ShiftMask = FindModifierMask(disp, XK_ISO_Level3_Shift);
int mods[] = {
0, //none
ShiftMask,
ModeSwitchMask,
ShiftMask | ModeSwitchMask,
// beyond this, its all guesswork since there's no documentation, but see this:
//
// http://superuser.com/questions/189869/xmodmap-six-characters-to-one-key
//
// Also, if you install mulitple keyboard layouts the number of keysyms-per-keycode
// will keep increasing to a max of 16 (up to 4 layouts can be installed together
// in Ubuntu 11.04). For some keycodes, you will actually have non-NoSymbol
// keysyms beyond the first four
//
// We probably shouldn't go here if Mode_switch and ISO_Level3_Shift are assigned to
// the same modifier mask
Level3ShiftMask,
ShiftMask | Level3ShiftMask,
ModeSwitchMask | Level3ShiftMask,
ShiftMask | ModeSwitchMask | Level3ShiftMask,
};
const int max_keysym_index = std::min(int(NumberOf(mods)), keysyms_per_keycode);
for (int idx = 0; idx < max_keysym_index; ++idx) {
if (symlist[idx] == sym)
return mods[idx];
}
}
// we should at least find the keysym without any mods (index 0)
assert(0);
return 0;
}
KeySym wchar2keysym(wchar_t wc)
{
if (wc < 0x100) {
if (wc >= 0x20)
return wc;
switch(wc) {
case L'\t': return XK_Tab;
case L'\r': return XK_Return;
case L'\n': return XK_Linefeed;
case '\010': return XK_BackSpace;
case '\177': return XK_Delete;
case '\033': return XK_Escape;
default:
return NoSymbol;
}
}
if (wc > 0x10ffff || (wc > 0x7e && wc < 0xa0))
return NoSymbol;
return wc | 0x01000000;
}
//converts a single wchar_t to a byte string [i.e. char*]
class wchar2bytes
{
private:
//MB_CUR_MAX is a function call, not a constant
char* bytes;
public:
wchar2bytes(wchar_t wc): bytes(new char[MB_CUR_MAX*2 + sizeof(wchar_t)*2 + 2 + 1]) {
mbstate_t ps = {0};
size_t n;
if ((n = wcrtomb(bytes, wc, &ps)) == size_t(-1))
snprintf(bytes, NumberOf(bytes), "U+%04X", int(wc));
else
bytes[n] = 0;
}
~wchar2bytes() { delete [] bytes; }
const char* str() const {return bytes;}
};
/*
* DoSendString - actually sends a string to the X Window having input focus
*
* The main task of this function is to convert the ascii char values
* into X KeyCodes. But they need to be converted to X KeySyms first
* and then to the keycodes. The KeyCodes can have any random values
* and are not contiguous like the ascii values are.
*
* Some escape sequences can be converted to the appropriate KeyCodes
* by this function. See the code below for details
*/
void DoSendString(const StringX& str, pws_os::AutotypeMethod method, unsigned delayMS)
{
if (!atGlobals.LiteralKeysymsInitialized) {
InitLiteralKeysyms();
atGlobals.LiteralKeysymsInitialized = True;
}
XKeyEvent event;
InitKeyEvent(&event);
// convert all the chars into keycodes and required shift states first
// Abort if any of the characters cannot be converted
typedef std::vector<KeyPressInfo> KeyPressInfoVector;
KeyPressInfoVector keypresses;
for (StringX::const_iterator srcIter = str.begin(); srcIter != str.end(); ++srcIter) {
//throw away 'vertical tab' chars which are only used on Windows to send a shift+tab
//as a workaround for some issues with IE
if (*srcIter == _T('\v'))
continue;
//Try a regular conversion first
KeySym sym = wchar2keysym(*srcIter);
if (NoSymbol != sym) {
KeyPressInfo keypress = {0, 0};
if ((keypress.code = XKeysymToKeycode(event.display, sym)) != 0) {
//non-zero return value implies sym -> code was successful
keypress.state |= CalcModifiersForKeysym(keypress.code, sym, event.display);
keypresses.push_back(keypress);
}
else {
const char* symStr = XKeysymToString(sym);
snprintf(atGlobals.errorString, NumberOf(atGlobals.errorString),
"Could not get keycode for key char(%s) - sym(%#X) - str(%s). Aborting autotype",
wchar2bytes(*srcIter).str(), static_cast<int>(sym), symStr ? symStr : "NULL");
atGlobals.error_detected = True;
return;
}
}
else {
snprintf(atGlobals.errorString, NumberOf(atGlobals.errorString),
"Cannot convert '%s' [U+%04X] to keysym. Aborting autotype", wchar2bytes(*srcIter).str(), int(*srcIter));
atGlobals.error_detected = True;
return;
}
}
XSetErrorHandler(ErrorHandler);
atGlobals.error_detected = False;
bool useXTEST = (UseXTest() && method != pws_os::ATMETHOD_XSENDKEYS);
void (*KeySendFunction)(XKeyEvent*);
if ( useXTEST) {
KeySendFunction = XTest_SendKeyEvent;
XTestGrabControl(event.display, True);
}
else {
KeySendFunction = XSendKeys_SendKeyEvent;
}
for (KeyPressInfoVector::const_iterator itr = keypresses.begin(); itr != keypresses.end()
&& !atGlobals.error_detected; ++itr) {
event.keycode = itr->code;
event.state = itr->state;
event.time = CurrentTime;
KeySendFunction(&event);
pws_os::sleep_ms(delayMS);
}
if (useXTEST) {
XTestGrabControl(event.display, False);
}
else {
XSync(event.display, False);
}
XSetErrorHandler(NULL);
}
} // anonymous namespace
/*
* SendString - The interface method for CKeySend
*
* The actual work is done by DoSendString above. This function just
* just throws an exception if DoSendString encounters an error.
*
*/
void pws_os::SendString(const StringX& str, AutotypeMethod method, unsigned delayMS)
{
atGlobals.error_detected = false;
atGlobals.errorString[0] = 0;
DoSendString(str, method, delayMS);
if (atGlobals.error_detected)
throw autotype_exception();
}
<|endoftext|> |
<commit_before><commit_msg>Correct lngmerge not to work with eof<commit_after><|endoftext|> |
<commit_before><commit_msg>convert system path to url<commit_after><|endoftext|> |
<commit_before>/*
* Copyright (C) 2018 Red Hat, Inc.
*
* Licensed under the GNU Lesser General Public License Version 2.1
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include "DependencySplitter.hpp"
#include "../dnf-sack.h"
#include "../utils/regex/regex.hpp"
namespace libdnf {
static const Regex RELDEP_REGEX =
Regex("^(\\S*)\\s*(<=|>=|<|>|=)?\\s*(\\S*)$", REG_EXTENDED);
static bool
getCmpFlags(int *cmp_type, std::string matchCmpType)
{
int subexpr_len = matchCmpType.size();
auto match_start = matchCmpType.c_str();
if (subexpr_len == 2) {
if (strncmp(match_start, "<=", 2) == 0) {
*cmp_type |= HY_LT;
*cmp_type |= HY_EQ;
}
else if (strncmp(match_start, ">=", 2) == 0) {
*cmp_type |= HY_GT;
*cmp_type |= HY_EQ;
}
else
return false;
} else if (subexpr_len == 1) {
if (*match_start == '<')
*cmp_type |= HY_LT;
else if (*match_start == '>')
*cmp_type |= HY_GT;
else if (*match_start == '=')
*cmp_type |= HY_EQ;
else
return false;
} else
return false;
return true;
}
bool
DependencySplitter::parse(const char * reldepStr)
{
enum { NAME = 1, CMP_TYPE = 2, EVR = 3, _LAST_ };
auto matchResult = RELDEP_REGEX.match(reldepStr, false, _LAST_);
if (!matchResult.isMatched() || matchResult.getMatchedLen(NAME) == 0) {
return false;
}
name = matchResult.getMatchedString(NAME);
evr = matchResult.getMatchedString(EVR);
cmpType = 0;
int evrLen = matchResult.getMatchedLen(EVR);
int cmpTypeLen = matchResult.getMatchedLen(CMP_TYPE);
if (cmpTypeLen < 1) {
if (evrLen > 0) {
// name contains the space char, e.g. filename like "hello world.jpg"
evr.clear();
name = reldepStr;
}
return true;
}
if (evrLen < 1)
return false;
return getCmpFlags(&cmpType, matchResult.getMatchedString(CMP_TYPE));
}
}
<commit_msg>Accept '==' as an operator in reldeps (RhBug:1847946)<commit_after>/*
* Copyright (C) 2018 Red Hat, Inc.
*
* Licensed under the GNU Lesser General Public License Version 2.1
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include "DependencySplitter.hpp"
#include "../dnf-sack.h"
#include "../log.hpp"
#include "../utils/regex/regex.hpp"
#include "bgettext/bgettext-lib.h"
#include "tinyformat/tinyformat.hpp"
namespace libdnf {
static const Regex RELDEP_REGEX =
Regex("^(\\S*)\\s*(<=|>=|<|>|=|==)?\\s*(\\S*)$", REG_EXTENDED);
static bool
getCmpFlags(int *cmp_type, std::string matchCmpType)
{
auto logger(Log::getLogger());
int subexpr_len = matchCmpType.size();
auto match_start = matchCmpType.c_str();
if (subexpr_len == 2) {
if (strncmp(match_start, "<=", 2) == 0) {
*cmp_type |= HY_LT;
*cmp_type |= HY_EQ;
}
else if (strncmp(match_start, ">=", 2) == 0) {
*cmp_type |= HY_GT;
*cmp_type |= HY_EQ;
}
else if (strncmp(match_start, "==", 2) == 0) {
auto msg = tfm::format(_("Using '==' operator in reldeps can result in an undefined "
"behavior. It is deprecated and the support will be dropped "
"in future versions. Use '=' operator instead."));
logger->warning(msg);
*cmp_type |= HY_EQ;
}
else
return false;
} else if (subexpr_len == 1) {
if (*match_start == '<')
*cmp_type |= HY_LT;
else if (*match_start == '>')
*cmp_type |= HY_GT;
else if (*match_start == '=')
*cmp_type |= HY_EQ;
else
return false;
} else
return false;
return true;
}
bool
DependencySplitter::parse(const char * reldepStr)
{
enum { NAME = 1, CMP_TYPE = 2, EVR = 3, _LAST_ };
auto matchResult = RELDEP_REGEX.match(reldepStr, false, _LAST_);
if (!matchResult.isMatched() || matchResult.getMatchedLen(NAME) == 0) {
return false;
}
name = matchResult.getMatchedString(NAME);
evr = matchResult.getMatchedString(EVR);
cmpType = 0;
int evrLen = matchResult.getMatchedLen(EVR);
int cmpTypeLen = matchResult.getMatchedLen(CMP_TYPE);
if (cmpTypeLen < 1) {
if (evrLen > 0) {
// name contains the space char, e.g. filename like "hello world.jpg"
evr.clear();
name = reldepStr;
}
return true;
}
if (evrLen < 1)
return false;
return getCmpFlags(&cmpType, matchResult.getMatchedString(CMP_TYPE));
}
}
<|endoftext|> |
<commit_before>// Copyright (C) 2010-2013 Joshua Boyce.
// See the file COPYING for copying permission.
#pragma once
#include <type_traits>
#include <utility>
#include <hadesmem/config.hpp>
// TODO: Implement same interface as std::optional<T> to make switching later
// easier.
// TODO: Add tests.
// TODO: Add constexpr support. (http://bit.ly/U7lSYy)
namespace hadesmem
{
namespace detail
{
// WARNING: T must have no-throw move, no-throw move assignment and
// no-throw destruction.
template <typename T>
class Optional
{
private:
using Boolean = void(Optional::*)() const;
public:
HADESMEM_DETAIL_CONSTEXPR Optional() HADESMEM_DETAIL_NOEXCEPT
: t_(),
valid_(false)
{ }
explicit Optional(T const& t)
: t_(),
valid_(false)
{
Construct(t);
}
// TODO: Conditional noexcept.
explicit Optional(T&& t)
: t_(),
valid_(false)
{
Construct(std::move(t));
}
Optional(Optional const& other)
: t_(),
valid_(false)
{
Construct(other.Get());
}
Optional& operator=(Optional const& other)
{
Optional tmp(other);
*this = std::move(tmp);
return *this;
}
// TODO: Conditional noexcept.
Optional(Optional&& other)
: t_(),
valid_(false)
{
Construct(std::move(other.Get()));
other.valid_ = false;
}
// TODO: Conditional noexcept.
Optional& operator=(Optional&& other)
{
Destroy();
Construct(std::move(other.Get()));
other.valid_ = false;
return *this;
}
Optional& operator=(T const& t)
{
Destroy();
Construct(t);
return *this;
}
Optional& operator=(T&& t) HADESMEM_DETAIL_NOEXCEPT
{
Destroy();
Construct(std::move(t));
return *this;
}
~Optional() HADESMEM_DETAIL_NOEXCEPT
{
Destroy();
}
// TODO: Emplacement support. (Including default construction of T.)
#if defined(HADESMEM_DETAIL_NO_EXPLICIT_CONVERSION_OPERATOR)
operator Boolean() const HADESMEM_DETAIL_NOEXCEPT
{
return valid_ ? &Optional::NotComparable : nullptr;
}
#else // #if defined(HADESMEM_DETAIL_NO_EXPLICIT_CONVERSION_OPERATOR)
explicit operator bool() const HADESMEM_DETAIL_NOEXCEPT
{
return valid_;
}
#endif // #if defined(HADESMEM_DETAIL_NO_EXPLICIT_CONVERSION_OPERATOR)
T& Get() HADESMEM_DETAIL_NOEXCEPT
{
return *GetPtr();
}
T const& Get() const HADESMEM_DETAIL_NOEXCEPT
{
return *GetPtr();
}
T& operator*() HADESMEM_DETAIL_NOEXCEPT
{
return Get();
}
T const& operator*() const HADESMEM_DETAIL_NOEXCEPT
{
return Get();
}
T* GetPtr() HADESMEM_DETAIL_NOEXCEPT
{
return static_cast<T*>(static_cast<void*>(&t_));
}
T const* GetPtr() const HADESMEM_DETAIL_NOEXCEPT
{
return static_cast<T const*>(static_cast<void const*>(&t_));
}
T* operator->() HADESMEM_DETAIL_NOEXCEPT
{
return GetPtr();
}
T const* operator->() const HADESMEM_DETAIL_NOEXCEPT
{
return GetPtr();
}
private:
void NotComparable() const HADESMEM_DETAIL_NOEXCEPT
{}
template <typename U>
void Construct(U&& u)
{
if (valid_)
{
Destroy();
}
new (&t_) T(std::forward<U>(u));
valid_ = true;
}
void Destroy() HADESMEM_DETAIL_NOEXCEPT
{
if (valid_)
{
GetPtr()->~T();
valid_ = false;
}
}
std::aligned_storage_t<sizeof(T), std::alignment_of<T>::value> t_;
bool valid_;
};
// TODO: Add conditional noexcept to operator overloads.
template <typename T>
inline bool operator==(Optional<T> const& lhs, Optional<T> const& rhs)
{
return (!lhs && !rhs) || ((rhs && lhs) && *rhs == *lhs);
}
template <typename T>
inline bool operator!=(Optional<T> const& lhs, Optional<T> const& rhs)
{
return !(lhs == rhs);
}
template <typename T>
inline bool operator<(Optional<T> const& lhs, Optional<T> const& rhs)
{
return (!lhs && !rhs) || ((rhs && lhs) && *rhs < *lhs);
}
}
}
<commit_msg>* [Optional] Clean up explicit bool operator.<commit_after>// Copyright (C) 2010-2013 Joshua Boyce.
// See the file COPYING for copying permission.
#pragma once
#include <type_traits>
#include <utility>
#include <hadesmem/config.hpp>
// TODO: Implement same interface as std::optional<T> to make switching later
// easier.
// TODO: Add tests.
// TODO: Add constexpr support. (http://bit.ly/U7lSYy)
namespace hadesmem
{
namespace detail
{
// WARNING: T must have no-throw move, no-throw move assignment and
// no-throw destruction.
template <typename T>
class Optional
{
public:
HADESMEM_DETAIL_CONSTEXPR Optional() HADESMEM_DETAIL_NOEXCEPT
: t_(),
valid_(false)
{ }
explicit Optional(T const& t)
: t_(),
valid_(false)
{
Construct(t);
}
// TODO: Conditional noexcept.
explicit Optional(T&& t)
: t_(),
valid_(false)
{
Construct(std::move(t));
}
Optional(Optional const& other)
: t_(),
valid_(false)
{
Construct(other.Get());
}
Optional& operator=(Optional const& other)
{
Optional tmp(other);
*this = std::move(tmp);
return *this;
}
// TODO: Conditional noexcept.
Optional(Optional&& other)
: t_(),
valid_(false)
{
Construct(std::move(other.Get()));
other.valid_ = false;
}
// TODO: Conditional noexcept.
Optional& operator=(Optional&& other)
{
Destroy();
Construct(std::move(other.Get()));
other.valid_ = false;
return *this;
}
Optional& operator=(T const& t)
{
Destroy();
Construct(t);
return *this;
}
Optional& operator=(T&& t) HADESMEM_DETAIL_NOEXCEPT
{
Destroy();
Construct(std::move(t));
return *this;
}
~Optional() HADESMEM_DETAIL_NOEXCEPT
{
Destroy();
}
// TODO: Emplacement support. (Including default construction of T.)
explicit operator bool() const HADESMEM_DETAIL_NOEXCEPT
{
return valid_;
}
T& Get() HADESMEM_DETAIL_NOEXCEPT
{
return *GetPtr();
}
T const& Get() const HADESMEM_DETAIL_NOEXCEPT
{
return *GetPtr();
}
T& operator*() HADESMEM_DETAIL_NOEXCEPT
{
return Get();
}
T const& operator*() const HADESMEM_DETAIL_NOEXCEPT
{
return Get();
}
T* GetPtr() HADESMEM_DETAIL_NOEXCEPT
{
return static_cast<T*>(static_cast<void*>(&t_));
}
T const* GetPtr() const HADESMEM_DETAIL_NOEXCEPT
{
return static_cast<T const*>(static_cast<void const*>(&t_));
}
T* operator->() HADESMEM_DETAIL_NOEXCEPT
{
return GetPtr();
}
T const* operator->() const HADESMEM_DETAIL_NOEXCEPT
{
return GetPtr();
}
private:
template <typename U>
void Construct(U&& u)
{
if (valid_)
{
Destroy();
}
new (&t_) T(std::forward<U>(u));
valid_ = true;
}
void Destroy() HADESMEM_DETAIL_NOEXCEPT
{
if (valid_)
{
GetPtr()->~T();
valid_ = false;
}
}
std::aligned_storage_t<sizeof(T), std::alignment_of<T>::value> t_;
bool valid_;
};
// TODO: Add conditional noexcept to operator overloads.
template <typename T>
inline bool operator==(Optional<T> const& lhs, Optional<T> const& rhs)
{
return (!lhs && !rhs) || ((rhs && lhs) && *rhs == *lhs);
}
template <typename T>
inline bool operator!=(Optional<T> const& lhs, Optional<T> const& rhs)
{
return !(lhs == rhs);
}
template <typename T>
inline bool operator<(Optional<T> const& lhs, Optional<T> const& rhs)
{
return (!lhs && !rhs) || ((rhs && lhs) && *rhs < *lhs);
}
}
}
<|endoftext|> |
<commit_before>//
// Copyright (c) 2013-2014 Christoph Malek
// See LICENSE for more information.
//
#ifndef RJ_GAME_COMPONENTS_STAR5_HPP
#define RJ_GAME_COMPONENTS_STAR5_HPP
#include <SFML/Graphics.hpp>
#include <cmath>
namespace rj
{
class star5 : public sf::ConvexShape
{
static constexpr float m_pi{3.14159265359f};
float m_length;
public:
star5(float length) :
m_length{length}
{this->init();}
void set_length(float l) noexcept
{m_length = l; this->recalculate();}
float get_length() const noexcept
{return m_length;}
private:
void init() noexcept
{
this->setPointCount(5);
this->recalculate();
}
void recalculate() noexcept
{
this->setPoint(0, {m_length * std::cos((2 * m_pi) / 5), m_length * std::sin((2 * m_pi) /5)});
this->setPoint(1, {m_length * std::cos((6 * m_pi) / 5), m_length * std::sin((6 * m_pi) / 5)});
this->setPoint(2, {m_length * std::cos((10 * m_pi) / 5), m_length * std::sin((10 * m_pi) / 5)});
this->setPoint(3, {m_length * std::cos((4 * m_pi) / 5), m_length * std::sin((4 * m_pi) / 5)});
this->setPoint(4, {m_length * std::cos((8 * m_pi) / 5), m_length * std::sin((8 * m_pi) / 5)});
}
};
}
#endif // RJ_GAME_COMPONENTS_STAR5_HPP
<commit_msg>added new ctor<commit_after>//
// Copyright (c) 2013-2014 Christoph Malek
// See LICENSE for more information.
//
#ifndef RJ_GAME_COMPONENTS_STAR5_HPP
#define RJ_GAME_COMPONENTS_STAR5_HPP
#include <rectojump/global/common.hpp>
#include <SFML/Graphics.hpp>
#include <cmath>
namespace rj
{
class star5 : public sf::ConvexShape
{
static constexpr float m_pi{3.14159265359f};
float m_length;
public:
star5(float length) :
m_length{length}
{this->init();}
star5(float length, const vec2f& pos) :
star5{length}
{this->setPosition(pos);}
void set_length(float l) noexcept
{m_length = l; this->recalculate();}
float get_length() const noexcept
{return m_length;}
private:
void init() noexcept
{
this->setPointCount(5);
this->recalculate();
}
void recalculate() noexcept
{
this->setPoint(0, {m_length * std::cos((2 * m_pi) / 5), m_length * std::sin((2 * m_pi) /5)});
this->setPoint(1, {m_length * std::cos((6 * m_pi) / 5), m_length * std::sin((6 * m_pi) / 5)});
this->setPoint(2, {m_length * std::cos((10 * m_pi) / 5), m_length * std::sin((10 * m_pi) / 5)});
this->setPoint(3, {m_length * std::cos((4 * m_pi) / 5), m_length * std::sin((4 * m_pi) / 5)});
this->setPoint(4, {m_length * std::cos((8 * m_pi) / 5), m_length * std::sin((8 * m_pi) / 5)});
}
};
}
#endif // RJ_GAME_COMPONENTS_STAR5_HPP
<|endoftext|> |
<commit_before>#define CATCH_CONFIG_MAIN
#include "catch.hpp"
#include "rapidjson/document.h"
#include "mstch/mstch.hpp"
#include "test_context.hpp"
#include "test_data.hpp"
#include "specs_data.hpp"
#include "specs_lambdas.hpp"
using namespace mstchtest;
mstch::node to_value(const rapidjson::Value& val) {
if (val.IsString())
return std::string{val.GetString()};
if (val.IsBool())
return val.GetBool();
if (val.IsDouble())
return val.GetDouble();
if (val.IsInt())
return val.GetInt();
return mstch::node{};
}
mstch::array to_array(const rapidjson::Value& val);
mstch::map to_object(const rapidjson::Value& val) {
mstch::map ret;
for (auto i = val.MemberBegin(); i != val.MemberEnd(); ++i) {
if (i->value.IsArray())
ret.insert(std::make_pair(i->name.GetString(), to_array(i->value)));
else if (i->value.IsObject())
ret.insert(std::make_pair(i->name.GetString(), to_object(i->value)));
else
ret.insert(std::make_pair(i->name.GetString(), to_value(i->value)));
}
return ret;
}
mstch::array to_array(const rapidjson::Value& val) {
mstch::array ret;
for (auto i = val.Begin(); i != val.End(); ++i) {
if (i->IsArray())
ret.push_back(to_array(*i));
else if (i->IsObject())
ret.push_back(to_object(*i));
else
ret.push_back(to_value(*i));
}
return ret;
}
mstch::node parse_with_rapidjson(const std::string& str) {
rapidjson::Document doc;
doc.Parse(str.c_str());
return to_object(doc);
}
#define MSTCH_PARTIAL_TEST(x) TEST_CASE(#x) { \
REQUIRE(x ## _txt == mstch::render(x ## _mustache, x ## _data, {{"partial", x ## _partial}})); \
}
#define MSTCH_TEST(x) TEST_CASE(#x) { \
REQUIRE(x ## _txt == mstch::render(x ## _mustache, x ## _data)); \
}
#define SPECS_TEST(x) TEST_CASE("specs_" #x) { \
using boost::get; \
auto data = parse_with_rapidjson(x ## _json); \
for (auto& test_item: get<mstch::array>(get<mstch::map>(data)["tests"])) {\
auto test = get<mstch::map>(test_item); \
std::map<std::string,std::string> partials; \
if (test.count("partials")) \
for (auto& partial_item: get<mstch::map>(test["partials"])) \
partials.insert(std::make_pair(partial_item.first, get<std::string>(partial_item.second))); \
for (auto& data_item: get<mstch::map>(test["data"])) \
if (data_item.first == "lambda") \
data_item.second = specs_lambdas[get<std::string>(test["name"])]; \
SECTION(get<std::string>(test["name"])) \
REQUIRE(mstch::render( \
get<std::string>(test["template"]), \
test["data"], partials) == \
get<std::string>(test["expected"])); \
} \
}
MSTCH_TEST(ampersand_escape)
MSTCH_TEST(apostrophe)
MSTCH_TEST(array_of_strings)
MSTCH_TEST(backslashes)
MSTCH_TEST(bug_11_eating_whitespace)
MSTCH_TEST(bug_length_property)
MSTCH_TEST(changing_delimiters)
MSTCH_TEST(comments)
MSTCH_TEST(complex)
MSTCH_TEST(context_lookup)
MSTCH_TEST(delimiters)
MSTCH_TEST(disappearing_whitespace)
MSTCH_TEST(dot_notation)
MSTCH_TEST(double_render)
MSTCH_TEST(empty_list)
MSTCH_TEST(empty_sections)
MSTCH_TEST(empty_string)
MSTCH_TEST(empty_template)
MSTCH_TEST(error_eof_in_section)
MSTCH_TEST(error_eof_in_tag)
MSTCH_TEST(error_not_found)
MSTCH_TEST(escaped)
MSTCH_TEST(falsy)
MSTCH_TEST(falsy_array)
MSTCH_TEST(grandparent_context)
MSTCH_TEST(higher_order_sections)
MSTCH_TEST(implicit_iterator)
MSTCH_TEST(included_tag)
MSTCH_TEST(inverted_section)
MSTCH_TEST(keys_with_questionmarks)
MSTCH_TEST(multiline_comment)
MSTCH_TEST(nested_dot)
MSTCH_TEST(nested_higher_order_sections)
MSTCH_TEST(nested_iterating)
MSTCH_TEST(nesting)
MSTCH_TEST(nesting_same_name)
MSTCH_TEST(null_lookup_array)
MSTCH_TEST(null_lookup_object)
MSTCH_TEST(null_string)
MSTCH_TEST(null_view)
MSTCH_PARTIAL_TEST(partial_array)
MSTCH_PARTIAL_TEST(partial_array_of_partials)
MSTCH_PARTIAL_TEST(partial_array_of_partials_implicit)
MSTCH_PARTIAL_TEST(partial_empty)
MSTCH_PARTIAL_TEST(partial_template)
MSTCH_PARTIAL_TEST(partial_view)
MSTCH_PARTIAL_TEST(partial_whitespace)
MSTCH_TEST(recursion_with_same_names)
MSTCH_TEST(reuse_of_enumerables)
MSTCH_TEST(section_as_context)
MSTCH_PARTIAL_TEST(section_functions_in_partials)
MSTCH_TEST(simple)
MSTCH_TEST(string_as_context)
MSTCH_TEST(two_in_a_row)
MSTCH_TEST(two_sections)
MSTCH_TEST(unescaped)
MSTCH_TEST(whitespace)
MSTCH_TEST(zero_view)
SPECS_TEST(comments)
SPECS_TEST(delimiters)
SPECS_TEST(interpolation)
SPECS_TEST(inverted)
SPECS_TEST(partials)
SPECS_TEST(sections)
SPECS_TEST(lambdas)
<commit_msg>fix for libc++<commit_after>#define CATCH_CONFIG_MAIN
#include "catch.hpp"
#include "rapidjson/document.h"
#include "mstch/mstch.hpp"
#include "test_context.hpp"
#include "test_data.hpp"
#include "specs_data.hpp"
#include "specs_lambdas.hpp"
using namespace mstchtest;
mstch::node to_value(const rapidjson::Value& val) {
if (val.IsString())
return std::string{val.GetString()};
if (val.IsBool())
return val.GetBool();
if (val.IsDouble())
return val.GetDouble();
if (val.IsInt())
return val.GetInt();
return mstch::node{};
}
mstch::array to_array(const rapidjson::Value& val);
mstch::map to_object(const rapidjson::Value& val) {
mstch::map ret;
for (auto i = val.MemberBegin(); i != val.MemberEnd(); ++i) {
if (i->value.IsArray())
ret.insert(std::make_pair(i->name.GetString(), to_array(i->value)));
else if (i->value.IsObject())
ret.insert(std::make_pair(i->name.GetString(), to_object(i->value)));
else
ret.insert(std::make_pair(i->name.GetString(), to_value(i->value)));
}
return ret;
}
mstch::array to_array(const rapidjson::Value& val) {
mstch::array ret;
for (auto i = val.Begin(); i != val.End(); ++i) {
if (i->IsArray())
ret.push_back(to_array(*i));
else if (i->IsObject())
ret.push_back(to_object(*i));
else
ret.push_back(to_value(*i));
}
return ret;
}
mstch::node parse_with_rapidjson(const std::string& str) {
rapidjson::Document doc;
doc.Parse(str.c_str());
return to_object(doc);
}
#define MSTCH_PARTIAL_TEST(x) TEST_CASE(#x) { \
REQUIRE(x ## _txt == mstch::render(x ## _mustache, x ## _data, {{"partial", x ## _partial}})); \
}
#define MSTCH_TEST(x) TEST_CASE(#x) { \
REQUIRE(x ## _txt == mstch::render(x ## _mustache, x ## _data)); \
}
#define SPECS_TEST(x) TEST_CASE("specs_" #x) { \
using boost::get; \
auto data = parse_with_rapidjson(x ## _json); \
for (auto& test_item: get<mstch::array>(get<mstch::map>(data)["tests"])) {\
auto test = get<mstch::map>(test_item); \
std::map<std::string,std::string> partials; \
if (test.count("partials")) \
for (auto& partial_item: get<mstch::map>(test["partials"])) \
partials.insert(std::make_pair(partial_item.first, get<std::string>(partial_item.second))); \
mstch::map context; \
for (auto& data_item: get<mstch::map>(test["data"])) \
if (data_item.first == "lambda") \
context.insert(std::make_pair(data_item.first, specs_lambdas[get<std::string>(test["name"])])); \
else \
context.insert(data_item); \
SECTION(get<std::string>(test["name"])) \
REQUIRE(mstch::render( \
get<std::string>(test["template"]), \
context, partials) == \
get<std::string>(test["expected"])); \
} \
}
MSTCH_TEST(ampersand_escape)
MSTCH_TEST(apostrophe)
MSTCH_TEST(array_of_strings)
MSTCH_TEST(backslashes)
MSTCH_TEST(bug_11_eating_whitespace)
MSTCH_TEST(bug_length_property)
MSTCH_TEST(changing_delimiters)
MSTCH_TEST(comments)
MSTCH_TEST(complex)
MSTCH_TEST(context_lookup)
MSTCH_TEST(delimiters)
MSTCH_TEST(disappearing_whitespace)
MSTCH_TEST(dot_notation)
MSTCH_TEST(double_render)
MSTCH_TEST(empty_list)
MSTCH_TEST(empty_sections)
MSTCH_TEST(empty_string)
MSTCH_TEST(empty_template)
MSTCH_TEST(error_eof_in_section)
MSTCH_TEST(error_eof_in_tag)
MSTCH_TEST(error_not_found)
MSTCH_TEST(escaped)
MSTCH_TEST(falsy)
MSTCH_TEST(falsy_array)
MSTCH_TEST(grandparent_context)
MSTCH_TEST(higher_order_sections)
MSTCH_TEST(implicit_iterator)
MSTCH_TEST(included_tag)
MSTCH_TEST(inverted_section)
MSTCH_TEST(keys_with_questionmarks)
MSTCH_TEST(multiline_comment)
MSTCH_TEST(nested_dot)
MSTCH_TEST(nested_higher_order_sections)
MSTCH_TEST(nested_iterating)
MSTCH_TEST(nesting)
MSTCH_TEST(nesting_same_name)
MSTCH_TEST(null_lookup_array)
MSTCH_TEST(null_lookup_object)
MSTCH_TEST(null_string)
MSTCH_TEST(null_view)
MSTCH_PARTIAL_TEST(partial_array)
MSTCH_PARTIAL_TEST(partial_array_of_partials)
MSTCH_PARTIAL_TEST(partial_array_of_partials_implicit)
MSTCH_PARTIAL_TEST(partial_empty)
MSTCH_PARTIAL_TEST(partial_template)
MSTCH_PARTIAL_TEST(partial_view)
MSTCH_PARTIAL_TEST(partial_whitespace)
MSTCH_TEST(recursion_with_same_names)
MSTCH_TEST(reuse_of_enumerables)
MSTCH_TEST(section_as_context)
MSTCH_PARTIAL_TEST(section_functions_in_partials)
MSTCH_TEST(simple)
MSTCH_TEST(string_as_context)
MSTCH_TEST(two_in_a_row)
MSTCH_TEST(two_sections)
MSTCH_TEST(unescaped)
MSTCH_TEST(whitespace)
MSTCH_TEST(zero_view)
SPECS_TEST(comments)
SPECS_TEST(delimiters)
SPECS_TEST(interpolation)
SPECS_TEST(inverted)
SPECS_TEST(partials)
SPECS_TEST(sections)
SPECS_TEST(lambdas)
<|endoftext|> |
<commit_before>/*
Copyright (c) 2013, Arvid Norberg
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in
the documentation and/or other materials provided with the distribution.
* Neither the name of the author nor the names of its
contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
#include "test.hpp"
#include "libtorrent/time.hpp"
#include "libtorrent/thread.hpp"
#include <boost/bind.hpp>
using namespace libtorrent;
void check_timer_loop(mutex& m, time_point& last, condition_variable& cv)
{
mutex::scoped_lock l(m);
cv.wait(l);
l.unlock();
for (int i = 0; i < 10000; ++i)
{
mutex::scoped_lock l(m);
time_point now = clock_type::now();
TEST_CHECK(now >= last);
last = now;
}
}
int test_main()
{
// make sure the time classes have correct semantics
TEST_EQUAL(total_milliseconds(milliseconds(100)), 100);
TEST_EQUAL(total_milliseconds(milliseconds(1)), 1);
TEST_EQUAL(total_milliseconds(seconds(1)), 1000);
TEST_EQUAL(total_seconds(minutes(1)), 60);
TEST_EQUAL(total_seconds(hours(1)), 3600);
// make sure it doesn't wrap at 32 bit arithmetic
TEST_EQUAL(total_seconds(seconds(281474976)), 281474976);
TEST_EQUAL(total_milliseconds(milliseconds(281474976)), 281474976);
// make sure the timer is monotonic
time_point now = clock_type::now();
time_point last = now;
for (int i = 0; i < 1000; ++i)
{
now = clock_type::now();
TEST_CHECK(now >= last);
last = now;
}
mutex m;
condition_variable cv;
thread t1(boost::bind(&check_timer_loop, boost::ref(m), boost::ref(last), boost::ref(cv)));
thread t2(boost::bind(&check_timer_loop, boost::ref(m), boost::ref(last), boost::ref(cv)));
thread t3(boost::bind(&check_timer_loop, boost::ref(m), boost::ref(last), boost::ref(cv)));
thread t4(boost::bind(&check_timer_loop, boost::ref(m), boost::ref(last), boost::ref(cv)));
sleep(100);
cv.notify_all();
t1.join();
t2.join();
t3.join();
t4.join();
return 0;
}
<commit_msg>fix test_time build<commit_after>/*
Copyright (c) 2013, Arvid Norberg
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in
the documentation and/or other materials provided with the distribution.
* Neither the name of the author nor the names of its
contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
#include "test.hpp"
#include "libtorrent/time.hpp"
#include "libtorrent/thread.hpp"
#include <boost/bind.hpp>
using namespace libtorrent;
void check_timer_loop(mutex& m, time_point& last, condition_variable& cv)
{
mutex::scoped_lock l(m);
cv.wait(l);
l.unlock();
for (int i = 0; i < 10000; ++i)
{
mutex::scoped_lock l(m);
time_point now = clock_type::now();
TEST_CHECK(now >= last);
last = now;
}
}
int test_main()
{
// make sure the time classes have correct semantics
TEST_EQUAL(total_milliseconds(milliseconds(100)), 100);
TEST_EQUAL(total_milliseconds(milliseconds(1)), 1);
TEST_EQUAL(total_milliseconds(seconds(1)), 1000);
TEST_EQUAL(total_seconds(minutes(1)), 60);
TEST_EQUAL(total_seconds(hours(1)), 3600);
// make sure it doesn't wrap at 32 bit arithmetic
TEST_EQUAL(total_seconds(seconds(281474976)), 281474976);
TEST_EQUAL(total_milliseconds(milliseconds(281474976)), 281474976);
// make sure the timer is monotonic
time_point now = clock_type::now();
time_point last = now;
for (int i = 0; i < 1000; ++i)
{
now = clock_type::now();
TEST_CHECK(now >= last);
last = now;
}
mutex m;
condition_variable cv;
thread t1(boost::bind(&check_timer_loop, boost::ref(m), boost::ref(last), boost::ref(cv)));
thread t2(boost::bind(&check_timer_loop, boost::ref(m), boost::ref(last), boost::ref(cv)));
thread t3(boost::bind(&check_timer_loop, boost::ref(m), boost::ref(last), boost::ref(cv)));
thread t4(boost::bind(&check_timer_loop, boost::ref(m), boost::ref(last), boost::ref(cv)));
test_sleep(100);
cv.notify_all();
t1.join();
t2.join();
t3.join();
t4.join();
return 0;
}
<|endoftext|> |
<commit_before>#include "testing/testing.hpp"
#include "indexer/cell_coverer.hpp"
#include "indexer/indexer_tests/bounds.hpp"
#include "geometry/covering_utils.hpp"
#include "coding/hex.hpp"
#include "base/logging.hpp"
// Unit test uses m2::CellId<30> for historical reasons, the actual production code uses RectId.
typedef m2::CellId<30> CellIdT;
UNIT_TEST(CellIdToStringRecode)
{
char const kTest[] = "21032012203";
TEST_EQUAL(CellIdT::FromString(kTest).ToString(), kTest, ());
}
UNIT_TEST(GoldenCoverRect)
{
vector<CellIdT> cells;
CoverRect<OrthoBounds>({27.43, 53.83, 27.70, 53.96}, 4, RectId::DEPTH_LEVELS - 1, cells);
TEST_EQUAL(cells.size(), 4, ());
TEST_EQUAL(cells[0].ToString(), "32012211300", ());
TEST_EQUAL(cells[1].ToString(), "32012211301", ());
TEST_EQUAL(cells[2].ToString(), "32012211302", ());
TEST_EQUAL(cells[3].ToString(), "32012211303", ());
}
UNIT_TEST(ArtificialCoverRect)
{
typedef Bounds<0, 0, 16, 16> TestBounds;
vector<CellIdT> cells;
CoverRect<TestBounds>({5, 5, 11, 11}, 4, RectId::DEPTH_LEVELS - 1, cells);
TEST_EQUAL(cells.size(), 4, ());
TEST_EQUAL(cells[0].ToString(), "03", ());
TEST_EQUAL(cells[1].ToString(), "12", ());
TEST_EQUAL(cells[2].ToString(), "21", ());
TEST_EQUAL(cells[3].ToString(), "30", ());
}
UNIT_TEST(MaxDepthCoverSpiral)
{
using TestBounds = Bounds<0, 0, 8, 8>;
for (auto levelMax = 0; levelMax <= 2; ++levelMax)
{
auto cells = vector<m2::CellId<3>>{};
CoverSpiral<TestBounds, m2::CellId<3>>({2.1, 4.1, 2.1, 4.1}, levelMax, cells);
TEST_EQUAL(cells.size(), 1, ());
TEST_EQUAL(cells[0].Level(), levelMax - 1, ());
}
}
<commit_msg>[indexer] Fix test MaxDepthCoverSpiral<commit_after>#include "testing/testing.hpp"
#include "indexer/cell_coverer.hpp"
#include "indexer/indexer_tests/bounds.hpp"
#include "geometry/covering_utils.hpp"
#include "coding/hex.hpp"
#include "base/logging.hpp"
// Unit test uses m2::CellId<30> for historical reasons, the actual production code uses RectId.
typedef m2::CellId<30> CellIdT;
UNIT_TEST(CellIdToStringRecode)
{
char const kTest[] = "21032012203";
TEST_EQUAL(CellIdT::FromString(kTest).ToString(), kTest, ());
}
UNIT_TEST(GoldenCoverRect)
{
vector<CellIdT> cells;
CoverRect<OrthoBounds>({27.43, 53.83, 27.70, 53.96}, 4, RectId::DEPTH_LEVELS - 1, cells);
TEST_EQUAL(cells.size(), 4, ());
TEST_EQUAL(cells[0].ToString(), "32012211300", ());
TEST_EQUAL(cells[1].ToString(), "32012211301", ());
TEST_EQUAL(cells[2].ToString(), "32012211302", ());
TEST_EQUAL(cells[3].ToString(), "32012211303", ());
}
UNIT_TEST(ArtificialCoverRect)
{
typedef Bounds<0, 0, 16, 16> TestBounds;
vector<CellIdT> cells;
CoverRect<TestBounds>({5, 5, 11, 11}, 4, RectId::DEPTH_LEVELS - 1, cells);
TEST_EQUAL(cells.size(), 4, ());
TEST_EQUAL(cells[0].ToString(), "03", ());
TEST_EQUAL(cells[1].ToString(), "12", ());
TEST_EQUAL(cells[2].ToString(), "21", ());
TEST_EQUAL(cells[3].ToString(), "30", ());
}
UNIT_TEST(MaxDepthCoverSpiral)
{
using TestBounds = Bounds<0, 0, 8, 8>;
for (auto levelMax = 0; levelMax <= 2; ++levelMax)
{
auto cells = vector<m2::CellId<3>>{};
CoverSpiral<TestBounds, m2::CellId<3>>({2.1, 4.1, 2.1, 4.1}, levelMax, cells);
TEST_EQUAL(cells.size(), 1, ());
TEST_EQUAL(cells[0].Level(), levelMax, ());
}
}
<|endoftext|> |
<commit_before>/*
Copyright (c) 2014, Arvid Norberg
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in
the documentation and/or other materials provided with the distribution.
* Neither the name of the author nor the names of its
contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
#include "test.hpp"
#include "libtorrent/utf8.hpp"
#include "libtorrent/ConvertUTF.h"
#include "setup_transfer.hpp" // for load_file
#include "libtorrent/file.hpp" // for combine_path
#include <vector>
using namespace libtorrent;
int test_main()
{
std::vector<char> utf8_source;
error_code ec;
load_file(combine_path("..", "utf8_test.txt"), utf8_source, ec, 1000000);
if (ec) fprintf(stderr, "failed to open file: (%d) %s\n", ec.value()
, ec.message().c_str());
TEST_CHECK(!ec);
// test lower level conversions
// utf8 -> utf16 -> utf32 -> utf8
{
std::vector<UTF16> utf16(utf8_source.size());
UTF8 const* in8 = (UTF8 const*)&utf8_source[0];
UTF16* out16 = &utf16[0];
ConversionResult ret = ConvertUTF8toUTF16(&in8, in8 + utf8_source.size()
, &out16, out16 + utf16.size(), strictConversion);
TEST_EQUAL(ret, conversionOK);
std::vector<UTF32> utf32(utf8_source.size());
UTF16 const* in16 = &utf16[0];
UTF32* out32 = &utf32[0];
ret = ConvertUTF16toUTF32(&in16, out16
, &out32, out32 + utf32.size(), strictConversion);
TEST_EQUAL(ret, conversionOK);
std::vector<UTF8> utf8(utf8_source.size());
UTF32 const* in32 = &utf32[0];
UTF8* out8 = &utf8[0];
ret = ConvertUTF32toUTF8(&in32, out32
, &out8, out8 + utf8.size(), strictConversion);
TEST_EQUAL(ret, conversionOK);
TEST_EQUAL(out8 - &utf8[0], utf8_source.size());
TEST_CHECK(std::equal(&utf8[0], out8, (UTF8 const*)&utf8_source[0]));
}
// utf8 -> utf32 -> utf16 -> utf8
{
std::vector<UTF32> utf32(utf8_source.size());
UTF8 const* in8 = (UTF8 const*)&utf8_source[0];
UTF32* out32 = &utf32[0];
ConversionResult ret = ConvertUTF8toUTF32(&in8, in8 + utf8_source.size()
, &out32, out32 + utf32.size(), strictConversion);
TEST_EQUAL(ret, conversionOK);
std::vector<UTF16> utf16(utf8_source.size());
UTF32 const* in32 = &utf32[0];
UTF16* out16 = &utf16[0];
ret = ConvertUTF32toUTF16(&in32, out32
, &out16, out16 + utf16.size(), strictConversion);
TEST_EQUAL(ret, conversionOK);
std::vector<UTF8> utf8(utf8_source.size());
UTF16 const* in16 = &utf16[0];
UTF8* out8 = &utf8[0];
ret = ConvertUTF16toUTF8(&in16, out16
, &out8, out8 + utf8.size(), strictConversion);
TEST_EQUAL(ret, conversionOK);
TEST_EQUAL(out8 - &utf8[0], utf8_source.size());
TEST_CHECK(std::equal(&utf8[0], out8, (UTF8 const*)&utf8_source[0]));
}
// test higher level conversions
std::string utf8;
std::copy(utf8_source.begin(), utf8_source.end(), std::back_inserter(utf8));
std::wstring wide;
utf8_conv_result_t ret = utf8_wchar(utf8, wide);
TEST_EQUAL(ret, conversion_ok);
std::string identity;
ret = wchar_utf8(wide, identity);
TEST_EQUAL(ret, conversion_ok);
TEST_EQUAL(utf8, identity);
return 0;
}
<commit_msg>extend utf8 unit test<commit_after>/*
Copyright (c) 2014, Arvid Norberg
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in
the documentation and/or other materials provided with the distribution.
* Neither the name of the author nor the names of its
contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
#include "test.hpp"
#include "libtorrent/utf8.hpp"
#include "libtorrent/ConvertUTF.h"
#include "setup_transfer.hpp" // for load_file
#include "libtorrent/file.hpp" // for combine_path
#include <vector>
using namespace libtorrent;
void verify_transforms(char const* utf8_source, int utf8_source_len = -1)
{
if (utf8_source_len == -1)
utf8_source_len = strlen(utf8_source);
// utf8 -> utf16 -> utf32 -> utf8
{
std::vector<UTF16> utf16(utf8_source_len);
UTF8 const* in8 = (UTF8 const*)utf8_source;
UTF16* out16 = &utf16[0];
ConversionResult ret = ConvertUTF8toUTF16(&in8, in8 + utf8_source_len
, &out16, out16 + utf16.size(), strictConversion);
TEST_EQUAL(ret, conversionOK);
if (ret != conversionOK && utf8_source_len < 10)
{
for (char const* i = utf8_source; *i != 0; ++i)
fprintf(stderr, "%x ", UTF8(*i));
}
std::vector<UTF32> utf32(utf8_source_len);
UTF16 const* in16 = &utf16[0];
UTF32* out32 = &utf32[0];
ret = ConvertUTF16toUTF32(&in16, out16
, &out32, out32 + utf32.size(), strictConversion);
TEST_EQUAL(ret, conversionOK);
if (ret != conversionOK && utf8_source_len < 10)
{
for (char const* i = utf8_source; *i != 0; ++i)
fprintf(stderr, "%x ", UTF8(*i));
}
std::vector<UTF8> utf8(utf8_source_len);
UTF32 const* in32 = &utf32[0];
UTF8* out8 = &utf8[0];
ret = ConvertUTF32toUTF8(&in32, out32
, &out8, out8 + utf8.size(), strictConversion);
TEST_EQUAL(ret, conversionOK);
if (ret != conversionOK && utf8_source_len < 10)
{
for (char const* i = utf8_source; *i != 0; ++i)
fprintf(stderr, "%x ", UTF8(*i));
}
TEST_EQUAL(out8 - &utf8[0], utf8_source_len);
TEST_CHECK(std::equal(&utf8[0], out8, (UTF8 const*)utf8_source));
}
// utf8 -> utf32 -> utf16 -> utf8
{
std::vector<UTF32> utf32(utf8_source_len);
UTF8 const* in8 = (UTF8 const*)utf8_source;
UTF32* out32 = &utf32[0];
ConversionResult ret = ConvertUTF8toUTF32(&in8, in8 + utf8_source_len
, &out32, out32 + utf32.size(), strictConversion);
TEST_EQUAL(ret, conversionOK);
if (ret != conversionOK && utf8_source_len < 10)
{
for (char const* i = utf8_source; *i != 0; ++i)
fprintf(stderr, "%x ", UTF8(*i));
}
std::vector<UTF16> utf16(utf8_source_len);
UTF32 const* in32 = &utf32[0];
UTF16* out16 = &utf16[0];
ret = ConvertUTF32toUTF16(&in32, out32
, &out16, out16 + utf16.size(), strictConversion);
TEST_EQUAL(ret, conversionOK);
if (ret != conversionOK && utf8_source_len < 10)
{
for (char const* i = utf8_source; *i != 0; ++i)
fprintf(stderr, "%x ", UTF8(*i));
}
std::vector<UTF8> utf8(utf8_source_len);
UTF16 const* in16 = &utf16[0];
UTF8* out8 = &utf8[0];
ret = ConvertUTF16toUTF8(&in16, out16
, &out8, out8 + utf8.size(), strictConversion);
TEST_EQUAL(ret, conversionOK);
if (ret != conversionOK && utf8_source_len < 10)
{
for (char const* i = utf8_source; *i != 0; ++i)
fprintf(stderr, "%x ", UTF8(*i));
}
TEST_EQUAL(out8 - &utf8[0], utf8_source_len);
TEST_CHECK(std::equal(&utf8[0], out8, (UTF8 const*)utf8_source));
}
}
void expect_error(char const* utf8, ConversionResult expect)
{
UTF8 const* in8 = (UTF8 const*)utf8;
std::vector<UTF32> utf32(strlen(utf8));
UTF32* out32 = &utf32[0];
ConversionResult ret = ConvertUTF8toUTF32(&in8, in8 + strlen(utf8)
, &out32, out32 + utf32.size(), strictConversion);
TEST_EQUAL(ret, expect);
if (ret != expect)
{
fprintf(stderr, "%d expected %d\n", ret, expect);
for (char const* i = utf8; *i != 0; ++i)
fprintf(stderr, "%x ", UTF8(*i));
}
in8 = (UTF8 const*)utf8;
std::vector<UTF16> utf16(strlen(utf8));
UTF16* out16 = &utf16[0];
ret = ConvertUTF8toUTF16(&in8, in8 + strlen(utf8)
, &out16, out16 + utf16.size(), strictConversion);
TEST_EQUAL(ret, expect);
if (ret != expect)
{
fprintf(stderr, "%d expected %d\n", ret, expect);
for (char const* i = utf8; *i != 0; ++i)
fprintf(stderr, "%x ", UTF8(*i));
}
}
int test_main()
{
std::vector<char> utf8_source;
error_code ec;
load_file(combine_path("..", "utf8_test.txt"), utf8_source, ec, 1000000);
if (ec) fprintf(stderr, "failed to open file: (%d) %s\n", ec.value()
, ec.message().c_str());
TEST_CHECK(!ec);
// test lower level conversions
verify_transforms(&utf8_source[0], utf8_source.size());
verify_transforms("\xc3\xb0");
verify_transforms("\xed\x9f\xbf");
verify_transforms("\xee\x80\x80");
verify_transforms("\xef\xbf\xbd");
verify_transforms("\xf4\x8f\xbf\xbf");
verify_transforms("\xf0\x91\x80\x80\x30");
// Unexpected continuation bytes
expect_error("\x80", sourceIllegal);
expect_error("\xbf", sourceIllegal);
// Impossible bytes
// The following two bytes cannot appear in a correct UTF-8 string
expect_error("\xff", sourceExhausted);
expect_error("\xfe", sourceExhausted);
expect_error("\xff\xff\xfe\xfe", sourceExhausted);
// Examples of an overlong ASCII character
expect_error("\xc0\xaf", sourceIllegal);
expect_error("\xe0\x80\xaf", sourceIllegal);
expect_error("\xf0\x80\x80\xaf", sourceIllegal);
expect_error("\xf8\x80\x80\x80\xaf ", sourceIllegal);
expect_error("\xfc\x80\x80\x80\x80\xaf", sourceIllegal);
// Maximum overlong sequences
expect_error("\xc1\xbf", sourceIllegal);
expect_error("\xe0\x9f\xbf", sourceIllegal);
expect_error("\xf0\x8f\xbf\xbf", sourceIllegal);
expect_error("\xf8\x87\xbf\xbf\xbf", sourceIllegal);
expect_error("\xfc\x83\xbf\xbf\xbf\xbf", sourceIllegal);
// Overlong representation of the NUL character
expect_error("\xc0\x80", sourceIllegal);
expect_error("\xe0\x80\x80", sourceIllegal);
expect_error("\xf0\x80\x80\x80", sourceIllegal);
expect_error("\xf8\x80\x80\x80\x80", sourceIllegal);
expect_error("\xfc\x80\x80\x80\x80\x80", sourceIllegal);
// Single UTF-16 surrogates
expect_error("\xed\xa0\x80", sourceIllegal);
expect_error("\xed\xad\xbf", sourceIllegal);
expect_error("\xed\xae\x80", sourceIllegal);
expect_error("\xed\xaf\xbf", sourceIllegal);
expect_error("\xed\xb0\x80", sourceIllegal);
expect_error("\xed\xbe\x80", sourceIllegal);
expect_error("\xed\xbf\xbf", sourceIllegal);
// Paired UTF-16 surrogates
expect_error("\xed\xa0\x80\xed\xb0\x80", sourceIllegal);
expect_error("\xed\xa0\x80\xed\xbf\xbf", sourceIllegal);
expect_error("\xed\xad\xbf\xed\xb0\x80", sourceIllegal);
expect_error("\xed\xad\xbf\xed\xbf\xbf", sourceIllegal);
expect_error("\xed\xae\x80\xed\xb0\x80", sourceIllegal);
expect_error("\xed\xae\x80\xed\xbf\xbf", sourceIllegal);
expect_error("\xed\xaf\xbf\xed\xb0\x80", sourceIllegal);
expect_error("\xed\xaf\xbf\xed\xbf\xbf", sourceIllegal);
// test higher level conversions
std::string utf8;
std::copy(utf8_source.begin(), utf8_source.end(), std::back_inserter(utf8));
std::wstring wide;
utf8_conv_result_t ret = utf8_wchar(utf8, wide);
TEST_EQUAL(ret, conversion_ok);
std::string identity;
ret = wchar_utf8(wide, identity);
TEST_EQUAL(ret, conversion_ok);
TEST_EQUAL(utf8, identity);
return 0;
}
<|endoftext|> |
<commit_before>/*******************************************************************************
**
** Filename : util
** Created on : 03 April, 2005
** Copyright : (c) 2005 Till Adam
** Email : <[email protected]>
**
*******************************************************************************/
/*******************************************************************************
**
** This program is free software; you can redistribute it and/or modify
** it under the terms of the GNU General Public License as published by
** the Free Software Foundation; either version 2 of the License, or
** (at your option) any later version.
**
** It is distributed in the hope that it will be useful, but
** WITHOUT ANY WARRANTY; without even the implied warranty of
** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
** General Public License for more details.
**
** You should have received a copy of the GNU General Public License
** along with this program; if not, write to the Free Software
** Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
**
** In addition, as a special exception, the copyright holders give
** permission to link the code of this program with any edition of
** the Qt library by Trolltech AS, Norway (or with modified versions
** of Qt that use the same license as Qt), and distribute linked
** combinations including the two. You must obey the GNU General
** Public License in all respects for all of the code used other than
** Qt. If you modify this file, you may extend this exception to
** your version of the file, but you are not obligated to do so. If
** you do not wish to do so, delete this exception statement from
** your version.
**
*******************************************************************************/
#include "util.h"
#include <stdlib.h>
#include <mimelib/string.h>
void KMail::Util::reconnectSignalSlotPair( QObject *src, const char *signal, QObject *dst, const char *slot )
{
QObject::disconnect( src, signal, dst, slot );
QObject::connect( src, signal, dst, slot );
}
size_t KMail::Util::crlf2lf( char* str, const size_t strLen )
{
if ( !str || strLen == 0 )
return 0;
const char* source = str;
const char* sourceEnd = source + strLen;
// search the first occurrence of "\r\n"
for ( ; source < sourceEnd - 1; ++source ) {
if ( *source == '\r' && *( source + 1 ) == '\n' )
break;
}
if ( source == sourceEnd - 1 ) {
// no "\r\n" found
return strLen;
}
// replace all occurrences of "\r\n" with "\n" (in place)
char* target = const_cast<char*>( source ); // target points to '\r'
++source; // source points to '\n'
for ( ; source < sourceEnd; ++source ) {
if ( *source != '\r' || *( source + 1 ) != '\n' )
* target++ = *source;
}
*target = '\0'; // terminate result
return target - str;
}
QByteArray KMail::Util::lf2crlf( const QByteArray & src )
{
QByteArray result;
result.resize( 2*src.size() ); // maximal possible length
QByteArray::ConstIterator s = src.begin();
QByteArray::Iterator d = result.begin();
// we use cPrev to make sure we insert '\r' only there where it is missing
char cPrev = '?';
const char* end = src.end();
while ( s != end ) {
if ( ('\n' == *s) && ('\r' != cPrev) )
*d++ = '\r';
cPrev = *s;
*d++ = *s++;
}
result.truncate( d - result.begin() );
return result;
}
QByteArray KMail::Util::ByteArray( const DwString& str )
{
const int strLen = str.size();
QByteArray arr;
arr.resize( strLen );
memcpy( arr.data(), str.data(), strLen );
return arr;
}
DwString KMail::Util::dwString( const QByteArray& str )
{
if ( !str.data() ) // DwString doesn't like char*=0
return DwString();
return DwString( str.data(), str.size() );
}
bool KMail::Util::checkOverwrite( const KUrl &url, QWidget *w )
{
if ( KIO::NetAccess::exists( url, KIO::NetAccess::DestinationSide, w ) ) {
if ( KMessageBox::Cancel == KMessageBox::warningContinueCancel(
w,
i18n( "A file named \"%1\" already exists. "
"Are you sure you want to overwrite it?", url.prettyUrl() ),
i18n( "Overwrite File?" ),
KStandardGuiItem::overwrite() ) )
return false;
}
return true;
}
#ifdef Q_WS_MACX
#include <QDesktopServices>
#endif
bool KMail::Util::handleUrlOnMac( const KUrl& url )
{
#ifdef Q_WS_MACX
QDesktopServices::openUrl( url );
return true;
#else
Q_UNUSED( url );
return false;
#endif
}
KMail::Util::RecursionPreventer::RecursionPreventer( int &counter )
: mCounter( counter )
{
mCounter++;
}
KMail::Util::RecursionPreventer::~RecursionPreventer()
{
mCounter--;
}
bool KMail::Util::RecursionPreventer::isRecursive() const
{
return mCounter > 1;
}<commit_msg>Fix minor krazy issue: source files should end with newlines.<commit_after>/*******************************************************************************
**
** Filename : util
** Created on : 03 April, 2005
** Copyright : (c) 2005 Till Adam
** Email : <[email protected]>
**
*******************************************************************************/
/*******************************************************************************
**
** This program is free software; you can redistribute it and/or modify
** it under the terms of the GNU General Public License as published by
** the Free Software Foundation; either version 2 of the License, or
** (at your option) any later version.
**
** It is distributed in the hope that it will be useful, but
** WITHOUT ANY WARRANTY; without even the implied warranty of
** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
** General Public License for more details.
**
** You should have received a copy of the GNU General Public License
** along with this program; if not, write to the Free Software
** Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
**
** In addition, as a special exception, the copyright holders give
** permission to link the code of this program with any edition of
** the Qt library by Trolltech AS, Norway (or with modified versions
** of Qt that use the same license as Qt), and distribute linked
** combinations including the two. You must obey the GNU General
** Public License in all respects for all of the code used other than
** Qt. If you modify this file, you may extend this exception to
** your version of the file, but you are not obligated to do so. If
** you do not wish to do so, delete this exception statement from
** your version.
**
*******************************************************************************/
#include "util.h"
#include <stdlib.h>
#include <mimelib/string.h>
void KMail::Util::reconnectSignalSlotPair( QObject *src, const char *signal, QObject *dst, const char *slot )
{
QObject::disconnect( src, signal, dst, slot );
QObject::connect( src, signal, dst, slot );
}
size_t KMail::Util::crlf2lf( char* str, const size_t strLen )
{
if ( !str || strLen == 0 )
return 0;
const char* source = str;
const char* sourceEnd = source + strLen;
// search the first occurrence of "\r\n"
for ( ; source < sourceEnd - 1; ++source ) {
if ( *source == '\r' && *( source + 1 ) == '\n' )
break;
}
if ( source == sourceEnd - 1 ) {
// no "\r\n" found
return strLen;
}
// replace all occurrences of "\r\n" with "\n" (in place)
char* target = const_cast<char*>( source ); // target points to '\r'
++source; // source points to '\n'
for ( ; source < sourceEnd; ++source ) {
if ( *source != '\r' || *( source + 1 ) != '\n' )
* target++ = *source;
}
*target = '\0'; // terminate result
return target - str;
}
QByteArray KMail::Util::lf2crlf( const QByteArray & src )
{
QByteArray result;
result.resize( 2*src.size() ); // maximal possible length
QByteArray::ConstIterator s = src.begin();
QByteArray::Iterator d = result.begin();
// we use cPrev to make sure we insert '\r' only there where it is missing
char cPrev = '?';
const char* end = src.end();
while ( s != end ) {
if ( ('\n' == *s) && ('\r' != cPrev) )
*d++ = '\r';
cPrev = *s;
*d++ = *s++;
}
result.truncate( d - result.begin() );
return result;
}
QByteArray KMail::Util::ByteArray( const DwString& str )
{
const int strLen = str.size();
QByteArray arr;
arr.resize( strLen );
memcpy( arr.data(), str.data(), strLen );
return arr;
}
DwString KMail::Util::dwString( const QByteArray& str )
{
if ( !str.data() ) // DwString doesn't like char*=0
return DwString();
return DwString( str.data(), str.size() );
}
bool KMail::Util::checkOverwrite( const KUrl &url, QWidget *w )
{
if ( KIO::NetAccess::exists( url, KIO::NetAccess::DestinationSide, w ) ) {
if ( KMessageBox::Cancel == KMessageBox::warningContinueCancel(
w,
i18n( "A file named \"%1\" already exists. "
"Are you sure you want to overwrite it?", url.prettyUrl() ),
i18n( "Overwrite File?" ),
KStandardGuiItem::overwrite() ) )
return false;
}
return true;
}
#ifdef Q_WS_MACX
#include <QDesktopServices>
#endif
bool KMail::Util::handleUrlOnMac( const KUrl& url )
{
#ifdef Q_WS_MACX
QDesktopServices::openUrl( url );
return true;
#else
Q_UNUSED( url );
return false;
#endif
}
KMail::Util::RecursionPreventer::RecursionPreventer( int &counter )
: mCounter( counter )
{
mCounter++;
}
KMail::Util::RecursionPreventer::~RecursionPreventer()
{
mCounter--;
}
bool KMail::Util::RecursionPreventer::isRecursive() const
{
return mCounter > 1;
}
<|endoftext|> |
<commit_before>/*!
\copyright (c) RDO-Team, 2011
\file main.cpp
\authors
\authors ([email protected])
\authors ([email protected])
\date 13.12.2009
\brief
\indent 4T
*/
// ---------------------------------------------------------------------------- PCH
// ----------------------------------------------------------------------- INCLUDES
#include <iostream>
#include <stdio.h>
#define BOOST_TEST_MODULE RDORuntime_Array_Test
#include <boost/test/included/unit_test.hpp>
// ----------------------------------------------------------------------- SYNOPSIS
#include "simulator/runtime/rdo_value.h"
#include "simulator/runtime/rdo_array.h"
#include "simulator/runtime/rdo_type.h"
// --------------------------------------------------------------------------------
BOOST_AUTO_TEST_SUITE(RDORuntime_Array_Test)
typedef rdo::vector<rsint> Container;
typedef std::pair<rdoRuntime::LPRDOArrayValue, rdoRuntime::RDOValue> Array;
Array createArray(CREF(Container) data)
{
rdoRuntime::LPRDOArrayType pType = rdo::Factory<rdoRuntime::RDOArrayType>::create(rdoRuntime::g_int);
ASSERT(pType);
rdoRuntime::LPRDOArrayValue pValue = rdo::Factory<rdoRuntime::RDOArrayValue>::create(pType);
ASSERT(pValue);
STL_FOR_ALL_CONST(data, it)
{
pValue->push_back(rdoRuntime::RDOValue(*it));
}
return std::make_pair(pValue, rdoRuntime::RDOValue(pType, pValue));
}
tstring getString(CREF(rdoRuntime::LPRDOArrayValue) pArray, CREF(rdoRuntime::LPRDOArrayIterator) pIt)
{
if (!pIt->equal(pArray->end()))
{
return pIt->getValue().getAsString();
}
return _T("");
}
tstring getString(CREF(rdoRuntime::RDOValue) it, CREF(rdoRuntime::RDOValue) end)
{
if (it != end)
{
return it.getAsString();
}
return _T("");
}
BOOST_AUTO_TEST_CASE(ArrayTestCreate)
{
BOOST_CHECK(createArray(Container()(1)(2)(3)).second.getAsString() == _T("[1, 2, 3]"));
}
BOOST_AUTO_TEST_CASE(ArrayTestInsert)
{
Array array1 = createArray(Container()(1)(2)(3));
Array array2 = createArray(Container()(4)(5)(6));
array1.first->insert(array1.first->begin()->next(), array2.first->begin(), array2.first->end());
BOOST_CHECK(array1.second.getAsString() == _T("[1, 4, 5, 6, 2, 3]"));
}
BOOST_AUTO_TEST_CASE(ArrayTestErase)
{
Array array = createArray(Container()(1)(2)(3));
array.first->erase(array.first->begin()->next(), array.first->begin()->preInc(3));
BOOST_CHECK(array.second.getAsString() == _T("[1]"));
}
BOOST_AUTO_TEST_CASE(ArrayTestIteratorPrePlus)
{
Array array = createArray(Container()(1)(2)(3));
tstring result;
rdoRuntime::LPRDOArrayIterator pIt = array.first->begin();
while (!pIt->equal(array.first->end()))
{
result += getString(array.first, pIt->preInc(1));
}
BOOST_CHECK(result == _T("23"));
}
BOOST_AUTO_TEST_CASE(ArrayTestIteratorPostPlus)
{
Array array = createArray(Container()(1)(2)(3));
tstring result;
rdoRuntime::LPRDOArrayIterator pIt = array.first->begin();
while (!pIt->equal(array.first->end()))
{
result += getString(array.first, pIt->postInc(1));
}
BOOST_CHECK(result == _T("123"));
}
BOOST_AUTO_TEST_CASE(ArrayTestIteratorPreMinus)
{
Array array = createArray(Container()(1)(2)(3));
tstring result;
rdoRuntime::LPRDOArrayIterator pIt = array.first->end();
do
{
result += getString(array.first, pIt->preInc(-1));
}
while (!pIt->equal(array.first->begin()));
BOOST_CHECK(result == _T("321"));
}
BOOST_AUTO_TEST_CASE(ArrayTestIteratorPostMinus)
{
Array array = createArray(Container()(1)(2)(3));
tstring result;
rdoRuntime::LPRDOArrayIterator pIt = array.first->end();
do
{
result += getString(array.first, pIt->postInc(-1));
}
while (!pIt->equal(array.first->begin()));
BOOST_CHECK(result == _T("32"));
}
BOOST_AUTO_TEST_CASE(ArrayTestValuePrePlus)
{
Array array = createArray(Container()(1)(2)(3));
tstring result;
rdoRuntime::LPRDOArrayIterator pIt = array.first->begin();
rdoRuntime::LPRDOArrayIterator pEnd = array.first->end ();
rdoRuntime::RDOValue it (pIt, pIt );
rdoRuntime::RDOValue end(pEnd, pEnd);
BOOST_CHECK(it != end);
while (it != end)
{
result += getString(++it, end);
}
BOOST_CHECK(result == _T("23"));
}
BOOST_AUTO_TEST_CASE(ArrayTestValuePostPlus)
{
Array array = createArray(Container()(1)(2)(3));
tstring result;
rdoRuntime::LPRDOArrayIterator pIt = array.first->begin();
rdoRuntime::LPRDOArrayIterator pEnd = array.first->end ();
rdoRuntime::RDOValue it (pIt, pIt );
rdoRuntime::RDOValue end(pEnd, pEnd);
BOOST_CHECK(it != end);
while (it != end)
{
result += getString(it++, end);
}
BOOST_CHECK(result == _T("123"));
}
BOOST_AUTO_TEST_CASE(ArrayTestValuePreMinus)
{
Array array = createArray(Container()(1)(2)(3));
tstring result;
rdoRuntime::LPRDOArrayIterator pIt = array.first->end ();
rdoRuntime::LPRDOArrayIterator pBegin = array.first->begin();
rdoRuntime::LPRDOArrayIterator pEnd = array.first->end ();
rdoRuntime::RDOValue it (pIt, pIt );
rdoRuntime::RDOValue begin(pBegin, pBegin);
rdoRuntime::RDOValue end (pEnd, pEnd );
BOOST_CHECK(it != begin);
BOOST_CHECK(it == end );
do
{
result += getString(--it, end);
}
while (it != begin);
BOOST_CHECK(result == _T("321"));
}
BOOST_AUTO_TEST_CASE(ArrayTestValuePostMinus)
{
Array array = createArray(Container()(1)(2)(3));
tstring result;
rdoRuntime::LPRDOArrayIterator pIt = array.first->end ();
rdoRuntime::LPRDOArrayIterator pBegin = array.first->begin();
rdoRuntime::LPRDOArrayIterator pEnd = array.first->end ();
rdoRuntime::RDOValue it (pIt, pIt );
rdoRuntime::RDOValue begin(pBegin, pBegin);
rdoRuntime::RDOValue end (pEnd, pEnd );
BOOST_CHECK(it != begin);
BOOST_CHECK(it == end );
do
{
result += getString(it--, end);
}
while (it != begin);
BOOST_CHECK(result == _T("32"));
}
BOOST_AUTO_TEST_CASE(ArrayTestSetItem)
{
Array array = createArray(Container()(1)(2)(3));
rdoRuntime::LPRDORuntime pRuntime = rdo::Factory<rdoRuntime::RDORuntime>::create();
ruint ind = 1;
ruint item = 48;
rdoRuntime::RDOValue index (ind);
rdoRuntime::RDOValue value (item);
array.first->setItem(index, value);
BOOST_CHECK(array.second.getAsString() == _T("[1, 48, 3]"));
ind = 3;
index = ind;
rbool found = false;
try
{
array.first->setItem(index, value);
}
catch (rdoRuntime::RDORuntimeException ex)
{
if (! ex.message().empty())
{
found = ex.message() == _T(" ");
}
}
if (!found)
BOOST_CHECK(false);
}
BOOST_AUTO_TEST_CASE(ArrayTestGetItem)
{
Array array = createArray(Container()(1)(48)(3));
rdoRuntime::LPRDORuntime pRuntime = rdo::Factory<rdoRuntime::RDORuntime>::create();
ruint ind = 1;
rdoRuntime::RDOValue index (ind);
rdoRuntime::RDOValue value (array.first->getItem(index));
BOOST_CHECK(value.getAsString() == _T("48"));
ind = 3;
index = ind;
rbool found = false;
try
{
array.first->getItem(index);
}
catch (rdoRuntime::RDORuntimeException ex)
{
if (! ex.message().empty())
{
found = ex.message() == _T(" ");
}
}
if (!found)
BOOST_CHECK(false);
}
BOOST_AUTO_TEST_SUITE_END() // RDORuntime_Array_Test
<commit_msg> - использование CREF - форматирование<commit_after>/*!
\copyright (c) RDO-Team, 2011
\file main.cpp
\authors
\authors ([email protected])
\authors ([email protected])
\date 13.12.2009
\brief
\indent 4T
*/
// ---------------------------------------------------------------------------- PCH
// ----------------------------------------------------------------------- INCLUDES
#include <iostream>
#include <stdio.h>
#define BOOST_TEST_MODULE RDORuntime_Array_Test
#include <boost/test/included/unit_test.hpp>
// ----------------------------------------------------------------------- SYNOPSIS
#include "simulator/runtime/rdo_value.h"
#include "simulator/runtime/rdo_array.h"
#include "simulator/runtime/rdo_type.h"
// --------------------------------------------------------------------------------
BOOST_AUTO_TEST_SUITE(RDORuntime_Array_Test)
typedef rdo::vector<rsint> Container;
typedef std::pair<rdoRuntime::LPRDOArrayValue, rdoRuntime::RDOValue> Array;
Array createArray(CREF(Container) data)
{
rdoRuntime::LPRDOArrayType pType = rdo::Factory<rdoRuntime::RDOArrayType>::create(rdoRuntime::g_int);
ASSERT(pType);
rdoRuntime::LPRDOArrayValue pValue = rdo::Factory<rdoRuntime::RDOArrayValue>::create(pType);
ASSERT(pValue);
STL_FOR_ALL_CONST(data, it)
{
pValue->push_back(rdoRuntime::RDOValue(*it));
}
return std::make_pair(pValue, rdoRuntime::RDOValue(pType, pValue));
}
tstring getString(CREF(rdoRuntime::LPRDOArrayValue) pArray, CREF(rdoRuntime::LPRDOArrayIterator) pIt)
{
if (!pIt->equal(pArray->end()))
{
return pIt->getValue().getAsString();
}
return _T("");
}
tstring getString(CREF(rdoRuntime::RDOValue) it, CREF(rdoRuntime::RDOValue) end)
{
if (it != end)
{
return it.getAsString();
}
return _T("");
}
BOOST_AUTO_TEST_CASE(ArrayTestCreate)
{
BOOST_CHECK(createArray(Container()(1)(2)(3)).second.getAsString() == _T("[1, 2, 3]"));
}
BOOST_AUTO_TEST_CASE(ArrayTestInsert)
{
Array array1 = createArray(Container()(1)(2)(3));
Array array2 = createArray(Container()(4)(5)(6));
array1.first->insert(array1.first->begin()->next(), array2.first->begin(), array2.first->end());
BOOST_CHECK(array1.second.getAsString() == _T("[1, 4, 5, 6, 2, 3]"));
}
BOOST_AUTO_TEST_CASE(ArrayTestErase)
{
Array array = createArray(Container()(1)(2)(3));
array.first->erase(array.first->begin()->next(), array.first->begin()->preInc(3));
BOOST_CHECK(array.second.getAsString() == _T("[1]"));
}
BOOST_AUTO_TEST_CASE(ArrayTestIteratorPrePlus)
{
Array array = createArray(Container()(1)(2)(3));
tstring result;
rdoRuntime::LPRDOArrayIterator pIt = array.first->begin();
while (!pIt->equal(array.first->end()))
{
result += getString(array.first, pIt->preInc(1));
}
BOOST_CHECK(result == _T("23"));
}
BOOST_AUTO_TEST_CASE(ArrayTestIteratorPostPlus)
{
Array array = createArray(Container()(1)(2)(3));
tstring result;
rdoRuntime::LPRDOArrayIterator pIt = array.first->begin();
while (!pIt->equal(array.first->end()))
{
result += getString(array.first, pIt->postInc(1));
}
BOOST_CHECK(result == _T("123"));
}
BOOST_AUTO_TEST_CASE(ArrayTestIteratorPreMinus)
{
Array array = createArray(Container()(1)(2)(3));
tstring result;
rdoRuntime::LPRDOArrayIterator pIt = array.first->end();
do
{
result += getString(array.first, pIt->preInc(-1));
}
while (!pIt->equal(array.first->begin()));
BOOST_CHECK(result == _T("321"));
}
BOOST_AUTO_TEST_CASE(ArrayTestIteratorPostMinus)
{
Array array = createArray(Container()(1)(2)(3));
tstring result;
rdoRuntime::LPRDOArrayIterator pIt = array.first->end();
do
{
result += getString(array.first, pIt->postInc(-1));
}
while (!pIt->equal(array.first->begin()));
BOOST_CHECK(result == _T("32"));
}
BOOST_AUTO_TEST_CASE(ArrayTestValuePrePlus)
{
Array array = createArray(Container()(1)(2)(3));
tstring result;
rdoRuntime::LPRDOArrayIterator pIt = array.first->begin();
rdoRuntime::LPRDOArrayIterator pEnd = array.first->end ();
rdoRuntime::RDOValue it (pIt, pIt );
rdoRuntime::RDOValue end(pEnd, pEnd);
BOOST_CHECK(it != end);
while (it != end)
{
result += getString(++it, end);
}
BOOST_CHECK(result == _T("23"));
}
BOOST_AUTO_TEST_CASE(ArrayTestValuePostPlus)
{
Array array = createArray(Container()(1)(2)(3));
tstring result;
rdoRuntime::LPRDOArrayIterator pIt = array.first->begin();
rdoRuntime::LPRDOArrayIterator pEnd = array.first->end ();
rdoRuntime::RDOValue it (pIt, pIt );
rdoRuntime::RDOValue end(pEnd, pEnd);
BOOST_CHECK(it != end);
while (it != end)
{
result += getString(it++, end);
}
BOOST_CHECK(result == _T("123"));
}
BOOST_AUTO_TEST_CASE(ArrayTestValuePreMinus)
{
Array array = createArray(Container()(1)(2)(3));
tstring result;
rdoRuntime::LPRDOArrayIterator pIt = array.first->end ();
rdoRuntime::LPRDOArrayIterator pBegin = array.first->begin();
rdoRuntime::LPRDOArrayIterator pEnd = array.first->end ();
rdoRuntime::RDOValue it (pIt, pIt );
rdoRuntime::RDOValue begin(pBegin, pBegin);
rdoRuntime::RDOValue end (pEnd, pEnd );
BOOST_CHECK(it != begin);
BOOST_CHECK(it == end );
do
{
result += getString(--it, end);
}
while (it != begin);
BOOST_CHECK(result == _T("321"));
}
BOOST_AUTO_TEST_CASE(ArrayTestValuePostMinus)
{
Array array = createArray(Container()(1)(2)(3));
tstring result;
rdoRuntime::LPRDOArrayIterator pIt = array.first->end ();
rdoRuntime::LPRDOArrayIterator pBegin = array.first->begin();
rdoRuntime::LPRDOArrayIterator pEnd = array.first->end ();
rdoRuntime::RDOValue it (pIt, pIt );
rdoRuntime::RDOValue begin(pBegin, pBegin);
rdoRuntime::RDOValue end (pEnd, pEnd );
BOOST_CHECK(it != begin);
BOOST_CHECK(it == end );
do
{
result += getString(it--, end);
}
while (it != begin);
BOOST_CHECK(result == _T("32"));
}
BOOST_AUTO_TEST_CASE(ArrayTestSetItem)
{
Array array = createArray(Container()(1)(2)(3));
rdoRuntime::LPRDORuntime pRuntime = rdo::Factory<rdoRuntime::RDORuntime>::create();
ruint ind = 1;
ruint item = 48;
rdoRuntime::RDOValue index(ind);
rdoRuntime::RDOValue value(item);
array.first->setItem(index, value);
BOOST_CHECK(array.second.getAsString() == _T("[1, 48, 3]"));
ind = 3;
index = ind;
rbool found = false;
try
{
array.first->setItem(index, value);
}
catch (CREF(rdoRuntime::RDORuntimeException) ex)
{
if (!ex.message().empty())
{
found = ex.message() == _T(" ");
}
}
if (!found)
{
BOOST_CHECK(false);
}
}
BOOST_AUTO_TEST_CASE(ArrayTestGetItem)
{
Array array = createArray(Container()(1)(48)(3));
rdoRuntime::LPRDORuntime pRuntime = rdo::Factory<rdoRuntime::RDORuntime>::create();
ruint ind = 1;
rdoRuntime::RDOValue index(ind);
rdoRuntime::RDOValue value(array.first->getItem(index));
BOOST_CHECK(value.getAsString() == _T("48"));
ind = 3;
index = ind;
rbool found = false;
try
{
array.first->getItem(index);
}
catch (CREF(rdoRuntime::RDORuntimeException) ex)
{
if (!ex.message().empty())
{
found = ex.message() == _T(" ");
}
}
if (!found)
{
BOOST_CHECK(false);
}
}
BOOST_AUTO_TEST_SUITE_END() // RDORuntime_Array_Test
<|endoftext|> |
<commit_before><commit_msg>coverity#705153 Missing break in switch, surely this is not intentional<commit_after><|endoftext|> |
<commit_before>/* Jim Viebke
Jun 3 2015 */
#include "non_player_character.h"
void NPC::a_star_pathfind(const int & x_dest, const int & y_dest, World & world)
{
cout << "\nSearching for path from " << x << "," << y << " to " << x_dest << "," << y_dest << ".\n";
/* F = G + H
G: actual cost to reach a certain room
H: estimated cost to reach destination from a certain room
f-cost = g + h */
vector<Node> open_list, closed_list;
// Add current room to open list.
open_list.push_back(Node(this->x, this->y, ""));
// calculate current room's costs. G cost starts at 0.
open_list[0].set_g_h_f(0, R::diagonal_distance(x_dest, y_dest, this->x, this->y));
// Do
do
{
/*// -- Find lowest f-cost room on open list
// -- Move it to closed list
Node current_room = move_and_get_lowest_f_cost(open_list, closed_list); */
// work through every open room
Node current_room = open_list[0]; // copy
closed_list.push_back(current_room); // move to closed
open_list.erase(open_list.begin()); // erase original
// -- For each adjacent room to current
for (const string & direction : C::direction_ids)
{
if (direction == C::UP || direction == C::DOWN) { continue; } // only pathfinding in 2D now
// calculate the location deltas
int dx = 0, dy = 0, dz = 0;
R::assign_movement_deltas(direction, dx, dy, dz);
// skip if the room is out of bounds
if (!R::bounds_check(current_room.x + dx, current_room.y + dy, C::GROUND_INDEX)) { continue; }
// skip the room if it is not loaded
if (world.room_at(current_room.x + dx, current_room.y + dy, C::GROUND_INDEX) == nullptr) { continue; }
// skip the room if it is not within view distance
if (!world.room_at(current_room.x + dx, current_room.y + dy, C::GROUND_INDEX)->is_observed_by(this->name)) { continue; }
// create a node to select the next adjacent room
Node adjacent_room(current_room.x + dx, current_room.y + dy, direction);
// -- -- pass if it is on the closed list
if (room_in_node_list(adjacent_room.x, adjacent_room.y, closed_list)) { continue; }
// -- -- pass if we can not travel to it from the current room
if (validate_movement(current_room.x, current_room.y, C::GROUND_INDEX, direction, dx, dy, 0, world) != C::GOOD_SIGNAL) { continue; }
// -- -- if room is not on open list
if (!room_in_node_list(adjacent_room.x, adjacent_room.y, open_list))
{
// -- -- -- Make current room the parent of adjacent
adjacent_room.parent_x = current_room.x;
adjacent_room.parent_y = current_room.y;
// -- -- -- Record F, G, H costs of room
adjacent_room.set_g_h_f(
current_room.g + (R::contains(C::primary_direction_ids, direction) ? C::AI_MOVEMENT_COST : C::AI_MOVEMENT_COST_DIAGONAL), // check if the movement is non-diagonal or diagonal
R::diagonal_distance(x_dest, y_dest, adjacent_room.x, adjacent_room.y));
}
// -- -- (else room is on open list)
else
{
// pull adjacent_room out of open_list
for (unsigned i = 0; i < open_list.size(); ++i) // for each node in the open list
{
if (open_list[i].x == adjacent_room.x && open_list[i].y == adjacent_room.y) // if the node is the current room
{
adjacent_room = get_node_at(adjacent_room.x, adjacent_room.y, open_list); // save it
open_list.erase(open_list.begin() + i); // erase the original
break; // adjacent_room is now the one from the list
}
}
// -- -- if this g-cost to room is less than current g-cost to room
if (current_room.g + (R::contains(C::primary_direction_ids, direction) ? C::AI_MOVEMENT_COST : C::AI_MOVEMENT_COST_DIAGONAL) < adjacent_room.g)
{
// -- -- -- update current room to new parent of room
adjacent_room.parent_x = current_room.x;
adjacent_room.parent_y = current_room.y;
// -- -- -- update costs
adjacent_room.set_g_h_f(
current_room.g + (R::contains(C::primary_direction_ids, direction) ? C::AI_MOVEMENT_COST : C::AI_MOVEMENT_COST_DIAGONAL), // check if the movement is non-diagonal or diagonal
R::diagonal_distance(x_dest, y_dest, adjacent_room.x, adjacent_room.y));
}
}
// -- -- -- Add room to open list
open_list.push_back(adjacent_room);
} // end for each adjacent room
// keep searching if we have not reached the destination OR there are still rooms to search
} while (!room_in_node_list(x_dest, y_dest, closed_list) || open_list.size() > 0);
// Starting from target room, continue finding parent until the current room is found
// (this represents the path in reverse)
// get the target room
Node current_room = get_node_at(x_dest, y_dest, closed_list);
// if there is no target room in the closed list, a path could not be found
if (current_room.x == -1 || current_room.y == -1) { return; }
do
{
// get the parent room
Node parent_room = get_node_at(current_room.parent_x, current_room.parent_y, closed_list);
cout << "\nI can get to " << current_room.x << "," << current_room.y << " from " << parent_room.x << "," << parent_room.y << ".";
// if the parent of current_room is our location, move to current_room
if (parent_room.x == this->x && parent_room.y == this->y)
{
// move to current
//this->move(C::opposite_direction_id.find(current_room.direction_from_parent)->second, world);
move(current_room.direction_from_parent, world);
// debugging
cout << endl;
for (const Node & node : closed_list)
{
cout << "Parent of " << node.x << "," << node.y << " is " << node.parent_x << "," << node.parent_y << endl <<
"Actual cost to reach this node: " << node.g << ". Estimated cost to target: " << node.h << endl << endl;
}
return; // we're done here
}
// if there is no parent room in the closed list (?!)
else if (parent_room.x == -1 || parent_room.y == -1)
{
return; // something went horribly wrong
}
// move up the path by one room
current_room = parent_room;
} while (true);
}
<commit_msg>comment out debug code<commit_after>/* Jim Viebke
Jun 3 2015 */
#include "non_player_character.h"
void NPC::a_star_pathfind(const int & x_dest, const int & y_dest, World & world)
{
// leave this for debugging
// cout << "\nSearching for path from " << x << "," << y << " to " << x_dest << "," << y_dest << ".\n";
/* F = G + H
G: actual cost to reach a certain room
H: estimated cost to reach destination from a certain room
f-cost = g + h */
vector<Node> open_list, closed_list;
// Add current room to open list.
open_list.push_back(Node(this->x, this->y, ""));
// calculate current room's costs. G cost starts at 0.
open_list[0].set_g_h_f(0, R::diagonal_distance(x_dest, y_dest, this->x, this->y));
// Do
do
{
/*// -- Find lowest f-cost room on open list
// -- Move it to closed list
Node current_room = move_and_get_lowest_f_cost(open_list, closed_list); */
// work through every open room
Node current_room = open_list[0]; // copy
closed_list.push_back(current_room); // move to closed
open_list.erase(open_list.begin()); // erase original
// -- For each adjacent room to current
for (const string & direction : C::direction_ids)
{
if (direction == C::UP || direction == C::DOWN) { continue; } // only pathfinding in 2D now
// calculate the location deltas
int dx = 0, dy = 0, dz = 0;
R::assign_movement_deltas(direction, dx, dy, dz);
// skip if the room is out of bounds
if (!R::bounds_check(current_room.x + dx, current_room.y + dy, C::GROUND_INDEX)) { continue; }
// skip the room if it is not loaded
if (world.room_at(current_room.x + dx, current_room.y + dy, C::GROUND_INDEX) == nullptr) { continue; }
// skip the room if it is not within view distance
if (!world.room_at(current_room.x + dx, current_room.y + dy, C::GROUND_INDEX)->is_observed_by(this->name)) { continue; }
// create a node to select the next adjacent room
Node adjacent_room(current_room.x + dx, current_room.y + dy, direction);
// -- -- pass if it is on the closed list
if (room_in_node_list(adjacent_room.x, adjacent_room.y, closed_list)) { continue; }
// -- -- pass if we can not travel to it from the current room
if (validate_movement(current_room.x, current_room.y, C::GROUND_INDEX, direction, dx, dy, 0, world) != C::GOOD_SIGNAL) { continue; }
// -- -- if room is not on open list
if (!room_in_node_list(adjacent_room.x, adjacent_room.y, open_list))
{
// -- -- -- Make current room the parent of adjacent
adjacent_room.parent_x = current_room.x;
adjacent_room.parent_y = current_room.y;
// -- -- -- Record F, G, H costs of room
adjacent_room.set_g_h_f(
current_room.g + (R::contains(C::primary_direction_ids, direction) ? C::AI_MOVEMENT_COST : C::AI_MOVEMENT_COST_DIAGONAL), // check if the movement is non-diagonal or diagonal
R::diagonal_distance(x_dest, y_dest, adjacent_room.x, adjacent_room.y));
}
// -- -- (else room is on open list)
else
{
// pull adjacent_room out of open_list
for (unsigned i = 0; i < open_list.size(); ++i) // for each node in the open list
{
if (open_list[i].x == adjacent_room.x && open_list[i].y == adjacent_room.y) // if the node is the current room
{
adjacent_room = get_node_at(adjacent_room.x, adjacent_room.y, open_list); // save it
open_list.erase(open_list.begin() + i); // erase the original
break; // adjacent_room is now the one from the list
}
}
// -- -- if this g-cost to room is less than current g-cost to room
if (current_room.g + (R::contains(C::primary_direction_ids, direction) ? C::AI_MOVEMENT_COST : C::AI_MOVEMENT_COST_DIAGONAL) < adjacent_room.g)
{
// -- -- -- update current room to new parent of room
adjacent_room.parent_x = current_room.x;
adjacent_room.parent_y = current_room.y;
// -- -- -- update costs
adjacent_room.set_g_h_f(
current_room.g + (R::contains(C::primary_direction_ids, direction) ? C::AI_MOVEMENT_COST : C::AI_MOVEMENT_COST_DIAGONAL), // check if the movement is non-diagonal or diagonal
R::diagonal_distance(x_dest, y_dest, adjacent_room.x, adjacent_room.y));
}
}
// -- -- -- Add room to open list
open_list.push_back(adjacent_room);
} // end for each adjacent room
// keep searching if we have not reached the destination OR there are still rooms to search
} while (/*!room_in_node_list(x_dest, y_dest, closed_list) ||*/ open_list.size() > 0);
// Starting from target room, continue finding parent until the current room is found
// (this represents the path in reverse)
// get the target room
Node current_room = get_node_at(x_dest, y_dest, closed_list);
// if there is no target room in the closed list, a path could not be found
if (current_room.x == -1 || current_room.y == -1) { return; }
do
{
// get the parent room
Node parent_room = get_node_at(current_room.parent_x, current_room.parent_y, closed_list);
// leave this here for debugging
// cout << "\nI can get to " << current_room.x << "," << current_room.y << " from " << parent_room.x << "," << parent_room.y << ".";
// if the parent of current_room is our location, move to current_room
if (parent_room.x == this->x && parent_room.y == this->y)
{
// move to current
//this->move(C::opposite_direction_id.find(current_room.direction_from_parent)->second, world);
move(current_room.direction_from_parent, world);
/* leave this here for debugging
cout << endl;
for (const Node & node : closed_list)
{
cout << "Parent of " << node.x << "," << node.y << " is " << node.parent_x << "," << node.parent_y << endl <<
"Actual cost to reach this node: " << node.g << ". Estimated cost to target: " << node.h << endl << endl;
}*/
return; // we're done here
}
// if there is no parent room in the closed list (?!)
else if (parent_room.x == -1 || parent_room.y == -1)
{
return; // something went horribly wrong
}
// move up the path by one room
current_room = parent_room;
} while (true);
}
<|endoftext|> |
<commit_before>/*
* examples/matrices.C
*
* Copyright (C) 2017 D. Saunders, Z. Wang, J-G Dumas
* ========LICENCE========
* This file is part of the library LinBox.
*
* LinBox is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
* ========LICENCE========
*/
/** \file examples/matrices.C
* @example examples/matrices.C
\brief example matrices that were chosen for Smith form testing.
\ingroup examples
\author bds & zw
Various Smith form algorithms may be used for matrices over the
integers or over Z_m. Moduli greater than 2^32 are not supported here.
Several types of example matrices may be constructed or the matrix be read from a file.
Run the program with no arguments for a synopsis of the command line parameters.
For the "adaptive" method, the matrix must be over the integers.
This is expected to work best for large matrices.
For the "2local" method, the computation is done mod 2^32.
For the "local" method, the modulus must be a prime power.
For the "ilio" method, the modulus may be arbitrary composite.
If the modulus is a multiple of the integer determinant, the integer Smith form is obtained.
Determinant plus ilio may be best for smaller matrices.
This example was used during the design process of the adaptive algorithm.
*/
#include <linbox/linbox-config.h>
#include <iostream>
#include <string>
using namespace std;
#include <linbox/util/timer.h>
#include <linbox/matrix/dense-matrix.h>
#include "matrices.h"
template <class PIR>
void Mat(LinBox::DenseMatrix<PIR>& M, PIR& R, int & n, string src) ;
int main(int argc, char* argv[])
{
if (argc < 3 or argc > 4) {
cout << "usage: " << argv[0] << " type n [filename]" << endl;
cout << " type = `random', `random-rough', `tref', or `fib',"
<< " and n is the dimension" << endl;
cout << " If filename is present, matrix is written there, else to cout." << endl;
return 0;
}
string type = argv[1];
int n = atoi(argv[2]);
// place B: Edit here and at place A for ring change
//typedef PIRModular<int32_t> PIR;
typedef Givaro::ZRing<Givaro::Integer> PIR;
PIR R;
LinBox::DenseMatrix<PIR> M(R);
Mat(M,R,n,type);
if (M.rowdim() <= 20 && M.coldim() <= 20) {
M.write(std::clog, LinBox::Tag::FileFormat::Maple) << std::endl;
}
if (argc == 4) {
ofstream out(argv[3]);
M.write(out) << endl;
} else {
M.write(cout) << endl;
}
}// main
/** Output matrix is determined by src which may be:
"random-rough"
This mat will have s, near sqrt(n), distinct invariant factors,
each repeated twice), involving the s primes 101, 103, ...
"random"
This mat will have the same nontrivial invariant factors as
diag(1,2,3,5,8, ... 999, 0, 1, 2, ...).
"fib"
This mat will have the same nontrivial invariant factors as
diag(1,2,3,5,8, ... fib(k)), where k is about sqrt(n).
The basic matrix is block diagonal with i-th block of order i and
being a tridiagonal {-1,0,1} matrix whose snf = diag(i-1 1's, fib(i)),
where fib(1) = 1, fib(2) = 2. But note that, depending on n,
the last block may be truncated, thus repeating an earlier fibonacci number.
"file" (or any other string)
Also "tref" and file with format "kdense"
*/
template <class PIR>
void Mat(LinBox::DenseMatrix<PIR>& M, PIR& R, int & n,
string src) {
if (src == "random-rough") RandomRoughMat(M, R, n);
else if (src == "random") RandomFromDiagMat(M, R, n);
else if (src == "fib") RandomFibMat(M, R, n);
else if (src == "tref") TrefMat(M, R, n);
else if (src == "krat") KratMat(M, R, n);
else { // from cin, mostly pointless, but may effect a file format change.
M.read(cin);
n = M.rowdim();
}
} // Mat
<commit_msg>add moler redheffer<commit_after>/*
* examples/matrices.C
*
* Copyright (C) 2017 D. Saunders, Z. Wang, J-G Dumas
* ========LICENCE========
* This file is part of the library LinBox.
*
* LinBox is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
* ========LICENCE========
*/
/** \file examples/matrices.C
* @example examples/matrices.C
\brief example matrices that were chosen for Smith form testing.
\ingroup examples
\author bds & zw
Various Smith form algorithms may be used for matrices over the
integers or over Z_m. Moduli greater than 2^32 are not supported here.
Several types of example matrices may be constructed or the matrix be read from a file.
Run the program with no arguments for a synopsis of the command line parameters.
For the "adaptive" method, the matrix must be over the integers.
This is expected to work best for large matrices.
For the "2local" method, the computation is done mod 2^32.
For the "local" method, the modulus must be a prime power.
For the "ilio" method, the modulus may be arbitrary composite.
If the modulus is a multiple of the integer determinant, the integer Smith form is obtained.
Determinant plus ilio may be best for smaller matrices.
This example was used during the design process of the adaptive algorithm.
*/
#include <linbox/linbox-config.h>
#include <iostream>
#include <string>
using namespace std;
#include <linbox/util/timer.h>
#include <linbox/matrix/dense-matrix.h>
#include "matrices.h"
template <class PIR>
void Mat(LinBox::DenseMatrix<PIR>& M, PIR& R, int & n, string src) ;
int main(int argc, char* argv[])
{
if (argc < 3 or argc > 4) {
cout << "usage: " << argv[0] << " type n [filename]" << endl;
cout << " type = `random', `random-rough', `tref',"
<< " 'moler', 'redheffer', "
<< " or `fib',"
<< " and n is the dimension" << endl;
cout << " If filename is present, matrix is written there, else to cout." << endl;
return 0;
}
string type = argv[1];
int n = atoi(argv[2]);
// place B: Edit here and at place A for ring change
//typedef PIRModular<int32_t> PIR;
typedef Givaro::ZRing<Givaro::Integer> PIR;
PIR R;
LinBox::DenseMatrix<PIR> M(R);
Mat(M,R,n,type);
if (M.rowdim() <= 20 && M.coldim() <= 20) {
M.write(std::clog, LinBox::Tag::FileFormat::Maple) << std::endl;
}
if (argc == 4) {
ofstream out(argv[3]);
M.write(out) << endl;
} else {
M.write(cout) << endl;
}
}// main
/** Output matrix is determined by src which may be:
"random-rough"
This mat will have s, near sqrt(n), distinct invariant factors,
each repeated twice), involving the s primes 101, 103, ...
"random"
This mat will have the same nontrivial invariant factors as
diag(1,2,3,5,8, ... 999, 0, 1, 2, ...).
"fib"
This mat will have the same nontrivial invariant factors as
diag(1,2,3,5,8, ... fib(k)), where k is about sqrt(n).
The basic matrix is block diagonal with i-th block of order i and
being a tridiagonal {-1,0,1} matrix whose snf = diag(i-1 1's, fib(i)),
where fib(1) = 1, fib(2) = 2. But note that, depending on n,
the last block may be truncated, thus repeating an earlier fibonacci number.
"file" (or any other string)
Also "tref" and file with format "kdense"
*/
template <class PIR>
void Mat(LinBox::DenseMatrix<PIR>& M, PIR& R, int & n,
string src) {
if (src == "random-rough") RandomRoughMat(M, R, n);
else if (src == "random") RandomFromDiagMat(M, R, n);
else if (src == "fib") RandomFibMat(M, R, n);
else if (src == "tref") TrefMat(M, R, n);
else if (src == "krat") KratMat(M, R, n);
else if (src == "moler") MolerMat(M, R, n);
else if (src == "redheffer") RedhefferMat(M, R, n);
else { // from cin, mostly pointless, but may effect a file format change.
M.read(cin);
n = M.rowdim();
}
} // Mat
<|endoftext|> |
<commit_before>#include "serial.h"
speed_t baud = 4800;
std::string port = "/dev/ttyUSB0";
Serial gps(baud, port, false);
void readGPS()
{
for(int i = 0; i < 4; ++i) {
while(gps.serialRead(1)) {
if (gps.getData() == "\n") break;
std::cout << gps.getData();
}
std::cout << std::endl;
}
}
void printConfig()
{
termios cur_config = gps.getConfig();
std::cout << "c_cflag: " << cur_config.c_cflag << std::endl;
std::cout << "c_iflag: " << cur_config.c_iflag << std::endl;
std::cout << "c_oflag: " << cur_config.c_oflag << std::endl;
std::cout << "c_lflag: " << cur_config.c_lflag << std::endl;
}
int main()
{
printConfig();
std::cout << "Baud 1: " << gps.getBaud() << std::endl;
std::cout << "Applying change: " << gps.applyNewConfig() << std::endl;
baud = 9600;
std::cout << "Setting Baud to " << baud << ": " << gps.setBaud(baud) << std::endl;
std::cout << "Applying change: " << gps.applyNewConfig() << std::endl;
std::cout << "Baud 2: " << gps.getBaud() << std::endl;
baud = 4800;
std::cout << "Setting Baud to " << baud << ": " << gps.setBaud(baud) << std::endl;
std::cout << "Applying change: " << gps.applyNewConfig() << std::endl;
readGPS();
baud = 4800;
std::cout << "Restoring baud to " << baud << ": " << gps.setBaud(baud) << std::endl;
std::cout << "Applying change: " << gps.applyNewConfig() << std::endl;
std::cout << "Baud 2: " << gps.getBaud() << std::endl;
readGPS();
return 0;
}
<commit_msg>Delete noCanon.cpp<commit_after><|endoftext|> |
<commit_before>#include "catch.hpp"
#include "../statemachine.hpp"
using namespace fsm11;
using StateMachine_t = fsm11::StateMachine<>;
using State_t = StateMachine_t::state_type;
TEST_CASE("construct a state", "[state]")
{
State_t s("name");
REQUIRE(s.childMode() == State_t::Exclusive);
REQUIRE(!std::strcmp(s.name(), "name"));
REQUIRE(s.parent() == 0);
REQUIRE(s.isAtomic());
REQUIRE(!s.isCompound());
REQUIRE(!s.isParallel());
REQUIRE(s.stateMachine() == 0);
REQUIRE(!s.isActive());
REQUIRE(s.beginTransitions() == s.endTransitions());
REQUIRE(s.cbeginTransitions() == s.cendTransitions());
}
TEST_CASE("set the parent of a state", "[state]")
{
State_t p1("p1");
State_t p2("p2");
State_t c("c", &p1);
REQUIRE(&p1 == c.parent());
REQUIRE(!p1.isAtomic());
REQUIRE(p2.isAtomic());
c.setParent(&p2);
REQUIRE(&p2 == c.parent());
REQUIRE(p1.isAtomic());
REQUIRE(!p2.isAtomic());
c.setParent(&p1);
REQUIRE(&p1 == c.parent());
REQUIRE(!p1.isAtomic());
REQUIRE(p2.isAtomic());
}
TEST_CASE("change the child mode", "[state]")
{
State_t s("s");
State_t c("c", &s);
REQUIRE(State_t::Exclusive == s.childMode());
REQUIRE(s.isCompound());
REQUIRE(!s.isParallel());
s.setChildMode(State_t::Parallel);
REQUIRE(State_t::Parallel == s.childMode());
REQUIRE(!s.isCompound());
REQUIRE(s.isParallel());
s.setChildMode(State_t::Exclusive);
REQUIRE(State_t::Exclusive == s.childMode());
REQUIRE(s.isCompound());
REQUIRE(!s.isParallel());
}
#if 0
TEST_CASE("find a child", "[state]")
{
State_t p("p");
State_t c1("c1", &p);
State_t c2("c2", &p);
State_t c3("c3", &p);
State_t c11("c11", &c1);
State_t c12("c12", &c1);
State_t c31("c31", &c3);
State_t c32("c32", &c3);
State_t* found = p.findChild("c1");
REQUIRE(found != 0);
REQUIRE(!std::strcmp("c1", found->name()));
found = p.findChild("c1", "c12");
REQUIRE(found != 0);
REQUIRE(!std::strcmp("c12", found->name()));
}
#endif
TEST_CASE("hierarchy properties", "[state]")
{
State_t p("p");
State_t c1("c1", &p);
State_t c2("c2", &p);
State_t c3("c3", &p);
State_t c11("c11", &c1);
State_t c12("c12", &c1);
State_t c31("c31", &c3);
State_t c32("c32", &c3);
REQUIRE(isAncestor(&p, &p));
REQUIRE(isDescendant(&p, &p));
REQUIRE(isAncestor(&p, &c1));
REQUIRE(isAncestor(&p, &c2));
REQUIRE(isAncestor(&p, &c3));
REQUIRE(isAncestor(&p, &c11));
REQUIRE(isAncestor(&p, &c12));
REQUIRE(isAncestor(&p, &c31));
REQUIRE(isAncestor(&p, &c32));
REQUIRE(isAncestor(&c1, &c11));
REQUIRE(isAncestor(&c1, &c12));
REQUIRE(!isAncestor(&c1, &c31));
REQUIRE(!isAncestor(&c1, &c32));
}
<commit_msg>More tests for the setters of State.<commit_after>#include "catch.hpp"
#include "../statemachine.hpp"
using namespace fsm11;
using StateMachine_t = fsm11::StateMachine<>;
using State_t = StateMachine_t::state_type;
TEST_CASE("construct a state", "[state]")
{
State_t s("name");
REQUIRE(s.childMode() == State_t::Exclusive);
REQUIRE(!std::strcmp(s.name(), "name"));
REQUIRE(s.parent() == 0);
REQUIRE(s.isAtomic());
REQUIRE(!s.isCompound());
REQUIRE(!s.isParallel());
REQUIRE(s.stateMachine() == 0);
REQUIRE(!s.isActive());
REQUIRE(s.beginTransitions() == s.endTransitions());
REQUIRE(s.cbeginTransitions() == s.cendTransitions());
}
TEST_CASE("set the parent of a state", "[state]")
{
State_t p1("p1");
State_t p2("p2");
State_t c("c", &p1);
REQUIRE(&p1 == c.parent());
REQUIRE(!p1.isAtomic());
REQUIRE(p2.isAtomic());
c.setParent(&p2);
REQUIRE(&p2 == c.parent());
REQUIRE(p1.isAtomic());
REQUIRE(!p2.isAtomic());
c.setParent(&p1);
REQUIRE(&p1 == c.parent());
REQUIRE(!p1.isAtomic());
REQUIRE(p2.isAtomic());
}
TEST_CASE("set the state machine", "[state]")
{
StateMachine_t sm1;
State_t s1("s1", &sm1);
State_t s2("s2");
State_t s3("s3", &s2);
REQUIRE(s1.stateMachine() == &sm1);
REQUIRE(s2.stateMachine() == 0);
REQUIRE(s3.stateMachine() == 0);
s2.setParent(&s1);
REQUIRE(s1.stateMachine() == &sm1);
REQUIRE(s2.stateMachine() == &sm1);
REQUIRE(s3.stateMachine() == &sm1);
State_t s4("s4", &s2);
REQUIRE(s4.stateMachine() == &sm1);
REQUIRE(!s1.isAtomic());
StateMachine_t sm2;
s2.setParent(&sm2);
REQUIRE(s1.stateMachine() == &sm1);
REQUIRE(s2.stateMachine() == &sm2);
REQUIRE(s3.stateMachine() == &sm2);
REQUIRE(s4.stateMachine() == &sm2);
REQUIRE(s1.isAtomic());
}
TEST_CASE("change the child mode", "[state]")
{
State_t s("s");
State_t c("c", &s);
REQUIRE(State_t::Exclusive == s.childMode());
REQUIRE(s.isCompound());
REQUIRE(!s.isParallel());
s.setChildMode(State_t::Parallel);
REQUIRE(State_t::Parallel == s.childMode());
REQUIRE(!s.isCompound());
REQUIRE(s.isParallel());
s.setChildMode(State_t::Exclusive);
REQUIRE(State_t::Exclusive == s.childMode());
REQUIRE(s.isCompound());
REQUIRE(!s.isParallel());
}
#if 0
TEST_CASE("find a child", "[state]")
{
State_t p("p");
State_t c1("c1", &p);
State_t c2("c2", &p);
State_t c3("c3", &p);
State_t c11("c11", &c1);
State_t c12("c12", &c1);
State_t c31("c31", &c3);
State_t c32("c32", &c3);
State_t* found = p.findChild("c1");
REQUIRE(found != 0);
REQUIRE(!std::strcmp("c1", found->name()));
found = p.findChild("c1", "c12");
REQUIRE(found != 0);
REQUIRE(!std::strcmp("c12", found->name()));
}
#endif
TEST_CASE("state relationship", "[state]")
{
State_t p("p");
State_t c1("c1", &p);
State_t c2("c2", &p);
State_t c3("c3", &p);
State_t c11("c11", &c1);
State_t c12("c12", &c1);
State_t c31("c31", &c3);
State_t c32("c32", &c3);
REQUIRE(isAncestor(&p, &p));
REQUIRE(isDescendant(&p, &p));
REQUIRE(isAncestor(&p, &c1));
REQUIRE(isAncestor(&p, &c2));
REQUIRE(isAncestor(&p, &c3));
REQUIRE(isAncestor(&p, &c11));
REQUIRE(isAncestor(&p, &c12));
REQUIRE(isAncestor(&p, &c31));
REQUIRE(isAncestor(&p, &c32));
REQUIRE(isAncestor(&c1, &c11));
REQUIRE(isAncestor(&c1, &c12));
REQUIRE(!isAncestor(&c1, &c31));
REQUIRE(!isAncestor(&c1, &c32));
REQUIRE(!isProperAncestor(&p, &p));
REQUIRE(!isProperAncestor(&c1, &p));
REQUIRE(isProperAncestor(&p, &c1));
REQUIRE(isProperAncestor(&p, &c11));
}
<|endoftext|> |
<commit_before>#include "notepad.h"
#include "ui_notepad.h"
#include <QFileDialog>
#include <QFile>
#include <QMessageBox>
#include <QTextStream>
#include <QListWidget>
#include <QtPrintSupport>
#include <QListView>
#include <fileviewmodel.h>
Notepad::Notepad(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::Notepad)
{
// TODO, not sure where to organize instantiating methods
// Temporarily changing to a directory
working_dir = QDir("/Users/pybae/Documents");
QStringList files = working_dir.entryList();
ui->setupUi(this);
FileViewModel *fileModel = new FileViewModel(files, 0);
ui->listView->setModel(fileModel);
ui->listView->show();
printf("%d\n", fileModel->rowCount());
}
Notepad::~Notepad()
{
delete ui;
}
// A helper method to save a file, given a fileName in the current working directory
void Notepad::saveFile(QString fileName)
{
if (!fileName.isEmpty()) {
QFile file(fileName);
if (!file.open(QIODevice::WriteOnly)) {
// error message
return;
} else {
QTextStream stream(&file);
stream << ui->mainTextEdit->toPlainText() << "\n";
stream.flush();
file.close();
}
}
else {
printf("File does not exist\n");
}
}
// Called when the "New" option is triggered by C-n or menu
void Notepad::on_actionNew_triggered()
{
QString newFileName = QFileDialog::getSaveFileName(this, tr("New File"), working_dir.absolutePath(),
tr("Text Files (*.txt);;C++ Files (*.cpp *.h)"));
saveFile(newFileName);
working_file_name = newFileName;
}
// Called when the "Open" option is triggered by C-o or menu
void Notepad::on_actionOpen_triggered()
{
QString fileName = QFileDialog::getOpenFileName(this, tr("Open File"), working_dir.absolutePath(),
tr("All Files (*.*);;Text Files (*.txt);;RTF Filess(*.rtf);;C++ Files (*.cpp *.h)"));
if (!fileName.isEmpty()) {
QFile file(fileName);
working_file_name = file.fileName();
if (!file.open(QIODevice::ReadOnly)) {
QMessageBox::critical(this, tr("Error"), tr("Could not open file"));
return;
}
QTextStream in(&file);
ui->mainTextEdit->setText(in.readAll());
file.close();
}
}
// Called when the "Save" option is triggered by C-s or menu
void Notepad::on_actionSave_triggered()
{
saveFile(working_file_name);
}
// Called when the "Save As" option is triggered by C-S (Ctrl shift s) or menu
void Notepad::on_actionSaveAs_triggered()
{
QString fileName = QFileDialog::getSaveFileName(this, tr("Save File"), QString(),
tr("Text Files (*.txt);;C++ Files (*.cpp *.h)"));
saveFile(fileName);
}
// Called when the "Print" option is triggered by C-p or menu
void Notepad::on_actionPrint_triggered()
{
// QPrinter printer;
// QPrintDialog dialog(&printer, this);
// dialog.setWindowTitle(tr("Print Document"));
// if (dialog.exec() != QDialog::Accepted) {
// return;
// }
}
// Called when the "Exit" option is triggered by C-q or menu
void Notepad::on_actionExit_triggered()
{
// TODO need to check if there are any unsaved buffers
qApp->quit();
}
// Triggered when the mainTextEdit region has its text changed
// TODO figure out how frequently this method is called
void Notepad::on_mainTextEdit_textChanged()
{
// Save the current buffer
// Notepad::on_actionSave_triggered();
}
<commit_msg>Fixed typo<commit_after>#include "notepad.h"
#include "ui_notepad.h"
#include <QFileDialog>
#include <QFile>
#include <QMessageBox>
#include <QTextStream>
#include <QListWidget>
#include <QtPrintSupport>
#include <QListView>
#include <fileviewmodel.h>
Notepad::Notepad(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::Notepad)
{
// TODO, not sure where to organize instantiating methods
// Temporarily changing to a directory
working_dir = QDir("/Users/pybae/Documents");
QStringList files = working_dir.entryList();
ui->setupUi(this);
FileViewModel *fileModel = new FileViewModel(files, 0);
ui->listView->setModel(fileModel);
ui->listView->show();
}
Notepad::~Notepad()
{
delete ui;
}
// A helper method to save a file, given a fileName in the current working directory
void Notepad::saveFile(QString fileName)
{
if (!fileName.isEmpty()) {
QFile file(fileName);
if (!file.open(QIODevice::WriteOnly)) {
// error message
return;
} else {
QTextStream stream(&file);
stream << ui->mainTextEdit->toPlainText() << "\n";
stream.flush();
file.close();
}
}
else {
printf("File does not exist\n");
}
}
// Called when the "New" option is triggered by C-n or menu
void Notepad::on_actionNew_triggered()
{
QString newFileName = QFileDialog::getSaveFileName(this, tr("New File"), working_dir.absolutePath(),
tr("Text Files (*.txt);;C++ Files (*.cpp *.h)"));
saveFile(newFileName);
working_file_name = newFileName;
}
// Called when the "Open" option is triggered by C-o or menu
void Notepad::on_actionOpen_triggered()
{
QString fileName = QFileDialog::getOpenFileName(this, tr("Open File"), working_dir.absolutePath(),
tr("All Files (*.*);;Text Files (*.txt);;RTF Files(*.rtf);;C++ Files (*.cpp *.h)"));
if (!fileName.isEmpty()) {
QFile file(fileName);
working_file_name = file.fileName();
if (!file.open(QIODevice::ReadOnly)) {
QMessageBox::critical(this, tr("Error"), tr("Could not open file"));
return;
}
QTextStream in(&file);
ui->mainTextEdit->setText(in.readAll());
file.close();
}
}
// Called when the "Save" option is triggered by C-s or menu
void Notepad::on_actionSave_triggered()
{
saveFile(working_file_name);
}
// Called when the "Save As" option is triggered by C-S (Ctrl shift s) or menu
void Notepad::on_actionSaveAs_triggered()
{
QString fileName = QFileDialog::getSaveFileName(this, tr("Save File"), QString(),
tr("Text Files (*.txt);;C++ Files (*.cpp *.h)"));
saveFile(fileName);
}
// Called when the "Print" option is triggered by C-p or menu
void Notepad::on_actionPrint_triggered()
{
// QPrinter printer;
// QPrintDialog dialog(&printer, this);
// dialog.setWindowTitle(tr("Print Document"));
// if (dialog.exec() != QDialog::Accepted) {
// return;
// }
}
// Called when the "Exit" option is triggered by C-q or menu
void Notepad::on_actionExit_triggered()
{
// TODO need to check if there are any unsaved buffers
qApp->quit();
}
// Triggered when the mainTextEdit region has its text changed
// TODO figure out how frequently this method is called
void Notepad::on_mainTextEdit_textChanged()
{
// Save the current buffer
// Notepad::on_actionSave_triggered();
}
<|endoftext|> |
<commit_before>#include "PrivateQGraphicsItem.h"
#include "MapInfoManager.h"
#include "MapGraphicsScene.h"
#include <QGraphicsSceneContextMenuEvent>
#include <QGraphicsSceneMouseEvent>
PrivateQGraphicsItem::PrivateQGraphicsItem(PrivateQGraphicsItemParent * user) : user(user)
{
this->setZValue(1.0);
}
QRectF PrivateQGraphicsItem::boundingRect() const
{
return this->user->boundingRect();
}
void PrivateQGraphicsItem::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget)
{
painter->save();
this->user->paint(painter,option,widget);
painter->restore();
if (option->state & QStyle::State_Selected)
{
const qreal penWidth = 0; // cosmetic pen
const QColor fgcolor = option->palette.windowText().color();
const QColor bgcolor( // ensure good contrast against fgcolor
fgcolor.red() > 127 ? 0 : 255,
fgcolor.green() > 127 ? 0 : 255,
fgcolor.blue() > 127 ? 0 : 255);
painter->setPen(QPen(bgcolor, penWidth, Qt::SolidLine));
painter->setBrush(Qt::NoBrush);
const qreal pad = 0.2;
painter->drawRect(this->boundingRect().adjusted(-pad, -pad, pad, pad));
painter->setPen(QPen(option->palette.windowText(), penWidth, Qt::DashLine));
painter->setBrush(Qt::NoBrush);
painter->drawRect(this->boundingRect().adjusted(-pad, -pad, pad, pad));
}
}
void PrivateQGraphicsItem::contextMenuEvent(QGraphicsSceneContextMenuEvent *event)
{
QSharedPointer<MapTileSource> source = MapInfoManager::getInstance()->getMapTileSource();
if (source.isNull())
return;
QGraphicsItem::contextMenuEvent(event);
/*
Then we can mangle the coordinates to geographic ones, but we have to mangle it back
when we're done because this event may be used again
*/
event->setScenePos(source->coordinateFromScenePixel(event->scenePos(),
this->user->scene()->getZoomLevel()));
this->user->contextMenuEvent(event);
event->setScenePos(source->scenePixelFromCoordinate(event->scenePos(),
this->user->scene()->getZoomLevel()));
}
void PrivateQGraphicsItem::mousePressEvent(QGraphicsSceneMouseEvent *event)
{
QSharedPointer<MapTileSource> source = MapInfoManager::getInstance()->getMapTileSource();
if (source.isNull())
return;
//Send the event to the parent class before we mangle the coordinates
QGraphicsItem::mousePressEvent(event);
/*
Then we can mangle the coordinates to geographic ones, but we have to mangle it back
when we're done because this event may be used again
*/
event->setScenePos(source->coordinateFromScenePixel(event->scenePos(),
this->user->scene()->getZoomLevel()));
this->user->mousePressEvent(event);
event->setScenePos(source->scenePixelFromCoordinate(event->scenePos(),
this->user->scene()->getZoomLevel()));
}
void PrivateQGraphicsItem::mouseReleaseEvent(QGraphicsSceneMouseEvent *event)
{
QSharedPointer<MapTileSource> source = MapInfoManager::getInstance()->getMapTileSource();
if (source.isNull())
return;
//Send the event to the parent class before we mangle the coordinates
QGraphicsItem::mouseReleaseEvent(event);
/*
Then we can mangle the coordinates to geographic ones, but we have to mangle it back
when we're done because this event may be used again
*/
event->setScenePos(source->coordinateFromScenePixel(event->scenePos(),
this->user->scene()->getZoomLevel()));
this->user->mouseReleaseEvent(event);
event->setScenePos(source->scenePixelFromCoordinate(event->scenePos(),
this->user->scene()->getZoomLevel()));
}
//protected
QVariant PrivateQGraphicsItem::itemChange(QGraphicsItem::GraphicsItemChange change, const QVariant &value)
{
return this->user->itemChange(change,value);
}
<commit_msg>Temporarily removed selection rectangle padding from PrivateQGraphicsItem. I like the idea of having padding but I need to make it respect different zoom levels before I put it back.<commit_after>#include "PrivateQGraphicsItem.h"
#include "MapInfoManager.h"
#include "MapGraphicsScene.h"
#include <QGraphicsSceneContextMenuEvent>
#include <QGraphicsSceneMouseEvent>
PrivateQGraphicsItem::PrivateQGraphicsItem(PrivateQGraphicsItemParent * user) : user(user)
{
this->setZValue(1.0);
}
QRectF PrivateQGraphicsItem::boundingRect() const
{
return this->user->boundingRect();
}
void PrivateQGraphicsItem::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget)
{
painter->save();
this->user->paint(painter,option,widget);
painter->restore();
if (option->state & QStyle::State_Selected)
{
const qreal penWidth = 0; // cosmetic pen
const QColor fgcolor = option->palette.windowText().color();
const QColor bgcolor( // ensure good contrast against fgcolor
fgcolor.red() > 127 ? 0 : 255,
fgcolor.green() > 127 ? 0 : 255,
fgcolor.blue() > 127 ? 0 : 255);
painter->setPen(QPen(bgcolor, penWidth, Qt::SolidLine));
painter->setBrush(Qt::NoBrush);
const qreal pad = 0.0;
painter->drawRect(this->boundingRect().adjusted(-pad, -pad, pad, pad));
painter->setPen(QPen(option->palette.windowText(), penWidth, Qt::DashLine));
painter->setBrush(Qt::NoBrush);
painter->drawRect(this->boundingRect().adjusted(-pad, -pad, pad, pad));
}
}
void PrivateQGraphicsItem::contextMenuEvent(QGraphicsSceneContextMenuEvent *event)
{
QSharedPointer<MapTileSource> source = MapInfoManager::getInstance()->getMapTileSource();
if (source.isNull())
return;
QGraphicsItem::contextMenuEvent(event);
/*
Then we can mangle the coordinates to geographic ones, but we have to mangle it back
when we're done because this event may be used again
*/
event->setScenePos(source->coordinateFromScenePixel(event->scenePos(),
this->user->scene()->getZoomLevel()));
this->user->contextMenuEvent(event);
event->setScenePos(source->scenePixelFromCoordinate(event->scenePos(),
this->user->scene()->getZoomLevel()));
}
void PrivateQGraphicsItem::mousePressEvent(QGraphicsSceneMouseEvent *event)
{
QSharedPointer<MapTileSource> source = MapInfoManager::getInstance()->getMapTileSource();
if (source.isNull())
return;
//Send the event to the parent class before we mangle the coordinates
QGraphicsItem::mousePressEvent(event);
/*
Then we can mangle the coordinates to geographic ones, but we have to mangle it back
when we're done because this event may be used again
*/
event->setScenePos(source->coordinateFromScenePixel(event->scenePos(),
this->user->scene()->getZoomLevel()));
this->user->mousePressEvent(event);
event->setScenePos(source->scenePixelFromCoordinate(event->scenePos(),
this->user->scene()->getZoomLevel()));
}
void PrivateQGraphicsItem::mouseReleaseEvent(QGraphicsSceneMouseEvent *event)
{
QSharedPointer<MapTileSource> source = MapInfoManager::getInstance()->getMapTileSource();
if (source.isNull())
return;
//Send the event to the parent class before we mangle the coordinates
QGraphicsItem::mouseReleaseEvent(event);
/*
Then we can mangle the coordinates to geographic ones, but we have to mangle it back
when we're done because this event may be used again
*/
event->setScenePos(source->coordinateFromScenePixel(event->scenePos(),
this->user->scene()->getZoomLevel()));
this->user->mouseReleaseEvent(event);
event->setScenePos(source->scenePixelFromCoordinate(event->scenePos(),
this->user->scene()->getZoomLevel()));
}
//protected
QVariant PrivateQGraphicsItem::itemChange(QGraphicsItem::GraphicsItemChange change, const QVariant &value)
{
return this->user->itemChange(change,value);
}
<|endoftext|> |
<commit_before>#include <ruby.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include "ewah.h"
typedef VALUE (ruby_method)(...);
typedef struct ewah {
EWAHBoolArray<uword64> *bits;
} EWAH;
extern "C" void ewah_free(EWAH *bits) {
delete(bits->bits);
free(bits);
}
extern "C" VALUE ewah_new(VALUE klass) {
EWAH *b = ALLOC(EWAH);
b->bits = new EWAHBoolArray<uword64>();
VALUE bitset = Data_Wrap_Struct(klass, 0, ewah_free, b);
rb_obj_call_init(bitset, 0, 0);
return bitset;
}
extern "C" VALUE ewah_init(VALUE self) {
return self;
}
/* Core API */
extern "C" VALUE ewah_set(VALUE self, VALUE position) {
if (position == Qnil) {
rb_raise(rb_eRuntimeError, "Position to set not specified");
}
EWAH *bitset;
Data_Get_Struct(self, EWAH, bitset);
bitset->bits->set(FIX2INT(position));
return self;
}
extern "C" VALUE ewah_each(VALUE self) {
EWAH *bitset;
Data_Get_Struct(self, EWAH, bitset);
for(EWAHBoolArray<uword64>::const_iterator i = bitset->bits->begin(); i != bitset->bits->end(); ++i)
rb_yield(INT2FIX(*i));
return Qnil;
}
extern "C" VALUE ewah_each_word(VALUE self) {
EWAH *bitset;
Data_Get_Struct(self, EWAH, bitset);
EWAHBoolArrayIterator<uword64> i = bitset->bits->uncompress();
while(i.hasNext()) {
rb_yield(INT2FIX(i.next()));
}
return Qnil;
}
extern "C" VALUE ewah_each_word_sparse(VALUE self) {
EWAH *bitset;
Data_Get_Struct(self, EWAH, bitset);
EWAHBoolArraySparseIterator<uword64> i = bitset->bits->sparse_uncompress();
while(i.hasNext()) {
rb_yield(INT2FIX(i.next()));
}
return Qnil;
}
extern "C" VALUE ewah_swap(VALUE self, VALUE other) {
EWAH *bitset;
EWAH *obitset;
Data_Get_Struct(self, EWAH, bitset);
Data_Get_Struct(other, EWAH, obitset);
bitset->bits->swap(*(obitset->bits));
return self;
}
extern "C" VALUE ewah_reset(VALUE self) {
EWAH *bitset;
Data_Get_Struct(self, EWAH, bitset);
bitset->bits->reset();
return self;
}
/* Set Operations */
extern "C" VALUE ewah_logical_or(VALUE self, VALUE other) {
EWAH *bitset;
EWAH *obitset;
Data_Get_Struct(self, EWAH, bitset);
Data_Get_Struct(other, EWAH, obitset);
VALUE newBitset = ewah_new(rb_path2class("EwahBitset"));
EWAH *newBits;
Data_Get_Struct(newBitset, EWAH, newBits);
bitset->bits->logicalor(*(obitset->bits), *(newBits->bits));
return newBitset;
}
extern "C" VALUE ewah_logical_and(VALUE self, VALUE other) {
EWAH *bitset;
EWAH *obitset;
Data_Get_Struct(self, EWAH, bitset);
Data_Get_Struct(other, EWAH, obitset);
VALUE newBitset = ewah_new(rb_path2class("EwahBitset"));
EWAH *newBits;
Data_Get_Struct(newBitset, EWAH, newBits);
bitset->bits->logicaland(*(obitset->bits), *(newBits->bits));
return newBitset;
}
extern "C" VALUE ewah_logical_not(VALUE self) {
EWAH *bitset;
Data_Get_Struct(self, EWAH, bitset);
VALUE newBitset = ewah_new(rb_path2class("EwahBitset"));
EWAH *newBits;
Data_Get_Struct(newBitset, EWAH, newBits);
bitset->bits->logicalnot(*(newBits->bits));
return newBitset;
}
extern "C" VALUE ewah_eq(VALUE self, VALUE other) {
EWAH *bitset;
EWAH *obitset;
Data_Get_Struct(self, EWAH, bitset);
Data_Get_Struct(other, EWAH, obitset);
if(*(bitset->bits) == *(obitset->bits)) {
return Qtrue;
} else {
return Qfalse;
}
}
extern "C" VALUE ewah_neq(VALUE self, VALUE other) {
EWAH *bitset;
EWAH *obitset;
Data_Get_Struct(self, EWAH, bitset);
Data_Get_Struct(other, EWAH, obitset);
if(*(bitset->bits) != *(obitset->bits)) {
return Qtrue;
} else {
return Qfalse;
}
}
/* Information & Serialization */
extern "C" VALUE ewah_size_in_bits(VALUE self) {
EWAH *bitset;
Data_Get_Struct(self, EWAH, bitset);
return INT2FIX(bitset->bits->sizeInBits());
}
extern "C" VALUE ewah_size_in_bytes(VALUE self) {
EWAH *bitset;
Data_Get_Struct(self, EWAH, bitset);
return INT2FIX(bitset->bits->sizeInBytes());
}
extern "C" VALUE ewah_to_binary_s(VALUE self) {
EWAH *bitset;
Data_Get_Struct(self, EWAH, bitset);
stringstream ss;
bitset->bits->printout(ss);
return rb_str_new(ss.str().c_str(), ss.str().size());
}
extern "C" VALUE ewah_serialize(VALUE self) {
EWAH *bitset;
Data_Get_Struct(self, EWAH, bitset);
stringstream ss;
bitset->bits->write(ss);
return rb_str_new(ss.str().c_str(), ss.str().size());
}
extern "C" VALUE ewah_deserialize(VALUE self, VALUE bytes) {
EWAH *bitset;
Data_Get_Struct(self, EWAH, bitset);
stringstream ss;
ss.write(RSTRING_PTR(bytes), RSTRING_LEN(bytes));
bitset->bits->read(ss, true);
return self;
}
static VALUE rb_cC;
extern "C" void Init_ewahbitset() {
rb_cC = rb_define_class("EwahBitset", rb_cObject);
rb_define_singleton_method(rb_cC, "new", (ruby_method*) &ewah_new, 0);
rb_define_method(rb_cC, "initialize", (ruby_method*) &ewah_init, 0);
rb_define_method(rb_cC, "set", (ruby_method*) &ewah_set, 1);
rb_define_method(rb_cC, "each", (ruby_method*) &ewah_each, 0);
rb_define_method(rb_cC, "swap", (ruby_method*) &ewah_swap, 1);
rb_define_method(rb_cC, "reset", (ruby_method*) &ewah_reset, 0);
rb_define_method(rb_cC, "each_word64", (ruby_method*) &ewah_each_word, 0);
rb_define_method(rb_cC, "each_word64_sparse", (ruby_method*) &ewah_each_word_sparse, 0);
rb_define_method(rb_cC, "==", (ruby_method*) &ewah_eq, 1);
rb_define_method(rb_cC, "!=", (ruby_method*) &ewah_neq, 1);
rb_define_method(rb_cC, "logical_or", (ruby_method*) &ewah_logical_or, 1);
rb_define_method(rb_cC, "logical_and", (ruby_method*) &ewah_logical_and, 1);
rb_define_method(rb_cC, "logical_not", (ruby_method*) &ewah_logical_not, 1);
rb_define_method(rb_cC, "to_binary_s", (ruby_method*) &ewah_to_binary_s, 0);
rb_define_method(rb_cC, "serialize", (ruby_method*) &ewah_serialize, 0);
rb_define_method(rb_cC, "deserialize", (ruby_method*) &ewah_deserialize, 1);
rb_define_method(rb_cC, "size_in_bits", (ruby_method*) ewah_size_in_bits, 0);
rb_define_method(rb_cC, "size_in_bytes", (ruby_method*) ewah_size_in_bytes, 0);
}<commit_msg>add to_s<commit_after>#include <ruby.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include "ewah.h"
typedef VALUE (ruby_method)(...);
typedef struct ewah {
EWAHBoolArray<uword64> *bits;
} EWAH;
extern "C" void ewah_free(EWAH *bits) {
delete(bits->bits);
free(bits);
}
extern "C" VALUE ewah_new(VALUE klass) {
EWAH *b = ALLOC(EWAH);
b->bits = new EWAHBoolArray<uword64>();
VALUE bitset = Data_Wrap_Struct(klass, 0, ewah_free, b);
rb_obj_call_init(bitset, 0, 0);
return bitset;
}
extern "C" VALUE ewah_init(VALUE self) {
return self;
}
/* Core API */
extern "C" VALUE ewah_set(VALUE self, VALUE position) {
if (position == Qnil) {
rb_raise(rb_eRuntimeError, "Position to set not specified");
}
EWAH *bitset;
Data_Get_Struct(self, EWAH, bitset);
bitset->bits->set(FIX2INT(position));
return self;
}
extern "C" VALUE ewah_each(VALUE self) {
EWAH *bitset;
Data_Get_Struct(self, EWAH, bitset);
for(EWAHBoolArray<uword64>::const_iterator i = bitset->bits->begin(); i != bitset->bits->end(); ++i)
rb_yield(INT2FIX(*i));
return Qnil;
}
extern "C" VALUE ewah_each_word(VALUE self) {
EWAH *bitset;
Data_Get_Struct(self, EWAH, bitset);
EWAHBoolArrayIterator<uword64> i = bitset->bits->uncompress();
while(i.hasNext()) {
rb_yield(INT2FIX(i.next()));
}
return Qnil;
}
extern "C" VALUE ewah_each_word_sparse(VALUE self) {
EWAH *bitset;
Data_Get_Struct(self, EWAH, bitset);
EWAHBoolArraySparseIterator<uword64> i = bitset->bits->sparse_uncompress();
while(i.hasNext()) {
rb_yield(INT2FIX(i.next()));
}
return Qnil;
}
extern "C" VALUE ewah_swap(VALUE self, VALUE other) {
EWAH *bitset;
EWAH *obitset;
Data_Get_Struct(self, EWAH, bitset);
Data_Get_Struct(other, EWAH, obitset);
bitset->bits->swap(*(obitset->bits));
return self;
}
extern "C" VALUE ewah_reset(VALUE self) {
EWAH *bitset;
Data_Get_Struct(self, EWAH, bitset);
bitset->bits->reset();
return self;
}
/* Set Operations */
extern "C" VALUE ewah_logical_or(VALUE self, VALUE other) {
EWAH *bitset;
EWAH *obitset;
Data_Get_Struct(self, EWAH, bitset);
Data_Get_Struct(other, EWAH, obitset);
VALUE newBitset = ewah_new(rb_path2class("EwahBitset"));
EWAH *newBits;
Data_Get_Struct(newBitset, EWAH, newBits);
bitset->bits->logicalor(*(obitset->bits), *(newBits->bits));
return newBitset;
}
extern "C" VALUE ewah_logical_and(VALUE self, VALUE other) {
EWAH *bitset;
EWAH *obitset;
Data_Get_Struct(self, EWAH, bitset);
Data_Get_Struct(other, EWAH, obitset);
VALUE newBitset = ewah_new(rb_path2class("EwahBitset"));
EWAH *newBits;
Data_Get_Struct(newBitset, EWAH, newBits);
bitset->bits->logicaland(*(obitset->bits), *(newBits->bits));
return newBitset;
}
extern "C" VALUE ewah_logical_not(VALUE self) {
EWAH *bitset;
Data_Get_Struct(self, EWAH, bitset);
VALUE newBitset = ewah_new(rb_path2class("EwahBitset"));
EWAH *newBits;
Data_Get_Struct(newBitset, EWAH, newBits);
bitset->bits->logicalnot(*(newBits->bits));
return newBitset;
}
extern "C" VALUE ewah_eq(VALUE self, VALUE other) {
EWAH *bitset;
EWAH *obitset;
Data_Get_Struct(self, EWAH, bitset);
Data_Get_Struct(other, EWAH, obitset);
if(*(bitset->bits) == *(obitset->bits)) {
return Qtrue;
} else {
return Qfalse;
}
}
extern "C" VALUE ewah_neq(VALUE self, VALUE other) {
EWAH *bitset;
EWAH *obitset;
Data_Get_Struct(self, EWAH, bitset);
Data_Get_Struct(other, EWAH, obitset);
if(*(bitset->bits) != *(obitset->bits)) {
return Qtrue;
} else {
return Qfalse;
}
}
/* Information & Serialization */
extern "C" VALUE ewah_size_in_bits(VALUE self) {
EWAH *bitset;
Data_Get_Struct(self, EWAH, bitset);
return INT2FIX(bitset->bits->sizeInBits());
}
extern "C" VALUE ewah_size_in_bytes(VALUE self) {
EWAH *bitset;
Data_Get_Struct(self, EWAH, bitset);
return INT2FIX(bitset->bits->sizeInBytes());
}
extern "C" VALUE ewah_to_binary_s(VALUE self) {
EWAH *bitset;
Data_Get_Struct(self, EWAH, bitset);
stringstream ss;
bitset->bits->printout(ss);
return rb_str_new(ss.str().c_str(), ss.str().size());
}
extern "C" VALUE ewah_serialize(VALUE self) {
EWAH *bitset;
Data_Get_Struct(self, EWAH, bitset);
stringstream ss;
bitset->bits->write(ss);
return rb_str_new(ss.str().c_str(), ss.str().size());
}
extern "C" VALUE ewah_deserialize(VALUE self, VALUE bytes) {
EWAH *bitset;
Data_Get_Struct(self, EWAH, bitset);
stringstream ss;
ss.write(RSTRING_PTR(bytes), RSTRING_LEN(bytes));
bitset->bits->read(ss, true);
return self;
}
static VALUE rb_cC;
extern "C" void Init_ewahbitset() {
rb_cC = rb_define_class("EwahBitset", rb_cObject);
rb_define_singleton_method(rb_cC, "new", (ruby_method*) &ewah_new, 0);
rb_define_method(rb_cC, "initialize", (ruby_method*) &ewah_init, 0);
rb_define_method(rb_cC, "set", (ruby_method*) &ewah_set, 1);
rb_define_method(rb_cC, "each", (ruby_method*) &ewah_each, 0);
rb_define_method(rb_cC, "swap", (ruby_method*) &ewah_swap, 1);
rb_define_method(rb_cC, "reset", (ruby_method*) &ewah_reset, 0);
rb_define_method(rb_cC, "each_word64", (ruby_method*) &ewah_each_word, 0);
rb_define_method(rb_cC, "each_word64_sparse", (ruby_method*) &ewah_each_word_sparse, 0);
rb_define_method(rb_cC, "==", (ruby_method*) &ewah_eq, 1);
rb_define_method(rb_cC, "!=", (ruby_method*) &ewah_neq, 1);
rb_define_method(rb_cC, "logical_or", (ruby_method*) &ewah_logical_or, 1);
rb_define_method(rb_cC, "logical_and", (ruby_method*) &ewah_logical_and, 1);
rb_define_method(rb_cC, "logical_not", (ruby_method*) &ewah_logical_not, 1);
rb_define_method(rb_cC, "to_s", (ruby_method*) &ewah_to_binary_s, 0);
rb_define_method(rb_cC, "to_binary_s", (ruby_method*) &ewah_to_binary_s, 0);
rb_define_method(rb_cC, "serialize", (ruby_method*) &ewah_serialize, 0);
rb_define_method(rb_cC, "deserialize", (ruby_method*) &ewah_deserialize, 1);
rb_define_method(rb_cC, "size_in_bits", (ruby_method*) ewah_size_in_bits, 0);
rb_define_method(rb_cC, "size_in_bytes", (ruby_method*) ewah_size_in_bytes, 0);
}<|endoftext|> |
<commit_before>/*
* Copyright 2011 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "gm.h"
#include "Resources.h"
#include "SkCanvas.h"
#include "SkStream.h"
#include "SkSurface.h"
#include "SkTypeface.h"
class DFTextGM : public skiagm::GM {
public:
DFTextGM() {
this->setBGColor(0xFFFFFFFF);
}
protected:
void onOnceBeforeDraw() override {
sk_tool_utils::emoji_typeface(&fEmojiTypeface);
fEmojiText = sk_tool_utils::emoji_sample_text();
}
SkString onShortName() override {
SkString name("dftext");
name.append(sk_tool_utils::platform_os_emoji());
return name;
}
SkISize onISize() override {
return SkISize::Make(1024, 768);
}
static void rotate_about(SkCanvas* canvas,
SkScalar degrees,
SkScalar px, SkScalar py) {
canvas->translate(px, py);
canvas->rotate(degrees);
canvas->translate(-px, -py);
}
virtual void onDraw(SkCanvas* inputCanvas) override {
#ifdef SK_BUILD_FOR_ANDROID
SkScalar textSizes[] = { 9.0f, 9.0f*2.0f, 9.0f*5.0f, 9.0f*2.0f*5.0f };
#else
SkScalar textSizes[] = { 11.0f, 11.0f*2.0f, 11.0f*5.0f, 11.0f*2.0f*5.0f };
#endif
SkScalar scales[] = { 2.0f*5.0f, 5.0f, 2.0f, 1.0f };
// set up offscreen rendering with distance field text
#if SK_SUPPORT_GPU
GrContext* ctx = inputCanvas->getGrContext();
SkImageInfo info = SkImageInfo::MakeN32Premul(onISize());
SkSurfaceProps props(SkSurfaceProps::kUseDistanceFieldFonts_Flag,
SkSurfaceProps::kLegacyFontHost_InitType);
SkAutoTUnref<SkSurface> surface(SkSurface::NewRenderTarget(ctx, SkSurface::kNo_Budgeted,
info, 0, &props));
SkCanvas* canvas = surface.get() ? surface->getCanvas() : inputCanvas;
// init our new canvas with the old canvas's matrix
canvas->setMatrix(inputCanvas->getTotalMatrix());
#else
SkCanvas* canvas = inputCanvas;
#endif
// apply global scale to test glyph positioning
canvas->scale(1.05f, 1.05f);
canvas->clear(0xffffffff);
SkPaint paint;
paint.setAntiAlias(true);
paint.setSubpixelText(true);
sk_tool_utils::set_portable_typeface_always(&paint, "serif", SkTypeface::kNormal);
const char* text = "Hamburgefons";
const size_t textLen = strlen(text);
// check scaling up
SkScalar x = SkIntToScalar(0);
SkScalar y = SkIntToScalar(78);
for (size_t i = 0; i < SK_ARRAY_COUNT(textSizes); ++i) {
SkAutoCanvasRestore acr(canvas, true);
canvas->translate(x, y);
canvas->scale(scales[i], scales[i]);
paint.setTextSize(textSizes[i]);
canvas->drawText(text, textLen, 0, 0, paint);
y += paint.getFontMetrics(NULL)*scales[i];
}
// check rotation
for (size_t i = 0; i < 5; ++i) {
SkScalar rotX = SkIntToScalar(10);
SkScalar rotY = y;
SkAutoCanvasRestore acr(canvas, true);
canvas->translate(SkIntToScalar(10 + i * 200), -80);
rotate_about(canvas, SkIntToScalar(i * 5), rotX, rotY);
for (int ps = 6; ps <= 32; ps += 3) {
paint.setTextSize(SkIntToScalar(ps));
canvas->drawText(text, textLen, rotX, rotY, paint);
rotY += paint.getFontMetrics(NULL);
}
}
// check scaling down
paint.setLCDRenderText(true);
x = SkIntToScalar(680);
y = SkIntToScalar(20);
size_t arraySize = SK_ARRAY_COUNT(textSizes);
for (size_t i = 0; i < arraySize; ++i) {
SkAutoCanvasRestore acr(canvas, true);
canvas->translate(x, y);
SkScalar scaleFactor = SkScalarInvert(scales[arraySize - i - 1]);
canvas->scale(scaleFactor, scaleFactor);
paint.setTextSize(textSizes[i]);
canvas->drawText(text, textLen, 0, 0, paint);
y += paint.getFontMetrics(NULL)*scaleFactor;
}
// check pos text
{
SkAutoCanvasRestore acr(canvas, true);
canvas->scale(2.0f, 2.0f);
SkAutoTArray<SkPoint> pos(SkToInt(textLen));
SkAutoTArray<SkScalar> widths(SkToInt(textLen));
paint.setTextSize(textSizes[0]);
paint.getTextWidths(text, textLen, &widths[0]);
SkScalar x = SkIntToScalar(340);
SkScalar y = SkIntToScalar(75);
for (unsigned int i = 0; i < textLen; ++i) {
pos[i].set(x, y);
x += widths[i];
}
canvas->drawPosText(text, textLen, &pos[0], paint);
}
// check gamma-corrected blending
const SkColor fg[] = {
0xFFFFFFFF,
0xFFFFFF00, 0xFFFF00FF, 0xFF00FFFF,
0xFFFF0000, 0xFF00FF00, 0xFF0000FF,
0xFF000000,
};
paint.setColor(0xFFF7F3F7);
SkRect r = SkRect::MakeLTRB(670, 250, 820, 460);
canvas->drawRect(r, paint);
x = SkIntToScalar(680);
y = SkIntToScalar(270);
#ifdef SK_BUILD_FOR_ANDROID
paint.setTextSize(SkIntToScalar(19));
#else
paint.setTextSize(SkIntToScalar(22));
#endif
for (size_t i = 0; i < SK_ARRAY_COUNT(fg); ++i) {
paint.setColor(fg[i]);
canvas->drawText(text, textLen, x, y, paint);
y += paint.getFontMetrics(NULL);
}
paint.setColor(0xFF181C18);
r = SkRect::MakeLTRB(820, 250, 970, 460);
canvas->drawRect(r, paint);
x = SkIntToScalar(830);
y = SkIntToScalar(270);
#ifdef SK_BUILD_FOR_ANDROID
paint.setTextSize(SkIntToScalar(19));
#else
paint.setTextSize(SkIntToScalar(22));
#endif
for (size_t i = 0; i < SK_ARRAY_COUNT(fg); ++i) {
paint.setColor(fg[i]);
canvas->drawText(text, textLen, x, y, paint);
y += paint.getFontMetrics(NULL);
}
// check skew
{
paint.setLCDRenderText(false);
SkAutoCanvasRestore acr(canvas, true);
canvas->skew(0.0f, 0.151515f);
paint.setTextSize(SkIntToScalar(32));
canvas->drawText(text, textLen, 745, 70, paint);
}
{
paint.setLCDRenderText(true);
SkAutoCanvasRestore acr(canvas, true);
canvas->skew(0.5f, 0.0f);
paint.setTextSize(SkIntToScalar(32));
canvas->drawText(text, textLen, 580, 230, paint);
}
// check color emoji
if (fEmojiTypeface) {
paint.setTypeface(fEmojiTypeface);
paint.setTextSize(SkIntToScalar(19));
canvas->drawText(fEmojiText, strlen(fEmojiText), 670, 100, paint);
}
#if SK_SUPPORT_GPU
// render offscreen buffer
if (surface) {
SkAutoCanvasRestore acr(inputCanvas, true);
// since we prepended this matrix already, we blit using identity
inputCanvas->resetMatrix();
SkImage* image = surface->newImageSnapshot();
inputCanvas->drawImage(image, 0, 0, NULL);
image->unref();
}
#endif
}
private:
SkAutoTUnref<SkTypeface> fEmojiTypeface;
const char* fEmojiText;
typedef skiagm::GM INHERITED;
};
DEF_GM( return SkNEW(DFTextGM); )
<commit_msg>make dftext the same on Linux and Android<commit_after>/*
* Copyright 2011 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "gm.h"
#include "Resources.h"
#include "SkCanvas.h"
#include "SkStream.h"
#include "SkSurface.h"
#include "SkTypeface.h"
class DFTextGM : public skiagm::GM {
public:
DFTextGM() {
this->setBGColor(0xFFFFFFFF);
}
protected:
void onOnceBeforeDraw() override {
sk_tool_utils::emoji_typeface(&fEmojiTypeface);
fEmojiText = sk_tool_utils::emoji_sample_text();
}
SkString onShortName() override {
SkString name("dftext");
name.append(sk_tool_utils::platform_os_emoji());
return name;
}
SkISize onISize() override {
return SkISize::Make(1024, 768);
}
static void rotate_about(SkCanvas* canvas,
SkScalar degrees,
SkScalar px, SkScalar py) {
canvas->translate(px, py);
canvas->rotate(degrees);
canvas->translate(-px, -py);
}
virtual void onDraw(SkCanvas* inputCanvas) override {
SkScalar textSizes[] = { 9.0f, 9.0f*2.0f, 9.0f*5.0f, 9.0f*2.0f*5.0f };
SkScalar scales[] = { 2.0f*5.0f, 5.0f, 2.0f, 1.0f };
// set up offscreen rendering with distance field text
#if SK_SUPPORT_GPU
GrContext* ctx = inputCanvas->getGrContext();
SkImageInfo info = SkImageInfo::MakeN32Premul(onISize());
SkSurfaceProps props(SkSurfaceProps::kUseDistanceFieldFonts_Flag,
SkSurfaceProps::kLegacyFontHost_InitType);
SkAutoTUnref<SkSurface> surface(SkSurface::NewRenderTarget(ctx, SkSurface::kNo_Budgeted,
info, 0, &props));
SkCanvas* canvas = surface.get() ? surface->getCanvas() : inputCanvas;
// init our new canvas with the old canvas's matrix
canvas->setMatrix(inputCanvas->getTotalMatrix());
#else
SkCanvas* canvas = inputCanvas;
#endif
// apply global scale to test glyph positioning
canvas->scale(1.05f, 1.05f);
canvas->clear(0xffffffff);
SkPaint paint;
paint.setAntiAlias(true);
paint.setSubpixelText(true);
sk_tool_utils::set_portable_typeface_always(&paint, "serif", SkTypeface::kNormal);
const char* text = "Hamburgefons";
const size_t textLen = strlen(text);
// check scaling up
SkScalar x = SkIntToScalar(0);
SkScalar y = SkIntToScalar(78);
for (size_t i = 0; i < SK_ARRAY_COUNT(textSizes); ++i) {
SkAutoCanvasRestore acr(canvas, true);
canvas->translate(x, y);
canvas->scale(scales[i], scales[i]);
paint.setTextSize(textSizes[i]);
canvas->drawText(text, textLen, 0, 0, paint);
y += paint.getFontMetrics(NULL)*scales[i];
}
// check rotation
for (size_t i = 0; i < 5; ++i) {
SkScalar rotX = SkIntToScalar(10);
SkScalar rotY = y;
SkAutoCanvasRestore acr(canvas, true);
canvas->translate(SkIntToScalar(10 + i * 200), -80);
rotate_about(canvas, SkIntToScalar(i * 5), rotX, rotY);
for (int ps = 6; ps <= 32; ps += 3) {
paint.setTextSize(SkIntToScalar(ps));
canvas->drawText(text, textLen, rotX, rotY, paint);
rotY += paint.getFontMetrics(NULL);
}
}
// check scaling down
paint.setLCDRenderText(true);
x = SkIntToScalar(680);
y = SkIntToScalar(20);
size_t arraySize = SK_ARRAY_COUNT(textSizes);
for (size_t i = 0; i < arraySize; ++i) {
SkAutoCanvasRestore acr(canvas, true);
canvas->translate(x, y);
SkScalar scaleFactor = SkScalarInvert(scales[arraySize - i - 1]);
canvas->scale(scaleFactor, scaleFactor);
paint.setTextSize(textSizes[i]);
canvas->drawText(text, textLen, 0, 0, paint);
y += paint.getFontMetrics(NULL)*scaleFactor;
}
// check pos text
{
SkAutoCanvasRestore acr(canvas, true);
canvas->scale(2.0f, 2.0f);
SkAutoTArray<SkPoint> pos(SkToInt(textLen));
SkAutoTArray<SkScalar> widths(SkToInt(textLen));
paint.setTextSize(textSizes[0]);
paint.getTextWidths(text, textLen, &widths[0]);
SkScalar x = SkIntToScalar(340);
SkScalar y = SkIntToScalar(75);
for (unsigned int i = 0; i < textLen; ++i) {
pos[i].set(x, y);
x += widths[i];
}
canvas->drawPosText(text, textLen, &pos[0], paint);
}
// check gamma-corrected blending
const SkColor fg[] = {
0xFFFFFFFF,
0xFFFFFF00, 0xFFFF00FF, 0xFF00FFFF,
0xFFFF0000, 0xFF00FF00, 0xFF0000FF,
0xFF000000,
};
paint.setColor(0xFFF7F3F7);
SkRect r = SkRect::MakeLTRB(670, 250, 820, 460);
canvas->drawRect(r, paint);
x = SkIntToScalar(680);
y = SkIntToScalar(270);
paint.setTextSize(SkIntToScalar(19));
for (size_t i = 0; i < SK_ARRAY_COUNT(fg); ++i) {
paint.setColor(fg[i]);
canvas->drawText(text, textLen, x, y, paint);
y += paint.getFontMetrics(NULL);
}
paint.setColor(0xFF181C18);
r = SkRect::MakeLTRB(820, 250, 970, 460);
canvas->drawRect(r, paint);
x = SkIntToScalar(830);
y = SkIntToScalar(270);
paint.setTextSize(SkIntToScalar(19));
for (size_t i = 0; i < SK_ARRAY_COUNT(fg); ++i) {
paint.setColor(fg[i]);
canvas->drawText(text, textLen, x, y, paint);
y += paint.getFontMetrics(NULL);
}
// check skew
{
paint.setLCDRenderText(false);
SkAutoCanvasRestore acr(canvas, true);
canvas->skew(0.0f, 0.151515f);
paint.setTextSize(SkIntToScalar(32));
canvas->drawText(text, textLen, 745, 70, paint);
}
{
paint.setLCDRenderText(true);
SkAutoCanvasRestore acr(canvas, true);
canvas->skew(0.5f, 0.0f);
paint.setTextSize(SkIntToScalar(32));
canvas->drawText(text, textLen, 580, 230, paint);
}
// check color emoji
if (fEmojiTypeface) {
paint.setTypeface(fEmojiTypeface);
paint.setTextSize(SkIntToScalar(19));
canvas->drawText(fEmojiText, strlen(fEmojiText), 670, 100, paint);
}
#if SK_SUPPORT_GPU
// render offscreen buffer
if (surface) {
SkAutoCanvasRestore acr(inputCanvas, true);
// since we prepended this matrix already, we blit using identity
inputCanvas->resetMatrix();
SkImage* image = surface->newImageSnapshot();
inputCanvas->drawImage(image, 0, 0, NULL);
image->unref();
}
#endif
}
private:
SkAutoTUnref<SkTypeface> fEmojiTypeface;
const char* fEmojiText;
typedef skiagm::GM INHERITED;
};
DEF_GM( return SkNEW(DFTextGM); )
<|endoftext|> |
<commit_before>// ---------------------------------------------------------------------
//
// Copyright (C) 1998 - 2016 by the deal.II authors
//
// This file is part of the deal.II library.
//
// The deal.II library is free software; you can use it, 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.
// The full text of the license can be found in the file LICENSE at
// the top level of the deal.II distribution.
//
// ---------------------------------------------------------------------
#include "../tests.h"
#include "../testmatrix.h"
#include <deal.II/lac/sparse_matrix.h>
#include <deal.II/lac/vector.h>
#include <deal.II/lac/vector_memory.h>
#include <deal.II/lac/solver_control.h>
#include <deal.II/lac/eigen.h>
#include <deal.II/lac/precondition.h>
int main()
{
std::ofstream logfile("output");
// logfile.setf(std::ios::fixed);
deallog << std::setprecision(4);
deallog.attach(logfile);
GrowingVectorMemory<> mem;
SolverControl control(1000, 1.e-5);
const unsigned int size = 10;
const unsigned int dim = (size-1)*(size-1);
/*
* Compute minimal and maximal
* eigenvalues of the 5-point
* stencil matrix
* (Hackbusch:Iterative Lsung...,
* Satz 4.1.1)
*/
const double h = 1./size;
const double s = std::sin(numbers::PI*h/2.);
const double c = std::cos(numbers::PI*h/2.);
const double lambda_max = 8.*c*c;
const double lambda_min = 8.*s*s;
FDMatrix testproblem(size, size);
SparsityPattern structure(dim, dim, 5);
testproblem.five_point_structure(structure);
structure.compress();
SparseMatrix<double> A(structure);
testproblem.five_point(A);
Vector<double> u(dim);
u = 1.;
double lambda;
EigenPower<> mises(control, mem);
mises.solve(lambda, A, u);
deallog << "Eigenvalue " << lambda << " Error " << lambda-lambda_max << std::endl;
double lambda2;
u = 1.;
EigenPower<> mises2(control, mem, -1.5*lambda);
mises2.solve(lambda2, A, u);
deallog << "Eigenvalue " << lambda2 << " Error " << lambda2-lambda_min << std::endl;
u = 1.;
lambda = 0.;
EigenInverse<> wieland(control, mem);
wieland.solve(lambda, A, u);
deallog << "Eigenvalue " << lambda << " Error " << lambda-lambda_min << std::endl;
u = 1.;
lambda = 10.;
wieland.solve(lambda, A, u);
deallog << "Eigenvalue " << lambda << " Error " << lambda-lambda_max << std::endl;
u = 1.;
lambda = 10.;
EigenInverse<> wieland2(control, mem, .2);
wieland2.solve(lambda, A, u);
deallog << "Eigenvalue " << lambda << " Error " << lambda-lambda_max << std::endl;
}
<commit_msg>fix illegal character (<F6> instead of oe)<commit_after>// ---------------------------------------------------------------------
//
// Copyright (C) 1998 - 2016 by the deal.II authors
//
// This file is part of the deal.II library.
//
// The deal.II library is free software; you can use it, 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.
// The full text of the license can be found in the file LICENSE at
// the top level of the deal.II distribution.
//
// ---------------------------------------------------------------------
#include "../tests.h"
#include "../testmatrix.h"
#include <deal.II/lac/sparse_matrix.h>
#include <deal.II/lac/vector.h>
#include <deal.II/lac/vector_memory.h>
#include <deal.II/lac/solver_control.h>
#include <deal.II/lac/eigen.h>
#include <deal.II/lac/precondition.h>
int main()
{
std::ofstream logfile("output");
// logfile.setf(std::ios::fixed);
deallog << std::setprecision(4);
deallog.attach(logfile);
GrowingVectorMemory<> mem;
SolverControl control(1000, 1.e-5);
const unsigned int size = 10;
const unsigned int dim = (size-1)*(size-1);
/*
* Compute minimal and maximal
* eigenvalues of the 5-point
* stencil matrix
* (Hackbusch:Iterative Loesung...,
* Satz 4.1.1)
*/
const double h = 1./size;
const double s = std::sin(numbers::PI*h/2.);
const double c = std::cos(numbers::PI*h/2.);
const double lambda_max = 8.*c*c;
const double lambda_min = 8.*s*s;
FDMatrix testproblem(size, size);
SparsityPattern structure(dim, dim, 5);
testproblem.five_point_structure(structure);
structure.compress();
SparseMatrix<double> A(structure);
testproblem.five_point(A);
Vector<double> u(dim);
u = 1.;
double lambda;
EigenPower<> mises(control, mem);
mises.solve(lambda, A, u);
deallog << "Eigenvalue " << lambda << " Error " << lambda-lambda_max << std::endl;
double lambda2;
u = 1.;
EigenPower<> mises2(control, mem, -1.5*lambda);
mises2.solve(lambda2, A, u);
deallog << "Eigenvalue " << lambda2 << " Error " << lambda2-lambda_min << std::endl;
u = 1.;
lambda = 0.;
EigenInverse<> wieland(control, mem);
wieland.solve(lambda, A, u);
deallog << "Eigenvalue " << lambda << " Error " << lambda-lambda_min << std::endl;
u = 1.;
lambda = 10.;
wieland.solve(lambda, A, u);
deallog << "Eigenvalue " << lambda << " Error " << lambda-lambda_max << std::endl;
u = 1.;
lambda = 10.;
EigenInverse<> wieland2(control, mem, .2);
wieland2.solve(lambda, A, u);
deallog << "Eigenvalue " << lambda << " Error " << lambda-lambda_max << std::endl;
}
<|endoftext|> |
<commit_before>#include <boost/make_shared.hpp>
#include <gtest/gtest.h>
#include <yamail/resource_pool.hpp>
namespace {
using namespace testing;
using namespace yamail::resource_pool;
using namespace yamail::resource_pool::sync;
using boost::make_shared;
struct resource {};
typedef boost::shared_ptr<resource> resource_ptr;
typedef pool<resource_ptr> resource_pool;
typedef resource_pool::handle_ptr resource_handle_ptr;
const boost::function<resource_ptr ()> make_resource = make_shared<resource>;
class my_resource_handle : public handle_facade<resource_pool> {
public:
my_resource_handle(const resource_handle_ptr& handle)
: handle_facade<resource_pool>(handle) {}
};
struct sync_resource_pool : Test {};
TEST(sync_resource_pool, dummy_create) {
resource_pool pool;
}
TEST(sync_resource_pool, dummy_create_not_empty) {
resource_pool pool(42);
}
TEST(sync_resource_pool, dummy_create_not_empty_with_factory) {
resource_pool pool(42, make_resource);
}
TEST(sync_resource_pool, check_metrics_for_empty) {
resource_pool pool;
EXPECT_EQ(pool.capacity(), 0);
EXPECT_EQ(pool.size(), 0);
EXPECT_EQ(pool.used(), 0);
EXPECT_EQ(pool.available(), 0);
}
TEST(sync_resource_pool, check_capacity) {
const std::size_t capacity = 42;
resource_pool pool(capacity);
EXPECT_EQ(pool.capacity(), capacity);
}
TEST(sync_resource_pool, dummy_get_auto_recylce_handle) {
resource_pool pool(1, make_resource);
resource_handle_ptr handle = pool.get_auto_recycle();
}
TEST(sync_resource_pool, dummy_get_auto_waste_handle) {
resource_pool pool(1, make_resource);
resource_handle_ptr handle = pool.get_auto_waste();
}
TEST(sync_resource_pool, check_metrics_for_not_empty) {
const std::size_t capacity = 42;
resource_pool pool(capacity, make_resource);
EXPECT_EQ(pool.size(), 0);
EXPECT_EQ(pool.used(), 0);
EXPECT_EQ(pool.available(), 0);
{
resource_handle_ptr handle = pool.get_auto_recycle();
EXPECT_EQ(pool.size(), 1);
EXPECT_EQ(pool.used(), 1);
EXPECT_EQ(pool.available(), 0);
}
EXPECT_EQ(pool.size(), 1);
EXPECT_EQ(pool.used(), 0);
EXPECT_EQ(pool.available(), 1);
{
resource_handle_ptr handle1 = pool.get_auto_recycle();
resource_handle_ptr handle2 = pool.get_auto_recycle();
EXPECT_EQ(pool.size(), 2);
EXPECT_EQ(pool.used(), 2);
EXPECT_EQ(pool.available(), 0);
}
EXPECT_EQ(pool.size(), 2);
EXPECT_EQ(pool.used(), 0);
EXPECT_EQ(pool.available(), 2);
{
resource_handle_ptr handle = pool.get_auto_waste();
EXPECT_EQ(pool.size(), 2);
EXPECT_EQ(pool.used(), 1);
EXPECT_EQ(pool.available(), 1);
}
EXPECT_EQ(pool.size(), 1);
EXPECT_EQ(pool.used(), 0);
EXPECT_EQ(pool.available(), 1);
}
TEST(sync_resource_pool, get_auto_recylce_handle_and_recycle) {
resource_pool pool(1, make_resource);
resource_handle_ptr handle = pool.get_auto_recycle();
handle->recycle();
}
TEST(sync_resource_pool, get_auto_recylce_handle_and_waste) {
resource_pool pool(1, make_resource);
resource_handle_ptr handle = pool.get_auto_recycle();
handle->waste();
}
TEST(sync_resource_pool, get_auto_waste_handle_and_recycle) {
resource_pool pool(1, make_resource);
resource_handle_ptr handle = pool.get_auto_waste();
handle->recycle();
}
TEST(sync_resource_pool, get_auto_waste_handle_and_waste) {
resource_pool pool(1, make_resource);
resource_handle_ptr handle = pool.get_auto_waste();
handle->waste();
}
TEST(sync_resource_pool, get_auto_recycle_handle_check_empty) {
resource_pool pool(1, make_resource);
resource_handle_ptr handle = pool.get_auto_recycle();
EXPECT_FALSE(handle->empty());
handle->recycle();
EXPECT_TRUE(handle->empty());
}
TEST(sync_resource_pool, get_auto_recycle_handle_and_get_recycled_expect_exception) {
resource_pool pool(1, make_resource);
resource_handle_ptr handle = pool.get_auto_recycle();
handle->recycle();
EXPECT_THROW(handle->get(), error::empty_handle);
}
TEST(sync_resource_pool, get_auto_recycle_handle_and_recycle_recycled_expect_exception) {
resource_pool pool(1, make_resource);
resource_handle_ptr handle = pool.get_auto_recycle();
handle->recycle();
EXPECT_THROW(handle->recycle(), error::empty_handle);
}
TEST(sync_resource_pool, get_auto_recycle_handle_from_empty_pool_returns_empty_handle) {
resource_pool pool(0, make_resource);
resource_handle_ptr handle = pool.get_auto_recycle();
EXPECT_EQ(handle->error(), error::get_resource_timeout);
}
TEST(sync_resource_pool, dummy_create_my_resoure_handle) {
resource_pool pool(1, make_resource);
my_resource_handle handle(pool.get_auto_recycle());
}
TEST(sync_resource_pool, check_pool_lifetime) {
resource_handle_ptr handle;
{
resource_pool pool(1, make_resource);
handle = pool.get_auto_recycle();
}
}
}
<commit_msg>Fix warnings<commit_after>#include <boost/make_shared.hpp>
#include <gtest/gtest.h>
#include <yamail/resource_pool.hpp>
namespace {
using namespace testing;
using namespace yamail::resource_pool;
using namespace yamail::resource_pool::sync;
using boost::make_shared;
struct resource {};
typedef boost::shared_ptr<resource> resource_ptr;
typedef pool<resource_ptr> resource_pool;
typedef resource_pool::handle_ptr resource_handle_ptr;
const boost::function<resource_ptr ()> make_resource = make_shared<resource>;
class my_resource_handle : public handle_facade<resource_pool> {
public:
my_resource_handle(const resource_handle_ptr& handle)
: handle_facade<resource_pool>(handle) {}
};
struct sync_resource_pool : Test {};
TEST(sync_resource_pool, dummy_create) {
resource_pool pool;
}
TEST(sync_resource_pool, dummy_create_not_empty) {
resource_pool pool(42);
}
TEST(sync_resource_pool, dummy_create_not_empty_with_factory) {
resource_pool pool(42, make_resource);
}
TEST(sync_resource_pool, check_metrics_for_empty) {
resource_pool pool;
EXPECT_EQ(pool.capacity(), 0ul);
EXPECT_EQ(pool.size(), 0ul);
EXPECT_EQ(pool.used(), 0ul);
EXPECT_EQ(pool.available(), 0ul);
}
TEST(sync_resource_pool, check_capacity) {
const std::size_t capacity = 42;
resource_pool pool(capacity);
EXPECT_EQ(pool.capacity(), capacity);
}
TEST(sync_resource_pool, dummy_get_auto_recylce_handle) {
resource_pool pool(1, make_resource);
resource_handle_ptr handle = pool.get_auto_recycle();
}
TEST(sync_resource_pool, dummy_get_auto_waste_handle) {
resource_pool pool(1, make_resource);
resource_handle_ptr handle = pool.get_auto_waste();
}
TEST(sync_resource_pool, check_metrics_for_not_empty) {
const std::size_t capacity = 42;
resource_pool pool(capacity, make_resource);
EXPECT_EQ(pool.size(), 0ul);
EXPECT_EQ(pool.used(), 0ul);
EXPECT_EQ(pool.available(), 0ul);
{
resource_handle_ptr handle = pool.get_auto_recycle();
EXPECT_EQ(pool.size(), 1ul);
EXPECT_EQ(pool.used(), 1ul);
EXPECT_EQ(pool.available(), 0ul);
}
EXPECT_EQ(pool.size(), 1ul);
EXPECT_EQ(pool.used(), 0ul);
EXPECT_EQ(pool.available(), 1ul);
{
resource_handle_ptr handle1 = pool.get_auto_recycle();
resource_handle_ptr handle2 = pool.get_auto_recycle();
EXPECT_EQ(pool.size(), 2ul);
EXPECT_EQ(pool.used(), 2ul);
EXPECT_EQ(pool.available(), 0ul);
}
EXPECT_EQ(pool.size(), 2ul);
EXPECT_EQ(pool.used(), 0ul);
EXPECT_EQ(pool.available(), 2ul);
{
resource_handle_ptr handle = pool.get_auto_waste();
EXPECT_EQ(pool.size(), 2ul);
EXPECT_EQ(pool.used(), 1ul);
EXPECT_EQ(pool.available(), 1ul);
}
EXPECT_EQ(pool.size(), 1ul);
EXPECT_EQ(pool.used(), 0ul);
EXPECT_EQ(pool.available(), 1ul);
}
TEST(sync_resource_pool, get_auto_recylce_handle_and_recycle) {
resource_pool pool(1, make_resource);
resource_handle_ptr handle = pool.get_auto_recycle();
handle->recycle();
}
TEST(sync_resource_pool, get_auto_recylce_handle_and_waste) {
resource_pool pool(1, make_resource);
resource_handle_ptr handle = pool.get_auto_recycle();
handle->waste();
}
TEST(sync_resource_pool, get_auto_waste_handle_and_recycle) {
resource_pool pool(1, make_resource);
resource_handle_ptr handle = pool.get_auto_waste();
handle->recycle();
}
TEST(sync_resource_pool, get_auto_waste_handle_and_waste) {
resource_pool pool(1, make_resource);
resource_handle_ptr handle = pool.get_auto_waste();
handle->waste();
}
TEST(sync_resource_pool, get_auto_recycle_handle_check_empty) {
resource_pool pool(1, make_resource);
resource_handle_ptr handle = pool.get_auto_recycle();
EXPECT_FALSE(handle->empty());
handle->recycle();
EXPECT_TRUE(handle->empty());
}
TEST(sync_resource_pool, get_auto_recycle_handle_and_get_recycled_expect_exception) {
resource_pool pool(1, make_resource);
resource_handle_ptr handle = pool.get_auto_recycle();
handle->recycle();
EXPECT_THROW(handle->get(), error::empty_handle);
}
TEST(sync_resource_pool, get_auto_recycle_handle_and_recycle_recycled_expect_exception) {
resource_pool pool(1, make_resource);
resource_handle_ptr handle = pool.get_auto_recycle();
handle->recycle();
EXPECT_THROW(handle->recycle(), error::empty_handle);
}
TEST(sync_resource_pool, get_auto_recycle_handle_from_empty_pool_returns_empty_handle) {
resource_pool pool(0, make_resource);
resource_handle_ptr handle = pool.get_auto_recycle();
EXPECT_EQ(handle->error(), error::get_resource_timeout);
}
TEST(sync_resource_pool, dummy_create_my_resoure_handle) {
resource_pool pool(1, make_resource);
my_resource_handle handle(pool.get_auto_recycle());
}
TEST(sync_resource_pool, check_pool_lifetime) {
resource_handle_ptr handle;
{
resource_pool pool(1, make_resource);
handle = pool.get_auto_recycle();
}
}
}
<|endoftext|> |
<commit_before>#include <tiramisu/tiramisu.h>
using namespace tiramisu;
void gen(std::string name, int size, int val0, int val1)
{
tiramisu::init(name);
tiramisu::function *function0 = global::get_implicit_function();
tiramisu::constant N("N", tiramisu::expr((int32_t) size), p_int32, true, NULL, 0, function0);
tiramisu::var i("i", 0, N), j("j", 0, N);
tiramisu::var i0("i0"), j0("j0"), i1("i1"), j1("j1");
tiramisu::computation S0(tiramisu::expr((uint8_t) (val0 + val1)), i, j);
S0.tile(i, j, 2, 2, i0, j0, i1, j1);
S0.tag_parallel_level(i0);
tiramisu::buffer buf0("buf0", {size, size}, tiramisu::p_uint8, a_output, function0);
S0.store_in(&buf0, {i ,j});
function0->codegen({&buf0}, "build/generated_fct_test_116.o");
}
int main(int argc, char **argv)
{
gen("func", 10, 3, 4);
return 0;
}
<commit_msg>Fix test<commit_after>#include <tiramisu/tiramisu.h>
using namespace tiramisu;
void gen(std::string name, int size, int val0, int val1)
{
tiramisu::init(name);
tiramisu::function *function0 = global::get_implicit_function();
tiramisu::constant N("N", tiramisu::expr((int32_t) size), p_int32, true, NULL, 0, function0);
tiramisu::var i("i", 0, N), j("j", 0, N);
tiramisu::var i0("i0"), j0("j0"), i1("i1"), j1("j1");
tiramisu::computation S0({i, j}, tiramisu::expr((uint8_t) (val0 + val1)));
S0.tile(i, j, 2, 2, i0, j0, i1, j1);
S0.tag_parallel_level(i0);
tiramisu::buffer buf0("buf0", {size, size}, tiramisu::p_uint8, a_output, function0);
S0.store_in(&buf0, {i ,j});
function0->codegen({&buf0}, "build/generated_fct_test_116.o");
}
int main(int argc, char **argv)
{
gen("func", 10, 3, 4);
return 0;
}
<|endoftext|> |
<commit_before>#include <catch.hpp>
#include <ecs.hpp>
enum class ColumnNames
{
Surname,
Age,
Height
};
template <ColumnNames Name, class T>
using mycolumn = helene::column_description<ColumnNames, Name, T>;
TEST_CASE("", "")
{
helene::table<ColumnNames,
mycolumn<ColumnNames::Surname, std::string>,
mycolumn<ColumnNames::Age, int>,
mycolumn<ColumnNames::Height, float>>
tb;
const auto first_row = tb.insert_row("Bergesen", 35, 1.83f);
const auto second_row = tb.insert_row("Lund-Hansen", 70, 1.80f);
CHECK(tb.get<ColumnNames::Surname>(first_row) == "Bergesen");
CHECK(tb.get<ColumnNames::Surname>(second_row) == "Lund-Hansen");
CHECK(tb.get<ColumnNames::Age>(first_row) == 35);
CHECK(tb.get<ColumnNames::Age>(second_row) == 70);
CHECK(tb.size() == 2);
SECTION("erase first row")
{
tb.erase_row(first_row);
CHECK(tb.get<ColumnNames::Surname>(second_row) == "Lund-Hansen");
CHECK(tb.get<ColumnNames::Age>(second_row) == 70);
CHECK(tb.size() == 1);
}
SECTION("erase second row")
{
tb.erase_row(second_row);
CHECK(tb.get<ColumnNames::Surname>(first_row) == "Bergesen");
CHECK(tb.get<ColumnNames::Age>(first_row) == 35);
CHECK(tb.size() == 1);
}
SECTION("get iterator range to Surname column")
{
auto it_beg = tb.column_begin<ColumnNames::Surname>();
auto it_end = tb.column_end<ColumnNames::Surname>();
}
}
<commit_msg>Add unit test for iterators. modified: tests/test_ecs.cpp<commit_after>#include <iterator>
#include <catch.hpp>
#include <ecs.hpp>
enum class ColumnNames
{
Surname,
Age,
Height
};
template <ColumnNames Name, class T>
using mycolumn = helene::column_description<ColumnNames, Name, T>;
TEST_CASE("", "")
{
helene::table<ColumnNames,
mycolumn<ColumnNames::Surname, std::string>,
mycolumn<ColumnNames::Age, int>,
mycolumn<ColumnNames::Height, float>>
tb;
const auto first_row = tb.insert_row("Bergesen", 35, 1.83f);
const auto second_row = tb.insert_row("Lund-Hansen", 70, 1.80f);
CHECK(tb.get<ColumnNames::Surname>(first_row) == "Bergesen");
CHECK(tb.get<ColumnNames::Surname>(second_row) == "Lund-Hansen");
CHECK(tb.get<ColumnNames::Age>(first_row) == 35);
CHECK(tb.get<ColumnNames::Age>(second_row) == 70);
CHECK(tb.size() == 2);
SECTION("erase first row")
{
tb.erase_row(first_row);
CHECK(tb.get<ColumnNames::Surname>(second_row) == "Lund-Hansen");
CHECK(tb.get<ColumnNames::Age>(second_row) == 70);
CHECK(tb.size() == 1);
}
SECTION("erase second row")
{
tb.erase_row(second_row);
CHECK(tb.get<ColumnNames::Surname>(first_row) == "Bergesen");
CHECK(tb.get<ColumnNames::Age>(first_row) == 35);
CHECK(tb.size() == 1);
}
SECTION("get iterator range to Surname column")
{
auto it_beg = tb.column_begin<ColumnNames::Surname>();
auto it_end = tb.column_end<ColumnNames::Surname>();
std::vector<std::string> surnames(it_beg, it_end);
CHECK(std::distance(it_beg, it_end) == 2);
CHECK_THAT(surnames, Catch::VectorContains(std::string("Bergesen")));
CHECK_THAT(surnames, Catch::VectorContains(std::string("Lund-Hansen")));
}
}
<|endoftext|> |
<commit_before>/*
* Copyright (C) 2016,2017 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 "test_guid.h"
#include "../src/guid/guid.h"
#include "utils.h"
constexpr int NUM_TESTS = 1000;
constexpr size_t MIN_COMPACTED_LENGTH = 2;
constexpr size_t MAX_COMPACTED_LENGTH = 11;
constexpr size_t MIN_CONDENSED_LENGTH = 2;
constexpr size_t MAX_CONDENSED_LENGTH = 16;
constexpr size_t MIN_EXPANDED_LENGTH = 3;
constexpr size_t MAX_EXPANDED_LENGTH = 17;
int test_guid() {
INIT_LOG
GuidGenerator generator;
auto g1 = generator.newGuid();
auto g2 = generator.newGuid();
auto g3 = generator.newGuid();
L_DEBUG(nullptr, "Guids generated: %s %s %s", repr(g1.to_string()).c_str(), repr(g2.to_string()).c_str(), repr(g3.to_string()).c_str());
if (g1 == g2 || g1 == g3 || g2 == g3) {
L_ERR(nullptr, "ERROR: Not all random guids are different");
RETURN(1);
}
std::string u1("3c0f2be3-ff4f-40ab-b157-c51a81eff176");
std::string u2("e47fcfdf-8db6-4469-a97f-57146dc41ced");
std::string u3("b2ce58e8-d049-4705-b0cb-fe7435843781");
Guid s1(u1);
Guid s2(u2);
Guid s3(u3);
Guid s4(u1);
if (s1 == s2) {
L_ERR(nullptr, "ERROR: s1 and s2 must be different");
RETURN(1);
}
if (s1 != s4) {
L_ERR(nullptr, "ERROR: s1 and s4 must be equal");
RETURN(1);
}
if (s1.to_string() != u1) {
L_ERR(nullptr, "ERROR: string generated from s1 is wrong");
RETURN(1);
}
if (s2.to_string() != u2) {
L_ERR(nullptr, "ERROR: string generated from s2 is wrong");
RETURN(1);
}
if (s3.to_string() != u3) {
L_ERR(nullptr, "ERROR: string generated from s3 is wrong");
RETURN(1);
}
RETURN(0);
}
int test_special_guids() {
std::vector<std::string> special_uuids({
"00000000-0000-0000-0000-000000000000",
"00000000-0000-1000-a000-000000000000",
"00000000-0000-4000-b000-000000000000",
"00000000-2000-1000-c000-000000000000",
"00000000-2000-4000-c000-000000000000",
"00000000-2000-2000-0000-000000000000",
});
int cont = 0;
for (const auto& uuid_orig : special_uuids) {
Guid guid(uuid_orig);
Guid guid2 = Guid::unserialise(guid.serialise());
const auto uuid_rec = guid2.to_string();
if (uuid_orig != uuid_rec) {
++cont;
L_ERR(nullptr, "ERROR: Expected: %s Result: %s", uuid_orig.c_str(), uuid_rec.c_str());
}
}
RETURN(cont);
}
int test_compacted_guids() {
int cont = 0;
size_t min_length = 20, max_length = 0;
for (int i = 0; i < NUM_TESTS; ++i) {
Guid guid = GuidGenerator().newGuid(true);
const auto uuid_orig = guid.to_string();
const auto serialised = guid.serialise();
Guid guid2 = Guid::unserialise(serialised);
const auto uuid_rec = guid2.to_string();
if (uuid_orig != uuid_rec) {
++cont;
L_ERR(stderr, "ERROR: Expected: %s Result: %s", uuid_orig.c_str(), uuid_rec.c_str());
}
if (max_length < serialised.length()) {
max_length = serialised.length();
}
if (min_length > serialised.length()) {
min_length = serialised.length();
}
}
if (max_length > MAX_COMPACTED_LENGTH) {
L_ERR(nullptr, "ERROR: Max length for compacted uuid is %zu", MAX_COMPACTED_LENGTH);
++cont;
}
if (min_length < MIN_COMPACTED_LENGTH) {
L_ERR(nullptr, "ERROR: Min length for compacted uuid is %zu", MIN_COMPACTED_LENGTH);
++cont;
}
RETURN(cont);
}
int test_condensed_guids() {
int cont = 0;
size_t min_length = 20, max_length = 0;
for (int i = 0; i < NUM_TESTS; ++i) {
Guid guid = GuidGenerator().newGuid(false);
const auto uuid_orig = guid.to_string();
const auto serialised = guid.serialise();
Guid guid2 = Guid::unserialise(serialised);
const auto uuid_rec = guid2.to_string();
if (uuid_orig != uuid_rec) {
++cont;
L_ERR(stderr, "ERROR: Expected: %s Result: %s", uuid_orig.c_str(), uuid_rec.c_str());
}
if (max_length < serialised.length()) {
max_length = serialised.length();
}
if (min_length > serialised.length()) {
min_length = serialised.length();
}
}
if (max_length > MAX_CONDENSED_LENGTH) {
L_ERR(nullptr, "ERROR: Max length for condensed uuid is %zu", MAX_CONDENSED_LENGTH);
++cont;
}
if (min_length < MIN_CONDENSED_LENGTH) {
L_ERR(nullptr, "ERROR: Min length for condensed uuid is %zu", MIN_CONDENSED_LENGTH);
++cont;
}
RETURN(cont);
}
int test_expanded_guids() {
int cont = 0;
size_t min_length = 20, max_length = 0;
for (auto i = 0; i < NUM_TESTS; ++i) {
std::string uuid_orig;
uuid_orig.reserve(36);
const char x[] = {
'0', '1', '2', '3', '4', '5', '6', '7',
'8', '9', 'a', 'b', 'c', 'd', 'e', 'f',
};
for (int i = 0; i < 8; ++i) {
uuid_orig.push_back(x[random_int(0, 15)]);
}
uuid_orig.push_back('-');
for (int i = 0; i < 4; ++i) {
uuid_orig.push_back(x[random_int(0, 15)]);
}
uuid_orig.push_back('-');
for (int i = 0; i < 4; ++i) {
uuid_orig.push_back(x[random_int(0, 15)]);
}
uuid_orig.push_back('-');
for (int i = 0; i < 4; ++i) {
uuid_orig.push_back(x[random_int(0, 15)]);
}
uuid_orig.push_back('-');
for (int i = 0; i < 12; ++i) {
uuid_orig.push_back(x[random_int(0, 15)]);
}
// If random uuid is rfc 4122, change the variant.
const auto& version = uuid_orig[14];
auto& variant = uuid_orig[19];
if ((version == 1 || version == 4) && (variant == '8' || variant == '9' || variant == 'a' || variant == 'b')) {
variant = '7';
}
Guid guid(uuid_orig);
const auto serialised = guid.serialise();
Guid guid2 = Guid::unserialise(serialised);
const auto uuid_rec = guid2.to_string();
if (uuid_orig != uuid_rec) {
++cont;
L_ERR(nullptr, "ERROR: Expected: %s Result: %s\n", uuid_orig.c_str(), uuid_rec.c_str());
}
if (max_length < serialised.length()) {
max_length = serialised.length();
}
if (min_length > serialised.length()) {
min_length = serialised.length();
}
}
if (max_length > MAX_EXPANDED_LENGTH) {
L_ERR(nullptr, "ERROR: Max length for expanded uuid is %zu", MAX_EXPANDED_LENGTH);
++cont;
}
if (min_length < MIN_EXPANDED_LENGTH) {
L_ERR(nullptr, "ERROR: Min length for expanded uuid is %zu", MIN_EXPANDED_LENGTH);
++cont;
}
RETURN(cont);
}
int test_several_guids() {
size_t cont = 0;
for (auto i = 0; i < NUM_TESTS; ++i) {
std::vector<std::string> str_uuids;
std::vector<std::string> norm_uuids;
switch (i % 3) {
case 0: {
Guid guid = GuidGenerator().newGuid(true);
str_uuids.push_back(guid.to_string());
norm_uuids.push_back(guid.to_string());
guid = GuidGenerator().newGuid(false);
str_uuids.push_back(guid.to_string());
norm_uuids.push_back(guid.to_string());
guid = GuidGenerator().newGuid(true);
str_uuids.push_back(guid.to_string());
norm_uuids.push_back(guid.to_string());
break;
}
case 1: {
Guid guid = GuidGenerator().newGuid(true);
str_uuids.push_back(guid.to_string());
norm_uuids.push_back(base64::encode(guid.serialise()));
guid = GuidGenerator().newGuid(false);
str_uuids.push_back(guid.to_string());
norm_uuids.push_back(base64::encode(guid.serialise()));
guid = GuidGenerator().newGuid(true);
str_uuids.push_back(guid.to_string());
norm_uuids.push_back(base64::encode(guid.serialise()));
break;
}
default: {
Guid guid = GuidGenerator().newGuid(true);
str_uuids.push_back(guid.to_string());
auto serialised = guid.serialise();
guid = GuidGenerator().newGuid(false);
str_uuids.push_back(guid.to_string());
serialised.append(guid.serialise());
guid = GuidGenerator().newGuid(true);
str_uuids.push_back(guid.to_string());
serialised.append(guid.serialise());
norm_uuids.push_back(base64::encode(serialised));
break;
}
}
std::vector<Guid> guids;
const auto serialised = Guid::serialise(norm_uuids.begin(), norm_uuids.end());
Guid::unserialise(serialised, std::back_inserter(guids));
if (guids.size() != str_uuids.size()) {
++cont;
L_ERR(nullptr, "ERROR: Different sizes. Expected: %zu Result: %zu", str_uuids.size(), guids.size());
} else {
auto it = str_uuids.begin();
for (const auto& guid : guids) {
const auto str_guid = guid.to_string();
if (str_guid != *it) {
++cont;
L_ERR(nullptr, "ERROR: Expected: %s Result: %s", it->c_str(), str_guid.c_str());
}
++it;
}
}
}
RETURN(cont);
}
<commit_msg>Add special uuid test<commit_after>/*
* Copyright (C) 2016,2017 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 "test_guid.h"
#include "../src/guid/guid.h"
#include "utils.h"
constexpr int NUM_TESTS = 1000;
constexpr size_t MIN_COMPACTED_LENGTH = 2;
constexpr size_t MAX_COMPACTED_LENGTH = 11;
constexpr size_t MIN_CONDENSED_LENGTH = 2;
constexpr size_t MAX_CONDENSED_LENGTH = 16;
constexpr size_t MIN_EXPANDED_LENGTH = 3;
constexpr size_t MAX_EXPANDED_LENGTH = 17;
int test_guid() {
INIT_LOG
GuidGenerator generator;
auto g1 = generator.newGuid();
auto g2 = generator.newGuid();
auto g3 = generator.newGuid();
L_DEBUG(nullptr, "Guids generated: %s %s %s", repr(g1.to_string()).c_str(), repr(g2.to_string()).c_str(), repr(g3.to_string()).c_str());
if (g1 == g2 || g1 == g3 || g2 == g3) {
L_ERR(nullptr, "ERROR: Not all random guids are different");
RETURN(1);
}
std::string u1("3c0f2be3-ff4f-40ab-b157-c51a81eff176");
std::string u2("e47fcfdf-8db6-4469-a97f-57146dc41ced");
std::string u3("b2ce58e8-d049-4705-b0cb-fe7435843781");
Guid s1(u1);
Guid s2(u2);
Guid s3(u3);
Guid s4(u1);
if (s1 == s2) {
L_ERR(nullptr, "ERROR: s1 and s2 must be different");
RETURN(1);
}
if (s1 != s4) {
L_ERR(nullptr, "ERROR: s1 and s4 must be equal");
RETURN(1);
}
if (s1.to_string() != u1) {
L_ERR(nullptr, "ERROR: string generated from s1 is wrong");
RETURN(1);
}
if (s2.to_string() != u2) {
L_ERR(nullptr, "ERROR: string generated from s2 is wrong");
RETURN(1);
}
if (s3.to_string() != u3) {
L_ERR(nullptr, "ERROR: string generated from s3 is wrong");
RETURN(1);
}
RETURN(0);
}
int test_special_guids() {
std::vector<std::string> special_uuids({
"00000000-0000-0000-0000-000000000000",
"00000000-0000-1000-8000-000000000000",
"00000000-0000-1000-a000-000000000000",
"00000000-0000-4000-b000-000000000000",
"00000000-2000-1000-c000-000000000000",
"00000000-2000-4000-c000-000000000000",
"00000000-2000-2000-0000-000000000000",
});
int cont = 0;
for (const auto& uuid_orig : special_uuids) {
Guid guid(uuid_orig);
Guid guid2 = Guid::unserialise(guid.serialise());
const auto uuid_rec = guid2.to_string();
if (uuid_orig != uuid_rec) {
++cont;
L_ERR(nullptr, "ERROR: Expected: %s Result: %s", uuid_orig.c_str(), uuid_rec.c_str());
}
}
RETURN(cont);
}
int test_compacted_guids() {
int cont = 0;
size_t min_length = 20, max_length = 0;
for (int i = 0; i < NUM_TESTS; ++i) {
Guid guid = GuidGenerator().newGuid(true);
const auto uuid_orig = guid.to_string();
const auto serialised = guid.serialise();
Guid guid2 = Guid::unserialise(serialised);
const auto uuid_rec = guid2.to_string();
if (uuid_orig != uuid_rec) {
++cont;
L_ERR(stderr, "ERROR: Expected: %s Result: %s", uuid_orig.c_str(), uuid_rec.c_str());
}
if (max_length < serialised.length()) {
max_length = serialised.length();
}
if (min_length > serialised.length()) {
min_length = serialised.length();
}
}
if (max_length > MAX_COMPACTED_LENGTH) {
L_ERR(nullptr, "ERROR: Max length for compacted uuid is %zu", MAX_COMPACTED_LENGTH);
++cont;
}
if (min_length < MIN_COMPACTED_LENGTH) {
L_ERR(nullptr, "ERROR: Min length for compacted uuid is %zu", MIN_COMPACTED_LENGTH);
++cont;
}
RETURN(cont);
}
int test_condensed_guids() {
int cont = 0;
size_t min_length = 20, max_length = 0;
for (int i = 0; i < NUM_TESTS; ++i) {
Guid guid = GuidGenerator().newGuid(false);
const auto uuid_orig = guid.to_string();
const auto serialised = guid.serialise();
Guid guid2 = Guid::unserialise(serialised);
const auto uuid_rec = guid2.to_string();
if (uuid_orig != uuid_rec) {
++cont;
L_ERR(stderr, "ERROR: Expected: %s Result: %s", uuid_orig.c_str(), uuid_rec.c_str());
}
if (max_length < serialised.length()) {
max_length = serialised.length();
}
if (min_length > serialised.length()) {
min_length = serialised.length();
}
}
if (max_length > MAX_CONDENSED_LENGTH) {
L_ERR(nullptr, "ERROR: Max length for condensed uuid is %zu", MAX_CONDENSED_LENGTH);
++cont;
}
if (min_length < MIN_CONDENSED_LENGTH) {
L_ERR(nullptr, "ERROR: Min length for condensed uuid is %zu", MIN_CONDENSED_LENGTH);
++cont;
}
RETURN(cont);
}
int test_expanded_guids() {
int cont = 0;
size_t min_length = 20, max_length = 0;
for (auto i = 0; i < NUM_TESTS; ++i) {
std::string uuid_orig;
uuid_orig.reserve(36);
const char x[] = {
'0', '1', '2', '3', '4', '5', '6', '7',
'8', '9', 'a', 'b', 'c', 'd', 'e', 'f',
};
for (int i = 0; i < 8; ++i) {
uuid_orig.push_back(x[random_int(0, 15)]);
}
uuid_orig.push_back('-');
for (int i = 0; i < 4; ++i) {
uuid_orig.push_back(x[random_int(0, 15)]);
}
uuid_orig.push_back('-');
for (int i = 0; i < 4; ++i) {
uuid_orig.push_back(x[random_int(0, 15)]);
}
uuid_orig.push_back('-');
for (int i = 0; i < 4; ++i) {
uuid_orig.push_back(x[random_int(0, 15)]);
}
uuid_orig.push_back('-');
for (int i = 0; i < 12; ++i) {
uuid_orig.push_back(x[random_int(0, 15)]);
}
// If random uuid is rfc 4122, change the variant.
const auto& version = uuid_orig[14];
auto& variant = uuid_orig[19];
if ((version == 1 || version == 4) && (variant == '8' || variant == '9' || variant == 'a' || variant == 'b')) {
variant = '7';
}
Guid guid(uuid_orig);
const auto serialised = guid.serialise();
Guid guid2 = Guid::unserialise(serialised);
const auto uuid_rec = guid2.to_string();
if (uuid_orig != uuid_rec) {
++cont;
L_ERR(nullptr, "ERROR: Expected: %s Result: %s\n", uuid_orig.c_str(), uuid_rec.c_str());
}
if (max_length < serialised.length()) {
max_length = serialised.length();
}
if (min_length > serialised.length()) {
min_length = serialised.length();
}
}
if (max_length > MAX_EXPANDED_LENGTH) {
L_ERR(nullptr, "ERROR: Max length for expanded uuid is %zu", MAX_EXPANDED_LENGTH);
++cont;
}
if (min_length < MIN_EXPANDED_LENGTH) {
L_ERR(nullptr, "ERROR: Min length for expanded uuid is %zu", MIN_EXPANDED_LENGTH);
++cont;
}
RETURN(cont);
}
int test_several_guids() {
size_t cont = 0;
for (auto i = 0; i < NUM_TESTS; ++i) {
std::vector<std::string> str_uuids;
std::vector<std::string> norm_uuids;
switch (i % 3) {
case 0: {
Guid guid = GuidGenerator().newGuid(true);
str_uuids.push_back(guid.to_string());
norm_uuids.push_back(guid.to_string());
guid = GuidGenerator().newGuid(false);
str_uuids.push_back(guid.to_string());
norm_uuids.push_back(guid.to_string());
guid = GuidGenerator().newGuid(true);
str_uuids.push_back(guid.to_string());
norm_uuids.push_back(guid.to_string());
break;
}
case 1: {
Guid guid = GuidGenerator().newGuid(true);
str_uuids.push_back(guid.to_string());
norm_uuids.push_back(base64::encode(guid.serialise()));
guid = GuidGenerator().newGuid(false);
str_uuids.push_back(guid.to_string());
norm_uuids.push_back(base64::encode(guid.serialise()));
guid = GuidGenerator().newGuid(true);
str_uuids.push_back(guid.to_string());
norm_uuids.push_back(base64::encode(guid.serialise()));
break;
}
default: {
Guid guid = GuidGenerator().newGuid(true);
str_uuids.push_back(guid.to_string());
auto serialised = guid.serialise();
guid = GuidGenerator().newGuid(false);
str_uuids.push_back(guid.to_string());
serialised.append(guid.serialise());
guid = GuidGenerator().newGuid(true);
str_uuids.push_back(guid.to_string());
serialised.append(guid.serialise());
norm_uuids.push_back(base64::encode(serialised));
break;
}
}
std::vector<Guid> guids;
const auto serialised = Guid::serialise(norm_uuids.begin(), norm_uuids.end());
Guid::unserialise(serialised, std::back_inserter(guids));
if (guids.size() != str_uuids.size()) {
++cont;
L_ERR(nullptr, "ERROR: Different sizes. Expected: %zu Result: %zu", str_uuids.size(), guids.size());
} else {
auto it = str_uuids.begin();
for (const auto& guid : guids) {
const auto str_guid = guid.to_string();
if (str_guid != *it) {
++cont;
L_ERR(nullptr, "ERROR: Expected: %s Result: %s", it->c_str(), str_guid.c_str());
}
++it;
}
}
}
RETURN(cont);
}
<|endoftext|> |
<commit_before>#define BOOST_TEST_MODULE json test
#include <boost/test/unit_test.hpp>
#include <ten/json.hh>
#ifdef TEN_JSON_CXX11
#include <ten/jserial.hh>
#include <ten/jserial_maybe.hh>
#include <ten/jserial_seq.hh>
#include <ten/jserial_assoc.hh>
#include <ten/jserial_enum.hh>
#endif
#include <array>
using namespace std;
using namespace ten;
const char json_text[] =
"{ \"store\": {"
" \"book\": ["
" { \"category\": \"reference\","
" \"author\": \"Nigel Rees\","
" \"title\": \"Sayings of the Century\","
" \"price\": 8.95"
" },"
" { \"category\": \"fiction\","
" \"author\": \"Evelyn Waugh\","
" \"title\": \"Sword of Honour\","
" \"price\": 12.99"
" },"
" { \"category\": \"fiction\","
" \"author\": \"Herman Melville\","
" \"title\": \"Moby Dick\","
" \"isbn\": \"0-553-21311-3\","
" \"price\": 8.99"
" },"
" { \"category\": \"fiction\","
" \"author\": \"J. R. R. Tolkien\","
" \"title\": \"The Lord of the Rings\","
" \"isbn\": \"0-395-19395-8\","
" \"price\": 22.99"
" }"
" ],"
" \"bicycle\": {"
" \"color\": \"red\","
" \"price\": 19.95"
" }"
" }"
"}";
BOOST_AUTO_TEST_CASE(json_test_path1) {
json o(json::load(json_text));
BOOST_REQUIRE(o.get());
static const char a1[] = "[\"Nigel Rees\", \"Evelyn Waugh\", \"Herman Melville\", \"J. R. R. Tolkien\"]";
json r1(o.path("/store/book/author"));
BOOST_CHECK_EQUAL(json::load(a1), r1);
json r2(o.path("//author"));
BOOST_CHECK_EQUAL(json::load(a1), r2);
// jansson hashtable uses size_t for hash
// we think this is causing the buckets to change on 32bit vs. 64bit
#if (__SIZEOF_SIZE_T__ == 4)
static const char a3[] = "[{\"category\": \"reference\", \"author\": \"Nigel Rees\", \"title\": \"Sayings of the Century\", \"price\": 8.95}, {\"category\": \"fiction\", \"author\": \"Evelyn Waugh\", \"title\": \"Sword of Honour\", \"price\": 12.99}, {\"category\": \"fiction\", \"author\": \"Herman Melville\", \"title\": \"Moby Dick\", \"isbn\": \"0-553-21311-3\", \"price\": 8.99}, {\"category\": \"fiction\", \"author\": \"J. R. R. Tolkien\", \"title\": \"The Lord of the Rings\", \"isbn\": \"0-395-19395-8\", \"price\": 22.99}, {\"color\": \"red\", \"price\": 19.95}]";
#elif (__SIZEOF_SIZE_T__ == 8)
static const char a3[] = "[{\"color\": \"red\", \"price\": 19.95}, {\"category\": \"reference\", \"author\": \"Nigel Rees\", \"title\": \"Sayings of the Century\", \"price\": 8.95}, {\"category\": \"fiction\", \"author\": \"Evelyn Waugh\", \"title\": \"Sword of Honour\", \"price\": 12.99}, {\"category\": \"fiction\", \"author\": \"Herman Melville\", \"title\": \"Moby Dick\", \"isbn\": \"0-553-21311-3\", \"price\": 8.99}, {\"category\": \"fiction\", \"author\": \"J. R. R. Tolkien\", \"title\": \"The Lord of the Rings\", \"isbn\": \"0-395-19395-8\", \"price\": 22.99}]";
#endif
json r3(o.path("/store/*"));
json t3(json::load(a3));
BOOST_CHECK_EQUAL(t3, r3);
#if (__SIZEOF_SIZE_T__ == 4)
static const char a4[] = "[8.95, 12.99, 8.99, 22.99, 19.95]";
#elif (__SIZEOF_SIZE_T__ == 8)
static const char a4[] = "[19.95, 8.95, 12.99, 8.99, 22.99]";
#endif
json r4(o.path("/store//price"));
BOOST_CHECK_EQUAL(json::load(a4), r4);
static const char a5[] = "{\"category\": \"fiction\", \"author\": \"J. R. R. Tolkien\", \"title\": \"The Lord of the Rings\", \"isbn\": \"0-395-19395-8\", \"price\": 22.99}";
json r5(o.path("//book[3]"));
BOOST_CHECK_EQUAL(json::load(a5), r5);
static const char a6[] = "\"J. R. R. Tolkien\"";
json r6(o.path("/store/book[3]/author"));
BOOST_CHECK_EQUAL(json::load(a6), r6);
BOOST_CHECK(json::load(a6) == r6);
static const char a7[] = "[{\"category\": \"fiction\", \"author\": \"Evelyn Waugh\", \"title\": \"Sword of Honour\", \"price\": 12.99}, {\"category\": \"fiction\", \"author\": \"Herman Melville\", \"title\": \"Moby Dick\", \"isbn\": \"0-553-21311-3\", \"price\": 8.99}, {\"category\": \"fiction\", \"author\": \"J. R. R. Tolkien\", \"title\": \"The Lord of the Rings\", \"isbn\": \"0-395-19395-8\", \"price\": 22.99}]";
json r7(o.path("/store/book[category=\"fiction\"]"));
BOOST_CHECK_EQUAL(json::load(a7), r7);
}
BOOST_AUTO_TEST_CASE(json_test_path2) {
json o(json::load("[{\"type\": 0}, {\"type\": 1}]"));
BOOST_CHECK_EQUAL(json::load("[{\"type\":1}]"), o.path("/[type=1]"));
}
BOOST_AUTO_TEST_CASE(json_test_filter_key_exists) {
json o(json::load(json_text));
BOOST_REQUIRE(o.get());
static const char a[] = "["
" { \"category\": \"fiction\","
" \"author\": \"Herman Melville\","
" \"title\": \"Moby Dick\","
" \"isbn\": \"0-553-21311-3\","
" \"price\": 8.99"
" },"
" { \"category\": \"fiction\","
" \"author\": \"J. R. R. Tolkien\","
" \"title\": \"The Lord of the Rings\","
" \"isbn\": \"0-395-19395-8\","
" \"price\": 22.99"
" }]";
json r(o.path("//book[isbn]"));
BOOST_CHECK_EQUAL(json::load(a), r);
json r1(o.path("//book[doesnotexist]"));
BOOST_REQUIRE(r1.is_array());
BOOST_CHECK_EQUAL(0, r1.asize());
}
BOOST_AUTO_TEST_CASE(json_test_truth) {
json o(json::object());
BOOST_CHECK(o.get("nothing").is_true() == false);
BOOST_CHECK(o.get("nothing").is_false() == false);
BOOST_CHECK(o.get("nothing").is_null() == false);
BOOST_CHECK(!o.get("nothing"));
}
BOOST_AUTO_TEST_CASE(json_test_path3) {
json o(json::load(json_text));
BOOST_REQUIRE(o.get());
BOOST_CHECK_EQUAL(o, o.path("/"));
BOOST_CHECK_EQUAL("Sayings of the Century",
o.path("/store/book[category=\"reference\"]/title"));
static const char text[] = "["
"{\"type\":\"a\", \"value\":0},"
"{\"type\":\"b\", \"value\":1},"
"{\"type\":\"c\", \"value\":2},"
"{\"type\":\"c\", \"value\":3}"
"]";
BOOST_CHECK_EQUAL(json(1), json::load(text).path("/[type=\"b\"]/value"));
}
BOOST_AUTO_TEST_CASE(json_init_list) {
json meta{
{ "foo", 17 },
{ "bar", 23 },
{ "baz", true },
{ "corge", json::array({ 1, 3.14159 }) },
{ "grault", json::array({ "hello", string("world") }) },
};
BOOST_REQUIRE(meta);
BOOST_REQUIRE(meta.is_object());
BOOST_CHECK_EQUAL(meta.osize(), 5);
BOOST_CHECK_EQUAL(meta["foo"].integer(), 17);
BOOST_CHECK_EQUAL(meta["corge"][0].integer(), 1);
BOOST_CHECK_EQUAL(meta["grault"][1].str(), "world");
}
template <class T>
inline void test_conv(T val, json j, json_type t) {
json j2 = to_json(val);
BOOST_CHECK_EQUAL(j2.type(), t);
BOOST_CHECK_EQUAL(j, j2);
T val2 = json_cast<T>(j2);
BOOST_CHECK_EQUAL(val, val2);
}
template <class T, json_type TYPE = JSON_INTEGER>
inline void test_conv_num() {
typedef numeric_limits<T> lim;
T range[5] = { lim::min(), T(-1), 0, T(1), lim::max() };
for (unsigned i = 0; i < 5; ++i)
test_conv<T>(range[i], json(range[i]), TYPE);
}
BOOST_AUTO_TEST_CASE(json_conversions) {
test_conv<string>(string("hello"), json::str("hello"), JSON_STRING);
BOOST_CHECK_EQUAL(to_json("world"), json::str("world"));
test_conv_num<short>();
test_conv_num<int>();
test_conv_num<long>();
test_conv_num<long long>();
test_conv_num<unsigned short>();
test_conv_num<unsigned>();
#if ULONG_MAX < LLONG_MAX
test_conv_num<unsigned long>();
#endif
test_conv_num<double, JSON_REAL>();
test_conv_num<float, JSON_REAL>();
test_conv<bool>(true, json::jtrue(), JSON_TRUE);
test_conv<bool>(false, json::jfalse(), JSON_FALSE);
}
BOOST_AUTO_TEST_CASE(json_create) {
json obj1;
obj1.set("test", "set");
BOOST_CHECK(obj1);
BOOST_CHECK(obj1.get("test"));
json root{
{"obj1", obj1}
};
BOOST_CHECK_EQUAL(root.get("obj1"), obj1);
obj1.set("this", "that");
BOOST_CHECK_EQUAL(root.get("obj1").get("this").str(), "that");
json obj2{ {"answer", 42} };
obj1.set("obj2", obj2);
BOOST_CHECK_EQUAL(root.get("obj1").get("obj2"), obj2);
}
#ifdef TEN_JSON_CXX11
struct corge {
int foo, bar;
corge() : foo(), bar() {}
corge(int foo_, int bar_) : foo(foo_), bar(bar_) {}
};
template <class AR>
inline void serialize(AR &ar, corge &c) {
ar & kv("foo", c.foo) & kv("bar", c.bar);
}
inline bool operator == (const corge &a, const corge &b) {
return a.foo == b.foo && a.bar == b.bar;
}
enum captain { kirk, picard, janeway, sisko };
const array<string, 4> captain_names = {{ "kirk", "picard", "janeway", "sisko" }};
template <class AR>
inline void serialize(AR &ar, captain &c) {
serialize_enum(ar, c, captain_names);
}
BOOST_AUTO_TEST_CASE(json_serial) {
corge c1(42, 17);
auto j = jsave_all(c1);
corge c2;
json_loader(j) >> c2;
BOOST_CHECK(c1 == c2);
map<string, int> m;
json_loader(j) >> m;
BOOST_CHECK_EQUAL(m.size(), 2);
BOOST_CHECK(m.find("foo") != m.end());
BOOST_CHECK(m.find("bar") != m.end());
BOOST_CHECK_EQUAL(m["foo"], 42);
BOOST_CHECK_EQUAL(m["bar"], 17);
#if BOOST_VERSION >= 104800
flat_map<string, int> f;
json_loader(j) >> f;
BOOST_CHECK_EQUAL(f.size(), 2);
BOOST_CHECK(f.find("foo") != f.end());
BOOST_CHECK(f.find("bar") != f.end());
BOOST_CHECK_EQUAL(f["foo"], 42);
BOOST_CHECK_EQUAL(f["bar"], 17);
#endif
maybe<int> a;
j = jsave_all(a);
BOOST_CHECK(!j);
a = 42;
j = jsave_all(a);
BOOST_CHECK_EQUAL(j, 42);
a.reset();
BOOST_CHECK(!a.ok());
j = 17;
json_loader(j) >> a;
BOOST_CHECK(a.ok());
BOOST_CHECK_EQUAL(a.get(), 17);
captain c = janeway;
j = jsave_all(c);
BOOST_CHECK_EQUAL(j, "janeway");
j = "kirk";
json_loader(j) >> c;
BOOST_CHECK_EQUAL(c, kirk);
}
#endif // TEN_JSON_CXX11
<commit_msg>cosmetic<commit_after>#define BOOST_TEST_MODULE json test
#include <boost/test/unit_test.hpp>
#include <ten/json.hh>
#ifdef TEN_JSON_CXX11
#include <ten/jserial.hh>
#include <ten/jserial_maybe.hh>
#include <ten/jserial_seq.hh>
#include <ten/jserial_assoc.hh>
#include <ten/jserial_enum.hh>
#endif
#include <array>
using namespace std;
using namespace ten;
const char json_text[] =
"{ \"store\": {"
" \"book\": ["
" { \"category\": \"reference\","
" \"author\": \"Nigel Rees\","
" \"title\": \"Sayings of the Century\","
" \"price\": 8.95"
" },"
" { \"category\": \"fiction\","
" \"author\": \"Evelyn Waugh\","
" \"title\": \"Sword of Honour\","
" \"price\": 12.99"
" },"
" { \"category\": \"fiction\","
" \"author\": \"Herman Melville\","
" \"title\": \"Moby Dick\","
" \"isbn\": \"0-553-21311-3\","
" \"price\": 8.99"
" },"
" { \"category\": \"fiction\","
" \"author\": \"J. R. R. Tolkien\","
" \"title\": \"The Lord of the Rings\","
" \"isbn\": \"0-395-19395-8\","
" \"price\": 22.99"
" }"
" ],"
" \"bicycle\": {"
" \"color\": \"red\","
" \"price\": 19.95"
" }"
" }"
"}";
BOOST_AUTO_TEST_CASE(json_test_path1) {
json o(json::load(json_text));
BOOST_REQUIRE(o.get());
static const char a1[] = "[\"Nigel Rees\", \"Evelyn Waugh\", \"Herman Melville\", \"J. R. R. Tolkien\"]";
json r1(o.path("/store/book/author"));
BOOST_CHECK_EQUAL(json::load(a1), r1);
json r2(o.path("//author"));
BOOST_CHECK_EQUAL(json::load(a1), r2);
// jansson hashtable uses size_t for hash
// we think this is causing the buckets to change on 32bit vs. 64bit
#if (__SIZEOF_SIZE_T__ == 4)
static const char a3[] = "[{\"category\": \"reference\", \"author\": \"Nigel Rees\", \"title\": \"Sayings of the Century\", \"price\": 8.95}, {\"category\": \"fiction\", \"author\": \"Evelyn Waugh\", \"title\": \"Sword of Honour\", \"price\": 12.99}, {\"category\": \"fiction\", \"author\": \"Herman Melville\", \"title\": \"Moby Dick\", \"isbn\": \"0-553-21311-3\", \"price\": 8.99}, {\"category\": \"fiction\", \"author\": \"J. R. R. Tolkien\", \"title\": \"The Lord of the Rings\", \"isbn\": \"0-395-19395-8\", \"price\": 22.99}, {\"color\": \"red\", \"price\": 19.95}]";
#elif (__SIZEOF_SIZE_T__ == 8)
static const char a3[] = "[{\"color\": \"red\", \"price\": 19.95}, {\"category\": \"reference\", \"author\": \"Nigel Rees\", \"title\": \"Sayings of the Century\", \"price\": 8.95}, {\"category\": \"fiction\", \"author\": \"Evelyn Waugh\", \"title\": \"Sword of Honour\", \"price\": 12.99}, {\"category\": \"fiction\", \"author\": \"Herman Melville\", \"title\": \"Moby Dick\", \"isbn\": \"0-553-21311-3\", \"price\": 8.99}, {\"category\": \"fiction\", \"author\": \"J. R. R. Tolkien\", \"title\": \"The Lord of the Rings\", \"isbn\": \"0-395-19395-8\", \"price\": 22.99}]";
#endif
json r3(o.path("/store/*"));
json t3(json::load(a3));
BOOST_CHECK_EQUAL(t3, r3);
#if (__SIZEOF_SIZE_T__ == 4)
static const char a4[] = "[8.95, 12.99, 8.99, 22.99, 19.95]";
#elif (__SIZEOF_SIZE_T__ == 8)
static const char a4[] = "[19.95, 8.95, 12.99, 8.99, 22.99]";
#endif
json r4(o.path("/store//price"));
BOOST_CHECK_EQUAL(json::load(a4), r4);
static const char a5[] = "{\"category\": \"fiction\", \"author\": \"J. R. R. Tolkien\", \"title\": \"The Lord of the Rings\", \"isbn\": \"0-395-19395-8\", \"price\": 22.99}";
json r5(o.path("//book[3]"));
BOOST_CHECK_EQUAL(json::load(a5), r5);
static const char a6[] = "\"J. R. R. Tolkien\"";
json r6(o.path("/store/book[3]/author"));
BOOST_CHECK_EQUAL(json::load(a6), r6);
BOOST_CHECK(json::load(a6) == r6);
static const char a7[] = "[{\"category\": \"fiction\", \"author\": \"Evelyn Waugh\", \"title\": \"Sword of Honour\", \"price\": 12.99}, {\"category\": \"fiction\", \"author\": \"Herman Melville\", \"title\": \"Moby Dick\", \"isbn\": \"0-553-21311-3\", \"price\": 8.99}, {\"category\": \"fiction\", \"author\": \"J. R. R. Tolkien\", \"title\": \"The Lord of the Rings\", \"isbn\": \"0-395-19395-8\", \"price\": 22.99}]";
json r7(o.path("/store/book[category=\"fiction\"]"));
BOOST_CHECK_EQUAL(json::load(a7), r7);
}
BOOST_AUTO_TEST_CASE(json_test_path2) {
json o(json::load("[{\"type\": 0}, {\"type\": 1}]"));
BOOST_CHECK_EQUAL(json::load("[{\"type\":1}]"), o.path("/[type=1]"));
}
BOOST_AUTO_TEST_CASE(json_test_filter_key_exists) {
json o(json::load(json_text));
BOOST_REQUIRE(o.get());
static const char a[] = "["
" { \"category\": \"fiction\","
" \"author\": \"Herman Melville\","
" \"title\": \"Moby Dick\","
" \"isbn\": \"0-553-21311-3\","
" \"price\": 8.99"
" },"
" { \"category\": \"fiction\","
" \"author\": \"J. R. R. Tolkien\","
" \"title\": \"The Lord of the Rings\","
" \"isbn\": \"0-395-19395-8\","
" \"price\": 22.99"
" }]";
json r(o.path("//book[isbn]"));
BOOST_CHECK_EQUAL(json::load(a), r);
json r1(o.path("//book[doesnotexist]"));
BOOST_REQUIRE(r1.is_array());
BOOST_CHECK_EQUAL(0, r1.asize());
}
BOOST_AUTO_TEST_CASE(json_test_truth) {
json o(json::object());
BOOST_CHECK(o.get("nothing").is_true() == false);
BOOST_CHECK(o.get("nothing").is_false() == false);
BOOST_CHECK(o.get("nothing").is_null() == false);
BOOST_CHECK(!o.get("nothing"));
}
BOOST_AUTO_TEST_CASE(json_test_path3) {
json o(json::load(json_text));
BOOST_REQUIRE(o.get());
BOOST_CHECK_EQUAL(o, o.path("/"));
BOOST_CHECK_EQUAL("Sayings of the Century",
o.path("/store/book[category=\"reference\"]/title"));
static const char text[] = "["
"{\"type\":\"a\", \"value\":0},"
"{\"type\":\"b\", \"value\":1},"
"{\"type\":\"c\", \"value\":2},"
"{\"type\":\"c\", \"value\":3}"
"]";
BOOST_CHECK_EQUAL(json(1), json::load(text).path("/[type=\"b\"]/value"));
}
BOOST_AUTO_TEST_CASE(json_init_list) {
json meta{
{ "foo", 17 },
{ "bar", 23 },
{ "baz", true },
{ "corge", json::array({ 1, 3.14159 }) },
{ "grault", json::array({ "hello", string("world") }) },
};
BOOST_REQUIRE(meta);
BOOST_REQUIRE(meta.is_object());
BOOST_CHECK_EQUAL(meta.osize(), 5);
BOOST_CHECK_EQUAL(meta["foo"].integer(), 17);
BOOST_CHECK_EQUAL(meta["corge"][0].integer(), 1);
BOOST_CHECK_EQUAL(meta["grault"][1].str(), "world");
}
template <class T>
inline void test_conv(T val, json j, json_type t) {
json j2 = to_json(val);
BOOST_CHECK_EQUAL(j2.type(), t);
BOOST_CHECK_EQUAL(j, j2);
T val2 = json_cast<T>(j2);
BOOST_CHECK_EQUAL(val, val2);
}
template <class T, json_type TYPE = JSON_INTEGER>
inline void test_conv_num() {
typedef numeric_limits<T> lim;
T range[5] = { lim::min(), T(-1), 0, T(1), lim::max() };
for (unsigned i = 0; i < 5; ++i)
test_conv<T>(range[i], json(range[i]), TYPE);
}
BOOST_AUTO_TEST_CASE(json_conversions) {
test_conv<string>(string("hello"), json::str("hello"), JSON_STRING);
BOOST_CHECK_EQUAL(to_json("world"), json::str("world"));
test_conv_num<short>();
test_conv_num<int>();
test_conv_num<long>();
test_conv_num<long long>();
test_conv_num<unsigned short>();
test_conv_num<unsigned>();
#if ULONG_MAX < LLONG_MAX
test_conv_num<unsigned long>();
#endif
test_conv_num<double, JSON_REAL>();
test_conv_num<float, JSON_REAL>();
test_conv<bool>(true, json::jtrue(), JSON_TRUE);
test_conv<bool>(false, json::jfalse(), JSON_FALSE);
}
BOOST_AUTO_TEST_CASE(json_create) {
json obj1;
obj1.set("test", "set");
BOOST_CHECK(obj1);
BOOST_CHECK(obj1.get("test"));
json root{
{"obj1", obj1}
};
BOOST_CHECK_EQUAL(root.get("obj1"), obj1);
obj1.set("this", "that");
BOOST_CHECK_EQUAL(root.get("obj1").get("this").str(), "that");
json obj2{ {"answer", 42} };
obj1.set("obj2", obj2);
BOOST_CHECK_EQUAL(root.get("obj1").get("obj2"), obj2);
}
#ifdef TEN_JSON_CXX11
struct corge {
int foo, bar;
corge() : foo(), bar() {}
corge(int foo_, int bar_) : foo(foo_), bar(bar_) {}
};
template <class AR>
inline void serialize(AR &ar, corge &c) {
ar & kv("foo", c.foo) & kv("bar", c.bar);
}
inline bool operator == (const corge &a, const corge &b) {
return a.foo == b.foo && a.bar == b.bar;
}
enum captain { kirk, picard, janeway, sisko };
const array<string, 4> captain_names = {{ "kirk", "picard", "janeway", "sisko" }};
template <class AR>
inline void serialize(AR &ar, captain &c) {
serialize_enum(ar, c, captain_names);
}
BOOST_AUTO_TEST_CASE(json_serial) {
corge c1(42, 17);
auto j = jsave_all(c1);
corge c2;
json_loader(j) >> c2;
BOOST_CHECK(c1 == c2);
map<string, int> m;
json_loader(j) >> m;
BOOST_CHECK_EQUAL(m.size(), 2);
BOOST_CHECK(m.find("foo") != m.end());
BOOST_CHECK(m.find("bar") != m.end());
BOOST_CHECK_EQUAL(m["foo"], 42);
BOOST_CHECK_EQUAL(m["bar"], 17);
#if BOOST_VERSION >= 104800
flat_map<string, int> f;
json_loader(j) >> f;
BOOST_CHECK_EQUAL(f.size(), 2);
BOOST_CHECK(f.find("foo") != f.end());
BOOST_CHECK(f.find("bar") != f.end());
BOOST_CHECK_EQUAL(f["foo"], 42);
BOOST_CHECK_EQUAL(f["bar"], 17);
#endif
maybe<int> a;
j = jsave_all(a);
BOOST_CHECK(!j);
a = 42;
j = jsave_all(a);
BOOST_CHECK_EQUAL(j, 42);
a.reset();
BOOST_CHECK(!a.ok());
j = 17;
json_loader(j) >> a;
BOOST_CHECK(a.ok());
BOOST_CHECK_EQUAL(a.get(), 17);
captain c = janeway;
j = jsave_all(c);
BOOST_CHECK_EQUAL(j, "janeway");
j = "kirk";
json_loader(j) >> c;
BOOST_CHECK_EQUAL(c, kirk);
}
#endif // TEN_JSON_CXX11
<|endoftext|> |
<commit_before>#define BOOST_TEST_MODULE json test
#include <boost/test/unit_test.hpp>
#include <ten/json.hh>
#ifdef TEN_JSON_CXX11
#include <ten/jserial.hh>
#include <ten/jserial_maybe.hh>
#include <ten/jserial_seq.hh>
#include <ten/jserial_assoc.hh>
#include <ten/jserial_enum.hh>
#endif
#include <array>
using namespace std;
using namespace ten;
const char json_text[] =
"{ \"store\": {"
" \"book\": ["
" { \"category\": \"reference\","
" \"author\": \"Nigel Rees\","
" \"title\": \"Sayings of the Century\","
" \"price\": 8.95"
" },"
" { \"category\": \"fiction\","
" \"author\": \"Evelyn Waugh\","
" \"title\": \"Sword of Honour\","
" \"price\": 12.99"
" },"
" { \"category\": \"fiction\","
" \"author\": \"Herman Melville\","
" \"title\": \"Moby Dick\","
" \"isbn\": \"0-553-21311-3\","
" \"price\": 8.99"
" },"
" { \"category\": \"fiction\","
" \"author\": \"J. R. R. Tolkien\","
" \"title\": \"The Lord of the Rings\","
" \"isbn\": \"0-395-19395-8\","
" \"price\": 22.99"
" }"
" ],"
" \"bicycle\": {"
" \"color\": \"red\","
" \"price\": 19.95"
" }"
" }"
"}";
BOOST_AUTO_TEST_CASE(json_test_path1) {
json o(json::load(json_text));
BOOST_REQUIRE(o.get());
static const char a1[] = "[\"Nigel Rees\", \"Evelyn Waugh\", \"Herman Melville\", \"J. R. R. Tolkien\"]";
json r1(o.path("/store/book/author"));
BOOST_CHECK_EQUAL(json::load(a1), r1);
json r2(o.path("//author"));
BOOST_CHECK_EQUAL(json::load(a1), r2);
// jansson hashtable uses size_t for hash
// we think this is causing the buckets to change on 32bit vs. 64bit
#if (__SIZEOF_SIZE_T__ == 4)
static const char a3[] = "[{\"category\": \"reference\", \"author\": \"Nigel Rees\", \"title\": \"Sayings of the Century\", \"price\": 8.95}, {\"category\": \"fiction\", \"author\": \"Evelyn Waugh\", \"title\": \"Sword of Honour\", \"price\": 12.99}, {\"category\": \"fiction\", \"author\": \"Herman Melville\", \"title\": \"Moby Dick\", \"isbn\": \"0-553-21311-3\", \"price\": 8.99}, {\"category\": \"fiction\", \"author\": \"J. R. R. Tolkien\", \"title\": \"The Lord of the Rings\", \"isbn\": \"0-395-19395-8\", \"price\": 22.99}, {\"color\": \"red\", \"price\": 19.95}]";
#elif (__SIZEOF_SIZE_T__ == 8)
static const char a3[] = "[{\"color\": \"red\", \"price\": 19.95}, {\"category\": \"reference\", \"author\": \"Nigel Rees\", \"title\": \"Sayings of the Century\", \"price\": 8.95}, {\"category\": \"fiction\", \"author\": \"Evelyn Waugh\", \"title\": \"Sword of Honour\", \"price\": 12.99}, {\"category\": \"fiction\", \"author\": \"Herman Melville\", \"title\": \"Moby Dick\", \"isbn\": \"0-553-21311-3\", \"price\": 8.99}, {\"category\": \"fiction\", \"author\": \"J. R. R. Tolkien\", \"title\": \"The Lord of the Rings\", \"isbn\": \"0-395-19395-8\", \"price\": 22.99}]";
#endif
json r3(o.path("/store/*"));
json t3(json::load(a3));
BOOST_CHECK_EQUAL(t3, r3);
#if (__SIZEOF_SIZE_T__ == 4)
static const char a4[] = "[8.95, 12.99, 8.99, 22.99, 19.95]";
#elif (__SIZEOF_SIZE_T__ == 8)
static const char a4[] = "[19.95, 8.95, 12.99, 8.99, 22.99]";
#endif
json r4(o.path("/store//price"));
BOOST_CHECK_EQUAL(json::load(a4), r4);
static const char a5[] = "{\"category\": \"fiction\", \"author\": \"J. R. R. Tolkien\", \"title\": \"The Lord of the Rings\", \"isbn\": \"0-395-19395-8\", \"price\": 22.99}";
json r5(o.path("//book[3]"));
BOOST_CHECK_EQUAL(json::load(a5), r5);
static const char a6[] = "\"J. R. R. Tolkien\"";
json r6(o.path("/store/book[3]/author"));
BOOST_CHECK_EQUAL(json::load(a6), r6);
BOOST_CHECK(json::load(a6) == r6);
static const char a7[] = "[{\"category\": \"fiction\", \"author\": \"Evelyn Waugh\", \"title\": \"Sword of Honour\", \"price\": 12.99}, {\"category\": \"fiction\", \"author\": \"Herman Melville\", \"title\": \"Moby Dick\", \"isbn\": \"0-553-21311-3\", \"price\": 8.99}, {\"category\": \"fiction\", \"author\": \"J. R. R. Tolkien\", \"title\": \"The Lord of the Rings\", \"isbn\": \"0-395-19395-8\", \"price\": 22.99}]";
json r7(o.path("/store/book[category=\"fiction\"]"));
BOOST_CHECK_EQUAL(json::load(a7), r7);
}
BOOST_AUTO_TEST_CASE(json_test_path2) {
json o(json::load("[{\"type\": 0}, {\"type\": 1}]"));
BOOST_CHECK_EQUAL(json::load("[{\"type\":1}]"), o.path("/[type=1]"));
}
BOOST_AUTO_TEST_CASE(json_test_filter_key_exists) {
json o(json::load(json_text));
BOOST_REQUIRE(o.get());
static const char a[] = "["
" { \"category\": \"fiction\","
" \"author\": \"Herman Melville\","
" \"title\": \"Moby Dick\","
" \"isbn\": \"0-553-21311-3\","
" \"price\": 8.99"
" },"
" { \"category\": \"fiction\","
" \"author\": \"J. R. R. Tolkien\","
" \"title\": \"The Lord of the Rings\","
" \"isbn\": \"0-395-19395-8\","
" \"price\": 22.99"
" }]";
json r(o.path("//book[isbn]"));
BOOST_CHECK_EQUAL(json::load(a), r);
json r1(o.path("//book[doesnotexist]"));
BOOST_REQUIRE(r1.is_array());
BOOST_CHECK_EQUAL(0, r1.asize());
}
BOOST_AUTO_TEST_CASE(json_test_truth) {
json o(json::object());
BOOST_CHECK(o.get("nothing").is_true() == false);
BOOST_CHECK(o.get("nothing").is_false() == false);
BOOST_CHECK(o.get("nothing").is_null() == false);
BOOST_CHECK(!o.get("nothing"));
}
BOOST_AUTO_TEST_CASE(json_test_path3) {
json o(json::load(json_text));
BOOST_REQUIRE(o.get());
BOOST_CHECK_EQUAL(o, o.path("/"));
BOOST_CHECK_EQUAL("Sayings of the Century",
o.path("/store/book[category=\"reference\"]/title"));
static const char text[] = "["
"{\"type\":\"a\", \"value\":0},"
"{\"type\":\"b\", \"value\":1},"
"{\"type\":\"c\", \"value\":2},"
"{\"type\":\"c\", \"value\":3}"
"]";
BOOST_CHECK_EQUAL(json(1), json::load(text).path("/[type=\"b\"]/value"));
}
BOOST_AUTO_TEST_CASE(json_init_list) {
json meta{
{ "foo", 17 },
{ "bar", 23 },
{ "baz", true },
{ "corge", json::array({ 1, 3.14159 }) },
{ "grault", json::array({ "hello", string("world") }) },
};
BOOST_REQUIRE(meta);
BOOST_REQUIRE(meta.is_object());
BOOST_CHECK_EQUAL(meta.osize(), 5);
BOOST_CHECK_EQUAL(meta["foo"].integer(), 17);
BOOST_CHECK_EQUAL(meta["corge"][0].integer(), 1);
BOOST_CHECK_EQUAL(meta["grault"][1].str(), "world");
}
template <class T>
inline void test_conv(T val, json j, json_type t) {
json j2 = to_json(val);
BOOST_CHECK_EQUAL(j2.type(), t);
BOOST_CHECK_EQUAL(j, j2);
T val2 = json_cast<T>(j2);
BOOST_CHECK_EQUAL(val, val2);
}
template <class T, json_type TYPE = JSON_INTEGER>
inline void test_conv_num() {
typedef numeric_limits<T> lim;
T range[5] = { lim::min(), T(-1), 0, T(1), lim::max() };
for (unsigned i = 0; i < 5; ++i)
test_conv<T>(range[i], json(range[i]), TYPE);
}
BOOST_AUTO_TEST_CASE(json_conversions) {
test_conv<string>(string("hello"), json::str("hello"), JSON_STRING);
BOOST_CHECK_EQUAL(to_json("world"), json::str("world"));
test_conv_num<short>();
test_conv_num<int>();
test_conv_num<long>();
test_conv_num<long long>();
test_conv_num<unsigned short>();
test_conv_num<unsigned>();
#if ULONG_MAX < LLONG_MAX
test_conv_num<unsigned long>();
#endif
test_conv_num<double, JSON_REAL>();
test_conv_num<float, JSON_REAL>();
test_conv<bool>(true, json::jtrue(), JSON_TRUE);
test_conv<bool>(false, json::jfalse(), JSON_FALSE);
}
BOOST_AUTO_TEST_CASE(json_create) {
json obj1{};
BOOST_CHECK(obj1);
obj1.set("test", "set");
BOOST_CHECK(obj1.get("test"));
json root{
{"obj1", obj1}
};
BOOST_CHECK_EQUAL(root.get("obj1"), obj1);
obj1.set("this", "that");
json obj2{};
BOOST_CHECK_EQUAL(root.get("obj1").get("this").str(), "that");
obj1.set("obj2", obj2);
BOOST_CHECK_EQUAL(root.get("obj1").get("obj2"), obj2);
}
#ifdef TEN_JSON_CXX11
struct corge {
int foo, bar;
corge() : foo(), bar() {}
corge(int foo_, int bar_) : foo(foo_), bar(bar_) {}
};
template <class AR>
inline AR & operator & (AR &ar, corge &c) {
return ar & kv("foo", c.foo) & kv("bar", c.bar);
}
inline bool operator == (const corge &a, const corge &b) {
return a.foo == b.foo && a.bar == b.bar;
}
enum captain { kirk, picard, janeway, sisko };
const array<string, 4> captain_names = {{ "kirk", "picard", "janeway", "sisko" }};
template <class AR>
inline AR & operator & (AR &ar, captain &c) {
return serialize_enum(ar, c, captain_names);
}
BOOST_AUTO_TEST_CASE(json_serial) {
corge c1(42, 17);
auto j = jsave_all(c1);
corge c2;
JLoad(j) >> c2;
BOOST_CHECK(c1 == c2);
map<string, int> m;
JLoad(j) >> m;
BOOST_CHECK_EQUAL(m.size(), 2);
BOOST_CHECK(m.find("foo") != m.end());
BOOST_CHECK(m.find("bar") != m.end());
BOOST_CHECK_EQUAL(m["foo"], 42);
BOOST_CHECK_EQUAL(m["bar"], 17);
#if BOOST_VERSION >= 104800
flat_map<string, int> f;
JLoad(j) >> f;
BOOST_CHECK_EQUAL(f.size(), 2);
BOOST_CHECK(f.find("foo") != f.end());
BOOST_CHECK(f.find("bar") != f.end());
BOOST_CHECK_EQUAL(f["foo"], 42);
BOOST_CHECK_EQUAL(f["bar"], 17);
#endif
maybe<int> a;
j = jsave_all(a);
BOOST_CHECK(!j);
a = 42;
j = jsave_all(a);
BOOST_CHECK_EQUAL(j, 42);
a.reset();
BOOST_CHECK(!a.ok());
j = 17;
JLoad(j) >> a;
BOOST_CHECK(a.ok());
BOOST_CHECK_EQUAL(a.get(), 17);
captain c = janeway;
j = jsave_all(c);
BOOST_CHECK_EQUAL(j, "janeway");
j = "kirk";
JLoad(j) >> c;
BOOST_CHECK_EQUAL(c, kirk);
}
#endif // TEN_JSON_CXX11
<commit_msg>update json_create to work even though {} is not init list<commit_after>#define BOOST_TEST_MODULE json test
#include <boost/test/unit_test.hpp>
#include <ten/json.hh>
#ifdef TEN_JSON_CXX11
#include <ten/jserial.hh>
#include <ten/jserial_maybe.hh>
#include <ten/jserial_seq.hh>
#include <ten/jserial_assoc.hh>
#include <ten/jserial_enum.hh>
#endif
#include <array>
using namespace std;
using namespace ten;
const char json_text[] =
"{ \"store\": {"
" \"book\": ["
" { \"category\": \"reference\","
" \"author\": \"Nigel Rees\","
" \"title\": \"Sayings of the Century\","
" \"price\": 8.95"
" },"
" { \"category\": \"fiction\","
" \"author\": \"Evelyn Waugh\","
" \"title\": \"Sword of Honour\","
" \"price\": 12.99"
" },"
" { \"category\": \"fiction\","
" \"author\": \"Herman Melville\","
" \"title\": \"Moby Dick\","
" \"isbn\": \"0-553-21311-3\","
" \"price\": 8.99"
" },"
" { \"category\": \"fiction\","
" \"author\": \"J. R. R. Tolkien\","
" \"title\": \"The Lord of the Rings\","
" \"isbn\": \"0-395-19395-8\","
" \"price\": 22.99"
" }"
" ],"
" \"bicycle\": {"
" \"color\": \"red\","
" \"price\": 19.95"
" }"
" }"
"}";
BOOST_AUTO_TEST_CASE(json_test_path1) {
json o(json::load(json_text));
BOOST_REQUIRE(o.get());
static const char a1[] = "[\"Nigel Rees\", \"Evelyn Waugh\", \"Herman Melville\", \"J. R. R. Tolkien\"]";
json r1(o.path("/store/book/author"));
BOOST_CHECK_EQUAL(json::load(a1), r1);
json r2(o.path("//author"));
BOOST_CHECK_EQUAL(json::load(a1), r2);
// jansson hashtable uses size_t for hash
// we think this is causing the buckets to change on 32bit vs. 64bit
#if (__SIZEOF_SIZE_T__ == 4)
static const char a3[] = "[{\"category\": \"reference\", \"author\": \"Nigel Rees\", \"title\": \"Sayings of the Century\", \"price\": 8.95}, {\"category\": \"fiction\", \"author\": \"Evelyn Waugh\", \"title\": \"Sword of Honour\", \"price\": 12.99}, {\"category\": \"fiction\", \"author\": \"Herman Melville\", \"title\": \"Moby Dick\", \"isbn\": \"0-553-21311-3\", \"price\": 8.99}, {\"category\": \"fiction\", \"author\": \"J. R. R. Tolkien\", \"title\": \"The Lord of the Rings\", \"isbn\": \"0-395-19395-8\", \"price\": 22.99}, {\"color\": \"red\", \"price\": 19.95}]";
#elif (__SIZEOF_SIZE_T__ == 8)
static const char a3[] = "[{\"color\": \"red\", \"price\": 19.95}, {\"category\": \"reference\", \"author\": \"Nigel Rees\", \"title\": \"Sayings of the Century\", \"price\": 8.95}, {\"category\": \"fiction\", \"author\": \"Evelyn Waugh\", \"title\": \"Sword of Honour\", \"price\": 12.99}, {\"category\": \"fiction\", \"author\": \"Herman Melville\", \"title\": \"Moby Dick\", \"isbn\": \"0-553-21311-3\", \"price\": 8.99}, {\"category\": \"fiction\", \"author\": \"J. R. R. Tolkien\", \"title\": \"The Lord of the Rings\", \"isbn\": \"0-395-19395-8\", \"price\": 22.99}]";
#endif
json r3(o.path("/store/*"));
json t3(json::load(a3));
BOOST_CHECK_EQUAL(t3, r3);
#if (__SIZEOF_SIZE_T__ == 4)
static const char a4[] = "[8.95, 12.99, 8.99, 22.99, 19.95]";
#elif (__SIZEOF_SIZE_T__ == 8)
static const char a4[] = "[19.95, 8.95, 12.99, 8.99, 22.99]";
#endif
json r4(o.path("/store//price"));
BOOST_CHECK_EQUAL(json::load(a4), r4);
static const char a5[] = "{\"category\": \"fiction\", \"author\": \"J. R. R. Tolkien\", \"title\": \"The Lord of the Rings\", \"isbn\": \"0-395-19395-8\", \"price\": 22.99}";
json r5(o.path("//book[3]"));
BOOST_CHECK_EQUAL(json::load(a5), r5);
static const char a6[] = "\"J. R. R. Tolkien\"";
json r6(o.path("/store/book[3]/author"));
BOOST_CHECK_EQUAL(json::load(a6), r6);
BOOST_CHECK(json::load(a6) == r6);
static const char a7[] = "[{\"category\": \"fiction\", \"author\": \"Evelyn Waugh\", \"title\": \"Sword of Honour\", \"price\": 12.99}, {\"category\": \"fiction\", \"author\": \"Herman Melville\", \"title\": \"Moby Dick\", \"isbn\": \"0-553-21311-3\", \"price\": 8.99}, {\"category\": \"fiction\", \"author\": \"J. R. R. Tolkien\", \"title\": \"The Lord of the Rings\", \"isbn\": \"0-395-19395-8\", \"price\": 22.99}]";
json r7(o.path("/store/book[category=\"fiction\"]"));
BOOST_CHECK_EQUAL(json::load(a7), r7);
}
BOOST_AUTO_TEST_CASE(json_test_path2) {
json o(json::load("[{\"type\": 0}, {\"type\": 1}]"));
BOOST_CHECK_EQUAL(json::load("[{\"type\":1}]"), o.path("/[type=1]"));
}
BOOST_AUTO_TEST_CASE(json_test_filter_key_exists) {
json o(json::load(json_text));
BOOST_REQUIRE(o.get());
static const char a[] = "["
" { \"category\": \"fiction\","
" \"author\": \"Herman Melville\","
" \"title\": \"Moby Dick\","
" \"isbn\": \"0-553-21311-3\","
" \"price\": 8.99"
" },"
" { \"category\": \"fiction\","
" \"author\": \"J. R. R. Tolkien\","
" \"title\": \"The Lord of the Rings\","
" \"isbn\": \"0-395-19395-8\","
" \"price\": 22.99"
" }]";
json r(o.path("//book[isbn]"));
BOOST_CHECK_EQUAL(json::load(a), r);
json r1(o.path("//book[doesnotexist]"));
BOOST_REQUIRE(r1.is_array());
BOOST_CHECK_EQUAL(0, r1.asize());
}
BOOST_AUTO_TEST_CASE(json_test_truth) {
json o(json::object());
BOOST_CHECK(o.get("nothing").is_true() == false);
BOOST_CHECK(o.get("nothing").is_false() == false);
BOOST_CHECK(o.get("nothing").is_null() == false);
BOOST_CHECK(!o.get("nothing"));
}
BOOST_AUTO_TEST_CASE(json_test_path3) {
json o(json::load(json_text));
BOOST_REQUIRE(o.get());
BOOST_CHECK_EQUAL(o, o.path("/"));
BOOST_CHECK_EQUAL("Sayings of the Century",
o.path("/store/book[category=\"reference\"]/title"));
static const char text[] = "["
"{\"type\":\"a\", \"value\":0},"
"{\"type\":\"b\", \"value\":1},"
"{\"type\":\"c\", \"value\":2},"
"{\"type\":\"c\", \"value\":3}"
"]";
BOOST_CHECK_EQUAL(json(1), json::load(text).path("/[type=\"b\"]/value"));
}
BOOST_AUTO_TEST_CASE(json_init_list) {
json meta{
{ "foo", 17 },
{ "bar", 23 },
{ "baz", true },
{ "corge", json::array({ 1, 3.14159 }) },
{ "grault", json::array({ "hello", string("world") }) },
};
BOOST_REQUIRE(meta);
BOOST_REQUIRE(meta.is_object());
BOOST_CHECK_EQUAL(meta.osize(), 5);
BOOST_CHECK_EQUAL(meta["foo"].integer(), 17);
BOOST_CHECK_EQUAL(meta["corge"][0].integer(), 1);
BOOST_CHECK_EQUAL(meta["grault"][1].str(), "world");
}
template <class T>
inline void test_conv(T val, json j, json_type t) {
json j2 = to_json(val);
BOOST_CHECK_EQUAL(j2.type(), t);
BOOST_CHECK_EQUAL(j, j2);
T val2 = json_cast<T>(j2);
BOOST_CHECK_EQUAL(val, val2);
}
template <class T, json_type TYPE = JSON_INTEGER>
inline void test_conv_num() {
typedef numeric_limits<T> lim;
T range[5] = { lim::min(), T(-1), 0, T(1), lim::max() };
for (unsigned i = 0; i < 5; ++i)
test_conv<T>(range[i], json(range[i]), TYPE);
}
BOOST_AUTO_TEST_CASE(json_conversions) {
test_conv<string>(string("hello"), json::str("hello"), JSON_STRING);
BOOST_CHECK_EQUAL(to_json("world"), json::str("world"));
test_conv_num<short>();
test_conv_num<int>();
test_conv_num<long>();
test_conv_num<long long>();
test_conv_num<unsigned short>();
test_conv_num<unsigned>();
#if ULONG_MAX < LLONG_MAX
test_conv_num<unsigned long>();
#endif
test_conv_num<double, JSON_REAL>();
test_conv_num<float, JSON_REAL>();
test_conv<bool>(true, json::jtrue(), JSON_TRUE);
test_conv<bool>(false, json::jfalse(), JSON_FALSE);
}
BOOST_AUTO_TEST_CASE(json_create) {
json obj1;
obj1.set("test", "set");
BOOST_CHECK(obj1);
BOOST_CHECK(obj1.get("test"));
json root{
{"obj1", obj1}
};
BOOST_CHECK_EQUAL(root.get("obj1"), obj1);
obj1.set("this", "that");
BOOST_CHECK_EQUAL(root.get("obj1").get("this").str(), "that");
json obj2{ {"answer", 42} };
obj1.set("obj2", obj2);
BOOST_CHECK_EQUAL(root.get("obj1").get("obj2"), obj2);
}
#ifdef TEN_JSON_CXX11
struct corge {
int foo, bar;
corge() : foo(), bar() {}
corge(int foo_, int bar_) : foo(foo_), bar(bar_) {}
};
template <class AR>
inline AR & operator & (AR &ar, corge &c) {
return ar & kv("foo", c.foo) & kv("bar", c.bar);
}
inline bool operator == (const corge &a, const corge &b) {
return a.foo == b.foo && a.bar == b.bar;
}
enum captain { kirk, picard, janeway, sisko };
const array<string, 4> captain_names = {{ "kirk", "picard", "janeway", "sisko" }};
template <class AR>
inline AR & operator & (AR &ar, captain &c) {
return serialize_enum(ar, c, captain_names);
}
BOOST_AUTO_TEST_CASE(json_serial) {
corge c1(42, 17);
auto j = jsave_all(c1);
corge c2;
JLoad(j) >> c2;
BOOST_CHECK(c1 == c2);
map<string, int> m;
JLoad(j) >> m;
BOOST_CHECK_EQUAL(m.size(), 2);
BOOST_CHECK(m.find("foo") != m.end());
BOOST_CHECK(m.find("bar") != m.end());
BOOST_CHECK_EQUAL(m["foo"], 42);
BOOST_CHECK_EQUAL(m["bar"], 17);
#if BOOST_VERSION >= 104800
flat_map<string, int> f;
JLoad(j) >> f;
BOOST_CHECK_EQUAL(f.size(), 2);
BOOST_CHECK(f.find("foo") != f.end());
BOOST_CHECK(f.find("bar") != f.end());
BOOST_CHECK_EQUAL(f["foo"], 42);
BOOST_CHECK_EQUAL(f["bar"], 17);
#endif
maybe<int> a;
j = jsave_all(a);
BOOST_CHECK(!j);
a = 42;
j = jsave_all(a);
BOOST_CHECK_EQUAL(j, 42);
a.reset();
BOOST_CHECK(!a.ok());
j = 17;
JLoad(j) >> a;
BOOST_CHECK(a.ok());
BOOST_CHECK_EQUAL(a.get(), 17);
captain c = janeway;
j = jsave_all(c);
BOOST_CHECK_EQUAL(j, "janeway");
j = "kirk";
JLoad(j) >> c;
BOOST_CHECK_EQUAL(c, kirk);
}
#endif // TEN_JSON_CXX11
<|endoftext|> |
<commit_before>//
// KinematicsSimulator.cpp
// GPcode01_01_xcode
//
// Created by young-min kang on 3/27/15.
// Copyright (c) 2015 young-min kang. All rights reserved.
//
#include "DynamicSimulator.h"
CDynamicSimulator::CDynamicSimulator() : CSimulator() {}
void CDynamicSimulator::init() {
for(int i=0;i<NUMPARTS;i++)particle[i].randomInit();
}
void CDynamicSimulator::clean() {
}
void CDynamicSimulator::doBeforeSimulation(double dt, double currentTime) {
// buoyancy here
}
void CDynamicSimulator::doSimulation(double dt, double currentTime) {
for(int i=0;i<NUMPARTS;i++)
particle[i].simulate(dt, currentTime);
}
void CDynamicSimulator::doAfterSimulation(double dt, double currentTime) {
for(int i=0;i<NUMPARTS;i++) {
particle[i].resetForce();
}
}
void CDynamicSimulator::visualize(void) {
for(int i=0;i<NUMPARTS;i++) {
particle[i].drawWithGL(SPHERE_DRAW);
}
}<commit_msg>Update DynamicSimulator.cpp<commit_after>//
// DynamicSimulator.cpp
// GPcode01_01_xcode
//
// Created by young-min kang on 3/27/15.
// Copyright (c) 2015 young-min kang. All rights reserved.
//
#include "DynamicSimulator.h"
CDynamicSimulator::CDynamicSimulator() : CSimulator() {}
void CDynamicSimulator::init() {
for(int i=0;i<NUMPARTS;i++)particle[i].randomInit();
}
void CDynamicSimulator::clean() {
}
void CDynamicSimulator::doBeforeSimulation(double dt, double currentTime) {
// buoyancy here
}
void CDynamicSimulator::doSimulation(double dt, double currentTime) {
for(int i=0;i<NUMPARTS;i++)
particle[i].simulate(dt, currentTime);
}
void CDynamicSimulator::doAfterSimulation(double dt, double currentTime) {
for(int i=0;i<NUMPARTS;i++) {
particle[i].resetForce();
}
}
void CDynamicSimulator::visualize(void) {
for(int i=0;i<NUMPARTS;i++) {
particle[i].drawWithGL(SPHERE_DRAW);
}
}
<|endoftext|> |
<commit_before>//===----------------------------------------------------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is dual licensed under the MIT and the University of Illinois Open
// Source Licenses. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
// test unsigned long to_ulong() const;
#include <bitset>
#include <algorithm>
#include <climits>
#include <cassert>
template <std::size_t N>
void test_to_ulong()
{
const std::size_t M = sizeof(unsigned long) * CHAR_BIT < N ? sizeof(unsigned long) * CHAR_BIT : N;
const std::size_t X = M == 0 ? sizeof(unsigned long) * CHAR_BIT - 1 : sizeof(unsigned long) * CHAR_BIT - M;
const std::size_t max = M == 0 ? 0 : std::size_t(-1) >> X;
std::size_t tests[] = {0,
std::min<std::size_t>(1, max),
std::min<std::size_t>(2, max),
std::min<std::size_t>(3, max),
std::min(max, max-3),
std::min(max, max-2),
std::min(max, max-1),
max};
for (std::size_t i = 0; i < sizeof(tests)/sizeof(tests[0]); ++i)
{
std::size_t j = tests[i];
std::bitset<N> v(j);
assert(j == v.to_ulong());
}
}
int main()
{
test_to_ulong<0>();
test_to_ulong<1>();
test_to_ulong<31>();
test_to_ulong<32>();
test_to_ulong<33>();
test_to_ulong<63>();
test_to_ulong<64>();
test_to_ulong<65>();
test_to_ulong<1000>();
}
<commit_msg>Test case was forming the wrong limits when size_t != unsigned long.<commit_after>//===----------------------------------------------------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is dual licensed under the MIT and the University of Illinois Open
// Source Licenses. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
// test unsigned long to_ulong() const;
#include <bitset>
#include <algorithm>
#include <limits>
#include <climits>
#include <cassert>
template <std::size_t N>
void test_to_ulong()
{
const std::size_t M = sizeof(unsigned long) * CHAR_BIT < N ? sizeof(unsigned long) * CHAR_BIT : N;
const std::size_t X = M == 0 ? sizeof(unsigned long) * CHAR_BIT - 1 : sizeof(unsigned long) * CHAR_BIT - M;
const std::size_t max = M == 0 ? 0 : std::size_t(std::numeric_limits<unsigned long>::max()) >> X;
std::size_t tests[] = {0,
std::min<std::size_t>(1, max),
std::min<std::size_t>(2, max),
std::min<std::size_t>(3, max),
std::min(max, max-3),
std::min(max, max-2),
std::min(max, max-1),
max};
for (std::size_t i = 0; i < sizeof(tests)/sizeof(tests[0]); ++i)
{
std::size_t j = tests[i];
std::bitset<N> v(j);
assert(j == v.to_ulong());
}
}
int main()
{
test_to_ulong<0>();
test_to_ulong<1>();
test_to_ulong<31>();
test_to_ulong<32>();
test_to_ulong<33>();
test_to_ulong<63>();
test_to_ulong<64>();
test_to_ulong<65>();
test_to_ulong<1000>();
}
<|endoftext|> |
<commit_before><commit_msg>Setting pending override mesh<commit_after><|endoftext|> |
<commit_before>#ifndef BENCHMARK_HPP_
#define BENCHMARK_HPP_
#define BOOST_TEST_NO_MAIN
#define BOOST_TEST_ALTERNATIVE_INIT_API
#include "application.hpp"
#include "options.hpp"
#include "benchmark_suite.hpp"
#include <boost/test/included/unit_test.hpp>
#include <boost/mpl/list.hpp>
namespace gearshifft {
/// List alias
template<typename... Types>
using List = boost::mpl::list<Types...>;
/**
* Benchmark API class for clients.
*
*/
template<typename Context>
class Benchmark {
using AppT = Application<Context>;
public:
Benchmark() = default;
~Benchmark() {
if(AppT::getInstance().isContextCreated()) {
AppT::getInstance().destroyContext();
}
}
void configure(int argc, char* argv[]) {
configured_ = false;
std::vector<char*> vargv(argv, argv+argc);
boost_vargv_.clear();
boost_vargv_.emplace_back(argv[0]); // [0] = name of application
if( Options::getInstance().parse(vargv, boost_vargv_) ) {
if( gearshifft::Options::getInstance().getListDevices() ) {
std::cout << Context::getListDevices() << std::endl;
}
}
else
configured_ = true;
}
template<typename T_FFT_Is_Normalized,
typename T_FFTs,
typename T_Precisions>
void run() {
if(configured_==false)
return;
AppT::getInstance().createContext();
auto init_function = []() {
Run<Context, T_FFT_Is_Normalized, T_FFTs, T_Precisions> instance;
::boost::unit_test::framework::master_test_suite().add( instance() );
return true;
};
::boost::unit_test::unit_test_main( init_function,
boost_vargv_.size(),
boost_vargv_.data() );
AppT::getInstance().destroyContext();
AppT::getInstance().dumpResults();
}
private:
bool configured_ = false;
std::vector<char*> boost_vargv_;
};
} // gearshifft
#endif // BENCHMARK_HPP_
<commit_msg>disabled using the boost test alternative stack to fix segfault at the end of fftw benchmarks<commit_after>#ifndef BENCHMARK_HPP_
#define BENCHMARK_HPP_
#define BOOST_TEST_DISABLE_ALT_STACK
#define BOOST_TEST_NO_MAIN
#define BOOST_TEST_ALTERNATIVE_INIT_API
#include "application.hpp"
#include "options.hpp"
#include "benchmark_suite.hpp"
#include <boost/test/included/unit_test.hpp>
#include <boost/mpl/list.hpp>
namespace gearshifft {
/// List alias
template<typename... Types>
using List = boost::mpl::list<Types...>;
/**
* Benchmark API class for clients.
*
*/
template<typename Context>
class Benchmark {
using AppT = Application<Context>;
public:
Benchmark() = default;
~Benchmark() {
if(AppT::getInstance().isContextCreated()) {
AppT::getInstance().destroyContext();
}
}
void configure(int argc, char* argv[]) {
configured_ = false;
std::vector<char*> vargv(argv, argv+argc);
boost_vargv_.clear();
boost_vargv_.emplace_back(argv[0]); // [0] = name of application
if( Options::getInstance().parse(vargv, boost_vargv_) ) {
if( gearshifft::Options::getInstance().getListDevices() ) {
std::cout << Context::getListDevices() << std::endl;
}
}
else
configured_ = true;
}
template<typename T_FFT_Is_Normalized,
typename T_FFTs,
typename T_Precisions>
void run() {
if(configured_==false)
return;
AppT::getInstance().createContext();
auto init_function = []() {
Run<Context, T_FFT_Is_Normalized, T_FFTs, T_Precisions> instance;
::boost::unit_test::framework::master_test_suite().add( instance() );
return true;
};
::boost::unit_test::unit_test_main( init_function,
boost_vargv_.size(),
boost_vargv_.data() );
AppT::getInstance().destroyContext();
AppT::getInstance().dumpResults();
}
private:
bool configured_ = false;
std::vector<char*> boost_vargv_;
};
} // gearshifft
#endif // BENCHMARK_HPP_
<|endoftext|> |
<commit_before>///////////////////////////////////////////////////////////////////////////////
//
// Copyright (C) 2014 Tavendo GmbH
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
///////////////////////////////////////////////////////////////////////////////
#include "wamp_message_type.hpp"
#include <boost/lexical_cast.hpp>
#include <stdexcept>
#include <tuple>
namespace autobahn {
inline wamp_invocation_impl::wamp_invocation_impl()
: m_zone()
, m_details(EMPTY_DETAILS)
, m_arguments(EMPTY_ARGUMENTS)
, m_kw_arguments(EMPTY_KW_ARGUMENTS)
, m_send_result_fn()
, m_request_id(0)
{
}
template <typename T>
T wamp_invocation_impl::details(const std::string& key) const
{
if (m_details.type != msgpack::type::MAP) {
throw msgpack::type_error();
}
for (std::size_t i = 0; i < m_details.via.map.size; ++i) {
const msgpack::object_kv& kv = m_details.via.map.ptr[i];
if (kv.key.type == msgpack::type::STR && key.size() == kv.key.via.str.size
&& key.compare(0, key.size(), kv.key.via.str.ptr, kv.key.via.str.size) == 0)
{
return kv.val.as<T>();
}
}
throw std::out_of_range(key + " detail argument doesn't exist");
}
template <typename T>
T wamp_invocation_impl::detail(const char *key) const
{
if (m_details.type != msgpack::type::MAP) {
throw msgpack::type_error();
}
std::size_t key_size = strlen(key);
for (std::size_t i = 0; i < m_details.via.map.size; ++i) {
const msgpack::object_kv& kv = m_details.via.map.ptr[i];
if (kv.key.type == msgpack::type::STR && key_size == kv.key.via.str.size
&& memcmp(key, kv.key.via.str.ptr, key_size) == 0)
{
return kv.val.as<T>();
}
}
throw std::out_of_range(std::string(key) + " keyword argument doesn't exist");
}
template<typename Map>
Map wamp_invocation_impl::details() const
{
return m_details.as<Map>();
}
inline std::size_t wamp_invocation_impl::number_of_arguments() const
{
return m_arguments.type == msgpack::type::ARRAY ? m_arguments.via.array.size : 0;
}
inline std::size_t wamp_invocation_impl::number_of_kw_arguments() const
{
return m_kw_arguments.type == msgpack::type::MAP ? m_kw_arguments.via.map.size : 0;
}
template <typename T>
inline T wamp_invocation_impl::argument(std::size_t index) const
{
if (m_arguments.type != msgpack::type::ARRAY || m_arguments.via.array.size <= index) {
throw std::out_of_range("no argument at index " + boost::lexical_cast<std::string>(index));
}
return m_arguments.via.array.ptr[index].as<T>();
}
template <typename List>
inline List wamp_invocation_impl::arguments() const
{
return m_arguments.as<List>();
}
template <typename List>
inline void wamp_invocation_impl::get_arguments(List& args) const
{
m_arguments.convert(args);
}
template <typename... T>
inline void wamp_invocation_impl::get_each_argument(T&... args) const
{
auto args_tuple = std::make_tuple(std::ref(args)...);
m_arguments.convert(args_tuple);
}
template <typename T>
inline T wamp_invocation_impl::kw_argument(const std::string& key) const
{
if (m_kw_arguments.type != msgpack::type::MAP) {
throw msgpack::type_error();
}
for (std::size_t i = 0; i < m_kw_arguments.via.map.size; ++i) {
const msgpack::object_kv& kv = m_kw_arguments.via.map.ptr[i];
if (kv.key.type == msgpack::type::STR && key.size() == kv.key.via.str.size
&& key.compare(0, key.size(), kv.key.via.str.ptr, kv.key.via.str.size) == 0)
{
return kv.val.as<T>();
}
}
throw std::out_of_range(key + " keyword argument doesn't exist");
}
template <typename T>
inline T wamp_invocation_impl::kw_argument(const char* key) const
{
if (m_kw_arguments.type != msgpack::type::MAP) {
throw msgpack::type_error();
}
std::size_t key_size = strlen(key);
for (std::size_t i = 0; i < m_kw_arguments.via.map.size; ++i) {
const msgpack::object_kv& kv = m_kw_arguments.via.map.ptr[i];
if (kv.key.type == msgpack::type::STR && key_size == kv.key.via.str.size
&& memcmp(key, kv.key.via.str.ptr, key_size) == 0)
{
return kv.val.as<T>();
}
}
throw std::out_of_range(std::string(key) + " keyword argument doesn't exist");
}
template <typename T>
inline T wamp_invocation_impl::kw_argument_or(const std::string& key, const T& fallback) const
{
if (m_kw_arguments.type != msgpack::type::MAP) {
throw msgpack::type_error();
}
for (std::size_t i = 0; i < m_kw_arguments.via.map.size; ++i) {
const msgpack::object_kv& kv = m_kw_arguments.via.map.ptr[i];
if (kv.key.type == msgpack::type::STR && key.size() == kv.key.via.str.size
&& key.compare(0, key.size(), kv.key.via.str.ptr, kv.key.via.str.size) == 0)
{
return kv.val.as<T>();
}
}
return fallback;
}
template <typename T>
inline T wamp_invocation_impl::kw_argument_or(const char* key, const T& fallback) const
{
if (m_kw_arguments.type != msgpack::type::MAP) {
throw msgpack::type_error();
}
std::size_t key_size = strlen(key);
for (std::size_t i = 0; i < m_kw_arguments.via.map.size; ++i) {
const msgpack::object_kv& kv = m_kw_arguments.via.map.ptr[i];
if (kv.key.type == msgpack::type::STR && key_size == kv.key.via.str.size
&& memcmp(key, kv.key.via.str.ptr, key_size) == 0)
{
return kv.val.as<T>();
}
}
throw fallback;
}
template <typename Map>
inline Map wamp_invocation_impl::kw_arguments() const
{
return m_kw_arguments.as<Map>();
}
template <typename Map>
inline void wamp_invocation_impl::get_kw_arguments(Map& kw_args) const
{
m_kw_arguments.convert(kw_args);
}
inline void wamp_invocation_impl::empty_result()
{
throw_if_not_sendable();
auto buffer = std::make_shared<msgpack::sbuffer>();
msgpack::packer<msgpack::sbuffer> packer(*buffer);
// [YIELD, INVOCATION.Request|id, Options|dict]
packer.pack_array(3);
packer.pack(static_cast<int>(message_type::YIELD));
packer.pack(m_request_id);
packer.pack_map(0);
m_send_result_fn(buffer);
m_send_result_fn = send_result_fn();
}
template<typename List>
inline void wamp_invocation_impl::result(const List& arguments)
{
throw_if_not_sendable();
auto buffer = std::make_shared<msgpack::sbuffer>();
msgpack::packer<msgpack::sbuffer> packer(*buffer);
// [YIELD, INVOCATION.Request|id, Options|dict, Arguments|list]
packer.pack_array(4);
packer.pack(static_cast<int>(message_type::YIELD));
packer.pack(m_request_id);
packer.pack_map(0);
packer.pack(arguments);
m_send_result_fn(buffer);
m_send_result_fn = send_result_fn();
}
template<typename List, typename Map>
inline void wamp_invocation_impl::result(
const List& arguments, const Map& kw_arguments)
{
throw_if_not_sendable();
auto buffer = std::make_shared<msgpack::sbuffer>();
msgpack::packer<msgpack::sbuffer> packer(*buffer);
// [YIELD, INVOCATION.Request|id, Options|dict, Arguments|list, ArgumentsKw|dict]
packer.pack_array(5);
packer.pack(static_cast<int>(message_type::YIELD));
packer.pack(m_request_id);
packer.pack_map(0);
packer.pack(arguments);
packer.pack(kw_arguments);
m_send_result_fn(buffer);
m_send_result_fn = send_result_fn();
}
inline void wamp_invocation_impl::error(const std::string& error_uri)
{
throw_if_not_sendable();
auto buffer = std::make_shared<msgpack::sbuffer>();
msgpack::packer<msgpack::sbuffer> packer(*buffer);
// [ERROR, INVOCATION, INVOCATION.Request|id, Details|dict, Error|uri]
packer.pack_array(5);
packer.pack(static_cast<int>(message_type::ERROR));
packer.pack(static_cast<int>(message_type::INVOCATION));
packer.pack(m_request_id);
packer.pack_map(0);
packer.pack(error_uri);
m_send_result_fn(buffer);
m_send_result_fn = send_result_fn();
}
template <typename List>
inline void wamp_invocation_impl::error(const std::string& error_uri, const List& arguments)
{
throw_if_not_sendable();
auto buffer = std::make_shared<msgpack::sbuffer>();
msgpack::packer<msgpack::sbuffer> packer(*buffer);
// [ERROR, INVOCATION, INVOCATION.Request|id, Details|dict, Error|uri, Arguments|list]
packer.pack_array(6);
packer.pack(static_cast<int>(message_type::ERROR));
packer.pack(static_cast<int>(message_type::INVOCATION));
packer.pack(m_request_id);
packer.pack_map(0);
packer.pack(error_uri);
packer.pack(arguments);
m_send_result_fn(buffer);
m_send_result_fn = send_result_fn();
}
template <typename List, typename Map>
inline void wamp_invocation_impl::error(
const std::string& error_uri,
const List& arguments, const Map& kw_arguments)
{
throw_if_not_sendable();
auto buffer = std::make_shared<msgpack::sbuffer>();
msgpack::packer<msgpack::sbuffer> packer(*buffer);
// [ERROR, INVOCATION, INVOCATION.Request|id, Details|dict, Error|uri, Arguments|list, ArgumentsKw|dict]
packer.pack_array(7);
packer.pack(static_cast<int>(message_type::ERROR));
packer.pack(static_cast<int>(message_type::INVOCATION));
packer.pack(m_request_id);
packer.pack_map(0);
packer.pack(error_uri);
packer.pack(arguments);
packer.pack(kw_arguments);
m_send_result_fn(buffer);
m_send_result_fn = send_result_fn();
}
inline void wamp_invocation_impl::set_send_result_fn(send_result_fn&& send_result)
{
m_send_result_fn = std::move(send_result);
}
inline void wamp_invocation_impl::set_request_id(std::uint64_t request_id)
{
m_request_id = request_id;
}
inline void wamp_invocation_impl::set_details(const msgpack::object& details)
{
m_details = details;
}
inline void wamp_invocation_impl::set_zone(msgpack::zone&& zone)
{
m_zone = std::move(zone);
}
inline void wamp_invocation_impl::set_arguments(const msgpack::object& arguments)
{
m_arguments = arguments;
}
inline void wamp_invocation_impl::set_kw_arguments(const msgpack::object& kw_arguments)
{
m_kw_arguments = kw_arguments;
}
inline bool wamp_invocation_impl::sendable() const
{
return static_cast<bool>(m_send_result_fn);
}
inline void wamp_invocation_impl::throw_if_not_sendable()
{
if (!sendable()) {
throw std::runtime_error("tried to call result() or error() but wamp_invocation "
"is not sendable (double call?)");
}
}
} // namespace autobahn
<commit_msg>Clean up exception wording<commit_after>///////////////////////////////////////////////////////////////////////////////
//
// Copyright (C) 2014 Tavendo GmbH
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
///////////////////////////////////////////////////////////////////////////////
#include "wamp_message_type.hpp"
#include <boost/lexical_cast.hpp>
#include <stdexcept>
#include <tuple>
namespace autobahn {
inline wamp_invocation_impl::wamp_invocation_impl()
: m_zone()
, m_details(EMPTY_DETAILS)
, m_arguments(EMPTY_ARGUMENTS)
, m_kw_arguments(EMPTY_KW_ARGUMENTS)
, m_send_result_fn()
, m_request_id(0)
{
}
template <typename T>
T wamp_invocation_impl::details(const std::string& key) const
{
if (m_details.type != msgpack::type::MAP) {
throw msgpack::type_error();
}
for (std::size_t i = 0; i < m_details.via.map.size; ++i) {
const msgpack::object_kv& kv = m_details.via.map.ptr[i];
if (kv.key.type == msgpack::type::STR && key.size() == kv.key.via.str.size
&& key.compare(0, key.size(), kv.key.via.str.ptr, kv.key.via.str.size) == 0)
{
return kv.val.as<T>();
}
}
throw std::out_of_range(key + " detail doesn't exist");
}
template <typename T>
T wamp_invocation_impl::detail(const char *key) const
{
if (m_details.type != msgpack::type::MAP) {
throw msgpack::type_error();
}
std::size_t key_size = strlen(key);
for (std::size_t i = 0; i < m_details.via.map.size; ++i) {
const msgpack::object_kv& kv = m_details.via.map.ptr[i];
if (kv.key.type == msgpack::type::STR && key_size == kv.key.via.str.size
&& memcmp(key, kv.key.via.str.ptr, key_size) == 0)
{
return kv.val.as<T>();
}
}
throw std::out_of_range(std::string(key) + " detail doesn't exist");
}
template<typename Map>
Map wamp_invocation_impl::details() const
{
return m_details.as<Map>();
}
inline std::size_t wamp_invocation_impl::number_of_arguments() const
{
return m_arguments.type == msgpack::type::ARRAY ? m_arguments.via.array.size : 0;
}
inline std::size_t wamp_invocation_impl::number_of_kw_arguments() const
{
return m_kw_arguments.type == msgpack::type::MAP ? m_kw_arguments.via.map.size : 0;
}
template <typename T>
inline T wamp_invocation_impl::argument(std::size_t index) const
{
if (m_arguments.type != msgpack::type::ARRAY || m_arguments.via.array.size <= index) {
throw std::out_of_range("no argument at index " + boost::lexical_cast<std::string>(index));
}
return m_arguments.via.array.ptr[index].as<T>();
}
template <typename List>
inline List wamp_invocation_impl::arguments() const
{
return m_arguments.as<List>();
}
template <typename List>
inline void wamp_invocation_impl::get_arguments(List& args) const
{
m_arguments.convert(args);
}
template <typename... T>
inline void wamp_invocation_impl::get_each_argument(T&... args) const
{
auto args_tuple = std::make_tuple(std::ref(args)...);
m_arguments.convert(args_tuple);
}
template <typename T>
inline T wamp_invocation_impl::kw_argument(const std::string& key) const
{
if (m_kw_arguments.type != msgpack::type::MAP) {
throw msgpack::type_error();
}
for (std::size_t i = 0; i < m_kw_arguments.via.map.size; ++i) {
const msgpack::object_kv& kv = m_kw_arguments.via.map.ptr[i];
if (kv.key.type == msgpack::type::STR && key.size() == kv.key.via.str.size
&& key.compare(0, key.size(), kv.key.via.str.ptr, kv.key.via.str.size) == 0)
{
return kv.val.as<T>();
}
}
throw std::out_of_range(key + " keyword argument doesn't exist");
}
template <typename T>
inline T wamp_invocation_impl::kw_argument(const char* key) const
{
if (m_kw_arguments.type != msgpack::type::MAP) {
throw msgpack::type_error();
}
std::size_t key_size = strlen(key);
for (std::size_t i = 0; i < m_kw_arguments.via.map.size; ++i) {
const msgpack::object_kv& kv = m_kw_arguments.via.map.ptr[i];
if (kv.key.type == msgpack::type::STR && key_size == kv.key.via.str.size
&& memcmp(key, kv.key.via.str.ptr, key_size) == 0)
{
return kv.val.as<T>();
}
}
throw std::out_of_range(std::string(key) + " keyword argument doesn't exist");
}
template <typename T>
inline T wamp_invocation_impl::kw_argument_or(const std::string& key, const T& fallback) const
{
if (m_kw_arguments.type != msgpack::type::MAP) {
throw msgpack::type_error();
}
for (std::size_t i = 0; i < m_kw_arguments.via.map.size; ++i) {
const msgpack::object_kv& kv = m_kw_arguments.via.map.ptr[i];
if (kv.key.type == msgpack::type::STR && key.size() == kv.key.via.str.size
&& key.compare(0, key.size(), kv.key.via.str.ptr, kv.key.via.str.size) == 0)
{
return kv.val.as<T>();
}
}
return fallback;
}
template <typename T>
inline T wamp_invocation_impl::kw_argument_or(const char* key, const T& fallback) const
{
if (m_kw_arguments.type != msgpack::type::MAP) {
throw msgpack::type_error();
}
std::size_t key_size = strlen(key);
for (std::size_t i = 0; i < m_kw_arguments.via.map.size; ++i) {
const msgpack::object_kv& kv = m_kw_arguments.via.map.ptr[i];
if (kv.key.type == msgpack::type::STR && key_size == kv.key.via.str.size
&& memcmp(key, kv.key.via.str.ptr, key_size) == 0)
{
return kv.val.as<T>();
}
}
throw fallback;
}
template <typename Map>
inline Map wamp_invocation_impl::kw_arguments() const
{
return m_kw_arguments.as<Map>();
}
template <typename Map>
inline void wamp_invocation_impl::get_kw_arguments(Map& kw_args) const
{
m_kw_arguments.convert(kw_args);
}
inline void wamp_invocation_impl::empty_result()
{
throw_if_not_sendable();
auto buffer = std::make_shared<msgpack::sbuffer>();
msgpack::packer<msgpack::sbuffer> packer(*buffer);
// [YIELD, INVOCATION.Request|id, Options|dict]
packer.pack_array(3);
packer.pack(static_cast<int>(message_type::YIELD));
packer.pack(m_request_id);
packer.pack_map(0);
m_send_result_fn(buffer);
m_send_result_fn = send_result_fn();
}
template<typename List>
inline void wamp_invocation_impl::result(const List& arguments)
{
throw_if_not_sendable();
auto buffer = std::make_shared<msgpack::sbuffer>();
msgpack::packer<msgpack::sbuffer> packer(*buffer);
// [YIELD, INVOCATION.Request|id, Options|dict, Arguments|list]
packer.pack_array(4);
packer.pack(static_cast<int>(message_type::YIELD));
packer.pack(m_request_id);
packer.pack_map(0);
packer.pack(arguments);
m_send_result_fn(buffer);
m_send_result_fn = send_result_fn();
}
template<typename List, typename Map>
inline void wamp_invocation_impl::result(
const List& arguments, const Map& kw_arguments)
{
throw_if_not_sendable();
auto buffer = std::make_shared<msgpack::sbuffer>();
msgpack::packer<msgpack::sbuffer> packer(*buffer);
// [YIELD, INVOCATION.Request|id, Options|dict, Arguments|list, ArgumentsKw|dict]
packer.pack_array(5);
packer.pack(static_cast<int>(message_type::YIELD));
packer.pack(m_request_id);
packer.pack_map(0);
packer.pack(arguments);
packer.pack(kw_arguments);
m_send_result_fn(buffer);
m_send_result_fn = send_result_fn();
}
inline void wamp_invocation_impl::error(const std::string& error_uri)
{
throw_if_not_sendable();
auto buffer = std::make_shared<msgpack::sbuffer>();
msgpack::packer<msgpack::sbuffer> packer(*buffer);
// [ERROR, INVOCATION, INVOCATION.Request|id, Details|dict, Error|uri]
packer.pack_array(5);
packer.pack(static_cast<int>(message_type::ERROR));
packer.pack(static_cast<int>(message_type::INVOCATION));
packer.pack(m_request_id);
packer.pack_map(0);
packer.pack(error_uri);
m_send_result_fn(buffer);
m_send_result_fn = send_result_fn();
}
template <typename List>
inline void wamp_invocation_impl::error(const std::string& error_uri, const List& arguments)
{
throw_if_not_sendable();
auto buffer = std::make_shared<msgpack::sbuffer>();
msgpack::packer<msgpack::sbuffer> packer(*buffer);
// [ERROR, INVOCATION, INVOCATION.Request|id, Details|dict, Error|uri, Arguments|list]
packer.pack_array(6);
packer.pack(static_cast<int>(message_type::ERROR));
packer.pack(static_cast<int>(message_type::INVOCATION));
packer.pack(m_request_id);
packer.pack_map(0);
packer.pack(error_uri);
packer.pack(arguments);
m_send_result_fn(buffer);
m_send_result_fn = send_result_fn();
}
template <typename List, typename Map>
inline void wamp_invocation_impl::error(
const std::string& error_uri,
const List& arguments, const Map& kw_arguments)
{
throw_if_not_sendable();
auto buffer = std::make_shared<msgpack::sbuffer>();
msgpack::packer<msgpack::sbuffer> packer(*buffer);
// [ERROR, INVOCATION, INVOCATION.Request|id, Details|dict, Error|uri, Arguments|list, ArgumentsKw|dict]
packer.pack_array(7);
packer.pack(static_cast<int>(message_type::ERROR));
packer.pack(static_cast<int>(message_type::INVOCATION));
packer.pack(m_request_id);
packer.pack_map(0);
packer.pack(error_uri);
packer.pack(arguments);
packer.pack(kw_arguments);
m_send_result_fn(buffer);
m_send_result_fn = send_result_fn();
}
inline void wamp_invocation_impl::set_send_result_fn(send_result_fn&& send_result)
{
m_send_result_fn = std::move(send_result);
}
inline void wamp_invocation_impl::set_request_id(std::uint64_t request_id)
{
m_request_id = request_id;
}
inline void wamp_invocation_impl::set_details(const msgpack::object& details)
{
m_details = details;
}
inline void wamp_invocation_impl::set_zone(msgpack::zone&& zone)
{
m_zone = std::move(zone);
}
inline void wamp_invocation_impl::set_arguments(const msgpack::object& arguments)
{
m_arguments = arguments;
}
inline void wamp_invocation_impl::set_kw_arguments(const msgpack::object& kw_arguments)
{
m_kw_arguments = kw_arguments;
}
inline bool wamp_invocation_impl::sendable() const
{
return static_cast<bool>(m_send_result_fn);
}
inline void wamp_invocation_impl::throw_if_not_sendable()
{
if (!sendable()) {
throw std::runtime_error("tried to call result() or error() but wamp_invocation "
"is not sendable (double call?)");
}
}
} // namespace autobahn
<|endoftext|> |
<commit_before>/*
* Copyright (c) 2013 The WebRTC project authors. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree. An additional intellectual property rights grant can be found
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
#include <string.h>
#include <algorithm>
#include <initializer_list>
#include <memory>
#include <utility>
#include "webrtc/modules/desktop_capture/screen_capturer.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "webrtc/base/checks.h"
#include "webrtc/base/constructormagic.h"
#include "webrtc/base/logging.h"
#include "webrtc/modules/desktop_capture/rgba_color.h"
#include "webrtc/modules/desktop_capture/desktop_capture_options.h"
#include "webrtc/modules/desktop_capture/desktop_frame.h"
#include "webrtc/modules/desktop_capture/desktop_region.h"
#include "webrtc/modules/desktop_capture/screen_capturer_mock_objects.h"
#include "webrtc/modules/desktop_capture/screen_drawer.h"
#include "webrtc/system_wrappers/include/sleep.h"
#if defined(WEBRTC_WIN)
#include "webrtc/modules/desktop_capture/win/screen_capturer_win_directx.h"
#endif // defined(WEBRTC_WIN)
using ::testing::_;
using ::testing::AnyNumber;
using ::testing::Return;
const int kTestSharedMemoryId = 123;
namespace webrtc {
namespace {
ACTION_P(SaveUniquePtrArg, dest) {
*dest = std::move(*arg1);
}
// Returns true if color in |rect| of |frame| is |color|.
bool ArePixelsColoredBy(const DesktopFrame& frame,
DesktopRect rect,
RgbaColor color) {
// updated_region() should cover the painted area.
DesktopRegion updated_region(frame.updated_region());
updated_region.IntersectWith(rect);
if (!updated_region.Equals(DesktopRegion(rect))) {
return false;
}
// Color in the |rect| should be |color|.
uint8_t* row = frame.GetFrameDataAtPos(rect.top_left());
for (int i = 0; i < rect.height(); i++) {
uint8_t* column = row;
for (int j = 0; j < rect.width(); j++) {
if (color != RgbaColor(column)) {
return false;
}
column += DesktopFrame::kBytesPerPixel;
}
row += frame.stride();
}
return true;
}
} // namespace
class ScreenCapturerTest : public testing::Test {
public:
void SetUp() override {
capturer_.reset(
ScreenCapturer::Create(DesktopCaptureOptions::CreateDefault()));
}
protected:
void TestCaptureUpdatedRegion(
std::initializer_list<ScreenCapturer*> capturers) {
RTC_DCHECK(capturers.size() > 0);
// A large enough area for the tests, which should be able to fulfill by
// most of systems.
const int kTestArea = 512;
const int kRectSize = 32;
std::unique_ptr<ScreenDrawer> drawer = ScreenDrawer::Create();
if (!drawer || drawer->DrawableRegion().is_empty()) {
LOG(LS_WARNING) << "No ScreenDrawer implementation for current platform.";
return;
}
if (drawer->DrawableRegion().width() < kTestArea ||
drawer->DrawableRegion().height() < kTestArea) {
LOG(LS_WARNING) << "ScreenDrawer::DrawableRegion() is too small for the "
"CaptureUpdatedRegion tests.";
return;
}
for (ScreenCapturer* capturer : capturers) {
capturer->Start(&callback_);
}
// Draw a set of |kRectSize| by |kRectSize| rectangles at (|i|, |i|). One of
// (controlled by |c|) its primary colors is |i|, and the other two are
// 0xff. So we won't draw a white rectangle.
for (int c = 0; c < 3; c++) {
for (int i = 0; i < kTestArea - kRectSize; i += 16) {
DesktopRect rect = DesktopRect::MakeXYWH(i, i, kRectSize, kRectSize);
rect.Translate(drawer->DrawableRegion().top_left());
RgbaColor color((c == 0 ? (i & 0xff) : 0x7f),
(c == 1 ? (i & 0xff) : 0x7f),
(c == 2 ? (i & 0xff) : 0x7f));
drawer->Clear();
drawer->DrawRectangle(rect, color);
TestCaptureOneFrame(capturers, drawer.get(), rect, color);
}
}
}
void TestCaptureUpdatedRegion() {
TestCaptureUpdatedRegion({capturer_.get()});
}
#if defined(WEBRTC_WIN)
bool CreateDirectxCapturer() {
if (!ScreenCapturerWinDirectx::IsSupported()) {
LOG(LS_WARNING) << "Directx capturer is not supported";
return false;
}
DesktopCaptureOptions options(DesktopCaptureOptions::CreateDefault());
options.set_allow_directx_capturer(true);
capturer_.reset(ScreenCapturer::Create(options));
return true;
}
void CreateMagnifierCapturer() {
DesktopCaptureOptions options(DesktopCaptureOptions::CreateDefault());
options.set_allow_use_magnification_api(true);
capturer_.reset(ScreenCapturer::Create(options));
}
#endif // defined(WEBRTC_WIN)
std::unique_ptr<ScreenCapturer> capturer_;
MockScreenCapturerCallback callback_;
private:
// Repeats capturing the frame by using |capturers| one-by-one for 600 times,
// typically 30 seconds, until they succeeded captured a |color| rectangle at
// |rect|. This function uses |drawer|->WaitForPendingDraws() between two
// attempts to wait for the screen to update.
void TestCaptureOneFrame(std::vector<ScreenCapturer*> capturers,
ScreenDrawer* drawer,
DesktopRect rect,
RgbaColor color) {
size_t succeeded_capturers = 0;
const int wait_capture_round = 600;
for (int i = 0; i < wait_capture_round; i++) {
drawer->WaitForPendingDraws();
for (size_t j = 0; j < capturers.size(); j++) {
if (capturers[j] == nullptr) {
// ScreenCapturer should return an empty updated_region() if no
// update detected. So we won't test it again if it has captured
// the rectangle we drew.
continue;
}
std::unique_ptr<DesktopFrame> frame = CaptureFrame(capturers[j]);
if (!frame) {
// CaptureFrame() has triggered an assertion failure already, we
// only need to return here.
return;
}
if (ArePixelsColoredBy(*frame, rect, color)) {
capturers[j] = nullptr;
succeeded_capturers++;
}
}
if (succeeded_capturers == capturers.size()) {
break;
}
}
ASSERT_EQ(succeeded_capturers, capturers.size());
}
// Expects |capturer| to successfully capture a frame, and returns it.
std::unique_ptr<DesktopFrame> CaptureFrame(ScreenCapturer* capturer) {
std::unique_ptr<DesktopFrame> frame;
EXPECT_CALL(callback_,
OnCaptureResultPtr(DesktopCapturer::Result::SUCCESS, _))
.WillOnce(SaveUniquePtrArg(&frame));
capturer->Capture(DesktopRegion());
EXPECT_TRUE(frame);
return frame;
}
};
class FakeSharedMemory : public SharedMemory {
public:
FakeSharedMemory(char* buffer, size_t size)
: SharedMemory(buffer, size, 0, kTestSharedMemoryId),
buffer_(buffer) {
}
virtual ~FakeSharedMemory() {
delete[] buffer_;
}
private:
char* buffer_;
RTC_DISALLOW_COPY_AND_ASSIGN(FakeSharedMemory);
};
class FakeSharedMemoryFactory : public SharedMemoryFactory {
public:
FakeSharedMemoryFactory() {}
~FakeSharedMemoryFactory() override {}
std::unique_ptr<SharedMemory> CreateSharedMemory(size_t size) override {
return std::unique_ptr<SharedMemory>(
new FakeSharedMemory(new char[size], size));
}
private:
RTC_DISALLOW_COPY_AND_ASSIGN(FakeSharedMemoryFactory);
};
TEST_F(ScreenCapturerTest, GetScreenListAndSelectScreen) {
webrtc::ScreenCapturer::ScreenList screens;
EXPECT_TRUE(capturer_->GetScreenList(&screens));
for (webrtc::ScreenCapturer::ScreenList::iterator it = screens.begin();
it != screens.end(); ++it) {
EXPECT_TRUE(capturer_->SelectScreen(it->id));
}
}
TEST_F(ScreenCapturerTest, StartCapturer) {
capturer_->Start(&callback_);
}
TEST_F(ScreenCapturerTest, Capture) {
// Assume that Start() treats the screen as invalid initially.
std::unique_ptr<DesktopFrame> frame;
EXPECT_CALL(callback_,
OnCaptureResultPtr(DesktopCapturer::Result::SUCCESS, _))
.WillOnce(SaveUniquePtrArg(&frame));
capturer_->Start(&callback_);
capturer_->Capture(DesktopRegion());
ASSERT_TRUE(frame);
EXPECT_GT(frame->size().width(), 0);
EXPECT_GT(frame->size().height(), 0);
EXPECT_GE(frame->stride(),
frame->size().width() * DesktopFrame::kBytesPerPixel);
EXPECT_TRUE(frame->shared_memory() == NULL);
// Verify that the region contains whole screen.
EXPECT_FALSE(frame->updated_region().is_empty());
DesktopRegion::Iterator it(frame->updated_region());
ASSERT_TRUE(!it.IsAtEnd());
EXPECT_TRUE(it.rect().equals(DesktopRect::MakeSize(frame->size())));
it.Advance();
EXPECT_TRUE(it.IsAtEnd());
}
TEST_F(ScreenCapturerTest, CaptureUpdatedRegion) {
TestCaptureUpdatedRegion();
}
// TODO(zijiehe): Find out the reason of failure of this test on trybot.
TEST_F(ScreenCapturerTest, DISABLED_TwoCapturers) {
std::unique_ptr<ScreenCapturer> capturer2 = std::move(capturer_);
SetUp();
TestCaptureUpdatedRegion({capturer_.get(), capturer2.get()});
}
#if defined(WEBRTC_WIN)
TEST_F(ScreenCapturerTest, UseSharedBuffers) {
std::unique_ptr<DesktopFrame> frame;
EXPECT_CALL(callback_,
OnCaptureResultPtr(DesktopCapturer::Result::SUCCESS, _))
.WillOnce(SaveUniquePtrArg(&frame));
capturer_->Start(&callback_);
capturer_->SetSharedMemoryFactory(
std::unique_ptr<SharedMemoryFactory>(new FakeSharedMemoryFactory()));
capturer_->Capture(DesktopRegion());
ASSERT_TRUE(frame);
ASSERT_TRUE(frame->shared_memory());
EXPECT_EQ(frame->shared_memory()->id(), kTestSharedMemoryId);
}
TEST_F(ScreenCapturerTest, UseMagnifier) {
CreateMagnifierCapturer();
std::unique_ptr<DesktopFrame> frame;
EXPECT_CALL(callback_,
OnCaptureResultPtr(DesktopCapturer::Result::SUCCESS, _))
.WillOnce(SaveUniquePtrArg(&frame));
capturer_->Start(&callback_);
capturer_->Capture(DesktopRegion());
ASSERT_TRUE(frame);
}
TEST_F(ScreenCapturerTest, UseDirectxCapturer) {
if (!CreateDirectxCapturer()) {
return;
}
std::unique_ptr<DesktopFrame> frame;
EXPECT_CALL(callback_,
OnCaptureResultPtr(DesktopCapturer::Result::SUCCESS, _))
.WillOnce(SaveUniquePtrArg(&frame));
capturer_->Start(&callback_);
capturer_->Capture(DesktopRegion());
ASSERT_TRUE(frame);
}
TEST_F(ScreenCapturerTest, UseDirectxCapturerWithSharedBuffers) {
if (!CreateDirectxCapturer()) {
return;
}
std::unique_ptr<DesktopFrame> frame;
EXPECT_CALL(callback_,
OnCaptureResultPtr(DesktopCapturer::Result::SUCCESS, _))
.WillOnce(SaveUniquePtrArg(&frame));
capturer_->Start(&callback_);
capturer_->SetSharedMemoryFactory(
std::unique_ptr<SharedMemoryFactory>(new FakeSharedMemoryFactory()));
capturer_->Capture(DesktopRegion());
ASSERT_TRUE(frame);
ASSERT_TRUE(frame->shared_memory());
EXPECT_EQ(frame->shared_memory()->id(), kTestSharedMemoryId);
}
TEST_F(ScreenCapturerTest, CaptureUpdatedRegionWithDirectxCapturer) {
if (!CreateDirectxCapturer()) {
return;
}
TestCaptureUpdatedRegion();
}
TEST_F(ScreenCapturerTest, TwoDirectxCapturers) {
if (!CreateDirectxCapturer()) {
return;
}
std::unique_ptr<ScreenCapturer> capturer2 = std::move(capturer_);
RTC_CHECK(CreateDirectxCapturer());
TestCaptureUpdatedRegion({capturer_.get(), capturer2.get()});
}
TEST_F(ScreenCapturerTest, TwoMagnifierCapturers) {
CreateMagnifierCapturer();
std::unique_ptr<ScreenCapturer> capturer2 = std::move(capturer_);
CreateMagnifierCapturer();
TestCaptureUpdatedRegion({capturer_.get(), capturer2.get()});
}
#endif // defined(WEBRTC_WIN)
} // namespace webrtc
<commit_msg>Disable all screen-capturer tests<commit_after>/*
* Copyright (c) 2013 The WebRTC project authors. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree. An additional intellectual property rights grant can be found
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
#include <string.h>
#include <algorithm>
#include <initializer_list>
#include <memory>
#include <utility>
#include "webrtc/modules/desktop_capture/screen_capturer.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "webrtc/base/checks.h"
#include "webrtc/base/constructormagic.h"
#include "webrtc/base/logging.h"
#include "webrtc/modules/desktop_capture/rgba_color.h"
#include "webrtc/modules/desktop_capture/desktop_capture_options.h"
#include "webrtc/modules/desktop_capture/desktop_frame.h"
#include "webrtc/modules/desktop_capture/desktop_region.h"
#include "webrtc/modules/desktop_capture/screen_capturer_mock_objects.h"
#include "webrtc/modules/desktop_capture/screen_drawer.h"
#include "webrtc/system_wrappers/include/sleep.h"
#if defined(WEBRTC_WIN)
#include "webrtc/modules/desktop_capture/win/screen_capturer_win_directx.h"
#endif // defined(WEBRTC_WIN)
using ::testing::_;
using ::testing::AnyNumber;
using ::testing::Return;
const int kTestSharedMemoryId = 123;
namespace webrtc {
namespace {
ACTION_P(SaveUniquePtrArg, dest) {
*dest = std::move(*arg1);
}
// Returns true if color in |rect| of |frame| is |color|.
bool ArePixelsColoredBy(const DesktopFrame& frame,
DesktopRect rect,
RgbaColor color) {
// updated_region() should cover the painted area.
DesktopRegion updated_region(frame.updated_region());
updated_region.IntersectWith(rect);
if (!updated_region.Equals(DesktopRegion(rect))) {
return false;
}
// Color in the |rect| should be |color|.
uint8_t* row = frame.GetFrameDataAtPos(rect.top_left());
for (int i = 0; i < rect.height(); i++) {
uint8_t* column = row;
for (int j = 0; j < rect.width(); j++) {
if (color != RgbaColor(column)) {
return false;
}
column += DesktopFrame::kBytesPerPixel;
}
row += frame.stride();
}
return true;
}
} // namespace
class ScreenCapturerTest : public testing::Test {
public:
void SetUp() override {
capturer_.reset(
ScreenCapturer::Create(DesktopCaptureOptions::CreateDefault()));
}
protected:
void TestCaptureUpdatedRegion(
std::initializer_list<ScreenCapturer*> capturers) {
RTC_DCHECK(capturers.size() > 0);
// A large enough area for the tests, which should be able to fulfill by
// most of systems.
const int kTestArea = 512;
const int kRectSize = 32;
std::unique_ptr<ScreenDrawer> drawer = ScreenDrawer::Create();
if (!drawer || drawer->DrawableRegion().is_empty()) {
LOG(LS_WARNING) << "No ScreenDrawer implementation for current platform.";
return;
}
if (drawer->DrawableRegion().width() < kTestArea ||
drawer->DrawableRegion().height() < kTestArea) {
LOG(LS_WARNING) << "ScreenDrawer::DrawableRegion() is too small for the "
"CaptureUpdatedRegion tests.";
return;
}
for (ScreenCapturer* capturer : capturers) {
capturer->Start(&callback_);
}
// Draw a set of |kRectSize| by |kRectSize| rectangles at (|i|, |i|). One of
// (controlled by |c|) its primary colors is |i|, and the other two are
// 0xff. So we won't draw a white rectangle.
for (int c = 0; c < 3; c++) {
for (int i = 0; i < kTestArea - kRectSize; i += 16) {
DesktopRect rect = DesktopRect::MakeXYWH(i, i, kRectSize, kRectSize);
rect.Translate(drawer->DrawableRegion().top_left());
RgbaColor color((c == 0 ? (i & 0xff) : 0x7f),
(c == 1 ? (i & 0xff) : 0x7f),
(c == 2 ? (i & 0xff) : 0x7f));
drawer->Clear();
drawer->DrawRectangle(rect, color);
TestCaptureOneFrame(capturers, drawer.get(), rect, color);
}
}
}
void TestCaptureUpdatedRegion() {
TestCaptureUpdatedRegion({capturer_.get()});
}
#if defined(WEBRTC_WIN)
bool CreateDirectxCapturer() {
if (!ScreenCapturerWinDirectx::IsSupported()) {
LOG(LS_WARNING) << "Directx capturer is not supported";
return false;
}
DesktopCaptureOptions options(DesktopCaptureOptions::CreateDefault());
options.set_allow_directx_capturer(true);
capturer_.reset(ScreenCapturer::Create(options));
return true;
}
void CreateMagnifierCapturer() {
DesktopCaptureOptions options(DesktopCaptureOptions::CreateDefault());
options.set_allow_use_magnification_api(true);
capturer_.reset(ScreenCapturer::Create(options));
}
#endif // defined(WEBRTC_WIN)
std::unique_ptr<ScreenCapturer> capturer_;
MockScreenCapturerCallback callback_;
private:
// Repeats capturing the frame by using |capturers| one-by-one for 600 times,
// typically 30 seconds, until they succeeded captured a |color| rectangle at
// |rect|. This function uses |drawer|->WaitForPendingDraws() between two
// attempts to wait for the screen to update.
void TestCaptureOneFrame(std::vector<ScreenCapturer*> capturers,
ScreenDrawer* drawer,
DesktopRect rect,
RgbaColor color) {
size_t succeeded_capturers = 0;
const int wait_capture_round = 600;
for (int i = 0; i < wait_capture_round; i++) {
drawer->WaitForPendingDraws();
for (size_t j = 0; j < capturers.size(); j++) {
if (capturers[j] == nullptr) {
// ScreenCapturer should return an empty updated_region() if no
// update detected. So we won't test it again if it has captured
// the rectangle we drew.
continue;
}
std::unique_ptr<DesktopFrame> frame = CaptureFrame(capturers[j]);
if (!frame) {
// CaptureFrame() has triggered an assertion failure already, we
// only need to return here.
return;
}
if (ArePixelsColoredBy(*frame, rect, color)) {
capturers[j] = nullptr;
succeeded_capturers++;
}
}
if (succeeded_capturers == capturers.size()) {
break;
}
}
ASSERT_EQ(succeeded_capturers, capturers.size());
}
// Expects |capturer| to successfully capture a frame, and returns it.
std::unique_ptr<DesktopFrame> CaptureFrame(ScreenCapturer* capturer) {
std::unique_ptr<DesktopFrame> frame;
EXPECT_CALL(callback_,
OnCaptureResultPtr(DesktopCapturer::Result::SUCCESS, _))
.WillOnce(SaveUniquePtrArg(&frame));
capturer->Capture(DesktopRegion());
EXPECT_TRUE(frame);
return frame;
}
};
class FakeSharedMemory : public SharedMemory {
public:
FakeSharedMemory(char* buffer, size_t size)
: SharedMemory(buffer, size, 0, kTestSharedMemoryId),
buffer_(buffer) {
}
virtual ~FakeSharedMemory() {
delete[] buffer_;
}
private:
char* buffer_;
RTC_DISALLOW_COPY_AND_ASSIGN(FakeSharedMemory);
};
class FakeSharedMemoryFactory : public SharedMemoryFactory {
public:
FakeSharedMemoryFactory() {}
~FakeSharedMemoryFactory() override {}
std::unique_ptr<SharedMemory> CreateSharedMemory(size_t size) override {
return std::unique_ptr<SharedMemory>(
new FakeSharedMemory(new char[size], size));
}
private:
RTC_DISALLOW_COPY_AND_ASSIGN(FakeSharedMemoryFactory);
};
TEST_F(ScreenCapturerTest, GetScreenListAndSelectScreen) {
webrtc::ScreenCapturer::ScreenList screens;
EXPECT_TRUE(capturer_->GetScreenList(&screens));
for (webrtc::ScreenCapturer::ScreenList::iterator it = screens.begin();
it != screens.end(); ++it) {
EXPECT_TRUE(capturer_->SelectScreen(it->id));
}
}
TEST_F(ScreenCapturerTest, StartCapturer) {
capturer_->Start(&callback_);
}
TEST_F(ScreenCapturerTest, Capture) {
// Assume that Start() treats the screen as invalid initially.
std::unique_ptr<DesktopFrame> frame;
EXPECT_CALL(callback_,
OnCaptureResultPtr(DesktopCapturer::Result::SUCCESS, _))
.WillOnce(SaveUniquePtrArg(&frame));
capturer_->Start(&callback_);
capturer_->Capture(DesktopRegion());
ASSERT_TRUE(frame);
EXPECT_GT(frame->size().width(), 0);
EXPECT_GT(frame->size().height(), 0);
EXPECT_GE(frame->stride(),
frame->size().width() * DesktopFrame::kBytesPerPixel);
EXPECT_TRUE(frame->shared_memory() == NULL);
// Verify that the region contains whole screen.
EXPECT_FALSE(frame->updated_region().is_empty());
DesktopRegion::Iterator it(frame->updated_region());
ASSERT_TRUE(!it.IsAtEnd());
EXPECT_TRUE(it.rect().equals(DesktopRect::MakeSize(frame->size())));
it.Advance();
EXPECT_TRUE(it.IsAtEnd());
}
// Disabled due to being flaky due to the fact that it useds rendering / UI,
// see webrtc/6366.
TEST_F(ScreenCapturerTest, DISABLED_CaptureUpdatedRegion) {
TestCaptureUpdatedRegion();
}
// Disabled due to being flaky due to the fact that it useds rendering / UI,
// see webrtc/6366.
// TODO(zijiehe): Find out the reason of failure of this test on trybot.
TEST_F(ScreenCapturerTest, DISABLED_TwoCapturers) {
std::unique_ptr<ScreenCapturer> capturer2 = std::move(capturer_);
SetUp();
TestCaptureUpdatedRegion({capturer_.get(), capturer2.get()});
}
#if defined(WEBRTC_WIN)
TEST_F(ScreenCapturerTest, UseSharedBuffers) {
std::unique_ptr<DesktopFrame> frame;
EXPECT_CALL(callback_,
OnCaptureResultPtr(DesktopCapturer::Result::SUCCESS, _))
.WillOnce(SaveUniquePtrArg(&frame));
capturer_->Start(&callback_);
capturer_->SetSharedMemoryFactory(
std::unique_ptr<SharedMemoryFactory>(new FakeSharedMemoryFactory()));
capturer_->Capture(DesktopRegion());
ASSERT_TRUE(frame);
ASSERT_TRUE(frame->shared_memory());
EXPECT_EQ(frame->shared_memory()->id(), kTestSharedMemoryId);
}
TEST_F(ScreenCapturerTest, UseMagnifier) {
CreateMagnifierCapturer();
std::unique_ptr<DesktopFrame> frame;
EXPECT_CALL(callback_,
OnCaptureResultPtr(DesktopCapturer::Result::SUCCESS, _))
.WillOnce(SaveUniquePtrArg(&frame));
capturer_->Start(&callback_);
capturer_->Capture(DesktopRegion());
ASSERT_TRUE(frame);
}
TEST_F(ScreenCapturerTest, UseDirectxCapturer) {
if (!CreateDirectxCapturer()) {
return;
}
std::unique_ptr<DesktopFrame> frame;
EXPECT_CALL(callback_,
OnCaptureResultPtr(DesktopCapturer::Result::SUCCESS, _))
.WillOnce(SaveUniquePtrArg(&frame));
capturer_->Start(&callback_);
capturer_->Capture(DesktopRegion());
ASSERT_TRUE(frame);
}
TEST_F(ScreenCapturerTest, UseDirectxCapturerWithSharedBuffers) {
if (!CreateDirectxCapturer()) {
return;
}
std::unique_ptr<DesktopFrame> frame;
EXPECT_CALL(callback_,
OnCaptureResultPtr(DesktopCapturer::Result::SUCCESS, _))
.WillOnce(SaveUniquePtrArg(&frame));
capturer_->Start(&callback_);
capturer_->SetSharedMemoryFactory(
std::unique_ptr<SharedMemoryFactory>(new FakeSharedMemoryFactory()));
capturer_->Capture(DesktopRegion());
ASSERT_TRUE(frame);
ASSERT_TRUE(frame->shared_memory());
EXPECT_EQ(frame->shared_memory()->id(), kTestSharedMemoryId);
}
// Disabled due to being flaky due to the fact that it useds rendering / UI,
// see webrtc/6366.
TEST_F(ScreenCapturerTest, DISABLED_CaptureUpdatedRegionWithDirectxCapturer) {
if (!CreateDirectxCapturer()) {
return;
}
TestCaptureUpdatedRegion();
}
// Disabled due to being flaky due to the fact that it useds rendering / UI,
// see webrtc/6366.
TEST_F(ScreenCapturerTest, DISABLED_TwoDirectxCapturers) {
if (!CreateDirectxCapturer()) {
return;
}
std::unique_ptr<ScreenCapturer> capturer2 = std::move(capturer_);
RTC_CHECK(CreateDirectxCapturer());
TestCaptureUpdatedRegion({capturer_.get(), capturer2.get()});
}
// Disabled due to being flaky due to the fact that it useds rendering / UI,
// see webrtc/6366.
TEST_F(ScreenCapturerTest, DISABLED_TwoMagnifierCapturers) {
CreateMagnifierCapturer();
std::unique_ptr<ScreenCapturer> capturer2 = std::move(capturer_);
CreateMagnifierCapturer();
TestCaptureUpdatedRegion({capturer_.get(), capturer2.get()});
}
#endif // defined(WEBRTC_WIN)
} // namespace webrtc
<|endoftext|> |
<commit_before>#include <iostream>
#include <string>
#include <fstream>
#include <cstdint>
using namespace std;
template <typename T>
struct Node {
Node *left;
Node *right;
T data;
};
template <typename T>
class BinaryTree
{
private:
Node<T>* root;
int CountElements = 0;
public:
BinaryTree();
~BinaryTree();
BinaryTree(const std::initializer_list<T>&);
unsigned int count() const;
void insert_node(const T&x);
Node<T> *find_node(const T&, Node<T>*)const;
Node<T>*root_();
void deleteNode(Node<T>* temp);
void writing(const std::string& filename)const;
void output(std::ostream& ost, const Node<T>* temp);
friend std::ostream& operator<< <> (std::ostream&, const BinaryTree<T>&);
};
template <typename T>
BinaryTree<T>::BinaryTree()
{
root = nullptr;
}
template<typename T>
Node<T>* BinaryTree<T>::root_()
{
return root;
}
template <typename T>
BinaryTree<T>::~BinaryTree()
{
deleteNode(root);
}
template<typename T>
void BinaryTree<T>::insert_node(const T&x)
{
if (find_node(x, root_())) return;
Node<T>* MyTree = new Node<T>;
MyTree->data = x;
MyTree->left = MyTree->right = 0;
Node<T>* buff = root;
Node<T>* temp = root;
while (temp)
{
buff = temp;
if (x < temp->data)
temp = temp->left;
else
temp = temp->right;
}
if (!buff)
root = MyTree;
else
{
if (x < buff->data)
buff->left = MyTree;
else
buff->right = MyTree;
}
++CountElements;
}
template<typename T>
Node<T>* BinaryTree<T>::find_node(const T& value, Node<T>* temp) const
{
if (temp == 0 || value == temp->data)
return temp;
if (value > temp->data)
return find_node(value, temp->right);
else
return find_node(value, temp->left);
}
template<typename T>
void BinaryTree<T>::deleteNode(Node<T>* temp)
{
if (!temp)
{
throw "error";
}
if (temp->left)
{
deleteNode(temp->left);
temp->left = nullptr;
}
if (temp->right)
{
deleteNode(temp->right);
temp->right = nullptr;
}
delete temp;
}
template<typename T>
void BinaryTree<T>::output(std::ostream& ost, const Node<T>* temp)
{
if (temp == nullptr)
{
throw "error";
return;
}
else
{
ost << temp->data << " ";
output(ost, temp->left);
output(ost, temp->right);
}
}
template<typename T>
void BinaryTree<T>::writing(const std::string& filename)const
{
ofstream file_1(filename);
file_1 << CountElements << "\t";
output(file_1, root);
file_1.close();
}
template <typename T>
std::ostream& show(std::ostream& ost, const Node<T>* node, unsigned int level)
{
if (!node)
return ost;
show(ost, node->right, level + 1);
for (unsigned int i = 0; i < level; i++)
ost << "\t";
ost << node->data << std::endl;
show(ost, node->left, level + 1);
return ost;
}
template <typename T>
std::ostream& operator<<(std::ostream& ost, const BinaryTree<T>& bst)
{
if (!bst.root)
throw "error";
show(ost, bst.root, 0);
return ost;
}
<commit_msg>Update BinaryTree.hpp<commit_after>#include <iostream>
#include <string>
#include <fstream>
#include <cstdint>
using namespace std;
+template<typename T>
+class BinaryTree;
+
+template<typename T>
+std::ostream& operator<<(ostream& ost, BinaryTree<T>& temp);
template <typename T>
struct Node {
Node *left;
Node *right;
T data;
};
template <typename T>
class BinaryTree
{
private:
Node<T>* root;
int CountElements = 0;
public:
BinaryTree();
~BinaryTree();
BinaryTree(const std::initializer_list<T>&);
unsigned int count() const;
void insert_node(const T&x);
Node<T> *find_node(const T&, Node<T>*)const;
Node<T>*root_();
void deleteNode(Node<T>* temp);
void writing(const std::string& filename)const;
void output(std::ostream& ost, const Node<T>* temp);
friend std::ostream& operator<< <> (std::ostream&, const BinaryTree<T>&);
};
template <typename T>
BinaryTree<T>::BinaryTree()
{
root = nullptr;
}
template<typename T>
Node<T>* BinaryTree<T>::root_()
{
return root;
}
template <typename T>
BinaryTree<T>::~BinaryTree()
{
deleteNode(root);
}
template<typename T>
void BinaryTree<T>::insert_node(const T&x)
{
if (find_node(x, root_())) return;
Node<T>* MyTree = new Node<T>;
MyTree->data = x;
MyTree->left = MyTree->right = 0;
Node<T>* buff = root;
Node<T>* temp = root;
while (temp)
{
buff = temp;
if (x < temp->data)
temp = temp->left;
else
temp = temp->right;
}
if (!buff)
root = MyTree;
else
{
if (x < buff->data)
buff->left = MyTree;
else
buff->right = MyTree;
}
++CountElements;
}
template<typename T>
Node<T>* BinaryTree<T>::find_node(const T& value, Node<T>* temp) const
{
if (temp == 0 || value == temp->data)
return temp;
if (value > temp->data)
return find_node(value, temp->right);
else
return find_node(value, temp->left);
}
template<typename T>
void BinaryTree<T>::deleteNode(Node<T>* temp)
{
if (!temp)
{
throw "error";
}
if (temp->left)
{
deleteNode(temp->left);
temp->left = nullptr;
}
if (temp->right)
{
deleteNode(temp->right);
temp->right = nullptr;
}
delete temp;
}
template<typename T>
void BinaryTree<T>::output(std::ostream& ost, const Node<T>* temp)
{
if (temp == nullptr)
{
throw "error";
return;
}
else
{
ost << temp->data << " ";
output(ost, temp->left);
output(ost, temp->right);
}
}
template<typename T>
void BinaryTree<T>::writing(const std::string& filename)const
{
ofstream file_1(filename);
file_1 << CountElements << "\t";
output(file_1, root);
file_1.close();
}
template <typename T>
std::ostream& show(std::ostream& ost, const Node<T>* node, unsigned int level)
{
if (!node)
return ost;
show(ost, node->right, level + 1);
for (unsigned int i = 0; i < level; i++)
ost << "\t";
ost << node->data << std::endl;
show(ost, node->left, level + 1);
return ost;
}
template <typename T>
std::ostream& operator<<(std::ostream& ost, const BinaryTree<T>& bst)
{
if (!bst.root)
throw "error";
show(ost, bst.root, 0);
return ost;
}
<|endoftext|> |
<commit_before>///////////////////////////////////////////////////////////////////////////////
//
// Copyright (C) 2014 Tavendo GmbH
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
///////////////////////////////////////////////////////////////////////////////
#ifndef AUTOBAHN_TCP_CLIENT_H
#define AUTOBAHN_TCP_CLIENT_H
#include <autobahn/autobahn.hpp>
#include <boost/asio.hpp>
#include <boost/version.hpp>
#include <iostream>
#include <memory>
#include <string>
#include <tuple>
namespace autobahn {
/**
* @brief a class that wraps intialization of a raw tcp socket and WAMP client session utilizing it
*/
class wamp_tcp_client {
typedef autobahn::wamp_session<boost::asio::ip::tcp::socket, boost::asio::ip::tcp::socket> wamp_tcp_session_t;
public:
wamp_tcp_client(std::shared_ptr<boost::asio::io_service> pIo,
const boost::asio::ip::tcp::endpoint &Endpoint,
const std::string &Realm,
bool Debug = false) :
m_realm(Realm),
m_rawsocket_endpoint(Endpoint),
m_pIo(pIo),
m_debug(Debug) {
init();
}
wamp_tcp_client(std::shared_ptr<boost::asio::io_service> pIo,
const std::string &IpAddress,
uint16_t Port,
const std::string &Realm,
bool Debug = false) :
m_realm(Realm),
m_rawsocket_endpoint(boost::asio::ip::address::from_string(IpAddress), Port),
m_pIo(pIo),
m_debug(Debug) {
init();
}
/**
* @brief initialize members, creating shared pointers for the socket, and session
*/
void init() {
m_pSession.reset();
m_pSocket.reset();
m_connected = boost::promise<bool>();
m_pSocket = std::make_shared<boost::asio::ip::tcp::socket>(*m_pIo);
m_pSession = std::make_shared<wamp_tcp_session_t>(*m_pIo, *m_pSocket, *m_pSocket, m_debug);
}
/**
* @brief launches the session asyncronously, returns a future containing an error code (0 means success)
*/
boost::future<bool> launch() {
m_pSocket->async_connect(m_rawsocket_endpoint, [&](boost::system::error_code ec) {
if (!ec) {
std::cerr << "connected to server" << std::endl;
m_startFuture = m_pSession->start().then([&](boost::future<bool> started) {
std::cerr << "session started" << std::endl;
m_joinFuture = m_pSession->join(m_realm).then([&](boost::future<uint64_t> connected) {
std::cerr << "connected to realm" << connected.get() << std::endl;
m_connected.set_value(true);
});
});
} else {
std::cerr << "connect failed: " << ec.message() << std::endl;
m_connected.set_value(false);
}
});
return m_connected.get_future();
}
~wamp_tcp_client() {
}
/**
* This operator is used to pass through calls to the WAMP session. i.e *(pClient)->call(...)
*/
std::shared_ptr<wamp_tcp_session_t> &operator->() {
return m_pSession;
}
private:
boost::future<void> m_stopFuture;
boost::future<void> m_startFuture;
boost::future<void> m_joinFuture;
boost::promise<bool> m_connected;
std::shared_ptr<wamp_tcp_session_t> m_pSession; //<need to be sure this is destructed before m_pSocket
std::shared_ptr<boost::asio::ip::tcp::socket> m_pSocket;
std::string m_realm;
boost::asio::ip::tcp::endpoint m_rawsocket_endpoint;
std::shared_ptr<boost::asio::io_service> m_pIo; ///<hold a reference so that we can clean up when the last user goes out of scope
bool m_debug;
};
} //namespace autobahn
#endif //AUTOBAHN_TCP_CLIENT_H
<commit_msg>typo cleanup<commit_after>///////////////////////////////////////////////////////////////////////////////
//
// Copyright (C) 2014 Tavendo GmbH
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
///////////////////////////////////////////////////////////////////////////////
#ifndef AUTOBAHN_TCP_CLIENT_H
#define AUTOBAHN_TCP_CLIENT_H
#include <autobahn/autobahn.hpp>
#include <boost/asio.hpp>
#include <boost/version.hpp>
#include <iostream>
#include <memory>
#include <string>
#include <tuple>
namespace autobahn {
/**
* @brief a class that wraps initialization of a raw tcp socket and WAMP client session utilizing it
*/
class wamp_tcp_client {
typedef autobahn::wamp_session<boost::asio::ip::tcp::socket, boost::asio::ip::tcp::socket> wamp_tcp_session_t;
public:
wamp_tcp_client(std::shared_ptr<boost::asio::io_service> pIo,
const boost::asio::ip::tcp::endpoint &Endpoint,
const std::string &Realm,
bool Debug = false) :
m_realm(Realm),
m_rawsocket_endpoint(Endpoint),
m_pIo(pIo),
m_debug(Debug) {
init();
}
wamp_tcp_client(std::shared_ptr<boost::asio::io_service> pIo,
const std::string &IpAddress,
uint16_t Port,
const std::string &Realm,
bool Debug = false) :
m_realm(Realm),
m_rawsocket_endpoint(boost::asio::ip::address::from_string(IpAddress), Port),
m_pIo(pIo),
m_debug(Debug) {
init();
}
/**
* @brief initialize members, creating shared pointers for the socket, and session
*/
void init() {
m_pSession.reset();
m_pSocket.reset();
m_connected = boost::promise<bool>();
m_pSocket = std::make_shared<boost::asio::ip::tcp::socket>(*m_pIo);
m_pSession = std::make_shared<wamp_tcp_session_t>(*m_pIo, *m_pSocket, *m_pSocket, m_debug);
}
/**
* @brief launches the session asynchronously, returns a future containing an error code (0 means success)
*/
boost::future<bool> launch() {
m_pSocket->async_connect(m_rawsocket_endpoint, [&](boost::system::error_code ec) {
if (!ec) {
m_startFuture = m_pSession->start().then([&](boost::future<bool> started) {
m_joinFuture = m_pSession->join(m_realm).then([&](boost::future<uint64_t> connected) {
m_connected.set_value(true);
});
});
} else {
std::cerr << "connect failed: " << ec.message() << std::endl;
m_connected.set_value(false);
}
});
return m_connected.get_future();
}
~wamp_tcp_client() {
}
/**
* This operator is used to pass through calls to the WAMP session. i.e *(pClient)->call(...)
*/
std::shared_ptr<wamp_tcp_session_t> &operator->() {
return m_pSession;
}
private:
boost::future<void> m_startFuture; ///<holds the future of the start() operation
boost::future<void> m_joinFuture; ///<holds the future of the join() operation
boost::promise<bool> m_connected; ///<holds the future state of the success of launch
std::shared_ptr<wamp_tcp_session_t> m_pSession; //<need to be sure this is destructed before m_pSocket
std::shared_ptr<boost::asio::ip::tcp::socket> m_pSocket;
std::string m_realm;
boost::asio::ip::tcp::endpoint m_rawsocket_endpoint;
std::shared_ptr<boost::asio::io_service> m_pIo; ///<hold a reference so that we can clean up when the last user goes out of scope
bool m_debug;
};
} //namespace autobahn
#endif //AUTOBAHN_TCP_CLIENT_H
<|endoftext|> |
<commit_before>#include <iostream>
#include <string>
#include <fstream>
#include <cstdint>
using namespace std;
template <typename T>
struct Node {
Node *left;
Node *right;
T data;
};
template <typename T>
class BinaryTree
{
private:
Node<T>*root();
int CountElements = 0;
public:
BinaryTree();
~BinaryTree();
BinaryTree(const std::initializer_list<T>&);
void _deleteElements(Node<T>*);
Node<T>* root_;
unsigned int count() const;
void insert_node(const T&x);
Node<T> *find_node(const T&, Node<T>*)const;
void deleteNode(Node<T>* temp);
void writing(const std::string& filename)const;
friend std::ostream& output(std::ostream& ost, const Node<T>* temp);
friend std::ostream& operator<<<>(std::ostream&, const BinaryTree<T>&);
};
template <typename T>
BinaryTree<T>::BinaryTree()
{
root = nullptr;
}
template<typename T>
Node<T>* BinaryTree<T>::root_()
{
return root;
}
template <typename T>
BinaryTree<T>::~BinaryTree()
{
deleteNode(root);
}
template<typename T>
void BinaryTree<T>::insert_node(const T&x)
{
if (find_node(x, root_())) return;
Node<T>* MyTree = new Node<T>;
MyTree->data = x;
MyTree->left = MyTree->right = 0;
Node<T>* buff = root;
Node<T>* temp = root;
while (temp)
{
buff = temp;
if (x < temp->data)
temp = temp->left;
else
temp = temp->right;
}
if (!buff)
root = MyTree;
else
{
if (x < buff->data)
buff->left = MyTree;
else
buff->right = MyTree;
}
++CountElements;
}
template<typename T>
Node<T>* BinaryTree<T>::find_node(const T& value, Node<T>* temp) const
{
if (temp == 0 || value == temp->data)
return temp;
if (value > temp->data)
return find_node(value, temp->right);
else
return find_node(value, temp->left);
}
template<typename T>
void BinaryTree<T>::deleteNode(Node<T>* temp)
{
if (!temp)
{
throw "error";
}
if (temp->left)
{
deleteNode(temp->left);
temp->left = nullptr;
}
if (temp->right)
{
deleteNode(temp->right);
temp->right = nullptr;
}
delete temp;
}
template<typename T>
std::ostream& show(std::ostream& ost, const Node<T>* temp)
{
if (temp == nullptr)
{
throw "error";
}
else
{
ost << temp->data << " ";
output(ost, temp->left);
output(ost, temp->right);
}
}
template<typename T>
void BinaryTree<T>::writing(const std::string& filename)const
{
ofstream file_1(filename);
file_1 << CountElements << "\t";
output(file_1, root);
file_1.close();
}
template <typename T>
std::ostream& show(std::ostream& ost, const Node<T>* node, unsigned int level)
{
if (!node)
return ost;
show(ost, node->right, level + 1);
for (unsigned int i = 0; i < level; i++)
ost << "\t";
ost << node->data << std::endl;
show(ost, node->left, level + 1);
return ost;
}
template <typename T>
std::ostream& operator<<(std::ostream& ost, const BinaryTree<T>& temp)
{
if (!temp.root)
throw "error";
show(ost, temp.root, 0);
return ost;
}
<commit_msg>Update BinaryTree.hpp<commit_after>#include <iostream>
#include <string>
#include <fstream>
#include <cstdint>
using namespace std;
template <typename T>
struct Node {
Node *left;
Node *right;
T data;
};
template <typename T>
class BinaryTree
{
private:
Node<T>*root;
int CountElements = 0;
public:
BinaryTree();
~BinaryTree();
BinaryTree(const std::initializer_list<T>&);
void _deleteElements(Node<T>*);
Node<T>* root_;
unsigned int count() const;
void insert_node(const T&x);
Node<T> *find_node(const T&, Node<T>*)const;
void deleteNode(Node<T>* temp);
void writing(const std::string& filename)const;
friend std::ostream& output(std::ostream& ost, const Node<T>* temp);
friend std::ostream& operator<<<>(std::ostream&, const BinaryTree<T>&);
};
template <typename T>
BinaryTree<T>::BinaryTree()
{
root = nullptr;
}
template<typename T>
Node<T>* BinaryTree<T>::root_()
{
return root;
}
template <typename T>
BinaryTree<T>::~BinaryTree()
{
deleteNode(root);
}
template<typename T>
void BinaryTree<T>::insert_node(const T&x)
{
if (find_node(x, root_())) return;
Node<T>* MyTree = new Node<T>;
MyTree->data = x;
MyTree->left = MyTree->right = 0;
Node<T>* buff = root;
Node<T>* temp = root;
while (temp)
{
buff = temp;
if (x < temp->data)
temp = temp->left;
else
temp = temp->right;
}
if (!buff)
root = MyTree;
else
{
if (x < buff->data)
buff->left = MyTree;
else
buff->right = MyTree;
}
++CountElements;
}
template<typename T>
Node<T>* BinaryTree<T>::find_node(const T& value, Node<T>* temp) const
{
if (temp == 0 || value == temp->data)
return temp;
if (value > temp->data)
return find_node(value, temp->right);
else
return find_node(value, temp->left);
}
template<typename T>
void BinaryTree<T>::deleteNode(Node<T>* temp)
{
if (!temp)
{
throw "error";
}
if (temp->left)
{
deleteNode(temp->left);
temp->left = nullptr;
}
if (temp->right)
{
deleteNode(temp->right);
temp->right = nullptr;
}
delete temp;
}
template<typename T>
std::ostream& show(std::ostream& ost, const Node<T>* temp)
{
if (temp == nullptr)
{
throw "error";
}
else
{
ost << temp->data << " ";
output(ost, temp->left);
output(ost, temp->right);
}
}
template<typename T>
void BinaryTree<T>::writing(const std::string& filename)const
{
ofstream file_1(filename);
file_1 << CountElements << "\t";
output(file_1, root);
file_1.close();
}
template <typename T>
std::ostream& show(std::ostream& ost, const Node<T>* node, unsigned int level)
{
if (!node)
return ost;
show(ost, node->right, level + 1);
for (unsigned int i = 0; i < level; i++)
ost << "\t";
ost << node->data << std::endl;
show(ost, node->left, level + 1);
return ost;
}
template <typename T>
std::ostream& operator<<(std::ostream& ost, const BinaryTree<T>& temp)
{
if (!temp.root)
throw "error";
show(ost, temp.root, 0);
return ost;
}
<|endoftext|> |
<commit_before>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/files/file_path.h"
#include "base/files/scoped_temp_dir.h"
#include "base/run_loop.h"
#include "chrome/app/chrome_command_ids.h"
#include "chrome/browser/extensions/extension_browsertest.h"
#include "chrome/browser/extensions/extension_prefs.h"
#include "chrome/browser/extensions/extension_service.h"
#include "chrome/browser/extensions/updater/extension_updater.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/browser/ui/global_error/global_error.h"
#include "chrome/browser/ui/global_error/global_error_service.h"
#include "chrome/browser/ui/global_error/global_error_service_factory.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/extensions/extension.h"
#include "content/test/net/url_request_prepackaged_interceptor.h"
#include "net/url_request/url_fetcher.h"
using extensions::Extension;
class ExtensionDisabledGlobalErrorTest : public ExtensionBrowserTest {
protected:
virtual void SetUpCommandLine(CommandLine* command_line) OVERRIDE {
ExtensionBrowserTest::SetUpCommandLine(command_line);
command_line->AppendSwitchASCII(switches::kAppsGalleryUpdateURL,
"http://localhost/autoupdate/updates.xml");
}
virtual void SetUpOnMainThread() OVERRIDE {
EXPECT_TRUE(scoped_temp_dir_.CreateUniqueTempDir());
service_ = browser()->profile()->GetExtensionService();
base::FilePath pem_path = test_data_dir_.
AppendASCII("permissions_increase").AppendASCII("permissions.pem");
path_v1_ = PackExtensionWithOptions(
test_data_dir_.AppendASCII("permissions_increase").AppendASCII("v1"),
scoped_temp_dir_.path().AppendASCII("permissions1.crx"),
pem_path,
base::FilePath());
path_v2_ = PackExtensionWithOptions(
test_data_dir_.AppendASCII("permissions_increase").AppendASCII("v2"),
scoped_temp_dir_.path().AppendASCII("permissions2.crx"),
pem_path,
base::FilePath());
path_v3_ = PackExtensionWithOptions(
test_data_dir_.AppendASCII("permissions_increase").AppendASCII("v3"),
scoped_temp_dir_.path().AppendASCII("permissions3.crx"),
pem_path,
base::FilePath());
}
// Returns the ExtensionDisabledGlobalError, if present.
// Caution: currently only supports one error at a time.
GlobalError* GetExtensionDisabledGlobalError() {
return GlobalErrorServiceFactory::GetForProfile(browser()->profile())->
GetGlobalErrorByMenuItemCommandID(IDC_EXTENSION_DISABLED_FIRST);
}
// Install the initial version, which should happen just fine.
const Extension* InstallIncreasingPermissionExtensionV1() {
size_t size_before = service_->extensions()->size();
const Extension* extension = InstallExtension(path_v1_, 1);
if (!extension)
return NULL;
if (service_->extensions()->size() != size_before + 1)
return NULL;
return extension;
}
// Upgrade to a version that wants more permissions. We should disable the
// extension and prompt the user to reenable.
const Extension* UpdateIncreasingPermissionExtension(
const Extension* extension,
const base::FilePath& crx_path,
int expected_change) {
size_t size_before = service_->extensions()->size();
if (UpdateExtension(extension->id(), crx_path, expected_change))
return NULL;
base::RunLoop().RunUntilIdle();
EXPECT_EQ(size_before + expected_change, service_->extensions()->size());
if (service_->disabled_extensions()->size() != 1u)
return NULL;
return *service_->disabled_extensions()->begin();
}
// Helper function to install an extension and upgrade it to a version
// requiring additional permissions. Returns the new disabled Extension.
const Extension* InstallAndUpdateIncreasingPermissionsExtension() {
const Extension* extension = InstallIncreasingPermissionExtensionV1();
extension = UpdateIncreasingPermissionExtension(extension, path_v2_, -1);
return extension;
}
ExtensionService* service_;
base::ScopedTempDir scoped_temp_dir_;
base::FilePath path_v1_;
base::FilePath path_v2_;
base::FilePath path_v3_;
};
// Tests the process of updating an extension to one that requires higher
// permissions, and accepting the permissions.
IN_PROC_BROWSER_TEST_F(ExtensionDisabledGlobalErrorTest, AcceptPermissions) {
const Extension* extension = InstallAndUpdateIncreasingPermissionsExtension();
ASSERT_TRUE(extension);
ASSERT_TRUE(GetExtensionDisabledGlobalError());
const size_t size_before = service_->extensions()->size();
service_->GrantPermissionsAndEnableExtension(extension);
EXPECT_EQ(size_before + 1, service_->extensions()->size());
EXPECT_EQ(0u, service_->disabled_extensions()->size());
ASSERT_FALSE(GetExtensionDisabledGlobalError());
}
// Tests uninstalling an extension that was disabled due to higher permissions.
IN_PROC_BROWSER_TEST_F(ExtensionDisabledGlobalErrorTest, Uninstall) {
const Extension* extension = InstallAndUpdateIncreasingPermissionsExtension();
ASSERT_TRUE(extension);
ASSERT_TRUE(GetExtensionDisabledGlobalError());
const size_t size_before = service_->extensions()->size();
UninstallExtension(extension->id());
EXPECT_EQ(size_before, service_->extensions()->size());
EXPECT_EQ(0u, service_->disabled_extensions()->size());
ASSERT_FALSE(GetExtensionDisabledGlobalError());
}
// Tests that no error appears if the user disabled the extension.
IN_PROC_BROWSER_TEST_F(ExtensionDisabledGlobalErrorTest, UserDisabled) {
const Extension* extension = InstallIncreasingPermissionExtensionV1();
DisableExtension(extension->id());
extension = UpdateIncreasingPermissionExtension(extension, path_v2_, 0);
ASSERT_FALSE(GetExtensionDisabledGlobalError());
}
// Test that no error appears if the disable reason is unknown
// (but probably was by the user).
IN_PROC_BROWSER_TEST_F(ExtensionDisabledGlobalErrorTest,
UnknownReasonSamePermissions) {
const Extension* extension = InstallIncreasingPermissionExtensionV1();
DisableExtension(extension->id());
// Clear disable reason to simulate legacy disables.
service_->extension_prefs()->ClearDisableReasons(extension->id());
// Upgrade to version 2. Infer from version 1 having the same permissions
// granted by the user that it was disabled by the user.
extension = UpdateIncreasingPermissionExtension(extension, path_v2_, 0);
ASSERT_TRUE(extension);
ASSERT_FALSE(GetExtensionDisabledGlobalError());
}
// Test that an error appears if the disable reason is unknown
// (but probably was for increased permissions).
// Disabled due to http://crbug.com/246431
IN_PROC_BROWSER_TEST_F(ExtensionDisabledGlobalErrorTest,
DISABLED_UnknownReasonHigherPermissions) {
const Extension* extension = InstallAndUpdateIncreasingPermissionsExtension();
// Clear disable reason to simulate legacy disables.
service_->extension_prefs()->ClearDisableReasons(extension->id());
// We now have version 2 but only accepted permissions for version 1.
GlobalError* error = GetExtensionDisabledGlobalError();
ASSERT_TRUE(error);
// Also, remove the upgrade error for version 2.
GlobalErrorServiceFactory::GetForProfile(browser()->profile())->
RemoveGlobalError(error);
delete error;
// Upgrade to version 3, with even higher permissions. Infer from
// version 2 having higher-than-granted permissions that it was disabled
// for permissions increase.
extension = UpdateIncreasingPermissionExtension(extension, path_v3_, 0);
ASSERT_TRUE(extension);
ASSERT_TRUE(GetExtensionDisabledGlobalError());
}
// Test that an error appears if the extension gets disabled because a
// version with higher permissions was installed by sync.
IN_PROC_BROWSER_TEST_F(ExtensionDisabledGlobalErrorTest,
HigherPermissionsFromSync) {
// Get data for extension v2 (disabled) into sync.
const Extension* extension = InstallAndUpdateIncreasingPermissionsExtension();
std::string extension_id = extension->id();
// service_->GrantPermissionsAndEnableExtension(extension, false);
extensions::ExtensionSyncData sync_data =
service_->GetExtensionSyncData(*extension);
UninstallExtension(extension_id);
extension = NULL;
// Install extension v1.
InstallIncreasingPermissionExtensionV1();
// Note: This interceptor gets requests on the IO thread.
content::URLLocalHostRequestPrepackagedInterceptor interceptor;
net::URLFetcher::SetEnableInterceptionForTests(true);
interceptor.SetResponseIgnoreQuery(
GURL("http://localhost/autoupdate/updates.xml"),
test_data_dir_.AppendASCII("permissions_increase")
.AppendASCII("updates.xml"));
interceptor.SetResponseIgnoreQuery(
GURL("http://localhost/autoupdate/v2.crx"),
scoped_temp_dir_.path().AppendASCII("permissions2.crx"));
extensions::ExtensionUpdater::CheckParams params;
params.check_blacklist = false;
service_->updater()->set_default_check_params(params);
// Sync is replacing an older version, so it pends.
EXPECT_FALSE(service_->ProcessExtensionSyncData(sync_data));
WaitForExtensionInstall();
base::RunLoop().RunUntilIdle();
extension = service_->GetExtensionById(extension_id, true);
ASSERT_TRUE(extension);
EXPECT_EQ("2", extension->VersionString());
EXPECT_EQ(1u, service_->disabled_extensions()->size());
EXPECT_EQ(Extension::DISABLE_PERMISSIONS_INCREASE,
service_->extension_prefs()->GetDisableReasons(extension_id));
EXPECT_TRUE(GetExtensionDisabledGlobalError());
}
<commit_msg>Another speculative fix for ExtensionDisabledGlobalErrorTests. Flush blocking tasks.<commit_after>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/files/file_path.h"
#include "base/files/scoped_temp_dir.h"
#include "base/threading/sequenced_worker_pool.h"
#include "chrome/app/chrome_command_ids.h"
#include "chrome/browser/extensions/extension_browsertest.h"
#include "chrome/browser/extensions/extension_prefs.h"
#include "chrome/browser/extensions/extension_service.h"
#include "chrome/browser/extensions/updater/extension_updater.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/browser/ui/global_error/global_error.h"
#include "chrome/browser/ui/global_error/global_error_service.h"
#include "chrome/browser/ui/global_error/global_error_service_factory.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/extensions/extension.h"
#include "content/test/net/url_request_prepackaged_interceptor.h"
#include "net/url_request/url_fetcher.h"
using extensions::Extension;
class ExtensionDisabledGlobalErrorTest : public ExtensionBrowserTest {
protected:
virtual void SetUpCommandLine(CommandLine* command_line) OVERRIDE {
ExtensionBrowserTest::SetUpCommandLine(command_line);
command_line->AppendSwitchASCII(switches::kAppsGalleryUpdateURL,
"http://localhost/autoupdate/updates.xml");
}
virtual void SetUpOnMainThread() OVERRIDE {
EXPECT_TRUE(scoped_temp_dir_.CreateUniqueTempDir());
service_ = browser()->profile()->GetExtensionService();
base::FilePath pem_path = test_data_dir_.
AppendASCII("permissions_increase").AppendASCII("permissions.pem");
path_v1_ = PackExtensionWithOptions(
test_data_dir_.AppendASCII("permissions_increase").AppendASCII("v1"),
scoped_temp_dir_.path().AppendASCII("permissions1.crx"),
pem_path,
base::FilePath());
path_v2_ = PackExtensionWithOptions(
test_data_dir_.AppendASCII("permissions_increase").AppendASCII("v2"),
scoped_temp_dir_.path().AppendASCII("permissions2.crx"),
pem_path,
base::FilePath());
path_v3_ = PackExtensionWithOptions(
test_data_dir_.AppendASCII("permissions_increase").AppendASCII("v3"),
scoped_temp_dir_.path().AppendASCII("permissions3.crx"),
pem_path,
base::FilePath());
}
// Returns the ExtensionDisabledGlobalError, if present.
// Caution: currently only supports one error at a time.
GlobalError* GetExtensionDisabledGlobalError() {
return GlobalErrorServiceFactory::GetForProfile(browser()->profile())->
GetGlobalErrorByMenuItemCommandID(IDC_EXTENSION_DISABLED_FIRST);
}
// Install the initial version, which should happen just fine.
const Extension* InstallIncreasingPermissionExtensionV1() {
size_t size_before = service_->extensions()->size();
const Extension* extension = InstallExtension(path_v1_, 1);
if (!extension)
return NULL;
if (service_->extensions()->size() != size_before + 1)
return NULL;
return extension;
}
// Upgrade to a version that wants more permissions. We should disable the
// extension and prompt the user to reenable.
const Extension* UpdateIncreasingPermissionExtension(
const Extension* extension,
const base::FilePath& crx_path,
int expected_change) {
size_t size_before = service_->extensions()->size();
if (UpdateExtension(extension->id(), crx_path, expected_change))
return NULL;
BrowserThread::GetBlockingPool()->FlushForTesting();
EXPECT_EQ(size_before + expected_change, service_->extensions()->size());
if (service_->disabled_extensions()->size() != 1u)
return NULL;
return *service_->disabled_extensions()->begin();
}
// Helper function to install an extension and upgrade it to a version
// requiring additional permissions. Returns the new disabled Extension.
const Extension* InstallAndUpdateIncreasingPermissionsExtension() {
const Extension* extension = InstallIncreasingPermissionExtensionV1();
extension = UpdateIncreasingPermissionExtension(extension, path_v2_, -1);
return extension;
}
ExtensionService* service_;
base::ScopedTempDir scoped_temp_dir_;
base::FilePath path_v1_;
base::FilePath path_v2_;
base::FilePath path_v3_;
};
// Tests the process of updating an extension to one that requires higher
// permissions, and accepting the permissions.
IN_PROC_BROWSER_TEST_F(ExtensionDisabledGlobalErrorTest, AcceptPermissions) {
const Extension* extension = InstallAndUpdateIncreasingPermissionsExtension();
ASSERT_TRUE(extension);
ASSERT_TRUE(GetExtensionDisabledGlobalError());
const size_t size_before = service_->extensions()->size();
service_->GrantPermissionsAndEnableExtension(extension);
EXPECT_EQ(size_before + 1, service_->extensions()->size());
EXPECT_EQ(0u, service_->disabled_extensions()->size());
ASSERT_FALSE(GetExtensionDisabledGlobalError());
}
// Tests uninstalling an extension that was disabled due to higher permissions.
IN_PROC_BROWSER_TEST_F(ExtensionDisabledGlobalErrorTest, Uninstall) {
const Extension* extension = InstallAndUpdateIncreasingPermissionsExtension();
ASSERT_TRUE(extension);
ASSERT_TRUE(GetExtensionDisabledGlobalError());
const size_t size_before = service_->extensions()->size();
UninstallExtension(extension->id());
EXPECT_EQ(size_before, service_->extensions()->size());
EXPECT_EQ(0u, service_->disabled_extensions()->size());
ASSERT_FALSE(GetExtensionDisabledGlobalError());
}
// Tests that no error appears if the user disabled the extension.
IN_PROC_BROWSER_TEST_F(ExtensionDisabledGlobalErrorTest, UserDisabled) {
const Extension* extension = InstallIncreasingPermissionExtensionV1();
DisableExtension(extension->id());
extension = UpdateIncreasingPermissionExtension(extension, path_v2_, 0);
ASSERT_FALSE(GetExtensionDisabledGlobalError());
}
// Test that no error appears if the disable reason is unknown
// (but probably was by the user).
IN_PROC_BROWSER_TEST_F(ExtensionDisabledGlobalErrorTest,
UnknownReasonSamePermissions) {
const Extension* extension = InstallIncreasingPermissionExtensionV1();
DisableExtension(extension->id());
// Clear disable reason to simulate legacy disables.
service_->extension_prefs()->ClearDisableReasons(extension->id());
// Upgrade to version 2. Infer from version 1 having the same permissions
// granted by the user that it was disabled by the user.
extension = UpdateIncreasingPermissionExtension(extension, path_v2_, 0);
ASSERT_TRUE(extension);
ASSERT_FALSE(GetExtensionDisabledGlobalError());
}
// Test that an error appears if the disable reason is unknown
// (but probably was for increased permissions).
// Disabled due to http://crbug.com/246431
IN_PROC_BROWSER_TEST_F(ExtensionDisabledGlobalErrorTest,
DISABLED_UnknownReasonHigherPermissions) {
const Extension* extension = InstallAndUpdateIncreasingPermissionsExtension();
// Clear disable reason to simulate legacy disables.
service_->extension_prefs()->ClearDisableReasons(extension->id());
// We now have version 2 but only accepted permissions for version 1.
GlobalError* error = GetExtensionDisabledGlobalError();
ASSERT_TRUE(error);
// Also, remove the upgrade error for version 2.
GlobalErrorServiceFactory::GetForProfile(browser()->profile())->
RemoveGlobalError(error);
delete error;
// Upgrade to version 3, with even higher permissions. Infer from
// version 2 having higher-than-granted permissions that it was disabled
// for permissions increase.
extension = UpdateIncreasingPermissionExtension(extension, path_v3_, 0);
ASSERT_TRUE(extension);
ASSERT_TRUE(GetExtensionDisabledGlobalError());
}
// Test that an error appears if the extension gets disabled because a
// version with higher permissions was installed by sync.
IN_PROC_BROWSER_TEST_F(ExtensionDisabledGlobalErrorTest,
HigherPermissionsFromSync) {
// Get data for extension v2 (disabled) into sync.
const Extension* extension = InstallAndUpdateIncreasingPermissionsExtension();
std::string extension_id = extension->id();
// service_->GrantPermissionsAndEnableExtension(extension, false);
extensions::ExtensionSyncData sync_data =
service_->GetExtensionSyncData(*extension);
UninstallExtension(extension_id);
extension = NULL;
// Install extension v1.
InstallIncreasingPermissionExtensionV1();
// Note: This interceptor gets requests on the IO thread.
content::URLLocalHostRequestPrepackagedInterceptor interceptor;
net::URLFetcher::SetEnableInterceptionForTests(true);
interceptor.SetResponseIgnoreQuery(
GURL("http://localhost/autoupdate/updates.xml"),
test_data_dir_.AppendASCII("permissions_increase")
.AppendASCII("updates.xml"));
interceptor.SetResponseIgnoreQuery(
GURL("http://localhost/autoupdate/v2.crx"),
scoped_temp_dir_.path().AppendASCII("permissions2.crx"));
extensions::ExtensionUpdater::CheckParams params;
params.check_blacklist = false;
service_->updater()->set_default_check_params(params);
// Sync is replacing an older version, so it pends.
EXPECT_FALSE(service_->ProcessExtensionSyncData(sync_data));
WaitForExtensionInstall();
BrowserThread::GetBlockingPool()->FlushForTesting();
extension = service_->GetExtensionById(extension_id, true);
ASSERT_TRUE(extension);
EXPECT_EQ("2", extension->VersionString());
EXPECT_EQ(1u, service_->disabled_extensions()->size());
EXPECT_EQ(Extension::DISABLE_PERMISSIONS_INCREASE,
service_->extension_prefs()->GetDisableReasons(extension_id));
EXPECT_TRUE(GetExtensionDisabledGlobalError());
}
<|endoftext|> |
<commit_before>#include <iostream>
#include <string>
#include <fstream>
using namespace std;
template<typename T>
struct Node
{
T x;
Node<T> * left;
Node<T> * right;
};
template<typename T>
class Tree
{
private:
Node<T> * root;
public:
Tree()
{
root->x = 0;
root->left = root->right = nullptr;
}
~Tree()
{
deleteNode(root);
}
void deleteNode(Node<T> * node)
{
if (node == NULL) return;
deleteNode(node->left);
deleteNode(node->right);
delete node;
}
T x_() const
{
return root->x;
}
Node<T> * left_() const
{
return root->left;
}
Node<T> * right_() const
{
return root->right;
}
void add(const T newEl)
{
if (root == nullptr)
root->x = newEl;
else
{
Node<T> * El = new Node<T>;
Node<T> * curEl = new Node<T>;
curEl = root;
while (curEl != nullptr)
{
El = curEl;
if (newEl > curEl->x)
curEl = curEl->right;
else
if (newEl < curEl->x)
curEl = curEl->left;
else return;
}
if (newEl > El->x)
{
El->right = new Node<T>;
El->right->x = newEl;
El->right->left = El->right->right = nullptr;
}
else
{
El->left = new Node<T>;
El->left->x = newEl;
El->left->left = El->left->right = nullptr;
}
}
}
Node<T> * search(const T x)
{
Node<T> * curEl = root;
while (curEl != nullptr)
{
if (curEl->x == x)
return curEl;
else
{
if (x > curEl->x)
curEl = curEl->right;
else curEl = curEl->left;
}
}
return nullptr;
}
void fIn(string filename)
{
ifstream fin;
fin.open(filename);
if (!fin.is_open())
cout << "The file isn't find" << endl;
else
{
deleteNode(root);
root = new Node<T>;
root->x = 0;
root->left = root->right = nullptr;
if (fin.eof()) return;
else
{
<commit_msg>Update BinaryTree.hpp<commit_after>#include <iostream>
#include <string>
#include <fstream>
using namespace std;
template<typename T>
struct Node
{
T x;
Node<T> * left;
Node<T> * right;
Node(T const& value) : x{value}, left{nullptr}, right{nullptr} {}
};
template<typename T>
class Tree
{
private:
Node<T> * root;
public:
Tree()
{
root = nullptr;
}
~Tree()
{
deleteNode(root);
}
void deleteNode(Node<T> * node)
{
if (node == NULL) return;
deleteNode(node->left);
deleteNode(node->right);
delete node;
}
T x_() const
{
return root->x;
}
Node<T> * left_() const
{
return root->left;
}
Node<T> * right_() const
{
return root->right;
}
void add(const T newEl)
{
if (root == nullptr)
root = new Node(newEl);
else
{
Node<T> * El = new Node<T>;
Node<T> *& curEl = new Node<T>;
curEl = root;
while (curEl != nullptr)
{
El = curEl;
if (newEl > curEl->x)
curEl = curEl->right;
else
if (newEl < curEl->x)
curEl = curEl->left;
else return;
}
if (newEl > El->x)
{
El->right = new Node<T>;
El->right->x = newEl;
El->right->left = El->right->right = nullptr;
}
else
{
El->left = new Node<T>;
El->left->x = newEl;
El->left->left = El->left->right = nullptr;
}
}
}
Node<T> * search(const T& x)
{
Node<T> * curEl = root;
while (curEl != nullptr)
{
if (curEl->x == x)
break;
else
{
if (x > curEl->x)
curEl = curEl->right;
else curEl = curEl->left;
}
}
return curEl;
}
void fIn(string filename)
{
ifstream fin;
fin.open(filename);
if (!fin.is_open())
cout << "The file isn't find" << endl;
else
{
deleteNode(root);
root = new Node<T>;
root->x = 0;
root->left = root->right = nullptr;
if (fin.eof()) return;
else
{
<|endoftext|> |
<commit_before>/* -*- coding: utf-8; mode: c++; tab-width: 3; indent-tabs-mode: nil -*-
Copyright 2010, 2011, 2012, 2013, 2014
Raffaello D. Di Napoli
This file is part of Application-Building Components (henceforth referred to as ABC).
ABC is free software: you can redistribute it and/or modify it under the terms of the GNU General
Public License as published by the Free Software Foundation, either version 3 of the License, or (at
your option) any later version.
ABC 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 ABC. If not, see
<http://www.gnu.org/licenses/>.
--------------------------------------------------------------------------------------------------*/
#ifndef _ABC_MEMORY_HXX
#define _ABC_MEMORY_HXX
#include <abc/core.hxx>
#ifdef ABC_CXX_PRAGMA_ONCE
#pragma once
#endif
#include <abc/exception.hxx>
#if ABC_HOST_API_POSIX
#include <stdlib.h> // free() malloc() realloc()
#include <memory.h> // memcpy() memmove() memset()
#elif ABC_HOST_API_WIN32 //if ABC_HOST_API_POSIX
// Clean up pollution caused by previous headers.
extern "C" {
// Rtl*Memory*
#undef RtlZeroMemory
WINBASEAPI void WINAPI RtlZeroMemory(void UNALIGNED * pDst, size_t cb);
#undef RtlFillMemory
WINBASEAPI void WINAPI RtlFillMemory(void UNALIGNED * pDst, size_t cb, UCHAR iValue);
#undef RtlFillMemoryUlong
WINBASEAPI void WINAPI RtlFillMemoryUlong(void * pDst, size_t cb, ULONG iValue);
#undef RtlFillMemoryUlonglong
WINBASEAPI void WINAPI RtlFillMemoryUlonglong(void * pDst, size_t cb, ULONGLONG iValue);
#undef RtlCopyMemory
WINBASEAPI void WINAPI RtlCopyMemory(
void UNALIGNED * pDst, void UNALIGNED const * pSrc, size_t cb
);
#undef RtlMoveMemory
WINBASEAPI void WINAPI RtlMoveMemory(
void UNALIGNED * pDst, void UNALIGNED const * pSrc, size_t cb
);
} //extern "C"
#endif //if ABC_HOST_API_POSIX … elif ABC_HOST_API_WIN32
/** TODO: comment or remove.
*/
#if ABC_HOST_GCC
#define _abc_alloca(cb) \
__builtin_alloca((cb))
#elif ABC_HOST_MSC
extern "C" void * ABC_STL_CALLCONV _alloca(size_t cb);
#define _abc_alloca(cb) \
_alloca(cb)
#endif
////////////////////////////////////////////////////////////////////////////////////////////////////
// :: globals - standard new/delete operators
#if ABC_HOST_MSC
#pragma warning(push)
// “'operator': exception specification does not match previous declaration”
#pragma warning(disable: 4986)
#endif
void * ABC_STL_CALLCONV operator new(size_t cb) ABC_STL_NOEXCEPT_FALSE((std::bad_alloc));
void * ABC_STL_CALLCONV operator new[](size_t cb) ABC_STL_NOEXCEPT_FALSE((std::bad_alloc));
void * ABC_STL_CALLCONV operator new(size_t cb, std::nothrow_t const &) ABC_STL_NOEXCEPT_TRUE();
void * ABC_STL_CALLCONV operator new[](size_t cb, std::nothrow_t const &) ABC_STL_NOEXCEPT_TRUE();
void ABC_STL_CALLCONV operator delete(void * p) ABC_STL_NOEXCEPT_TRUE();
void ABC_STL_CALLCONV operator delete[](void * p) ABC_STL_NOEXCEPT_TRUE();
void ABC_STL_CALLCONV operator delete(void * p, std::nothrow_t const &) ABC_STL_NOEXCEPT_TRUE();
void ABC_STL_CALLCONV operator delete[](void * p, std::nothrow_t const &) ABC_STL_NOEXCEPT_TRUE();
#if ABC_HOST_MSC
#pragma warning(pop)
#endif
////////////////////////////////////////////////////////////////////////////////////////////////////
// abc::memory::freeing_deleter
namespace abc {
namespace memory {
// Forward declaration.
template <typename T>
void free(T const * pt);
/** Deleter that deallocates memory using memory::free().
*/
template <typename T>
struct freeing_deleter {
/** Deallocates the specified memory block.
pt
Pointer to the object to delete.
*/
void operator()(T * pt) const {
free(pt);
}
};
// Specialization for arrays.
template <typename T>
struct freeing_deleter<T[]> :
public freeing_deleter<T> {
/** Deallocates the specified array. See also freeing_deleter<T>::operator()().
pt
Pointer to the array to deallocate.
*/
template <typename T2>
void operator()(T2 * pt) const {
freeing_deleter<T>::operator()(pt);
}
};
} //namespace memory
} //namespace abc
////////////////////////////////////////////////////////////////////////////////////////////////////
// abc::memory::conditional_deleter
namespace abc {
namespace memory {
/** Wrapper that invokes a deleter if and only if a set condition is true.
*/
template <typename T, typename TDeleter = std::default_delete<T>>
class conditional_deleter :
public TDeleter {
public:
/** Constructor.
bEnabled
If true, the deleter will delete objects when invoked; if false, it will do nothing.
cd
Source deleter.
*/
conditional_deleter(bool bEnabled) :
TDeleter(),
m_bEnabled(bEnabled) {
}
template <typename T2, typename TDeleter2>
conditional_deleter(conditional_deleter<T2, TDeleter2> const & cd) :
TDeleter(static_cast<TDeleter2 const &>(cd)),
m_bEnabled(cd.enabled()) {
}
/** Deletes the specified object if the condition set in the constructor was true.
pt
Pointer to the object to delete.
*/
void operator()(T * pt) const {
if (m_bEnabled) {
TDeleter::operator()(pt);
}
}
/** Returns true if the deleter is enabled.
return
true if the deleter is enable, or false otherwise.
*/
bool enabled() const {
return m_bEnabled;
}
protected:
bool m_bEnabled;
};
// Specialization for arrays.
template <typename T, typename TDeleter>
class conditional_deleter<T[], TDeleter> :
public conditional_deleter<T, TDeleter> {
public:
/** See conditional_deleter<T>::conditional_deleter().
*/
conditional_deleter(bool bEnabled) :
conditional_deleter<T, TDeleter>(bEnabled) {
}
template <typename T2, typename TDeleter2>
conditional_deleter(conditional_deleter<T2, TDeleter2> const & cd) :
conditional_deleter<T, TDeleter>(cd) {
}
/** Deletes the specified array if the condition set in the constructor was true. See also
conditional_deleter<T, TDeleter>::operator()().
pt
Pointer to the array to delete.
*/
template <typename T2>
void operator()(T2 * pt) const {
if (this->m_bEnabled) {
TDeleter::operator()(pt);
}
}
};
} //namespace memory
} //namespace abc
////////////////////////////////////////////////////////////////////////////////////////////////////
// abc::memory globals - management
namespace abc {
namespace memory {
/** Requests the dynamic allocation of a memory block of the specified number of bytes.
TODO: comment signature.
*/
inline void * _raw_alloc(size_t cb) {
void * p(::malloc(cb));
if (!p) {
ABC_THROW(memory_allocation_error, ());
}
return p;
}
/** Resizes a dynamically allocated memory block.
TODO: comment signature.
*/
inline void * _raw_realloc(void * p, size_t cb) {
p = ::realloc(p, cb);
if (!p) {
ABC_THROW(memory_allocation_error, ());
}
return p;
}
/** Requests the dynamic allocation of a memory block large enough to contain c objects of type T,
plus an additional cbExtra bytes. With specialization that ignores types (void) and allocates the
specified number of bytes.
TODO: comment signature.
*/
template <typename T>
inline std::unique_ptr<T, freeing_deleter<T>> alloc(size_t c = 1, size_t cbExtra = 0) {
return std::unique_ptr<T, freeing_deleter<T>>(
static_cast<T *>(_raw_alloc(sizeof(T) * c + cbExtra))
);
}
template <>
inline std::unique_ptr<void, freeing_deleter<void>> alloc(
size_t cb /*= 1*/, size_t cbExtra /*= 0*/
) {
return std::unique_ptr<void, freeing_deleter<void>>(_raw_alloc(cb + cbExtra));
}
/** Releases a block of dynamically allocated memory.
pt
Pointer to the memory block to be released.
*/
template <typename T>
inline void free(T const * pt) {
::free(const_cast<T *>(pt));
}
/** Changes the size of a block of dynamically allocated memory. Both overloads have a
specialization that ignores pointer types (void), and allocates the specified number of bytes.
TODO: comment signature.
*/
template <typename T>
inline T * realloc(T * pt, size_t c, size_t cbExtra = 0) {
return static_cast<T *>(_raw_realloc(pt, sizeof(T) * c + cbExtra));
}
template <>
inline void * realloc(void * p, size_t cb, size_t cbExtra /*= 0*/) {
return _raw_realloc(p, cb + cbExtra);
}
template <typename T>
inline void realloc(std::unique_ptr<T, freeing_deleter<T>> * ppt, size_t c, size_t cbExtra = 0) {
typedef typename std::unique_ptr<T, freeing_deleter<T>>::element_type TElt;
TElt * pt(static_cast<TElt *>(_raw_realloc(ppt->get(), sizeof(TElt) * c + cbExtra)));
ppt->release();
ppt->reset(pt);
}
template <>
inline void realloc(
std::unique_ptr<void, freeing_deleter<void>> * pp, size_t cb, size_t cbExtra /*= 0*/
) {
void * p(_raw_realloc(pp->get(), cb + cbExtra));
pp->release();
pp->reset(p);
}
} //namespace memory
} //namespace abc
////////////////////////////////////////////////////////////////////////////////////////////////////
// abc::memory globals - manipulation
namespace abc {
namespace memory {
/** Sets to the value 0 every item in an array.
TODO: comment signature.
*/
template <typename T>
inline T * clear(T * ptDst, size_t c = 1) {
return static_cast<T *>(clear<void>(ptDst, sizeof(T) * c));
}
template <>
inline void * clear(void * pDst, size_t cb /*= 1*/) {
#if ABC_HOST_API_POSIX
::memset(pDst, 0, cb);
#elif ABC_HOST_API_WIN32
::RtlZeroMemory(pDst, cb);
#else
#error TODO-PORT: HOST_API
#endif
return pDst;
}
/** Copies memory, by number of items. With specialization that ignores pointer types (void), and
copies the specified number of bytes.
TODO: comment signature.
*/
template <typename T>
inline T * copy(T * ptDst, T const * ptSrc) {
// Optimization: if the copy can be made by mem-reg-mem transfers, avoid calling a function, so
// that the compiler can inline the copy.
switch (sizeof(T)) {
case sizeof(int8_t):
*reinterpret_cast<int8_t *>(ptDst) = *reinterpret_cast<int8_t const *>(ptSrc);
break;
case sizeof(int16_t):
*reinterpret_cast<int16_t *>(ptDst) = *reinterpret_cast<int16_t const *>(ptSrc);
break;
case sizeof(int32_t):
*reinterpret_cast<int32_t *>(ptDst) = *reinterpret_cast<int32_t const *>(ptSrc);
break;
case sizeof(int64_t):
*reinterpret_cast<int64_t *>(ptDst) = *reinterpret_cast<int64_t const *>(ptSrc);
break;
default:
copy<void>(ptDst, ptSrc, sizeof(T));
break;
}
return static_cast<T *>(ptDst);
}
// Nobody should want to use this, but it’s here for consistency.
template <>
inline void * copy(void * pDst, void const * pSrc) {
*reinterpret_cast<int8_t *>(pDst) = *reinterpret_cast<int8_t const *>(pSrc);
return pDst;
}
template <typename T>
inline T * copy(T * ptDst, T const * ptSrc, size_t c) {
return static_cast<T *>(copy<void>(ptDst, ptSrc, sizeof(T) * c));
}
template <>
inline void * copy(void * pDst, void const * pSrc, size_t cb) {
#if ABC_HOST_API_POSIX
::memcpy(pDst, pSrc, cb);
#elif ABC_HOST_API_WIN32
::RtlMoveMemory(pDst, pSrc, cb);
#else
#error TODO-PORT: HOST_API
#endif
return pDst;
}
/** Copies possibly overlapping memory, by number of items. With specialization that ignores pointer
types (void), and copies the specified number of bytes.
TODO: comment signature.
*/
template <typename T>
inline T * move(T * ptDst, T const * ptSrc, size_t c) {
return static_cast<T *>(move<void>(ptDst, ptSrc, sizeof(T) * c));
}
template <>
inline void * move(void * pDst, void const * pSrc, size_t cb) {
#if ABC_HOST_API_POSIX
::memmove(pDst, pSrc, cb);
#elif ABC_HOST_API_WIN32
::RtlMoveMemory(pDst, pSrc, cb);
#else
#error TODO-PORT: HOST_API
#endif
return pDst;
}
/** Copies a value over each item of a static array.
TODO: comment signature.
*/
template <typename T>
inline T * set(T * ptDst, T const & tValue, size_t c) {
switch (sizeof(T)) {
#if ABC_HOST_API_POSIX
case sizeof(int8_t):
::memset(ptDst, tValue, c);
break;
#elif ABC_HOST_API_WIN32
case sizeof(UCHAR):
::RtlFillMemory(ptDst, c, tValue);
break;
#endif
default:
for (T const * ptDstMax(ptDst + c); ptDst < ptDstMax; ++ptDst) {
copy(ptDst, &tValue);
}
break;
}
return ptDst;
}
} //namespace memory
} //namespace abc
////////////////////////////////////////////////////////////////////////////////////////////////////
#endif //ifdef _ABC_MEMORY_HXX
<commit_msg>Refactor abc::memory::alloc() to support std::unique_ptr<T[]><commit_after>/* -*- coding: utf-8; mode: c++; tab-width: 3; indent-tabs-mode: nil -*-
Copyright 2010, 2011, 2012, 2013, 2014
Raffaello D. Di Napoli
This file is part of Application-Building Components (henceforth referred to as ABC).
ABC is free software: you can redistribute it and/or modify it under the terms of the GNU General
Public License as published by the Free Software Foundation, either version 3 of the License, or (at
your option) any later version.
ABC 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 ABC. If not, see
<http://www.gnu.org/licenses/>.
--------------------------------------------------------------------------------------------------*/
#ifndef _ABC_MEMORY_HXX
#define _ABC_MEMORY_HXX
#include <abc/core.hxx>
#ifdef ABC_CXX_PRAGMA_ONCE
#pragma once
#endif
#include <abc/exception.hxx>
#if ABC_HOST_API_POSIX
#include <stdlib.h> // free() malloc() realloc()
#include <memory.h> // memcpy() memmove() memset()
#elif ABC_HOST_API_WIN32 //if ABC_HOST_API_POSIX
// Clean up pollution caused by previous headers.
extern "C" {
// Rtl*Memory*
#undef RtlZeroMemory
WINBASEAPI void WINAPI RtlZeroMemory(void UNALIGNED * pDst, size_t cb);
#undef RtlFillMemory
WINBASEAPI void WINAPI RtlFillMemory(void UNALIGNED * pDst, size_t cb, UCHAR iValue);
#undef RtlFillMemoryUlong
WINBASEAPI void WINAPI RtlFillMemoryUlong(void * pDst, size_t cb, ULONG iValue);
#undef RtlFillMemoryUlonglong
WINBASEAPI void WINAPI RtlFillMemoryUlonglong(void * pDst, size_t cb, ULONGLONG iValue);
#undef RtlCopyMemory
WINBASEAPI void WINAPI RtlCopyMemory(
void UNALIGNED * pDst, void UNALIGNED const * pSrc, size_t cb
);
#undef RtlMoveMemory
WINBASEAPI void WINAPI RtlMoveMemory(
void UNALIGNED * pDst, void UNALIGNED const * pSrc, size_t cb
);
} //extern "C"
#endif //if ABC_HOST_API_POSIX … elif ABC_HOST_API_WIN32
/** TODO: comment or remove.
*/
#if ABC_HOST_GCC
#define _abc_alloca(cb) \
__builtin_alloca((cb))
#elif ABC_HOST_MSC
extern "C" void * ABC_STL_CALLCONV _alloca(size_t cb);
#define _abc_alloca(cb) \
_alloca(cb)
#endif
////////////////////////////////////////////////////////////////////////////////////////////////////
// :: globals - standard new/delete operators
#if ABC_HOST_MSC
#pragma warning(push)
// “'operator': exception specification does not match previous declaration”
#pragma warning(disable: 4986)
#endif
void * ABC_STL_CALLCONV operator new(size_t cb) ABC_STL_NOEXCEPT_FALSE((std::bad_alloc));
void * ABC_STL_CALLCONV operator new[](size_t cb) ABC_STL_NOEXCEPT_FALSE((std::bad_alloc));
void * ABC_STL_CALLCONV operator new(size_t cb, std::nothrow_t const &) ABC_STL_NOEXCEPT_TRUE();
void * ABC_STL_CALLCONV operator new[](size_t cb, std::nothrow_t const &) ABC_STL_NOEXCEPT_TRUE();
void ABC_STL_CALLCONV operator delete(void * p) ABC_STL_NOEXCEPT_TRUE();
void ABC_STL_CALLCONV operator delete[](void * p) ABC_STL_NOEXCEPT_TRUE();
void ABC_STL_CALLCONV operator delete(void * p, std::nothrow_t const &) ABC_STL_NOEXCEPT_TRUE();
void ABC_STL_CALLCONV operator delete[](void * p, std::nothrow_t const &) ABC_STL_NOEXCEPT_TRUE();
#if ABC_HOST_MSC
#pragma warning(pop)
#endif
////////////////////////////////////////////////////////////////////////////////////////////////////
// abc::memory::freeing_deleter
namespace abc {
namespace memory {
// Forward declaration.
template <typename T>
void free(T const * pt);
/** Deleter that deallocates memory using memory::free().
*/
template <typename T>
struct freeing_deleter {
/** Deallocates the specified memory block.
pt
Pointer to the object to delete.
*/
void operator()(T * pt) const {
free(pt);
}
};
// Specialization for arrays.
template <typename T>
struct freeing_deleter<T[]> :
public freeing_deleter<T> {
/** Deallocates the specified array. See also freeing_deleter<T>::operator()().
pt
Pointer to the array to deallocate.
*/
template <typename T2>
void operator()(T2 * pt) const {
freeing_deleter<T>::operator()(pt);
}
};
} //namespace memory
} //namespace abc
////////////////////////////////////////////////////////////////////////////////////////////////////
// abc::memory::conditional_deleter
namespace abc {
namespace memory {
/** Wrapper that invokes a deleter if and only if a set condition is true.
*/
template <typename T, typename TDeleter = std::default_delete<T>>
class conditional_deleter :
public TDeleter {
public:
/** Constructor.
bEnabled
If true, the deleter will delete objects when invoked; if false, it will do nothing.
cd
Source deleter.
*/
conditional_deleter(bool bEnabled) :
TDeleter(),
m_bEnabled(bEnabled) {
}
template <typename T2, typename TDeleter2>
conditional_deleter(conditional_deleter<T2, TDeleter2> const & cd) :
TDeleter(static_cast<TDeleter2 const &>(cd)),
m_bEnabled(cd.enabled()) {
}
/** Deletes the specified object if the condition set in the constructor was true.
pt
Pointer to the object to delete.
*/
void operator()(T * pt) const {
if (m_bEnabled) {
TDeleter::operator()(pt);
}
}
/** Returns true if the deleter is enabled.
return
true if the deleter is enable, or false otherwise.
*/
bool enabled() const {
return m_bEnabled;
}
protected:
bool m_bEnabled;
};
// Specialization for arrays.
template <typename T, typename TDeleter>
class conditional_deleter<T[], TDeleter> :
public conditional_deleter<T, TDeleter> {
public:
/** See conditional_deleter<T>::conditional_deleter().
*/
conditional_deleter(bool bEnabled) :
conditional_deleter<T, TDeleter>(bEnabled) {
}
template <typename T2, typename TDeleter2>
conditional_deleter(conditional_deleter<T2, TDeleter2> const & cd) :
conditional_deleter<T, TDeleter>(cd) {
}
/** Deletes the specified array if the condition set in the constructor was true. See also
conditional_deleter<T, TDeleter>::operator()().
pt
Pointer to the array to delete.
*/
template <typename T2>
void operator()(T2 * pt) const {
if (this->m_bEnabled) {
TDeleter::operator()(pt);
}
}
};
} //namespace memory
} //namespace abc
////////////////////////////////////////////////////////////////////////////////////////////////////
// abc::memory globals - management
namespace abc {
namespace memory {
/** Requests the dynamic allocation of a memory block of the specified number of bytes.
TODO: comment signature.
*/
inline void * _raw_alloc(size_t cb) {
void * p(::malloc(cb));
if (!p) {
ABC_THROW(memory_allocation_error, ());
}
return p;
}
/** Resizes a dynamically allocated memory block.
TODO: comment signature.
*/
inline void * _raw_realloc(void * p, size_t cb) {
p = ::realloc(p, cb);
if (!p) {
ABC_THROW(memory_allocation_error, ());
}
return p;
}
/** Requests the dynamic allocation of a memory block large enough to contain c objects of type T,
plus an additional cbExtra bytes. With specialization that ignores types (void) and allocates the
specified number of bytes.
TODO: comment signature.
*/
template <typename T>
inline std::unique_ptr<T, freeing_deleter<T>> alloc(size_t c = 1, size_t cbExtra = 0) {
typedef typename std::unique_ptr<T, freeing_deleter<T>>::element_type TElt;
return std::unique_ptr<T, freeing_deleter<T>>(
static_cast<TElt *>(_raw_alloc(sizeof(TElt) * c + cbExtra))
);
}
template <>
inline std::unique_ptr<void, freeing_deleter<void>> alloc(
size_t cb /*= 1*/, size_t cbExtra /*= 0*/
) {
return std::unique_ptr<void, freeing_deleter<void>>(_raw_alloc(cb + cbExtra));
}
/** Releases a block of dynamically allocated memory.
pt
Pointer to the memory block to be released.
*/
template <typename T>
inline void free(T const * pt) {
::free(const_cast<T *>(pt));
}
/** Changes the size of a block of dynamically allocated memory. Both overloads have a
specialization that ignores pointer types (void), and allocates the specified number of bytes.
TODO: comment signature.
*/
template <typename T>
inline T * realloc(T * pt, size_t c, size_t cbExtra = 0) {
return static_cast<T *>(_raw_realloc(pt, sizeof(T) * c + cbExtra));
}
template <>
inline void * realloc(void * p, size_t cb, size_t cbExtra /*= 0*/) {
return _raw_realloc(p, cb + cbExtra);
}
template <typename T>
inline void realloc(std::unique_ptr<T, freeing_deleter<T>> * ppt, size_t c, size_t cbExtra = 0) {
typedef typename std::unique_ptr<T, freeing_deleter<T>>::element_type TElt;
TElt * pt(static_cast<TElt *>(_raw_realloc(ppt->get(), sizeof(TElt) * c + cbExtra)));
ppt->release();
ppt->reset(pt);
}
template <>
inline void realloc(
std::unique_ptr<void, freeing_deleter<void>> * pp, size_t cb, size_t cbExtra /*= 0*/
) {
void * p(_raw_realloc(pp->get(), cb + cbExtra));
pp->release();
pp->reset(p);
}
} //namespace memory
} //namespace abc
////////////////////////////////////////////////////////////////////////////////////////////////////
// abc::memory globals - manipulation
namespace abc {
namespace memory {
/** Sets to the value 0 every item in an array.
TODO: comment signature.
*/
template <typename T>
inline T * clear(T * ptDst, size_t c = 1) {
return static_cast<T *>(clear<void>(ptDst, sizeof(T) * c));
}
template <>
inline void * clear(void * pDst, size_t cb /*= 1*/) {
#if ABC_HOST_API_POSIX
::memset(pDst, 0, cb);
#elif ABC_HOST_API_WIN32
::RtlZeroMemory(pDst, cb);
#else
#error TODO-PORT: HOST_API
#endif
return pDst;
}
/** Copies memory, by number of items. With specialization that ignores pointer types (void), and
copies the specified number of bytes.
TODO: comment signature.
*/
template <typename T>
inline T * copy(T * ptDst, T const * ptSrc) {
// Optimization: if the copy can be made by mem-reg-mem transfers, avoid calling a function, so
// that the compiler can inline the copy.
switch (sizeof(T)) {
case sizeof(int8_t):
*reinterpret_cast<int8_t *>(ptDst) = *reinterpret_cast<int8_t const *>(ptSrc);
break;
case sizeof(int16_t):
*reinterpret_cast<int16_t *>(ptDst) = *reinterpret_cast<int16_t const *>(ptSrc);
break;
case sizeof(int32_t):
*reinterpret_cast<int32_t *>(ptDst) = *reinterpret_cast<int32_t const *>(ptSrc);
break;
case sizeof(int64_t):
*reinterpret_cast<int64_t *>(ptDst) = *reinterpret_cast<int64_t const *>(ptSrc);
break;
default:
copy<void>(ptDst, ptSrc, sizeof(T));
break;
}
return static_cast<T *>(ptDst);
}
// Nobody should want to use this, but it’s here for consistency.
template <>
inline void * copy(void * pDst, void const * pSrc) {
*reinterpret_cast<int8_t *>(pDst) = *reinterpret_cast<int8_t const *>(pSrc);
return pDst;
}
template <typename T>
inline T * copy(T * ptDst, T const * ptSrc, size_t c) {
return static_cast<T *>(copy<void>(ptDst, ptSrc, sizeof(T) * c));
}
template <>
inline void * copy(void * pDst, void const * pSrc, size_t cb) {
#if ABC_HOST_API_POSIX
::memcpy(pDst, pSrc, cb);
#elif ABC_HOST_API_WIN32
::RtlMoveMemory(pDst, pSrc, cb);
#else
#error TODO-PORT: HOST_API
#endif
return pDst;
}
/** Copies possibly overlapping memory, by number of items. With specialization that ignores pointer
types (void), and copies the specified number of bytes.
TODO: comment signature.
*/
template <typename T>
inline T * move(T * ptDst, T const * ptSrc, size_t c) {
return static_cast<T *>(move<void>(ptDst, ptSrc, sizeof(T) * c));
}
template <>
inline void * move(void * pDst, void const * pSrc, size_t cb) {
#if ABC_HOST_API_POSIX
::memmove(pDst, pSrc, cb);
#elif ABC_HOST_API_WIN32
::RtlMoveMemory(pDst, pSrc, cb);
#else
#error TODO-PORT: HOST_API
#endif
return pDst;
}
/** Copies a value over each item of a static array.
TODO: comment signature.
*/
template <typename T>
inline T * set(T * ptDst, T const & tValue, size_t c) {
switch (sizeof(T)) {
#if ABC_HOST_API_POSIX
case sizeof(int8_t):
::memset(ptDst, tValue, c);
break;
#elif ABC_HOST_API_WIN32
case sizeof(UCHAR):
::RtlFillMemory(ptDst, c, tValue);
break;
#endif
default:
for (T const * ptDstMax(ptDst + c); ptDst < ptDstMax; ++ptDst) {
copy(ptDst, &tValue);
}
break;
}
return ptDst;
}
} //namespace memory
} //namespace abc
////////////////////////////////////////////////////////////////////////////////////////////////////
#endif //ifdef _ABC_MEMORY_HXX
<|endoftext|> |
<commit_before>#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
struct option
{
option (
string optionShortName,
string optionLongName,
string optionDescription)
: fOptionShortName (optionShortName),
fOptionLongName (optionLongName),
fOptionDescription (optionDescription)
{}
string operator() () const
{ return fOptionDescription; }
void print (ostream& os) const
{
os <<
"fOptionShortName:" << fOptionShortName << endl <<
"fOptionLongName:" << fOptionLongName << endl <<
"fOptionDescription:" << fOptionDescription << endl;
}
private:
string fOptionShortName;
string fOptionLongName;
string fOptionDescription;
};
ostream& operator<< (ostream& os, const option& elt)
{
elt.print (os);
return os;
}
int main()
{
vector<option> vec {
option ("1short", "1long", "descr1"),
option ("2short", "1long", "descr2")
};
int counter = 0;
cout <<
"The contents of 'vec' is:" << endl << endl;
for (option i : vec)
{
cout <<
"Element " << counter << ":" << endl <<
i << endl;
counter++;
}
cout << "Which element should be printed? ";
int n;
cin >> n;
cout << endl;
if (n < vec.size ())
cout <<
"Element " << n << " constains:" << endl <<
endl <<
vec [n] << endl;
else
cout <<
"Sorry, only elements from 0 to " << vec.size () - 1 << " exist" << endl;
}
<commit_msg>c++ functors tests 2<commit_after>#include <iostream>
#include <vector>
#include <algorithm>
#include <iomanip> // setw, set::precision, ...
#include <getopt.h>
using namespace std;
struct myOption
{
myOption (
string optionShortName,
string optionLongName,
string optionDescription)
: fOptionShortName (optionShortName),
fOptionLongName (optionLongName),
fOptionDescription (optionDescription)
{
fOptionSelected = 0;
}
string operator() () const
{ return fOptionDescription; }
void print (ostream& os) const
{
const int fieldWidth = 19;
os <<
setw(fieldWidth) <<
"fOptionShortName" << " : " << fOptionShortName <<
endl <<
setw(fieldWidth) <<
"fOptionLongName" << " : " << fOptionLongName <<
endl <<
setw(fieldWidth) <<
"fOptionDescription" << " : " << fOptionDescription <<
endl <<
setw(fieldWidth) <<
"fOptionSelected" << " : " << fOptionSelected <<
endl;
}
private:
string fOptionShortName;
string fOptionLongName;
string fOptionDescription;
int fOptionSelected;
};
ostream& operator<< (ostream& os, const myOption& elt)
{
elt.print (os);
return os;
}
//_______________________________________________________________________________
void analyzeOptions (
int argc,
char* argv[])
{
}
int main (int argc, char *argv[])
{
vector<myOption> vec {
myOption ("1short", "1long", "descr1"),
myOption ("2short", "1long", "descr2")
};
int counter = 0;
cout <<
"The contents of 'vec' is:" <<
endl << endl;
for (myOption i : vec)
{
cout <<
"Element " << counter << ":" <<
endl <<
i <<
endl;
counter++;
}
/*
struct option
{
const char *name;
// has_arg can't be an enum because some compilers complain about
// type mismatches in all the code that assumes it is an int.
int has_arg;
int *flag;
int val;
};
*/
vector<struct option> myLongOptions {
option ("1short", no_argument, &vec [0].fOptionSelected, 1),
option ("1long", no_argument, &vec [0].fOptionSelected, 1),
option ("2short", required_argument, &vec [1].fOptionSelected, 1),
option ("2long", required_argument, &vec [1].fOptionSelected, 1),
option (0, 0, 0, 0) // option trailer
};
/*
cout << "Which element should be printed? ";
int n;
cin >> n;
cout << endl;
if (n < vec.size ())
cout <<
"Element " << n << " constains:" <<
endl <<
endl <<
vec [n] <<
endl;
else
cout <<
"Sorry, only elements from 0 to " << vec.size () - 1 << " exist" <<
endl;
*/
analyzeOptions (
argc, argv);
}
<|endoftext|> |
<commit_before>/*
This file is part of the ORK library.
Full copyright and license terms can be found in the LICENSE.txt file.
*/
#pragma once
#include "ork/ork.hpp"
#if ORK_USE_GLM
# include "glm/fwd.hpp"
#endif // ORK_USE_GLM
namespace ork {
/*
From color.hpp
*/
enum class color_space;
#if ORK_USE_GLM
using color4 = glm::vec4;
#endif // ORK_USE_GLM
/*
From command_line.hpp
*/
#if ORK_USE_BOOST
class command_handler;
#endif // ORK_USE_BOOST
/*
From distribution.hpp
*/
#if ORK_USE_BOOST
class command_handler;
class random;
#endif // ORK_USE_BOOST
template<typename T>
class triangle_distribution;
template<typename T>
class trapezoid_distribution;
/*
From file_utils.hpp
*/
template<class functor, class iter_t, class sort>
struct directory_executer;
template<class functor, class search_type = flat_search, class sort_type = unsorted>
struct iterate_directory;
template<class T>
struct directory_range;
/*
From filter.hpp
*/
#if ORK_USE_BOOST
template<unsigned C>
struct ring;
template<unsigned order, unsigned inverse_alpha>
struct butterworth;
#endif // ORK_USE_BOOST
/*
From geometry.hpp
*/
enum class angle;
template<angle>
struct circle;
namespace GLM {
class bounding_box;
class interval;
struct segment;
class chain;
namespace MC {
struct view;
struct rotated_view;
} // namespace MC
} // namespace GLM
/*
From glm.hpp
*/
namespace GLM {
struct dunit3;
template<typename T>
struct default_epsilon_factor;
} // namespace GLM
/*
From html.hpp
*/
enum class align;
enum class border;
namespace html {
struct exportable;
struct pair;
struct string;
struct heading;
struct page_break;
struct padding;
struct image;
struct style;
struct image_style;
struct div_style;
struct table_style;
struct line_style;
struct style_set;
struct header;
struct line;
struct label;
struct table_element;
struct table;
struct div;
struct body;
struct document;
} // namespace html
} // namespace ork
<commit_msg>Added memory to fwd<commit_after>/*
This file is part of the ORK library.
Full copyright and license terms can be found in the LICENSE.txt file.
*/
#pragma once
#include "ork/ork.hpp"
#if ORK_USE_GLM
# include "glm/fwd.hpp"
#endif // ORK_USE_GLM
namespace ork {
/*
From color.hpp
*/
enum class color_space;
#if ORK_USE_GLM
using color4 = glm::vec4;
#endif // ORK_USE_GLM
/*
From command_line.hpp
*/
#if ORK_USE_BOOST
class command_handler;
#endif // ORK_USE_BOOST
/*
From distribution.hpp
*/
#if ORK_USE_BOOST
class command_handler;
class random;
#endif // ORK_USE_BOOST
template<typename T>
class triangle_distribution;
template<typename T>
class trapezoid_distribution;
/*
From file_utils.hpp
*/
template<class functor, class iter_t, class sort>
struct directory_executer;
template<class functor, class search_type, class sort_type>
struct iterate_directory;
template<class T>
struct directory_range;
/*
From filter.hpp
*/
#if ORK_USE_BOOST
template<unsigned C>
struct ring;
template<unsigned order, unsigned inverse_alpha>
struct butterworth;
#endif // ORK_USE_BOOST
/*
From geometry.hpp
*/
enum class angle;
template<angle>
struct circle;
namespace GLM {
class bounding_box;
class interval;
struct segment;
class chain;
namespace MC {
struct view;
struct rotated_view;
} // namespace MC
} // namespace GLM
/*
From glm.hpp
*/
namespace GLM {
struct dunit3;
template<typename T>
struct default_epsilon_factor;
} // namespace GLM
/*
From html.hpp
*/
enum class align;
enum class border;
namespace html {
struct exportable;
struct pair;
struct string;
struct heading;
struct page_break;
struct padding;
struct image;
struct style;
struct image_style;
struct div_style;
struct table_style;
struct line_style;
struct style_set;
struct header;
struct line;
struct label;
struct table_element;
struct table;
struct div;
struct body;
struct document;
} // namespace html
/*
From memory.hpp
*/
template<typename T>
struct default_deleter;
template<typename T>
struct singleton_deleter;
template<class T, class D>
class value_ptr;
template<typename T, typename D>
class shared_ptr;
} // namespace ork
<|endoftext|> |
<commit_before>//=======================================================================
// Copyright (c) 2015 Baptiste Wicht
// Distributed under the terms of the MIT License.
// (See accompanying file LICENSE or copy at
// http://opensource.org/licenses/MIT)
//=======================================================================
#ifndef CPM_COMPAT_HPP
#define CPM_COMPAT_HPP
#ifdef __clang__
#define cpp14_constexpr constexpr
#else
#define cpp14_constexpr
#endif
//Fix an assertion failed in Intel C++ Compiler
#ifdef __INTEL_COMPILER
#define intel_decltype_auto auto
#else
#define intel_decltype_auto decltype(auto)
#endif
#endif //CPM_COMPAT_HPP
<commit_msg>Safety for macros<commit_after>//=======================================================================
// Copyright (c) 2015 Baptiste Wicht
// Distributed under the terms of the MIT License.
// (See accompanying file LICENSE or copy at
// http://opensource.org/licenses/MIT)
//=======================================================================
#ifndef CPM_COMPAT_HPP
#define CPM_COMPAT_HPP
#ifndef cpp14_constexpr
#ifdef __clang__
#define cpp14_constexpr constexpr
#else
#define cpp14_constexpr
#endif
#endif
//Fix an assertion failed in Intel C++ Compiler
#ifndef intel_decltype_auto
#ifdef __INTEL_COMPILER
#define intel_decltype_auto auto
#else
#define intel_decltype_auto decltype(auto)
#endif
#endif
#endif //CPM_COMPAT_HPP
<|endoftext|> |
<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
* This file is part of the LibreOffice project.
*
* Based on LLVM/Clang.
*
* This file is distributed under the University of Illinois Open Source
* License. See LICENSE.TXT for details.
*
*/
#ifndef PLUGIN_H
#define PLUGIN_H
#include <config_clang.h>
#include <clang/AST/ASTContext.h>
#include <clang/AST/RecursiveASTVisitor.h>
#include <clang/Basic/FileManager.h>
#include <clang/Basic/SourceManager.h>
#include <clang/Frontend/CompilerInstance.h>
#include <clang/Lex/Preprocessor.h>
#include <unordered_map>
#if __clang_major__ < 3 || __clang_major__ == 3 && __clang_minor__ < 2
#include <clang/Rewrite/Rewriter.h>
#else
#include <clang/Rewrite/Core/Rewriter.h>
#endif
using namespace clang;
using namespace llvm;
using namespace std;
namespace loplugin
{
class PluginHandler;
/**
Base class for plugins.
If you want to create a non-rewriter action, inherit from this class. Remember to also
use Plugin::Registration.
*/
class Plugin
{
public:
struct InstantiationData
{
const char* name;
PluginHandler& handler;
CompilerInstance& compiler;
Rewriter* rewriter;
};
explicit Plugin( const InstantiationData& data );
virtual ~Plugin();
virtual void run() = 0;
template< typename T > class Registration;
enum { isPPCallback = false };
// Returns location right after the end of the token that starts at the given location.
SourceLocation locationAfterToken( SourceLocation location );
protected:
DiagnosticBuilder report( DiagnosticsEngine::Level level, StringRef message, SourceLocation loc = SourceLocation()) const;
bool ignoreLocation( SourceLocation loc );
bool ignoreLocation( const Decl* decl );
bool ignoreLocation( const Stmt* stmt );
CompilerInstance& compiler;
PluginHandler& handler;
/**
Returns the parent of the given AST node. Clang's internal AST representation doesn't provide this information,
it can only provide children, but getting the parent is often useful for inspecting a part of the AST.
*/
const Stmt* parentStmt( const Stmt* stmt );
Stmt* parentStmt( Stmt* stmt );
private:
static void registerPlugin( Plugin* (*create)( const InstantiationData& ), const char* optionName, bool isPPCallback, bool byDefault );
template< typename T > static Plugin* createHelper( const InstantiationData& data );
enum { isRewriter = false };
const char* name;
static unordered_map< const Stmt*, const Stmt* > parents;
static void buildParents( CompilerInstance& compiler );
};
/**
Base class for rewriter plugins.
Remember to also use Plugin::Registration.
*/
class RewritePlugin
: public Plugin
{
public:
explicit RewritePlugin( const InstantiationData& data );
protected:
enum RewriteOption
{
// This enum allows passing just 'RemoveLineIfEmpty' to functions below.
// If the resulting line would be completely empty, it'll be removed.
RemoveLineIfEmpty = 1 << 0,
// Use this to remove the declaration/statement as a whole, i.e. all whitespace before the statement
// and the trailing semicolor (is not part of the AST element range itself).
// The trailing semicolon must be present.
RemoveWholeStatement = 1 << 1,
// Removes also all whitespace preceding and following the expression (completely, so that
// the preceding and following tokens would be right next to each other, follow with insertText( " " )
// if this is not wanted). Despite the name, indentation whitespace is not removed.
RemoveAllWhitespace = 1 << 2
};
struct RewriteOptions
: public Rewriter::RewriteOptions
{
RewriteOptions();
RewriteOptions( RewriteOption option );
const int flags;
};
// syntactic sugar to be able to write 'RemoveLineIfEmpty | RemoveWholeStatement'
friend RewriteOption operator|( RewriteOption option1, RewriteOption option2 );
// These following insert/remove/replaceText functions map to functions
// in clang::Rewriter, with these differences:
// - they (more intuitively) return false on failure rather than true
// - they report a warning when the change cannot be done
// - There are more options for easier removal of surroundings of a statement/expression.
bool insertText( SourceLocation Loc, StringRef Str,
bool InsertAfter = true, bool indentNewLines = false );
bool insertTextAfter( SourceLocation Loc, StringRef Str );
bool insertTextAfterToken( SourceLocation Loc, StringRef Str );
bool insertTextBefore( SourceLocation Loc, StringRef Str );
bool removeText( SourceLocation Start, unsigned Length, RewriteOptions opts = RewriteOptions());
bool removeText( CharSourceRange range, RewriteOptions opts = RewriteOptions());
bool removeText( SourceRange range, RewriteOptions opts = RewriteOptions());
bool replaceText( SourceLocation Start, unsigned OrigLength, StringRef NewStr );
bool replaceText( SourceRange range, StringRef NewStr );
bool replaceText( SourceRange range, SourceRange replacementRange );
Rewriter* rewriter;
private:
template< typename T > friend class Plugin::Registration;
enum { isRewriter = true };
bool reportEditFailure( SourceLocation loc );
bool adjustRangeForOptions( CharSourceRange* range, RewriteOptions options );
};
/**
Plugin registration helper.
If you create a new helper class, create also an instance of this class to automatically register it.
The passed argument is name of the plugin, used for explicitly invoking rewriter plugins
(it is ignored for non-rewriter plugins).
@code
static Plugin::Registration< NameOfClass > X( "nameofclass" );
@endcode
*/
template< typename T >
class Plugin::Registration
{
public:
Registration( const char* optionName, bool byDefault = !T::isRewriter );
};
class RegistrationCreate
{
public:
template< typename T, bool > static T* create( const Plugin::InstantiationData& data );
};
/////
inline
Plugin::~Plugin()
{
}
inline
bool Plugin::ignoreLocation( const Decl* decl )
{
return ignoreLocation( decl->getLocation());
}
inline
bool Plugin::ignoreLocation( const Stmt* stmt )
{
return ignoreLocation( stmt->getLocStart());
}
template< typename T >
Plugin* Plugin::createHelper( const InstantiationData& data )
{
return new T( data );
}
template< typename T >
inline
Plugin::Registration< T >::Registration( const char* optionName, bool byDefault )
{
registerPlugin( &T::template createHelper< T >, optionName, T::isPPCallback, byDefault );
}
inline
RewritePlugin::RewriteOptions::RewriteOptions()
: flags( 0 )
{
}
inline
RewritePlugin::RewriteOptions::RewriteOptions( RewriteOption option )
: flags( option )
{
// Note that 'flags' stores also RemoveLineIfEmpty, it must be kept in sync with the base class.
if( flags & RewritePlugin::RemoveLineIfEmpty )
this->RemoveLineIfEmpty = true;
}
inline
RewritePlugin::RewriteOption operator|( RewritePlugin::RewriteOption option1, RewritePlugin::RewriteOption option2 )
{
return static_cast< RewritePlugin::RewriteOption >( int( option1 ) | int( option2 ));
}
} // namespace
#endif // COMPILEPLUGIN_H
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<commit_msg>Handle ImplicitCastExpr w/ invalid loc from Objective C code<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
* This file is part of the LibreOffice project.
*
* Based on LLVM/Clang.
*
* This file is distributed under the University of Illinois Open Source
* License. See LICENSE.TXT for details.
*
*/
#ifndef PLUGIN_H
#define PLUGIN_H
#include <config_clang.h>
#include <clang/AST/ASTContext.h>
#include <clang/AST/RecursiveASTVisitor.h>
#include <clang/Basic/FileManager.h>
#include <clang/Basic/SourceManager.h>
#include <clang/Frontend/CompilerInstance.h>
#include <clang/Lex/Preprocessor.h>
#include <unordered_map>
#if __clang_major__ < 3 || __clang_major__ == 3 && __clang_minor__ < 2
#include <clang/Rewrite/Rewriter.h>
#else
#include <clang/Rewrite/Core/Rewriter.h>
#endif
using namespace clang;
using namespace llvm;
using namespace std;
namespace loplugin
{
class PluginHandler;
/**
Base class for plugins.
If you want to create a non-rewriter action, inherit from this class. Remember to also
use Plugin::Registration.
*/
class Plugin
{
public:
struct InstantiationData
{
const char* name;
PluginHandler& handler;
CompilerInstance& compiler;
Rewriter* rewriter;
};
explicit Plugin( const InstantiationData& data );
virtual ~Plugin();
virtual void run() = 0;
template< typename T > class Registration;
enum { isPPCallback = false };
// Returns location right after the end of the token that starts at the given location.
SourceLocation locationAfterToken( SourceLocation location );
protected:
DiagnosticBuilder report( DiagnosticsEngine::Level level, StringRef message, SourceLocation loc = SourceLocation()) const;
bool ignoreLocation( SourceLocation loc );
bool ignoreLocation( const Decl* decl );
bool ignoreLocation( const Stmt* stmt );
CompilerInstance& compiler;
PluginHandler& handler;
/**
Returns the parent of the given AST node. Clang's internal AST representation doesn't provide this information,
it can only provide children, but getting the parent is often useful for inspecting a part of the AST.
*/
const Stmt* parentStmt( const Stmt* stmt );
Stmt* parentStmt( Stmt* stmt );
private:
static void registerPlugin( Plugin* (*create)( const InstantiationData& ), const char* optionName, bool isPPCallback, bool byDefault );
template< typename T > static Plugin* createHelper( const InstantiationData& data );
enum { isRewriter = false };
const char* name;
static unordered_map< const Stmt*, const Stmt* > parents;
static void buildParents( CompilerInstance& compiler );
};
/**
Base class for rewriter plugins.
Remember to also use Plugin::Registration.
*/
class RewritePlugin
: public Plugin
{
public:
explicit RewritePlugin( const InstantiationData& data );
protected:
enum RewriteOption
{
// This enum allows passing just 'RemoveLineIfEmpty' to functions below.
// If the resulting line would be completely empty, it'll be removed.
RemoveLineIfEmpty = 1 << 0,
// Use this to remove the declaration/statement as a whole, i.e. all whitespace before the statement
// and the trailing semicolor (is not part of the AST element range itself).
// The trailing semicolon must be present.
RemoveWholeStatement = 1 << 1,
// Removes also all whitespace preceding and following the expression (completely, so that
// the preceding and following tokens would be right next to each other, follow with insertText( " " )
// if this is not wanted). Despite the name, indentation whitespace is not removed.
RemoveAllWhitespace = 1 << 2
};
struct RewriteOptions
: public Rewriter::RewriteOptions
{
RewriteOptions();
RewriteOptions( RewriteOption option );
const int flags;
};
// syntactic sugar to be able to write 'RemoveLineIfEmpty | RemoveWholeStatement'
friend RewriteOption operator|( RewriteOption option1, RewriteOption option2 );
// These following insert/remove/replaceText functions map to functions
// in clang::Rewriter, with these differences:
// - they (more intuitively) return false on failure rather than true
// - they report a warning when the change cannot be done
// - There are more options for easier removal of surroundings of a statement/expression.
bool insertText( SourceLocation Loc, StringRef Str,
bool InsertAfter = true, bool indentNewLines = false );
bool insertTextAfter( SourceLocation Loc, StringRef Str );
bool insertTextAfterToken( SourceLocation Loc, StringRef Str );
bool insertTextBefore( SourceLocation Loc, StringRef Str );
bool removeText( SourceLocation Start, unsigned Length, RewriteOptions opts = RewriteOptions());
bool removeText( CharSourceRange range, RewriteOptions opts = RewriteOptions());
bool removeText( SourceRange range, RewriteOptions opts = RewriteOptions());
bool replaceText( SourceLocation Start, unsigned OrigLength, StringRef NewStr );
bool replaceText( SourceRange range, StringRef NewStr );
bool replaceText( SourceRange range, SourceRange replacementRange );
Rewriter* rewriter;
private:
template< typename T > friend class Plugin::Registration;
enum { isRewriter = true };
bool reportEditFailure( SourceLocation loc );
bool adjustRangeForOptions( CharSourceRange* range, RewriteOptions options );
};
/**
Plugin registration helper.
If you create a new helper class, create also an instance of this class to automatically register it.
The passed argument is name of the plugin, used for explicitly invoking rewriter plugins
(it is ignored for non-rewriter plugins).
@code
static Plugin::Registration< NameOfClass > X( "nameofclass" );
@endcode
*/
template< typename T >
class Plugin::Registration
{
public:
Registration( const char* optionName, bool byDefault = !T::isRewriter );
};
class RegistrationCreate
{
public:
template< typename T, bool > static T* create( const Plugin::InstantiationData& data );
};
/////
inline
Plugin::~Plugin()
{
}
inline
bool Plugin::ignoreLocation( const Decl* decl )
{
return ignoreLocation( decl->getLocation());
}
inline
bool Plugin::ignoreLocation( const Stmt* stmt )
{
// Invalid location can happen at least for ImplicitCastExpr of
// ImplicitParam 'self' in Objective C method declarations:
return stmt->getLocStart().isValid() && ignoreLocation( stmt->getLocStart());
}
template< typename T >
Plugin* Plugin::createHelper( const InstantiationData& data )
{
return new T( data );
}
template< typename T >
inline
Plugin::Registration< T >::Registration( const char* optionName, bool byDefault )
{
registerPlugin( &T::template createHelper< T >, optionName, T::isPPCallback, byDefault );
}
inline
RewritePlugin::RewriteOptions::RewriteOptions()
: flags( 0 )
{
}
inline
RewritePlugin::RewriteOptions::RewriteOptions( RewriteOption option )
: flags( option )
{
// Note that 'flags' stores also RemoveLineIfEmpty, it must be kept in sync with the base class.
if( flags & RewritePlugin::RemoveLineIfEmpty )
this->RemoveLineIfEmpty = true;
}
inline
RewritePlugin::RewriteOption operator|( RewritePlugin::RewriteOption option1, RewritePlugin::RewriteOption option2 )
{
return static_cast< RewritePlugin::RewriteOption >( int( option1 ) | int( option2 ));
}
} // namespace
#endif // COMPILEPLUGIN_H
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<|endoftext|> |
<commit_before>/*
* Copyright (c) 2016 dresden elektronik ingenieurtechnik gmbh.
* All rights reserved.
*
* The software in this package is published under the terms of the BSD
* style license a copy of which has been included with this distribution in
* the LICENSE.txt file.
*
*/
#include <QApplication>
#include <QDesktopServices>
#include <QFile>
#include <QDir>
#include <QString>
#include <QProcess>
#include "de_web_plugin.h"
#include "de_web_plugin_private.h"
#define FW_IDLE_TIMEOUT (10 * 1000)
#define FW_WAIT_UPDATE_READY (2) //s
#define FW_IDLE_TIMEOUT_LONG (240 * 1000)
#define FW_WAIT_USER_TIMEOUT (120 * 1000)
/*! Inits the firmware update manager.
*/
void DeRestPluginPrivate::initFirmwareUpdate()
{
fwProcess = 0;
fwUpdateState = FW_Idle;
Q_ASSERT(apsCtrl);
apsCtrl->setParameter(deCONZ::ParamFirmwareUpdateActive, deCONZ::FirmwareUpdateIdle);
fwUpdateStartedByUser = false;
fwUpdateTimer = new QTimer(this);
fwUpdateTimer->setSingleShot(true);
connect(fwUpdateTimer, SIGNAL(timeout()),
this, SLOT(firmwareUpdateTimerFired()));
fwUpdateTimer->start(5000);
}
/*! Starts the actual firmware update process.
*/
void DeRestPluginPrivate::updateFirmware()
{
if (gwFirmwareNeedUpdate)
{
gwFirmwareNeedUpdate = false;
}
Q_ASSERT(apsCtrl);
if (apsCtrl->getParameter(deCONZ::ParamFirmwareUpdateActive) == deCONZ::FirmwareUpdateIdle ||
apsCtrl->getParameter(deCONZ::ParamDeviceConnected) == 1)
{
DBG_Printf(DBG_INFO, "GW firmware update conditions not met, abort\n");
fwUpdateState = FW_Idle;
fwUpdateTimer->start(FW_IDLE_TIMEOUT);
updateEtag(gwConfigEtag);
return;
}
QString gcfFlasherBin = qApp->applicationDirPath() + "/GCFFlasher";
#ifdef Q_OS_WIN
gcfFlasherBin.append(".exe");
QString bin = gcfFlasherBin;
#elif defined(Q_OS_LINUX) && !defined(ARCH_ARM) // on RPi a normal sudo is ok since we don't need password there
QString bin = "pkexec";
gcfFlasherBin = "/usr/bin/GCFFlasher_internal";
fwProcessArgs.prepend(gcfFlasherBin);
#elif defined(Q_OS_OSX)
// TODO
// /usr/bin/osascript -e 'do shell script "make install" with administrator privileges'
QString bin = "sudo";
fwProcessArgs.prepend(gcfFlasherBin);
#else
QString bin = "sudo";
gcfFlasherBin = "/usr/bin/GCFFlasher_internal";
fwProcessArgs.prepend(gcfFlasherBin);
#endif
if (!fwProcess)
{
fwProcess = new QProcess(this);
}
fwProcessArgs << "-f" << fwUpdateFile;
fwUpdateState = FW_UpdateWaitFinished;
updateEtag(gwConfigEtag);
fwUpdateTimer->start(250);
fwProcess->start(bin, fwProcessArgs);
}
/*! Observes the firmware update process.
*/
void DeRestPluginPrivate::updateFirmwareWaitFinished()
{
if (fwProcess)
{
if (fwProcess->bytesAvailable())
{
QByteArray data = fwProcess->readAllStandardOutput();
DBG_Printf(DBG_INFO, "%s", qPrintable(data));
if (apsCtrl->getParameter(deCONZ::ParamFirmwareUpdateActive) != deCONZ::FirmwareUpdateRunning)
{
if (data.contains("flashing"))
{
apsCtrl->setParameter(deCONZ::ParamFirmwareUpdateActive, deCONZ::FirmwareUpdateRunning);
}
}
}
if (fwProcess->state() == QProcess::Starting)
{
DBG_Printf(DBG_INFO, "GW firmware update starting ..\n");
}
else if (fwProcess->state() == QProcess::Running)
{
DBG_Printf(DBG_INFO_L2, "GW firmware update running ..\n");
}
else if (fwProcess->state() == QProcess::NotRunning)
{
if (fwProcess->exitStatus() == QProcess::NormalExit)
{
DBG_Printf(DBG_INFO, "GW firmware update exit code %d\n", fwProcess->exitCode());
}
else if (fwProcess->exitStatus() == QProcess::CrashExit)
{
DBG_Printf(DBG_INFO, "GW firmware update crashed %s\n", qPrintable(fwProcess->errorString()));
}
fwProcess->deleteLater();
fwProcess = 0;
}
}
// done
if (fwProcess == 0)
{
fwUpdateStartedByUser = false;
gwFirmwareNeedUpdate = false;
updateEtag(gwConfigEtag);
apsCtrl->setParameter(deCONZ::ParamFirmwareUpdateActive, deCONZ::FirmwareUpdateIdle);
fwUpdateState = FW_Idle;
fwUpdateTimer->start(FW_IDLE_TIMEOUT);
}
else // recheck
{
fwUpdateTimer->start(250);
}
}
/*! Starts the device disconnect so that the serial port is released.
*/
void DeRestPluginPrivate::updateFirmwareDisconnectDevice()
{
Q_ASSERT(apsCtrl);
// if (apsCtrl->getParameter(deCONZ::ParamFirmwareUpdateActive) == deCONZ::FirmwareUpdateIdle)
// {
// if (apsCtrl->getParameter(deCONZ::ParamDeviceConnected) == 1)
// {
// DBG_Printf(DBG_INFO, "GW firmware disconnect device before update\n");
// }
// }
if (apsCtrl->getParameter(deCONZ::ParamDeviceConnected) == 1)
{
fwUpdateTimer->start(100); // recheck
}
else
{
DBG_Printf(DBG_INFO, "GW firmware start update (device not connected)\n");
fwUpdateState = FW_Update;
fwUpdateTimer->start(0);
updateEtag(gwConfigEtag);
}
}
/*! Starts the firmware update.
*/
bool DeRestPluginPrivate::startUpdateFirmware()
{
fwUpdateStartedByUser = true;
if (fwUpdateState == FW_WaitUserConfirm)
{
apsCtrl->setParameter(deCONZ::ParamFirmwareUpdateActive, deCONZ::FirmwareUpdateRunning);
updateEtag(gwConfigEtag);
fwUpdateState = FW_DisconnectDevice;
fwUpdateTimer->start(100);
return true;
}
return false;
}
/*! Delayed trigger to update the firmware.
*/
void DeRestPluginPrivate::firmwareUpdateTimerFired()
{
if (fwUpdateState == FW_Idle)
{
if (gwFirmwareNeedUpdate)
{
gwFirmwareNeedUpdate = false;
updateEtag(gwConfigEtag);
}
fwUpdateState = FW_CheckDevices;
fwUpdateTimer->start(0);
}
else if (fwUpdateState == FW_CheckDevices)
{
checkFirmwareDevices();
}
else if (fwUpdateState == FW_CheckVersion)
{
queryFirmwareVersion();
}
else if (fwUpdateState == FW_DisconnectDevice)
{
updateFirmwareDisconnectDevice();
}
else if (fwUpdateState == FW_Update)
{
updateFirmware();
}
else if (fwUpdateState == FW_UpdateWaitFinished)
{
updateFirmwareWaitFinished();
}
else if (fwUpdateState == FW_WaitUserConfirm)
{
fwUpdateState = FW_Idle;
fwUpdateTimer->start(FW_IDLE_TIMEOUT);
}
else
{
fwUpdateState = FW_Idle;
fwUpdateTimer->start(FW_IDLE_TIMEOUT);
}
}
/*! Lazy query of firmware version.
Because the device might not be connected at first optaining the
firmware version must be delayed.
If the firmware is older then the min required firmware for the platform
and a proper firmware update file exists, the API will announce that a
firmware update is available.
*/
void DeRestPluginPrivate::queryFirmwareVersion()
{
Q_ASSERT(apsCtrl);
if (!apsCtrl)
{
return;
}
{ // check for GCFFlasher binary
QString gcfFlasherBin = qApp->applicationDirPath() + "/GCFFlasher";
#ifdef Q_OS_WIN
gcfFlasherBin.append(".exe");
#elif defined(Q_OS_LINUX) && !defined(ARCH_ARM) // on RPi a normal sudo is ok since we don't need password there
gcfFlasherBin = "/usr/bin/GCFFlasher_internal";
#elif defined(Q_OS_OSX)
// TODO
#else
gcfFlasherBin = "/usr/bin/GCFFlasher_internal";
#endif
if (!QFile::exists(gcfFlasherBin))
{
DBG_Printf(DBG_INFO, "GW update firmware failed, %s doesn't exist\n", qPrintable(gcfFlasherBin));
fwUpdateState = FW_Idle;
fwUpdateTimer->start(FW_IDLE_TIMEOUT_LONG);
return;
}
}
// does the update file exist?
if (fwUpdateFile.isEmpty())
{
QString fileName;
fileName.sprintf("deCONZ_Rpi_0x%08x.bin.GCF", GW_MIN_RPI_FW_VERSION);
// search in different locations
std::vector<QString> paths;
#ifdef Q_OS_LINUX
paths.push_back(QLatin1String("/usr/share/deCONZ/firmware/"));
#endif
paths.push_back(deCONZ::getStorageLocation(deCONZ::ApplicationsDataLocation) + QLatin1String("/firmware/"));
paths.push_back(deCONZ::getStorageLocation(deCONZ::HomeLocation) + QLatin1String("/raspbee_firmware/"));
#ifdef Q_OS_OSX
QDir dir(qApp->applicationDirPath());
dir.cdUp();
dir.cd("Resources");
paths.push_back(dir.path() + "/");
#endif
std::vector<QString>::const_iterator i = paths.begin();
std::vector<QString>::const_iterator end = paths.end();
for (; i != end; ++i)
{
if (QFile::exists(*i + fileName))
{
fwUpdateFile = *i + fileName;
DBG_Printf(DBG_INFO, "GW update firmware found: %s\n", qPrintable(fwUpdateFile));
break;
}
}
}
if (fwUpdateFile.isEmpty())
{
DBG_Printf(DBG_ERROR, "GW update firmware not found: %s\n", qPrintable(fwUpdateFile));
fwUpdateState = FW_Idle;
fwUpdateTimer->start(FW_IDLE_TIMEOUT);
return;
}
uint8_t devConnected = apsCtrl->getParameter(deCONZ::ParamDeviceConnected);
uint32_t fwVersion = apsCtrl->getParameter(deCONZ::ParamFirmwareVersion);
Q_ASSERT(!gwFirmwareNeedUpdate);
if (devConnected == 0 || fwVersion == 0)
{
// if even after some time no firmware was detected
// ASSUME that a device is present and reachable but might not have firmware installed
// if (getUptime() >= FW_WAIT_UPDATE_READY)
{
QString str;
str.sprintf("0x%08x", GW_MIN_RPI_FW_VERSION);
gwFirmwareVersion = "0x00000000"; // unknown
gwFirmwareVersionUpdate = str;
gwConfig["fwversion"] = gwFirmwareVersion;
gwFirmwareNeedUpdate = true;
updateEtag(gwConfigEtag);
fwUpdateState = FW_WaitUserConfirm;
fwUpdateTimer->start(FW_WAIT_USER_TIMEOUT);
apsCtrl->setParameter(deCONZ::ParamFirmwareUpdateActive, deCONZ::FirmwareUpdateReadyToStart);
if (fwUpdateStartedByUser)
{
startUpdateFirmware();
}
}
return;
}
else if (devConnected)
{
QString str;
str.sprintf("0x%08x", fwVersion);
if (gwFirmwareVersion != str)
{
gwFirmwareVersion = str;
gwConfig["fwversion"] = str;
updateEtag(gwConfigEtag);
}
DBG_Printf(DBG_INFO, "GW firmware version: %s\n", qPrintable(gwFirmwareVersion));
// if the device is detected check that the firmware version is >= min version
if ((fwVersion & FW_PLATFORM_MASK) == FW_PLATFORM_RPI)
{
if (fwVersion < GW_MIN_RPI_FW_VERSION)
{
gwFirmwareVersionUpdate.sprintf("0x%08x", GW_MIN_RPI_FW_VERSION);
gwFirmwareNeedUpdate = true;
updateEtag(gwConfigEtag);
DBG_Printf(DBG_INFO, "GW firmware version shall be updated to: 0x%08x\n", GW_MIN_RPI_FW_VERSION);
fwUpdateState = FW_WaitUserConfirm;
fwUpdateTimer->start(FW_WAIT_USER_TIMEOUT);
apsCtrl->setParameter(deCONZ::ParamFirmwareUpdateActive, deCONZ::FirmwareUpdateReadyToStart);
return;
}
else
{
DBG_Printf(DBG_INFO, "GW firmware version is up to date: 0x%08x\n", fwVersion);
fwUpdateState = FW_Idle;
fwUpdateTimer->start(FW_IDLE_TIMEOUT_LONG);
return;
}
}
if (!gwFirmwareVersionUpdate.isEmpty())
{
gwFirmwareVersionUpdate.clear();
updateEtag(gwConfigEtag);
}
}
fwUpdateState = FW_Idle;
fwUpdateTimer->start(FW_IDLE_TIMEOUT);
}
/*! Checks if devices for firmware update are present.
*/
void DeRestPluginPrivate::checkFirmwareDevices()
{
deCONZ::DeviceEnumerator devEnumerator;
fwProcessArgs.clear();
devEnumerator.listSerialPorts();
const std::vector<deCONZ::DeviceEntry> &availPorts = devEnumerator.getList();
std::vector<deCONZ::DeviceEntry>::const_iterator i = availPorts.begin();
std::vector<deCONZ::DeviceEntry>::const_iterator end = availPorts.end();
int raspBeeCount = 0;
int usbDongleCount = 0;
QString ttyPath;
for (; i != end; ++i)
{
if (i->friendlyName.contains(QLatin1String("ConBee")))
{
usbDongleCount++;
}
else if (i->friendlyName.contains(QLatin1String("RaspBee")))
{
raspBeeCount = 1;
ttyPath = i->path;
}
}
if (usbDongleCount > 1)
{
DBG_Printf(DBG_INFO_L2, "GW firmware update too many USB devices connected, abort\n");
}
else if (usbDongleCount == 1)
{
DBG_Printf(DBG_INFO_L2, "GW firmware update select USB device\n");
fwProcessArgs << "-d" << "0";
}
else if (raspBeeCount > 0 && usbDongleCount == 0 && !ttyPath.isEmpty())
{
DBG_Printf(DBG_INFO_L2, "GW firmware update select %s device\n", qPrintable(ttyPath));
fwProcessArgs << "-d" << "RaspBee";
}
if (!fwProcessArgs.isEmpty())
{
fwUpdateState = FW_CheckVersion;
fwUpdateTimer->start(0);
return;
}
fwUpdateState = FW_Idle;
fwUpdateTimer->start(FW_IDLE_TIMEOUT);
}
<commit_msg>Wait longer after firmware update before recheck new firmware<commit_after>/*
* Copyright (c) 2016 dresden elektronik ingenieurtechnik gmbh.
* All rights reserved.
*
* The software in this package is published under the terms of the BSD
* style license a copy of which has been included with this distribution in
* the LICENSE.txt file.
*
*/
#include <QApplication>
#include <QDesktopServices>
#include <QFile>
#include <QDir>
#include <QString>
#include <QProcess>
#include "de_web_plugin.h"
#include "de_web_plugin_private.h"
#define FW_IDLE_TIMEOUT (10 * 1000)
#define FW_WAIT_UPDATE_READY (2) //s
#define FW_IDLE_TIMEOUT_LONG (240 * 1000)
#define FW_WAIT_USER_TIMEOUT (120 * 1000)
/*! Inits the firmware update manager.
*/
void DeRestPluginPrivate::initFirmwareUpdate()
{
fwProcess = 0;
fwUpdateState = FW_Idle;
Q_ASSERT(apsCtrl);
apsCtrl->setParameter(deCONZ::ParamFirmwareUpdateActive, deCONZ::FirmwareUpdateIdle);
fwUpdateStartedByUser = false;
fwUpdateTimer = new QTimer(this);
fwUpdateTimer->setSingleShot(true);
connect(fwUpdateTimer, SIGNAL(timeout()),
this, SLOT(firmwareUpdateTimerFired()));
fwUpdateTimer->start(5000);
}
/*! Starts the actual firmware update process.
*/
void DeRestPluginPrivate::updateFirmware()
{
if (gwFirmwareNeedUpdate)
{
gwFirmwareNeedUpdate = false;
}
Q_ASSERT(apsCtrl);
if (apsCtrl->getParameter(deCONZ::ParamFirmwareUpdateActive) == deCONZ::FirmwareUpdateIdle ||
apsCtrl->getParameter(deCONZ::ParamDeviceConnected) == 1)
{
DBG_Printf(DBG_INFO, "GW firmware update conditions not met, abort\n");
fwUpdateState = FW_Idle;
fwUpdateTimer->start(FW_IDLE_TIMEOUT);
updateEtag(gwConfigEtag);
return;
}
QString gcfFlasherBin = qApp->applicationDirPath() + "/GCFFlasher";
#ifdef Q_OS_WIN
gcfFlasherBin.append(".exe");
QString bin = gcfFlasherBin;
#elif defined(Q_OS_LINUX) && !defined(ARCH_ARM) // on RPi a normal sudo is ok since we don't need password there
QString bin = "pkexec";
gcfFlasherBin = "/usr/bin/GCFFlasher_internal";
fwProcessArgs.prepend(gcfFlasherBin);
#elif defined(Q_OS_OSX)
// TODO
// /usr/bin/osascript -e 'do shell script "make install" with administrator privileges'
QString bin = "sudo";
fwProcessArgs.prepend(gcfFlasherBin);
#else
QString bin = "sudo";
gcfFlasherBin = "/usr/bin/GCFFlasher_internal";
fwProcessArgs.prepend(gcfFlasherBin);
#endif
if (!fwProcess)
{
fwProcess = new QProcess(this);
}
fwProcessArgs << "-f" << fwUpdateFile;
fwUpdateState = FW_UpdateWaitFinished;
updateEtag(gwConfigEtag);
fwUpdateTimer->start(250);
fwProcess->start(bin, fwProcessArgs);
}
/*! Observes the firmware update process.
*/
void DeRestPluginPrivate::updateFirmwareWaitFinished()
{
if (fwProcess)
{
if (fwProcess->bytesAvailable())
{
QByteArray data = fwProcess->readAllStandardOutput();
DBG_Printf(DBG_INFO, "%s", qPrintable(data));
if (apsCtrl->getParameter(deCONZ::ParamFirmwareUpdateActive) != deCONZ::FirmwareUpdateRunning)
{
if (data.contains("flashing"))
{
apsCtrl->setParameter(deCONZ::ParamFirmwareUpdateActive, deCONZ::FirmwareUpdateRunning);
}
}
}
if (fwProcess->state() == QProcess::Starting)
{
DBG_Printf(DBG_INFO, "GW firmware update starting ..\n");
}
else if (fwProcess->state() == QProcess::Running)
{
DBG_Printf(DBG_INFO_L2, "GW firmware update running ..\n");
}
else if (fwProcess->state() == QProcess::NotRunning)
{
if (fwProcess->exitStatus() == QProcess::NormalExit)
{
DBG_Printf(DBG_INFO, "GW firmware update exit code %d\n", fwProcess->exitCode());
}
else if (fwProcess->exitStatus() == QProcess::CrashExit)
{
DBG_Printf(DBG_INFO, "GW firmware update crashed %s\n", qPrintable(fwProcess->errorString()));
}
fwProcess->deleteLater();
fwProcess = 0;
}
}
// done
if (fwProcess == 0)
{
fwUpdateStartedByUser = false;
gwFirmwareNeedUpdate = false;
updateEtag(gwConfigEtag);
apsCtrl->setParameter(deCONZ::ParamFirmwareUpdateActive, deCONZ::FirmwareUpdateIdle);
fwUpdateState = FW_Idle;
fwUpdateTimer->start(FW_IDLE_TIMEOUT_LONG);
}
else // recheck
{
fwUpdateTimer->start(250);
}
}
/*! Starts the device disconnect so that the serial port is released.
*/
void DeRestPluginPrivate::updateFirmwareDisconnectDevice()
{
Q_ASSERT(apsCtrl);
// if (apsCtrl->getParameter(deCONZ::ParamFirmwareUpdateActive) == deCONZ::FirmwareUpdateIdle)
// {
// if (apsCtrl->getParameter(deCONZ::ParamDeviceConnected) == 1)
// {
// DBG_Printf(DBG_INFO, "GW firmware disconnect device before update\n");
// }
// }
if (apsCtrl->getParameter(deCONZ::ParamDeviceConnected) == 1)
{
fwUpdateTimer->start(100); // recheck
}
else
{
DBG_Printf(DBG_INFO, "GW firmware start update (device not connected)\n");
fwUpdateState = FW_Update;
fwUpdateTimer->start(0);
updateEtag(gwConfigEtag);
}
}
/*! Starts the firmware update.
*/
bool DeRestPluginPrivate::startUpdateFirmware()
{
fwUpdateStartedByUser = true;
if (fwUpdateState == FW_WaitUserConfirm)
{
apsCtrl->setParameter(deCONZ::ParamFirmwareUpdateActive, deCONZ::FirmwareUpdateRunning);
updateEtag(gwConfigEtag);
fwUpdateState = FW_DisconnectDevice;
fwUpdateTimer->start(100);
return true;
}
return false;
}
/*! Delayed trigger to update the firmware.
*/
void DeRestPluginPrivate::firmwareUpdateTimerFired()
{
if (fwUpdateState == FW_Idle)
{
if (gwFirmwareNeedUpdate)
{
gwFirmwareNeedUpdate = false;
updateEtag(gwConfigEtag);
}
fwUpdateState = FW_CheckDevices;
fwUpdateTimer->start(0);
}
else if (fwUpdateState == FW_CheckDevices)
{
checkFirmwareDevices();
}
else if (fwUpdateState == FW_CheckVersion)
{
queryFirmwareVersion();
}
else if (fwUpdateState == FW_DisconnectDevice)
{
updateFirmwareDisconnectDevice();
}
else if (fwUpdateState == FW_Update)
{
updateFirmware();
}
else if (fwUpdateState == FW_UpdateWaitFinished)
{
updateFirmwareWaitFinished();
}
else if (fwUpdateState == FW_WaitUserConfirm)
{
fwUpdateState = FW_Idle;
fwUpdateTimer->start(FW_IDLE_TIMEOUT);
}
else
{
fwUpdateState = FW_Idle;
fwUpdateTimer->start(FW_IDLE_TIMEOUT);
}
}
/*! Lazy query of firmware version.
Because the device might not be connected at first optaining the
firmware version must be delayed.
If the firmware is older then the min required firmware for the platform
and a proper firmware update file exists, the API will announce that a
firmware update is available.
*/
void DeRestPluginPrivate::queryFirmwareVersion()
{
Q_ASSERT(apsCtrl);
if (!apsCtrl)
{
return;
}
{ // check for GCFFlasher binary
QString gcfFlasherBin = qApp->applicationDirPath() + "/GCFFlasher";
#ifdef Q_OS_WIN
gcfFlasherBin.append(".exe");
#elif defined(Q_OS_LINUX) && !defined(ARCH_ARM) // on RPi a normal sudo is ok since we don't need password there
gcfFlasherBin = "/usr/bin/GCFFlasher_internal";
#elif defined(Q_OS_OSX)
// TODO
#else
gcfFlasherBin = "/usr/bin/GCFFlasher_internal";
#endif
if (!QFile::exists(gcfFlasherBin))
{
DBG_Printf(DBG_INFO, "GW update firmware failed, %s doesn't exist\n", qPrintable(gcfFlasherBin));
fwUpdateState = FW_Idle;
fwUpdateTimer->start(FW_IDLE_TIMEOUT_LONG);
return;
}
}
// does the update file exist?
if (fwUpdateFile.isEmpty())
{
QString fileName;
fileName.sprintf("deCONZ_Rpi_0x%08x.bin.GCF", GW_MIN_RPI_FW_VERSION);
// search in different locations
std::vector<QString> paths;
#ifdef Q_OS_LINUX
paths.push_back(QLatin1String("/usr/share/deCONZ/firmware/"));
#endif
paths.push_back(deCONZ::getStorageLocation(deCONZ::ApplicationsDataLocation) + QLatin1String("/firmware/"));
paths.push_back(deCONZ::getStorageLocation(deCONZ::HomeLocation) + QLatin1String("/raspbee_firmware/"));
#ifdef Q_OS_OSX
QDir dir(qApp->applicationDirPath());
dir.cdUp();
dir.cd("Resources");
paths.push_back(dir.path() + "/");
#endif
std::vector<QString>::const_iterator i = paths.begin();
std::vector<QString>::const_iterator end = paths.end();
for (; i != end; ++i)
{
if (QFile::exists(*i + fileName))
{
fwUpdateFile = *i + fileName;
DBG_Printf(DBG_INFO, "GW update firmware found: %s\n", qPrintable(fwUpdateFile));
break;
}
}
}
if (fwUpdateFile.isEmpty())
{
DBG_Printf(DBG_ERROR, "GW update firmware not found: %s\n", qPrintable(fwUpdateFile));
fwUpdateState = FW_Idle;
fwUpdateTimer->start(FW_IDLE_TIMEOUT);
return;
}
uint8_t devConnected = apsCtrl->getParameter(deCONZ::ParamDeviceConnected);
uint32_t fwVersion = apsCtrl->getParameter(deCONZ::ParamFirmwareVersion);
Q_ASSERT(!gwFirmwareNeedUpdate);
if (devConnected == 0 || fwVersion == 0)
{
// if even after some time no firmware was detected
// ASSUME that a device is present and reachable but might not have firmware installed
// if (getUptime() >= FW_WAIT_UPDATE_READY)
{
QString str;
str.sprintf("0x%08x", GW_MIN_RPI_FW_VERSION);
gwFirmwareVersion = "0x00000000"; // unknown
gwFirmwareVersionUpdate = str;
gwConfig["fwversion"] = gwFirmwareVersion;
gwFirmwareNeedUpdate = true;
updateEtag(gwConfigEtag);
fwUpdateState = FW_WaitUserConfirm;
fwUpdateTimer->start(FW_WAIT_USER_TIMEOUT);
apsCtrl->setParameter(deCONZ::ParamFirmwareUpdateActive, deCONZ::FirmwareUpdateReadyToStart);
if (fwUpdateStartedByUser)
{
startUpdateFirmware();
}
}
return;
}
else if (devConnected)
{
QString str;
str.sprintf("0x%08x", fwVersion);
if (gwFirmwareVersion != str)
{
gwFirmwareVersion = str;
gwConfig["fwversion"] = str;
updateEtag(gwConfigEtag);
}
DBG_Printf(DBG_INFO, "GW firmware version: %s\n", qPrintable(gwFirmwareVersion));
// if the device is detected check that the firmware version is >= min version
if ((fwVersion & FW_PLATFORM_MASK) == FW_PLATFORM_RPI)
{
if (fwVersion < GW_MIN_RPI_FW_VERSION)
{
gwFirmwareVersionUpdate.sprintf("0x%08x", GW_MIN_RPI_FW_VERSION);
gwFirmwareNeedUpdate = true;
updateEtag(gwConfigEtag);
DBG_Printf(DBG_INFO, "GW firmware version shall be updated to: 0x%08x\n", GW_MIN_RPI_FW_VERSION);
fwUpdateState = FW_WaitUserConfirm;
fwUpdateTimer->start(FW_WAIT_USER_TIMEOUT);
apsCtrl->setParameter(deCONZ::ParamFirmwareUpdateActive, deCONZ::FirmwareUpdateReadyToStart);
return;
}
else
{
DBG_Printf(DBG_INFO, "GW firmware version is up to date: 0x%08x\n", fwVersion);
fwUpdateState = FW_Idle;
fwUpdateTimer->start(FW_IDLE_TIMEOUT_LONG);
return;
}
}
if (!gwFirmwareVersionUpdate.isEmpty())
{
gwFirmwareVersionUpdate.clear();
updateEtag(gwConfigEtag);
}
}
fwUpdateState = FW_Idle;
fwUpdateTimer->start(FW_IDLE_TIMEOUT);
}
/*! Checks if devices for firmware update are present.
*/
void DeRestPluginPrivate::checkFirmwareDevices()
{
deCONZ::DeviceEnumerator devEnumerator;
fwProcessArgs.clear();
devEnumerator.listSerialPorts();
const std::vector<deCONZ::DeviceEntry> &availPorts = devEnumerator.getList();
std::vector<deCONZ::DeviceEntry>::const_iterator i = availPorts.begin();
std::vector<deCONZ::DeviceEntry>::const_iterator end = availPorts.end();
int raspBeeCount = 0;
int usbDongleCount = 0;
QString ttyPath;
for (; i != end; ++i)
{
if (i->friendlyName.contains(QLatin1String("ConBee")))
{
usbDongleCount++;
}
else if (i->friendlyName.contains(QLatin1String("RaspBee")))
{
raspBeeCount = 1;
ttyPath = i->path;
}
}
if (usbDongleCount > 1)
{
DBG_Printf(DBG_INFO_L2, "GW firmware update too many USB devices connected, abort\n");
}
else if (usbDongleCount == 1)
{
DBG_Printf(DBG_INFO_L2, "GW firmware update select USB device\n");
fwProcessArgs << "-d" << "0";
}
else if (raspBeeCount > 0 && usbDongleCount == 0 && !ttyPath.isEmpty())
{
DBG_Printf(DBG_INFO_L2, "GW firmware update select %s device\n", qPrintable(ttyPath));
fwProcessArgs << "-d" << "RaspBee";
}
if (!fwProcessArgs.isEmpty())
{
fwUpdateState = FW_CheckVersion;
fwUpdateTimer->start(0);
return;
}
fwUpdateState = FW_Idle;
fwUpdateTimer->start(FW_IDLE_TIMEOUT);
}
<|endoftext|> |
<commit_before>/**
* @file osc.cpp
* @brief Brief description of file.
*
*/
#include "angort/angort.h"
#include "../wrappers.h"
#include <lo/lo.h>
#define THROWOSC(e) throw RUNT("ex$diamond",e.what())
using namespace angort;
static BasicWrapperType<lo_address> tLoAddr("LOAD");
%type LoAddr tLoAddr lo_address
%name osc
%shared
%wordargs makeport s (s ---) make a new OSC port on localhost, given the port name
{
lo_address lo = lo_address_new(NULL,p0);
if(!lo)
a->pushNone();
else
tLoAddr.set(a->pushval(),lo);
}
%wordargs send lsA|LoAddr (floatlist path port -- ret) send to path from a port, returns none on fail.
{
lo_message msg = lo_message_new();
ArrayListIterator<Value> iter(p0);
int i=0;
for(iter.first();!iter.isDone();iter.next(),i++){
lo_message_add_float(msg,iter.current()->toFloat());
}
int ret = lo_send_message(*p2,p1,msg);
if(ret<0)
a->pushNone();
else
a->pushInt(0);
lo_message_free(msg);
}
%init
{
fprintf(stderr,"Initialising OSC plugin (send only), %s %s\n",__DATE__,__TIME__);
}
%shutdown
{
}
<commit_msg>description<commit_after>/**
* @file osc.cpp
* @brief Brief description of file.
*
*/
#include "angort/angort.h"
#include "../wrappers.h"
#include <lo/lo.h>
#define THROWOSC(e) throw RUNT("ex$diamond",e.what())
using namespace angort;
static BasicWrapperType<lo_address> tLoAddr("LOAD");
%type LoAddr tLoAddr lo_address
%name osc
%shared
%wordargs makeport s (s ---) make a new OSC port on localhost, given the port name
{
lo_address lo = lo_address_new(NULL,p0);
if(!lo)
a->pushNone();
else
tLoAddr.set(a->pushval(),lo);
}
%wordargs send lsA|LoAddr (floatlist path port -- ret) send to path on a port, returns none on fail.
{
lo_message msg = lo_message_new();
ArrayListIterator<Value> iter(p0);
int i=0;
for(iter.first();!iter.isDone();iter.next(),i++){
lo_message_add_float(msg,iter.current()->toFloat());
}
int ret = lo_send_message(*p2,p1,msg);
if(ret<0)
a->pushNone();
else
a->pushInt(0);
lo_message_free(msg);
}
%init
{
fprintf(stderr,"Initialising OSC plugin (send only), %s %s\n",__DATE__,__TIME__);
}
%shutdown
{
}
<|endoftext|> |
<commit_before>/* This file is part of Mapnik (c++ mapping toolkit)
* Copyright (C) 2005 Artem Pavlenko
*
* Mapnik is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*/
//$Id$
#ifndef EXPRESSION_HPP
#define EXPRESSION_HPP
#include "value.hpp"
#include "filter_visitor.hpp"
namespace mapnik
{
template <typename FeatureT> class filter_visitor;
template <typename FeatureT>
struct expression
{
virtual value get_value(FeatureT const& feature) const=0;
virtual void accept(filter_visitor<FeatureT>& v)=0;
virtual expression<FeatureT>* clone() const=0;
virtual std::string to_string() const=0;
virtual ~expression() {}
};
template <typename FeatureT>
class literal : public expression<FeatureT>
{
public:
literal(int val)
: expression<FeatureT>(),
value_(val) {}
literal(double val)
: expression<FeatureT>(),
value_(val) {}
literal(std::string const& val)
: expression<FeatureT>(),
value_(val) {}
literal(literal const& other)
: expression<FeatureT>(),
value_(other.value_) {}
value get_value(FeatureT const& /*feature*/) const
{
return value_;
}
void accept(filter_visitor<FeatureT>& v)
{
v.visit(*this);
}
expression<FeatureT>* clone() const
{
return new literal(*this);
}
std::string to_string() const
{
return "'"+value_.to_string()+"'";
}
~literal() {}
private:
value value_;
};
template <typename FeatureT>
class property : public expression<FeatureT>
{
public:
property(std::string const& name)
: expression<FeatureT>(),
name_(name),
index_(0),
valid_(false) {}
property(property const& other)
: expression<FeatureT>(),
name_(other.name_),
index_(other.index_),
valid_(other.valid_) {}
value get_value(FeatureT const& feature) const
{
return feature.get_property(index_);
}
void accept(filter_visitor<FeatureT>& v)
{
v.visit(*this);
}
expression<FeatureT>* clone() const
{
return new property(*this);
}
std::string const& name() const
{
return name_;
}
void set_index(size_t index)
{
index_=index;
valid_=true;
}
std::string to_string() const
{
return "["+name_+"]";
}
~property() {}
private:
std::string name_;
size_t index_;
bool valid_;
};
}
#endif //EXPRESSION_HPP
<commit_msg> fixed to_string() method for filter expressions<commit_after>/* This file is part of Mapnik (c++ mapping toolkit)
* Copyright (C) 2005 Artem Pavlenko
*
* Mapnik is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*/
//$Id$
#ifndef EXPRESSION_HPP
#define EXPRESSION_HPP
#include "value.hpp"
#include "filter_visitor.hpp"
namespace mapnik
{
template <typename FeatureT> class filter_visitor;
template <typename FeatureT>
struct expression
{
virtual value get_value(FeatureT const& feature) const=0;
virtual void accept(filter_visitor<FeatureT>& v)=0;
virtual expression<FeatureT>* clone() const=0;
virtual std::string to_string() const=0;
virtual ~expression() {}
};
template <typename FeatureT>
class literal : public expression<FeatureT>
{
public:
literal(int val)
: expression<FeatureT>(),
value_(val) {}
literal(double val)
: expression<FeatureT>(),
value_(val) {}
literal(std::string const& val)
: expression<FeatureT>(),
value_(val) {}
literal(literal const& other)
: expression<FeatureT>(),
value_(other.value_) {}
value get_value(FeatureT const& /*feature*/) const
{
return value_;
}
void accept(filter_visitor<FeatureT>& v)
{
v.visit(*this);
}
expression<FeatureT>* clone() const
{
return new literal(*this);
}
std::string to_string() const
{
return value_.to_string();
}
~literal() {}
private:
value value_;
};
template <typename FeatureT>
class property : public expression<FeatureT>
{
public:
property(std::string const& name)
: expression<FeatureT>(),
name_(name),
index_(0),
valid_(false) {}
property(property const& other)
: expression<FeatureT>(),
name_(other.name_),
index_(other.index_),
valid_(other.valid_) {}
value get_value(FeatureT const& feature) const
{
return feature.get_property(index_);
}
void accept(filter_visitor<FeatureT>& v)
{
v.visit(*this);
}
expression<FeatureT>* clone() const
{
return new property(*this);
}
std::string const& name() const
{
return name_;
}
void set_index(size_t index)
{
index_=index;
valid_=true;
}
std::string to_string() const
{
return "["+name_+"]";
}
~property() {}
private:
std::string name_;
size_t index_;
bool valid_;
};
}
#endif //EXPRESSION_HPP
<|endoftext|> |
<commit_before>/*
This file is part of Bohrium and copyright (c) 2012 the Bohrium team:
http://bohrium.bitbucket.org
Bohrium is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as
published by the Free Software Foundation, either version 3
of the License, or (at your option) any later version.
Bohrium 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 Lesser General Public License along with Bohrium.
If not, see <http://www.gnu.org/licenses/>.
*/
#include <iostream>
#include "traits.hpp" // Traits for assigning type to constants and multi_arrays.
#include "runtime.hpp"
#include <sstream>
namespace bh {
template <typename T>
void multi_array<T>::init() // Pseudo-default constructor
{
key = keys++;
temp = false;
storage.insert(key, new bh_array);
assign_array_type<T>(&storage[key]);
}
template <typename T> // Default constructor - rank 0
multi_array<T>::multi_array() : key(0), temp(false) { }
/**
* Inherit ndim / shape from another operand
* Does not copy data.
*
*/
template <typename T> // Copy constructor
multi_array<T>::multi_array(const multi_array<T>& operand)
{
init();
storage[key].data = NULL;
storage[key].base = NULL;
storage[key].ndim = storage[operand.getKey()].ndim;
storage[key].start = storage[operand.getKey()].start;
for(int64_t i=0; i< storage[operand.getKey()].ndim; i++) {
storage[key].shape[i] = storage[operand.getKey()].shape[i];
}
for(int64_t i=0; i< storage[operand.getKey()].ndim; i++) {
storage[key].stride[i] = storage[operand.getKey()].stride[i];
}
}
template <typename T>
template <typename ...Dimensions> // Variadic constructor
multi_array<T>::multi_array(Dimensions... shape)
{
init();
storage[key].data = NULL;
storage[key].base = NULL;
storage[key].ndim = sizeof...(Dimensions);
storage[key].start = 0;
unpack_shape(storage[key].shape, 0, shape...);
int64_t stride = 1; // Setup strides
for(int64_t i=storage[key].ndim-1; 0 <= i; --i) {
storage[key].stride[i] = stride;
stride *= storage[key].shape[i];
}
}
template <typename T> // Deconstructor
multi_array<T>::~multi_array()
{
if (key>0) {
if (NULL == storage[key].base) { // Only send free on base-array
Runtime::instance()->enqueue((bh_opcode)BH_FREE, *this);
}
Runtime::instance()->enqueue((bh_opcode)BH_DISCARD, *this);
Runtime::instance()->trash(key);
}
}
template <typename T>
inline
size_t multi_array<T>::getKey() const
{
return key;
}
template <typename T>
inline
unsigned long multi_array<T>::getRank() const
{
return (unsigned long)*(&storage[key].ndim);
}
template <typename T>
inline
bool multi_array<T>::getTemp() const
{
return temp;
}
template <typename T>
inline
void multi_array<T>::setTemp(bool temp)
{
this->temp = temp;
}
template <typename T>
inline
size_t multi_array<T>::len()
{
size_t nelements = 1;
for (int i = 0; i < storage[key].ndim; ++i) {
nelements *= storage[key].shape[i];
}
return nelements;
}
template <typename T>
typename multi_array<T>::iterator multi_array<T>::begin()
{
Runtime::instance()->enqueue((bh_opcode)BH_SYNC, *this);
Runtime::instance()->flush();
return multi_array<T>::iterator(storage[this->key]);
}
template <typename T>
typename multi_array<T>::iterator multi_array<T>::end()
{
return multi_array<T>::iterator();
}
//
// Increment / decrement
//
template <typename T>
multi_array<T>& multi_array<T>::operator++()
{
Runtime::instance()->enqueue((bh_opcode)BH_ADD, *this, *this, (T)1);
return *this;
}
template <typename T>
multi_array<T>& multi_array<T>::operator++(int)
{
Runtime::instance()->enqueue((bh_opcode)BH_ADD, *this, *this, (T)1);
return *this;
}
template <typename T>
multi_array<T>& multi_array<T>::operator--()
{
Runtime::instance()->enqueue((bh_opcode)BH_SUBTRACT, *this, *this, (T)1);
return *this;
}
template <typename T>
multi_array<T>& multi_array<T>::operator--(int)
{
Runtime::instance()->enqueue((bh_opcode)BH_SUBTRACT, *this, *this, (T)1);
return *this;
}
//
// Output / Printing
//
template <typename T>
std::ostream& operator<< (std::ostream& stream, multi_array<T>& rhs)
{
bool first = true;
typename multi_array<T>::iterator it = rhs.begin();
typename multi_array<T>::iterator end = rhs.end();
stream << "[ ";
for(; it != end; it++) {
if (!first) {
stream << ", ";
} else {
first = false;
}
stream << *it;
}
stream << " ]" << std::endl;
if (rhs.getTemp()) { // Cleanup temporary
delete &rhs;
}
return stream;
}
//
// Slicing
//
template <typename T>
slice<T>& multi_array<T>::operator[](int rhs) {
return (*(new slice<T>(*this)))[rhs];
}
template <typename T>
slice<T>& multi_array<T>::operator[](slice_range& rhs) {
return (*(new slice<T>(*this)))[rhs];
}
//
// Reshaping
//
template <typename T>
multi_array<T>& multi_array<T>::operator()(const T& n) {
std::cout << "Reshape to: " << n << std::endl;
return *this;
}
// Initialization
template <typename T>
multi_array<T>& multi_array<T>::operator=(const T& rhs)
{
Runtime::instance()->enqueue((bh_opcode)BH_IDENTITY, *this, rhs);
return *this;
}
// Linking
template <typename T>
void multi_array<T>::link(const size_t ext_key)
{
if (0!=key) {
throw std::runtime_error("Dude you are ALREADY linked!");
}
key = ext_key;
}
template <typename T>
size_t multi_array<T>::unlink()
{
if (0==key) {
throw std::runtime_error("Dude! THis one aint linked at all!");
}
size_t retKey = key;
key = 0;
return retKey;
}
// Aliasing
template <typename T>
multi_array<T>& multi_array<T>::operator=(multi_array<T>& rhs)
{
if (key != rhs.getKey()) { // Prevent self-aliasing
if (key>0) { // Release current linkage
if (NULL == storage[key].base) {
Runtime::instance()->enqueue((bh_opcode)BH_FREE, *this);
}
Runtime::instance()->enqueue((bh_opcode)BH_DISCARD, *this);
unlink();
}
if (rhs.getTemp()) { // Take over temporary reference
link(rhs.unlink());
temp = false;
delete &rhs;
} else { // Create an alias of rhs.
init();
storage[key].data = NULL;
storage[key].base = &storage[rhs.getKey()];
storage[key].ndim = storage[rhs.getKey()].ndim;
storage[key].start = storage[rhs.getKey()].start;
for(int64_t i=0; i< storage[rhs.getKey()].ndim; i++) {
storage[key].shape[i] = storage[rhs.getKey()].shape[i];
}
for(int64_t i=0; i< storage[rhs.getKey()].ndim; i++) {
storage[key].stride[i] = storage[rhs.getKey()].stride[i];
}
}
}
return *this;
}
/**
* Aliasing via slicing
*
* Construct a view based on a slice.
* Such as:
*
* center = grid[_(1,-1,1)][_(1,-1,1)];
*
* TODO: this is probobaly not entirely correct...
*/
template <typename T>
multi_array<T>& multi_array<T>::operator=(slice<T>& rhs)
{
multi_array<T>* vv = &rhs.view();
if (key>0) { // Release current linkage
if (NULL == storage[key].base) {
Runtime::instance()->enqueue((bh_opcode)BH_FREE, *this);
}
Runtime::instance()->enqueue((bh_opcode)BH_DISCARD, *this);
unlink();
}
link(vv->unlink());
delete vv;
return *this;
}
//
// Typecasting
//
template <typename T> template <typename Ret>
multi_array<Ret>& multi_array<T>::as()
{
multi_array<Ret>* result = &Runtime::instance()->temp<Ret>();
result->setTemp(true);
storage[result->getKey()].base = NULL;
storage[result->getKey()].ndim = storage[this->getKey()].ndim;
storage[result->getKey()].start = storage[this->getKey()].start;
for(int64_t i=0; i< storage[this->getKey()].ndim; i++) {
storage[result->getKey()].shape[i] = storage[this->getKey()].shape[i];
}
for(int64_t i=0; i< storage[this->getKey()].ndim; i++) {
storage[result->getKey()].stride[i] = storage[this->getKey()].stride[i];
}
storage[result->getKey()].data = NULL;
Runtime::instance()->enqueue((bh_opcode)BH_IDENTITY, *result, *this);
return *result;
}
/**
* Update operand!
*/
template <typename T>
multi_array<T>& multi_array<T>::update(multi_array& rhs)
{
if (1>key) { // We do not have anything to update!
throw std::runtime_error("Far out dude! you are trying to update "
"something that does not exist!");
}
Runtime::instance()->enqueue((bh_opcode)BH_IDENTITY, *this, rhs);
return *this;
}
}
<commit_msg>cppb: Moved functionality of multi_array.update() to multi_array.operator().<commit_after>/*
This file is part of Bohrium and copyright (c) 2012 the Bohrium team:
http://bohrium.bitbucket.org
Bohrium is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as
published by the Free Software Foundation, either version 3
of the License, or (at your option) any later version.
Bohrium 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 Lesser General Public License along with Bohrium.
If not, see <http://www.gnu.org/licenses/>.
*/
#include <iostream>
#include "traits.hpp" // Traits for assigning type to constants and multi_arrays.
#include "runtime.hpp"
#include <sstream>
namespace bh {
template <typename T>
void multi_array<T>::init() // Pseudo-default constructor
{
key = keys++;
temp = false;
storage.insert(key, new bh_array);
assign_array_type<T>(&storage[key]);
}
template <typename T> // Default constructor - rank 0
multi_array<T>::multi_array() : key(0), temp(false) { }
/**
* Inherit ndim / shape from another operand
* Does not copy data.
*
*/
template <typename T> // Copy constructor
multi_array<T>::multi_array(const multi_array<T>& operand)
{
init();
storage[key].data = NULL;
storage[key].base = NULL;
storage[key].ndim = storage[operand.getKey()].ndim;
storage[key].start = storage[operand.getKey()].start;
for(int64_t i=0; i< storage[operand.getKey()].ndim; i++) {
storage[key].shape[i] = storage[operand.getKey()].shape[i];
}
for(int64_t i=0; i< storage[operand.getKey()].ndim; i++) {
storage[key].stride[i] = storage[operand.getKey()].stride[i];
}
}
template <typename T>
template <typename ...Dimensions> // Variadic constructor
multi_array<T>::multi_array(Dimensions... shape)
{
init();
storage[key].data = NULL;
storage[key].base = NULL;
storage[key].ndim = sizeof...(Dimensions);
storage[key].start = 0;
unpack_shape(storage[key].shape, 0, shape...);
int64_t stride = 1; // Setup strides
for(int64_t i=storage[key].ndim-1; 0 <= i; --i) {
storage[key].stride[i] = stride;
stride *= storage[key].shape[i];
}
}
template <typename T> // Deconstructor
multi_array<T>::~multi_array()
{
if (key>0) {
if (NULL == storage[key].base) { // Only send free on base-array
Runtime::instance()->enqueue((bh_opcode)BH_FREE, *this);
}
Runtime::instance()->enqueue((bh_opcode)BH_DISCARD, *this);
Runtime::instance()->trash(key);
}
}
template <typename T>
inline
size_t multi_array<T>::getKey() const
{
return key;
}
template <typename T>
inline
unsigned long multi_array<T>::getRank() const
{
return (unsigned long)*(&storage[key].ndim);
}
template <typename T>
inline
bool multi_array<T>::getTemp() const
{
return temp;
}
template <typename T>
inline
void multi_array<T>::setTemp(bool temp)
{
this->temp = temp;
}
template <typename T>
inline
size_t multi_array<T>::len()
{
size_t nelements = 1;
for (int i = 0; i < storage[key].ndim; ++i) {
nelements *= storage[key].shape[i];
}
return nelements;
}
template <typename T>
typename multi_array<T>::iterator multi_array<T>::begin()
{
Runtime::instance()->enqueue((bh_opcode)BH_SYNC, *this);
Runtime::instance()->flush();
return multi_array<T>::iterator(storage[this->key]);
}
template <typename T>
typename multi_array<T>::iterator multi_array<T>::end()
{
return multi_array<T>::iterator();
}
//
// Increment / decrement
//
template <typename T>
multi_array<T>& multi_array<T>::operator++()
{
Runtime::instance()->enqueue((bh_opcode)BH_ADD, *this, *this, (T)1);
return *this;
}
template <typename T>
multi_array<T>& multi_array<T>::operator++(int)
{
Runtime::instance()->enqueue((bh_opcode)BH_ADD, *this, *this, (T)1);
return *this;
}
template <typename T>
multi_array<T>& multi_array<T>::operator--()
{
Runtime::instance()->enqueue((bh_opcode)BH_SUBTRACT, *this, *this, (T)1);
return *this;
}
template <typename T>
multi_array<T>& multi_array<T>::operator--(int)
{
Runtime::instance()->enqueue((bh_opcode)BH_SUBTRACT, *this, *this, (T)1);
return *this;
}
//
// Output / Printing
//
template <typename T>
std::ostream& operator<< (std::ostream& stream, multi_array<T>& rhs)
{
bool first = true;
typename multi_array<T>::iterator it = rhs.begin();
typename multi_array<T>::iterator end = rhs.end();
stream << "[ ";
for(; it != end; it++) {
if (!first) {
stream << ", ";
} else {
first = false;
}
stream << *it;
}
stream << " ]" << std::endl;
if (rhs.getTemp()) { // Cleanup temporary
delete &rhs;
}
return stream;
}
//
// Slicing
//
template <typename T>
slice<T>& multi_array<T>::operator[](int rhs) {
return (*(new slice<T>(*this)))[rhs];
}
template <typename T>
slice<T>& multi_array<T>::operator[](slice_range& rhs) {
return (*(new slice<T>(*this)))[rhs];
}
// Initialization
template <typename T>
multi_array<T>& multi_array<T>::operator=(const T& rhs)
{
Runtime::instance()->enqueue((bh_opcode)BH_IDENTITY, *this, rhs);
return *this;
}
// Linking
template <typename T>
void multi_array<T>::link(const size_t ext_key)
{
if (0!=key) {
throw std::runtime_error("Dude you are ALREADY linked!");
}
key = ext_key;
}
template <typename T>
size_t multi_array<T>::unlink()
{
if (0==key) {
throw std::runtime_error("Dude! THis one aint linked at all!");
}
size_t retKey = key;
key = 0;
return retKey;
}
// Aliasing
template <typename T>
multi_array<T>& multi_array<T>::operator=(multi_array<T>& rhs)
{
if (key != rhs.getKey()) { // Prevent self-aliasing
if (key>0) { // Release current linkage
if (NULL == storage[key].base) {
Runtime::instance()->enqueue((bh_opcode)BH_FREE, *this);
}
Runtime::instance()->enqueue((bh_opcode)BH_DISCARD, *this);
unlink();
}
if (rhs.getTemp()) { // Take over temporary reference
link(rhs.unlink());
temp = false;
delete &rhs;
} else { // Create an alias of rhs.
init();
storage[key].data = NULL;
storage[key].base = &storage[rhs.getKey()];
storage[key].ndim = storage[rhs.getKey()].ndim;
storage[key].start = storage[rhs.getKey()].start;
for(int64_t i=0; i< storage[rhs.getKey()].ndim; i++) {
storage[key].shape[i] = storage[rhs.getKey()].shape[i];
}
for(int64_t i=0; i< storage[rhs.getKey()].ndim; i++) {
storage[key].stride[i] = storage[rhs.getKey()].stride[i];
}
}
}
return *this;
}
/**
* Aliasing via slicing
*
* Construct a view based on a slice.
* Such as:
*
* center = grid[_(1,-1,1)][_(1,-1,1)];
*
* TODO: this is probobaly not entirely correct...
*/
template <typename T>
multi_array<T>& multi_array<T>::operator=(slice<T>& rhs)
{
multi_array<T>* vv = &rhs.view();
if (key>0) { // Release current linkage
if (NULL == storage[key].base) {
Runtime::instance()->enqueue((bh_opcode)BH_FREE, *this);
}
Runtime::instance()->enqueue((bh_opcode)BH_DISCARD, *this);
unlink();
}
link(vv->unlink());
delete vv;
return *this;
}
//
// Typecasting
//
template <typename T> template <typename Ret>
multi_array<Ret>& multi_array<T>::as()
{
multi_array<Ret>* result = &Runtime::instance()->temp<Ret>();
result->setTemp(true);
storage[result->getKey()].base = NULL;
storage[result->getKey()].ndim = storage[this->getKey()].ndim;
storage[result->getKey()].start = storage[this->getKey()].start;
for(int64_t i=0; i< storage[this->getKey()].ndim; i++) {
storage[result->getKey()].shape[i] = storage[this->getKey()].shape[i];
}
for(int64_t i=0; i< storage[this->getKey()].ndim; i++) {
storage[result->getKey()].stride[i] = storage[this->getKey()].stride[i];
}
storage[result->getKey()].data = NULL;
Runtime::instance()->enqueue((bh_opcode)BH_IDENTITY, *result, *this);
return *result;
}
//
// Update
//
template <typename T>
multi_array<T>& multi_array<T>::operator()(multi_array& rhs)
{
if (1>key) { // We do not have anything to update!
throw std::runtime_error("Far out dude! you are trying to update "
"something that does not exist!");
}
Runtime::instance()->enqueue((bh_opcode)BH_IDENTITY, *this, rhs);
return *this;
}
template <typename T>
multi_array<T>& multi_array<T>::operator()(const T& value) {
if (1>key) { // We do not have anything to update!
throw std::runtime_error("Far out dude! you are trying to update "
"something that does not exist!");
}
Runtime::instance()->enqueue((bh_opcode)BH_IDENTITY, *this, value);
return *this;
}
}
<|endoftext|> |
<commit_before>/*
* Firmware flashing tool for Blu-Ray drives using the Mediatek MT1939 chip.
* Copyright (c) 2014 Micah Elizabeth Scott
*
* 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 <algorithm>
#include "mt1939.h"
int main(int argc, char** argv)
{
TinySCSI scsi;
MT1939::DeviceInfo info;
MT1939::FirmwareImage fw;
if (!MT1939::open(scsi)) {
return 1;
}
if (!MT1939::deviceInfo(scsi, &info)) {
return 1;
}
info.print();
// Various usage formats...
if (argc == 1) {
return 0;
} else if (argc == 2 && !strcmp("--erase", argv[1])) {
fw.erase();
} else if (argc >= 3 && !strcmp("--scsi", argv[1])) {
uint8_t cdb[12];
const char *dumpfile = "result.log";
static uint8_t data[1024*1024*128];
unsigned len = std::min<unsigned>(strtol(argv[2], 0, 16), sizeof data - 1);
memset(cdb, 0, sizeof cdb);
for (int i = 0; i < sizeof cdb; i++) {
const char *arg = argv[3+i];
if (!arg) {
break;
}
cdb[i] = strtol(arg, 0, 16);
}
fprintf(stderr, "\nCDB:\n");
hexdump(cdb, sizeof cdb);
if (scsi.in(cdb, sizeof cdb, data, len)) {
fprintf(stderr, "\nData returned:\n");
hexdump(data, len);
if (len) {
FILE *f = fopen(dumpfile, "wb");
if (f && fwrite(data, len, 1, f) == 1) {
fprintf(stderr, "Saved %d bytes to %s\n", len, dumpfile);
fclose(f);
}
}
}
return 0;
} else if (argc == 2 && fw.open(argv[1])) {
fprintf(stderr, "Firmware image loaded from disk\n");
} else {
fprintf(stderr,
"\n"
"usage:\n"
" mtflash Shows device version info, changes nothing\n"
" mtflash fw.bin Program a 2MB raw firmware image file.\n"
" The first 64 kiB is locked and can't be programmed,\n"
" so these bytes in the image are ignored.\n"
" mtflash --erase Send an image of all 0xFFs, erasing the unlocked\n"
" portions of flash.\n"
" mtflash --scsi Send a low level SCSI command.\n"
"\n"
"scsi examples:\n"
" mtflash --scsi 60 12 00 00 00 60 Long inquiry command\n"
" mtflash --scsi 8 ff 00 ff Firmware version\n"
" mtflash --scsi 2 ff 00 05 Read appselect bit0\n"
" mtflash --scsi 0 ff 00 04 00 00 01 Set appselect bit0\n"
" mtflash --scsi 0 ff 00 04 00 00 00 Clear appselect bit0\n"
" mtflash --scsi ffff 3c 6 0 0 0 0 0 ff ff Read first 64k of DRAM\n"
);
return 1;
}
fw.print();
unsigned delay = 2;
fprintf(stderr, "--- WRITING in %d seconds ---\n", delay);
sleep(delay);
if (!MT1939::writeFirmware(scsi, &fw)) {
return 1;
}
return 0;
}
<commit_msg>Remove pre-flash delay<commit_after>/*
* Firmware flashing tool for Blu-Ray drives using the Mediatek MT1939 chip.
* Copyright (c) 2014 Micah Elizabeth Scott
*
* 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 <algorithm>
#include "mt1939.h"
int main(int argc, char** argv)
{
TinySCSI scsi;
MT1939::DeviceInfo info;
MT1939::FirmwareImage fw;
if (!MT1939::open(scsi)) {
return 1;
}
if (!MT1939::deviceInfo(scsi, &info)) {
return 1;
}
info.print();
// Various usage formats...
if (argc == 1) {
return 0;
} else if (argc == 2 && !strcmp("--erase", argv[1])) {
fw.erase();
} else if (argc >= 3 && !strcmp("--scsi", argv[1])) {
uint8_t cdb[12];
const char *dumpfile = "result.log";
static uint8_t data[1024*1024*128];
unsigned len = std::min<unsigned>(strtol(argv[2], 0, 16), sizeof data - 1);
memset(cdb, 0, sizeof cdb);
for (int i = 0; i < sizeof cdb; i++) {
const char *arg = argv[3+i];
if (!arg) {
break;
}
cdb[i] = strtol(arg, 0, 16);
}
fprintf(stderr, "\nCDB:\n");
hexdump(cdb, sizeof cdb);
if (scsi.in(cdb, sizeof cdb, data, len)) {
fprintf(stderr, "\nData returned:\n");
hexdump(data, len);
if (len) {
FILE *f = fopen(dumpfile, "wb");
if (f && fwrite(data, len, 1, f) == 1) {
fprintf(stderr, "Saved %d bytes to %s\n", len, dumpfile);
fclose(f);
}
}
}
return 0;
} else if (argc == 2 && fw.open(argv[1])) {
fprintf(stderr, "Firmware image loaded from disk\n");
} else {
fprintf(stderr,
"\n"
"usage:\n"
" mtflash Shows device version info, changes nothing\n"
" mtflash fw.bin Program a 2MB raw firmware image file.\n"
" The first 64 kiB is locked and can't be programmed,\n"
" so these bytes in the image are ignored.\n"
" mtflash --erase Send an image of all 0xFFs, erasing the unlocked\n"
" portions of flash.\n"
" mtflash --scsi Send a low level SCSI command.\n"
"\n"
"scsi examples:\n"
" mtflash --scsi 60 12 00 00 00 60 Long inquiry command\n"
" mtflash --scsi 8 ff 00 ff Firmware version\n"
" mtflash --scsi 2 ff 00 05 Read appselect bit0\n"
" mtflash --scsi 0 ff 00 04 00 00 01 Set appselect bit0\n"
" mtflash --scsi 0 ff 00 04 00 00 00 Clear appselect bit0\n"
" mtflash --scsi ffff 3c 6 0 0 0 0 0 ff ff Read first 64k of DRAM\n"
);
return 1;
}
fw.print();
if (!MT1939::writeFirmware(scsi, &fw)) {
return 1;
}
return 0;
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: FDatabaseMetaDataResultSetMetaData.hxx,v $
*
* $Revision: 1.5 $
*
* last change: $Author: rt $ $Date: 2005-09-08 06:37:17 $
*
* 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 _CONNECTIVITY_DATABASEMETADATARESULTSETMETADATA_HXX_
#define _CONNECTIVITY_DATABASEMETADATARESULTSETMETADATA_HXX_
#ifndef _COM_SUN_STAR_SDBC_XRESULTSETMETADATA_HPP_
#include <com/sun/star/sdbc/XResultSetMetaData.hpp>
#endif
#ifndef _CPPUHELPER_IMPLBASE1_HXX_
#include <cppuhelper/implbase1.hxx>
#endif
#ifndef _VECTOR_
#include <vector>
#endif
#ifndef _CONNECTIVITY_FDATABASEMETADATARESULTSET_HXX_
#include "FDatabaseMetaDataResultSet.hxx"
#endif
#ifndef _CONNECTIVITY_COLUMN_HXX_
#include "OColumn.hxx"
#endif
#ifndef CONNECTIVITY_STDTYPEDEFS_HXX
#include "connectivity/StdTypeDefs.hxx"
#endif
namespace connectivity
{
//**************************************************************
//************ Class: ODatabaseMetaDataResultSetMetaData
//**************************************************************
typedef ::cppu::WeakImplHelper1< ::com::sun::star::sdbc::XResultSetMetaData> ODatabaseMetaResultSetMetaData_BASE;
class ODatabaseMetaDataResultSetMetaData : public ODatabaseMetaResultSetMetaData_BASE
{
TIntVector m_vMapping; // when not every column is needed
::std::map<sal_Int32,connectivity::OColumn> m_mColumns;
::std::map<sal_Int32,connectivity::OColumn>::const_iterator m_mColumnsIter;
sal_Int32 m_nColCount;
protected:
virtual ~ODatabaseMetaDataResultSetMetaData();
public:
// ein Konstruktor, der fuer das Returnen des Objektes benoetigt wird:
ODatabaseMetaDataResultSetMetaData( )
: m_nColCount(0)
{
}
/// Avoid ambigous cast error from the compiler.
inline operator ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XResultSetMetaData > () throw()
{ return this; }
virtual sal_Int32 SAL_CALL getColumnCount( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
virtual sal_Bool SAL_CALL isAutoIncrement( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
virtual sal_Bool SAL_CALL isCaseSensitive( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
virtual sal_Bool SAL_CALL isSearchable( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
virtual sal_Bool SAL_CALL isCurrency( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
virtual sal_Int32 SAL_CALL isNullable( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
virtual sal_Bool SAL_CALL isSigned( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
virtual sal_Int32 SAL_CALL getColumnDisplaySize( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
virtual ::rtl::OUString SAL_CALL getColumnLabel( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
virtual ::rtl::OUString SAL_CALL getColumnName( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
virtual ::rtl::OUString SAL_CALL getSchemaName( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
virtual sal_Int32 SAL_CALL getPrecision( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
virtual sal_Int32 SAL_CALL getScale( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
virtual ::rtl::OUString SAL_CALL getTableName( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
virtual ::rtl::OUString SAL_CALL getCatalogName( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
virtual sal_Int32 SAL_CALL getColumnType( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
virtual ::rtl::OUString SAL_CALL getColumnTypeName( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
virtual sal_Bool SAL_CALL isReadOnly( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
virtual sal_Bool SAL_CALL isWritable( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
virtual sal_Bool SAL_CALL isDefinitelyWritable( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
virtual ::rtl::OUString SAL_CALL getColumnServiceName( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
// methods to set the right column mapping
void setColumnPrivilegesMap();
void setColumnsMap();
void setTablesMap();
void setProcedureColumnsMap();
void setPrimaryKeysMap();
void setIndexInfoMap();
void setTablePrivilegesMap();
void setCrossReferenceMap();
void setTypeInfoMap();
void setProceduresMap();
void setTableTypes();
void setBestRowIdentifierMap() { setVersionColumnsMap();}
void setVersionColumnsMap();
void setExportedKeysMap() { setCrossReferenceMap(); }
void setImportedKeysMap() { setCrossReferenceMap(); }
void setCatalogsMap();
void setSchemasMap();
};
}
#endif // _CONNECTIVITY_FILE_ADATABASEMETARESULTSETMETADATA_HXX_
<commit_msg>INTEGRATION: CWS oj14 (1.5.26); FILE MERGED 2006/11/08 08:00:58 oj 1.5.26.1: add missing methods<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: FDatabaseMetaDataResultSetMetaData.hxx,v $
*
* $Revision: 1.6 $
*
* last change: $Author: rt $ $Date: 2007-07-06 06:48:34 $
*
* 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 _CONNECTIVITY_DATABASEMETADATARESULTSETMETADATA_HXX_
#define _CONNECTIVITY_DATABASEMETADATARESULTSETMETADATA_HXX_
#ifndef _COM_SUN_STAR_SDBC_XRESULTSETMETADATA_HPP_
#include <com/sun/star/sdbc/XResultSetMetaData.hpp>
#endif
#ifndef _CPPUHELPER_IMPLBASE1_HXX_
#include <cppuhelper/implbase1.hxx>
#endif
#ifndef _VECTOR_
#include <vector>
#endif
#ifndef _CONNECTIVITY_FDATABASEMETADATARESULTSET_HXX_
#include "FDatabaseMetaDataResultSet.hxx"
#endif
#ifndef _CONNECTIVITY_COLUMN_HXX_
#include "OColumn.hxx"
#endif
#ifndef CONNECTIVITY_STDTYPEDEFS_HXX
#include "connectivity/StdTypeDefs.hxx"
#endif
namespace connectivity
{
//**************************************************************
//************ Class: ODatabaseMetaDataResultSetMetaData
//**************************************************************
typedef ::cppu::WeakImplHelper1< ::com::sun::star::sdbc::XResultSetMetaData> ODatabaseMetaResultSetMetaData_BASE;
class ODatabaseMetaDataResultSetMetaData : public ODatabaseMetaResultSetMetaData_BASE
{
TIntVector m_vMapping; // when not every column is needed
::std::map<sal_Int32,connectivity::OColumn> m_mColumns;
::std::map<sal_Int32,connectivity::OColumn>::const_iterator m_mColumnsIter;
sal_Int32 m_nColCount;
protected:
virtual ~ODatabaseMetaDataResultSetMetaData();
public:
// ein Konstruktor, der fuer das Returnen des Objektes benoetigt wird:
ODatabaseMetaDataResultSetMetaData( )
: m_nColCount(0)
{
}
/// Avoid ambigous cast error from the compiler.
inline operator ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XResultSetMetaData > () throw()
{ return this; }
virtual sal_Int32 SAL_CALL getColumnCount( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
virtual sal_Bool SAL_CALL isAutoIncrement( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
virtual sal_Bool SAL_CALL isCaseSensitive( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
virtual sal_Bool SAL_CALL isSearchable( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
virtual sal_Bool SAL_CALL isCurrency( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
virtual sal_Int32 SAL_CALL isNullable( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
virtual sal_Bool SAL_CALL isSigned( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
virtual sal_Int32 SAL_CALL getColumnDisplaySize( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
virtual ::rtl::OUString SAL_CALL getColumnLabel( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
virtual ::rtl::OUString SAL_CALL getColumnName( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
virtual ::rtl::OUString SAL_CALL getSchemaName( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
virtual sal_Int32 SAL_CALL getPrecision( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
virtual sal_Int32 SAL_CALL getScale( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
virtual ::rtl::OUString SAL_CALL getTableName( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
virtual ::rtl::OUString SAL_CALL getCatalogName( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
virtual sal_Int32 SAL_CALL getColumnType( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
virtual ::rtl::OUString SAL_CALL getColumnTypeName( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
virtual sal_Bool SAL_CALL isReadOnly( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
virtual sal_Bool SAL_CALL isWritable( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
virtual sal_Bool SAL_CALL isDefinitelyWritable( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
virtual ::rtl::OUString SAL_CALL getColumnServiceName( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
// methods to set the right column mapping
void setColumnPrivilegesMap();
void setColumnMap();
void setColumnsMap();
void setTableNameMap();
void setTablesMap();
void setProcedureColumnsMap();
void setPrimaryKeysMap();
void setIndexInfoMap();
void setTablePrivilegesMap();
void setCrossReferenceMap();
void setTypeInfoMap();
void setProcedureNameMap();
void setProceduresMap();
void setTableTypes();
void setBestRowIdentifierMap() { setVersionColumnsMap();}
void setVersionColumnsMap();
void setExportedKeysMap() { setCrossReferenceMap(); }
void setImportedKeysMap() { setCrossReferenceMap(); }
void setCatalogsMap();
void setSchemasMap();
};
}
#endif // _CONNECTIVITY_FILE_ADATABASEMETARESULTSETMETADATA_HXX_
<|endoftext|> |
<commit_before>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "content/browser/accessibility/browser_accessibility_manager.h"
#include "base/logging.h"
#include "content/browser/accessibility/browser_accessibility.h"
#include "content/common/accessibility_messages.h"
using webkit_glue::WebAccessibility;
BrowserAccessibility* BrowserAccessibilityFactory::Create() {
return BrowserAccessibility::Create();
}
// Start child IDs at -1 and decrement each time, because clients use
// child IDs of 1, 2, 3, ... to access the children of an object by
// index, so we use negative IDs to clearly distinguish between indices
// and unique IDs.
// static
int32 BrowserAccessibilityManager::next_child_id_ = -1;
#if (defined(OS_POSIX) && !defined(OS_MACOSX)) || defined(USE_AURA)
// There's no OS-specific implementation of BrowserAccessibilityManager
// on Unix, so just instantiate the base class.
// static
BrowserAccessibilityManager* BrowserAccessibilityManager::Create(
gfx::NativeView parent_view,
const WebAccessibility& src,
BrowserAccessibilityDelegate* delegate,
BrowserAccessibilityFactory* factory) {
return new BrowserAccessibilityManager(
parent_view, src, delegate, factory);
}
#endif
// static
BrowserAccessibilityManager* BrowserAccessibilityManager::CreateEmptyDocument(
gfx::NativeView parent_view,
WebAccessibility::State state,
BrowserAccessibilityDelegate* delegate,
BrowserAccessibilityFactory* factory) {
// Use empty document to process notifications
webkit_glue::WebAccessibility empty_document;
empty_document.id = 0;
empty_document.role = WebAccessibility::ROLE_ROOT_WEB_AREA;
empty_document.state = state;
return BrowserAccessibilityManager::Create(
parent_view, empty_document, delegate, factory);
}
BrowserAccessibilityManager::BrowserAccessibilityManager(
gfx::NativeView parent_view,
const WebAccessibility& src,
BrowserAccessibilityDelegate* delegate,
BrowserAccessibilityFactory* factory)
: parent_view_(parent_view),
delegate_(delegate),
factory_(factory),
focus_(NULL) {
root_ = CreateAccessibilityTree(NULL, src, 0, false);
if (!focus_)
SetFocus(root_, false);
}
// static
int32 BrowserAccessibilityManager::GetNextChildID() {
// Get the next child ID, and wrap around when we get near the end
// of a 32-bit integer range. It's okay to wrap around; we just want
// to avoid it as long as possible because clients may cache the ID of
// an object for a while to determine if they've seen it before.
next_child_id_--;
if (next_child_id_ == -2000000000)
next_child_id_ = -1;
return next_child_id_;
}
BrowserAccessibilityManager::~BrowserAccessibilityManager() {
// Clients could still hold references to some nodes of the tree, so
// calling InternalReleaseReference will make sure that as many nodes
// as possible are released now, and remaining nodes are marked as
// inactive so that calls to any methods on them will fail gracefully.
focus_->InternalReleaseReference(false);
root_->InternalReleaseReference(true);
}
BrowserAccessibility* BrowserAccessibilityManager::GetRoot() {
return root_;
}
BrowserAccessibility* BrowserAccessibilityManager::GetFromChildID(
int32 child_id) {
base::hash_map<int32, BrowserAccessibility*>::iterator iter =
child_id_map_.find(child_id);
if (iter != child_id_map_.end()) {
return iter->second;
} else {
return NULL;
}
}
BrowserAccessibility* BrowserAccessibilityManager::GetFromRendererID(
int32 renderer_id) {
base::hash_map<int32, int32>::iterator iter =
renderer_id_to_child_id_map_.find(renderer_id);
if (iter == renderer_id_to_child_id_map_.end())
return NULL;
int32 child_id = iter->second;
return GetFromChildID(child_id);
}
void BrowserAccessibilityManager::GotFocus() {
if (!focus_)
return;
NotifyAccessibilityEvent(AccessibilityNotificationFocusChanged, focus_);
}
void BrowserAccessibilityManager::Remove(int32 child_id, int32 renderer_id) {
child_id_map_.erase(child_id);
// TODO(ctguil): Investigate if hit. We should never have a newer entry.
DCHECK(renderer_id_to_child_id_map_[renderer_id] == child_id);
// Make sure we don't overwrite a newer entry (see UpdateNode for a possible
// corner case).
if (renderer_id_to_child_id_map_[renderer_id] == child_id)
renderer_id_to_child_id_map_.erase(renderer_id);
}
void BrowserAccessibilityManager::OnAccessibilityNotifications(
const std::vector<AccessibilityHostMsg_NotificationParams>& params) {
for (uint32 index = 0; index < params.size(); index++) {
const AccessibilityHostMsg_NotificationParams& param = params[index];
// Update the tree.
UpdateNode(param.acc_tree, param.includes_children);
// Find the node corresponding to the id that's the target of the
// notification (which may not be the root of the update tree).
base::hash_map<int32, int32>::iterator iter =
renderer_id_to_child_id_map_.find(param.id);
if (iter == renderer_id_to_child_id_map_.end()) {
continue;
}
int32 child_id = iter->second;
BrowserAccessibility* node = GetFromChildID(child_id);
if (!node) {
NOTREACHED();
continue;
}
int notification_type = param.notification_type;
if (notification_type == AccessibilityNotificationFocusChanged) {
SetFocus(node, false);
// Don't send a native focus event if the window itself doesn't
// have focus.
if (delegate_ && !delegate_->HasFocus())
continue;
}
// Send the notification event to the operating system.
NotifyAccessibilityEvent(notification_type, node);
// Set initial focus when a page is loaded.
if (notification_type == AccessibilityNotificationLoadComplete) {
if (!focus_)
SetFocus(root_, false);
if (!delegate_ || delegate_->HasFocus())
NotifyAccessibilityEvent(AccessibilityNotificationFocusChanged, focus_);
}
}
}
gfx::NativeView BrowserAccessibilityManager::GetParentView() {
return parent_view_;
}
BrowserAccessibility* BrowserAccessibilityManager::GetFocus(
BrowserAccessibility* root) {
if (focus_ && (!root || focus_->IsDescendantOf(root)))
return focus_;
return NULL;
}
void BrowserAccessibilityManager::SetFocus(
BrowserAccessibility* node, bool notify) {
if (focus_ != node) {
if (focus_)
focus_->InternalReleaseReference(false);
focus_ = node;
if (focus_)
focus_->InternalAddReference();
}
if (notify && node && delegate_)
delegate_->SetAccessibilityFocus(node->renderer_id());
}
void BrowserAccessibilityManager::DoDefaultAction(
const BrowserAccessibility& node) {
if (delegate_)
delegate_->AccessibilityDoDefaultAction(node.renderer_id());
}
void BrowserAccessibilityManager::ScrollToMakeVisible(
const BrowserAccessibility& node, gfx::Rect subfocus) {
if (delegate_) {
delegate_->AccessibilityScrollToMakeVisible(node.renderer_id(), subfocus);
}
}
void BrowserAccessibilityManager::ScrollToPoint(
const BrowserAccessibility& node, gfx::Point point) {
if (delegate_) {
delegate_->AccessibilityScrollToPoint(node.renderer_id(), point);
}
}
void BrowserAccessibilityManager::SetTextSelection(
const BrowserAccessibility& node, int start_offset, int end_offset) {
if (delegate_) {
delegate_->AccessibilitySetTextSelection(
node.renderer_id(), start_offset, end_offset);
}
}
gfx::Rect BrowserAccessibilityManager::GetViewBounds() {
if (delegate_)
return delegate_->GetViewBounds();
return gfx::Rect();
}
void BrowserAccessibilityManager::UpdateNode(
const WebAccessibility& src,
bool include_children) {
BrowserAccessibility* current = NULL;
// Look for the node to replace. Either we're replacing the whole tree
// (role is ROOT_WEB_AREA) or we look it up based on its renderer ID.
if (src.role == WebAccessibility::ROLE_ROOT_WEB_AREA) {
current = root_;
} else {
base::hash_map<int32, int32>::iterator iter =
renderer_id_to_child_id_map_.find(src.id);
if (iter != renderer_id_to_child_id_map_.end()) {
int32 child_id = iter->second;
current = GetFromChildID(child_id);
}
}
// If we can't find the node to replace, we're out of sync with the
// renderer (this would be a bug).
DCHECK(current);
if (!current)
return;
// If this update is just for a single node (|include_children| is false),
// modify |current| directly and return - no tree changes are needed.
if (!include_children) {
DCHECK_EQ(0U, src.children.size());
current->PreInitialize(
this,
current->parent(),
current->child_id(),
current->index_in_parent(),
src);
current->PostInitialize();
return;
}
BrowserAccessibility* current_parent = current->parent();
int current_index_in_parent = current->index_in_parent();
// Detach all of the nodes in the old tree and get a single flat vector
// of all node pointers.
std::vector<BrowserAccessibility*> old_tree_nodes;
current->DetachTree(&old_tree_nodes);
// Build a new tree, reusing old nodes if possible. Each node that's
// reused will have its reference count incremented by one.
current = CreateAccessibilityTree(
current_parent, src, current_index_in_parent, true);
// Decrement the reference count of all nodes in the old tree, which will
// delete any nodes no longer needed.
for (int i = 0; i < static_cast<int>(old_tree_nodes.size()); i++)
old_tree_nodes[i]->InternalReleaseReference(false);
// If the only reference to the focused node is focus_ itself, then the
// focused node is no longer in the tree, so set the focus to the root.
if (focus_ && focus_->ref_count() == 1) {
SetFocus(root_, false);
if (delegate_ && delegate_->HasFocus())
NotifyAccessibilityEvent(AccessibilityNotificationBlur, focus_);
}
}
BrowserAccessibility* BrowserAccessibilityManager::CreateAccessibilityTree(
BrowserAccessibility* parent,
const WebAccessibility& src,
int index_in_parent,
bool send_show_events) {
BrowserAccessibility* instance = NULL;
int32 child_id = 0;
bool children_can_send_show_events = send_show_events;
base::hash_map<int32, int32>::iterator iter =
renderer_id_to_child_id_map_.find(src.id);
// If a BrowserAccessibility instance for this ID already exists, add a
// new reference to it and retrieve its children vector.
if (iter != renderer_id_to_child_id_map_.end()) {
child_id = iter->second;
instance = GetFromChildID(child_id);
}
// If the node has changed roles, don't reuse a BrowserAccessibility
// object, that could confuse a screen reader.
// TODO(dtseng): Investigate when this gets hit; See crbug.com/93095.
DCHECK(!instance || instance->role() == src.role);
// If we're reusing a node, it should already be detached from a parent
// and any children. If not, that means we have a serious bug somewhere,
// like the same child is reachable from two places in the same tree.
if (instance && (instance->parent() != NULL || instance->child_count() > 0)) {
NOTREACHED();
instance = NULL;
}
if (instance) {
// If we're reusing a node, update its parent and increment its
// reference count.
instance->UpdateParent(parent, index_in_parent);
instance->InternalAddReference();
send_show_events = false;
} else {
// Otherwise, create a new instance.
instance = factory_->Create();
child_id = GetNextChildID();
children_can_send_show_events = false;
}
instance->PreInitialize(this, parent, child_id, index_in_parent, src);
child_id_map_[child_id] = instance;
renderer_id_to_child_id_map_[src.id] = child_id;
if ((src.state >> WebAccessibility::STATE_FOCUSED) & 1)
SetFocus(instance, false);
for (int i = 0; i < static_cast<int>(src.children.size()); ++i) {
BrowserAccessibility* child = CreateAccessibilityTree(
instance, src.children[i], i, children_can_send_show_events);
instance->AddChild(child);
}
if (src.role == WebAccessibility::ROLE_ROOT_WEB_AREA)
root_ = instance;
// Note: the purpose of send_show_events and children_can_send_show_events
// is so that we send a single ObjectShow event for the root of a subtree
// that just appeared for the first time, but not on any descendant of
// that subtree.
if (send_show_events)
NotifyAccessibilityEvent(AccessibilityNotificationObjectShow, instance);
instance->PostInitialize();
return instance;
}
<commit_msg>The browser accessibility manager should transition focus away on receiving the AccessibilityNotificationBlur event.<commit_after>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "content/browser/accessibility/browser_accessibility_manager.h"
#include "base/logging.h"
#include "content/browser/accessibility/browser_accessibility.h"
#include "content/common/accessibility_messages.h"
using webkit_glue::WebAccessibility;
BrowserAccessibility* BrowserAccessibilityFactory::Create() {
return BrowserAccessibility::Create();
}
// Start child IDs at -1 and decrement each time, because clients use
// child IDs of 1, 2, 3, ... to access the children of an object by
// index, so we use negative IDs to clearly distinguish between indices
// and unique IDs.
// static
int32 BrowserAccessibilityManager::next_child_id_ = -1;
#if (defined(OS_POSIX) && !defined(OS_MACOSX)) || defined(USE_AURA)
// There's no OS-specific implementation of BrowserAccessibilityManager
// on Unix, so just instantiate the base class.
// static
BrowserAccessibilityManager* BrowserAccessibilityManager::Create(
gfx::NativeView parent_view,
const WebAccessibility& src,
BrowserAccessibilityDelegate* delegate,
BrowserAccessibilityFactory* factory) {
return new BrowserAccessibilityManager(
parent_view, src, delegate, factory);
}
#endif
// static
BrowserAccessibilityManager* BrowserAccessibilityManager::CreateEmptyDocument(
gfx::NativeView parent_view,
WebAccessibility::State state,
BrowserAccessibilityDelegate* delegate,
BrowserAccessibilityFactory* factory) {
// Use empty document to process notifications
webkit_glue::WebAccessibility empty_document;
empty_document.id = 0;
empty_document.role = WebAccessibility::ROLE_ROOT_WEB_AREA;
empty_document.state = state;
return BrowserAccessibilityManager::Create(
parent_view, empty_document, delegate, factory);
}
BrowserAccessibilityManager::BrowserAccessibilityManager(
gfx::NativeView parent_view,
const WebAccessibility& src,
BrowserAccessibilityDelegate* delegate,
BrowserAccessibilityFactory* factory)
: parent_view_(parent_view),
delegate_(delegate),
factory_(factory),
focus_(NULL) {
root_ = CreateAccessibilityTree(NULL, src, 0, false);
if (!focus_)
SetFocus(root_, false);
}
// static
int32 BrowserAccessibilityManager::GetNextChildID() {
// Get the next child ID, and wrap around when we get near the end
// of a 32-bit integer range. It's okay to wrap around; we just want
// to avoid it as long as possible because clients may cache the ID of
// an object for a while to determine if they've seen it before.
next_child_id_--;
if (next_child_id_ == -2000000000)
next_child_id_ = -1;
return next_child_id_;
}
BrowserAccessibilityManager::~BrowserAccessibilityManager() {
// Clients could still hold references to some nodes of the tree, so
// calling InternalReleaseReference will make sure that as many nodes
// as possible are released now, and remaining nodes are marked as
// inactive so that calls to any methods on them will fail gracefully.
focus_->InternalReleaseReference(false);
root_->InternalReleaseReference(true);
}
BrowserAccessibility* BrowserAccessibilityManager::GetRoot() {
return root_;
}
BrowserAccessibility* BrowserAccessibilityManager::GetFromChildID(
int32 child_id) {
base::hash_map<int32, BrowserAccessibility*>::iterator iter =
child_id_map_.find(child_id);
if (iter != child_id_map_.end()) {
return iter->second;
} else {
return NULL;
}
}
BrowserAccessibility* BrowserAccessibilityManager::GetFromRendererID(
int32 renderer_id) {
base::hash_map<int32, int32>::iterator iter =
renderer_id_to_child_id_map_.find(renderer_id);
if (iter == renderer_id_to_child_id_map_.end())
return NULL;
int32 child_id = iter->second;
return GetFromChildID(child_id);
}
void BrowserAccessibilityManager::GotFocus() {
if (!focus_)
return;
NotifyAccessibilityEvent(AccessibilityNotificationFocusChanged, focus_);
}
void BrowserAccessibilityManager::Remove(int32 child_id, int32 renderer_id) {
child_id_map_.erase(child_id);
// TODO(ctguil): Investigate if hit. We should never have a newer entry.
DCHECK(renderer_id_to_child_id_map_[renderer_id] == child_id);
// Make sure we don't overwrite a newer entry (see UpdateNode for a possible
// corner case).
if (renderer_id_to_child_id_map_[renderer_id] == child_id)
renderer_id_to_child_id_map_.erase(renderer_id);
}
void BrowserAccessibilityManager::OnAccessibilityNotifications(
const std::vector<AccessibilityHostMsg_NotificationParams>& params) {
for (uint32 index = 0; index < params.size(); index++) {
const AccessibilityHostMsg_NotificationParams& param = params[index];
// Update the tree.
UpdateNode(param.acc_tree, param.includes_children);
// Find the node corresponding to the id that's the target of the
// notification (which may not be the root of the update tree).
base::hash_map<int32, int32>::iterator iter =
renderer_id_to_child_id_map_.find(param.id);
if (iter == renderer_id_to_child_id_map_.end()) {
continue;
}
int32 child_id = iter->second;
BrowserAccessibility* node = GetFromChildID(child_id);
if (!node) {
NOTREACHED();
continue;
}
int notification_type = param.notification_type;
if (notification_type == AccessibilityNotificationFocusChanged ||
notification_type == AccessibilityNotificationBlur) {
SetFocus(node, false);
// Don't send a native focus event if the window itself doesn't
// have focus.
if (delegate_ && !delegate_->HasFocus())
continue;
}
// Send the notification event to the operating system.
NotifyAccessibilityEvent(notification_type, node);
// Set initial focus when a page is loaded.
if (notification_type == AccessibilityNotificationLoadComplete) {
if (!focus_)
SetFocus(root_, false);
if (!delegate_ || delegate_->HasFocus())
NotifyAccessibilityEvent(AccessibilityNotificationFocusChanged, focus_);
}
}
}
gfx::NativeView BrowserAccessibilityManager::GetParentView() {
return parent_view_;
}
BrowserAccessibility* BrowserAccessibilityManager::GetFocus(
BrowserAccessibility* root) {
if (focus_ && (!root || focus_->IsDescendantOf(root)))
return focus_;
return NULL;
}
void BrowserAccessibilityManager::SetFocus(
BrowserAccessibility* node, bool notify) {
if (focus_ != node) {
if (focus_)
focus_->InternalReleaseReference(false);
focus_ = node;
if (focus_)
focus_->InternalAddReference();
}
if (notify && node && delegate_)
delegate_->SetAccessibilityFocus(node->renderer_id());
}
void BrowserAccessibilityManager::DoDefaultAction(
const BrowserAccessibility& node) {
if (delegate_)
delegate_->AccessibilityDoDefaultAction(node.renderer_id());
}
void BrowserAccessibilityManager::ScrollToMakeVisible(
const BrowserAccessibility& node, gfx::Rect subfocus) {
if (delegate_) {
delegate_->AccessibilityScrollToMakeVisible(node.renderer_id(), subfocus);
}
}
void BrowserAccessibilityManager::ScrollToPoint(
const BrowserAccessibility& node, gfx::Point point) {
if (delegate_) {
delegate_->AccessibilityScrollToPoint(node.renderer_id(), point);
}
}
void BrowserAccessibilityManager::SetTextSelection(
const BrowserAccessibility& node, int start_offset, int end_offset) {
if (delegate_) {
delegate_->AccessibilitySetTextSelection(
node.renderer_id(), start_offset, end_offset);
}
}
gfx::Rect BrowserAccessibilityManager::GetViewBounds() {
if (delegate_)
return delegate_->GetViewBounds();
return gfx::Rect();
}
void BrowserAccessibilityManager::UpdateNode(
const WebAccessibility& src,
bool include_children) {
BrowserAccessibility* current = NULL;
// Look for the node to replace. Either we're replacing the whole tree
// (role is ROOT_WEB_AREA) or we look it up based on its renderer ID.
if (src.role == WebAccessibility::ROLE_ROOT_WEB_AREA) {
current = root_;
} else {
base::hash_map<int32, int32>::iterator iter =
renderer_id_to_child_id_map_.find(src.id);
if (iter != renderer_id_to_child_id_map_.end()) {
int32 child_id = iter->second;
current = GetFromChildID(child_id);
}
}
// If we can't find the node to replace, we're out of sync with the
// renderer (this would be a bug).
DCHECK(current);
if (!current)
return;
// If this update is just for a single node (|include_children| is false),
// modify |current| directly and return - no tree changes are needed.
if (!include_children) {
DCHECK_EQ(0U, src.children.size());
current->PreInitialize(
this,
current->parent(),
current->child_id(),
current->index_in_parent(),
src);
current->PostInitialize();
return;
}
BrowserAccessibility* current_parent = current->parent();
int current_index_in_parent = current->index_in_parent();
// Detach all of the nodes in the old tree and get a single flat vector
// of all node pointers.
std::vector<BrowserAccessibility*> old_tree_nodes;
current->DetachTree(&old_tree_nodes);
// Build a new tree, reusing old nodes if possible. Each node that's
// reused will have its reference count incremented by one.
current = CreateAccessibilityTree(
current_parent, src, current_index_in_parent, true);
// Decrement the reference count of all nodes in the old tree, which will
// delete any nodes no longer needed.
for (int i = 0; i < static_cast<int>(old_tree_nodes.size()); i++)
old_tree_nodes[i]->InternalReleaseReference(false);
// If the only reference to the focused node is focus_ itself, then the
// focused node is no longer in the tree, so set the focus to the root.
if (focus_ && focus_->ref_count() == 1) {
SetFocus(root_, false);
if (delegate_ && delegate_->HasFocus())
NotifyAccessibilityEvent(AccessibilityNotificationBlur, focus_);
}
}
BrowserAccessibility* BrowserAccessibilityManager::CreateAccessibilityTree(
BrowserAccessibility* parent,
const WebAccessibility& src,
int index_in_parent,
bool send_show_events) {
BrowserAccessibility* instance = NULL;
int32 child_id = 0;
bool children_can_send_show_events = send_show_events;
base::hash_map<int32, int32>::iterator iter =
renderer_id_to_child_id_map_.find(src.id);
// If a BrowserAccessibility instance for this ID already exists, add a
// new reference to it and retrieve its children vector.
if (iter != renderer_id_to_child_id_map_.end()) {
child_id = iter->second;
instance = GetFromChildID(child_id);
}
// If the node has changed roles, don't reuse a BrowserAccessibility
// object, that could confuse a screen reader.
// TODO(dtseng): Investigate when this gets hit; See crbug.com/93095.
DCHECK(!instance || instance->role() == src.role);
// If we're reusing a node, it should already be detached from a parent
// and any children. If not, that means we have a serious bug somewhere,
// like the same child is reachable from two places in the same tree.
if (instance && (instance->parent() != NULL || instance->child_count() > 0)) {
NOTREACHED();
instance = NULL;
}
if (instance) {
// If we're reusing a node, update its parent and increment its
// reference count.
instance->UpdateParent(parent, index_in_parent);
instance->InternalAddReference();
send_show_events = false;
} else {
// Otherwise, create a new instance.
instance = factory_->Create();
child_id = GetNextChildID();
children_can_send_show_events = false;
}
instance->PreInitialize(this, parent, child_id, index_in_parent, src);
child_id_map_[child_id] = instance;
renderer_id_to_child_id_map_[src.id] = child_id;
if ((src.state >> WebAccessibility::STATE_FOCUSED) & 1)
SetFocus(instance, false);
for (int i = 0; i < static_cast<int>(src.children.size()); ++i) {
BrowserAccessibility* child = CreateAccessibilityTree(
instance, src.children[i], i, children_can_send_show_events);
instance->AddChild(child);
}
if (src.role == WebAccessibility::ROLE_ROOT_WEB_AREA)
root_ = instance;
// Note: the purpose of send_show_events and children_can_send_show_events
// is so that we send a single ObjectShow event for the root of a subtree
// that just appeared for the first time, but not on any descendant of
// that subtree.
if (send_show_events)
NotifyAccessibilityEvent(AccessibilityNotificationObjectShow, instance);
instance->PostInitialize();
return instance;
}
<|endoftext|> |
<commit_before>#include "viewer/primitives/simple_geometry.hh"
#include "viewer/window_3d.hh"
#include "estimation/jet/jet_filter.hh"
#include "estimation/jet/jet_pose_opt.hh"
#include "estimation/jet/jet_rk4.hh"
#include "util/environment.hh"
#include "eigen.hh"
#include "sophus.hh"
namespace estimation {
namespace jet_filter {
namespace {
Parameters mock_parameters() {
Parameters p;
const jcc::Vec3 g(0.0, 0.0, -1.3);
p.g_world = g;
// const jcc::Vec3 t(0.1, 0.5, 0.1);
const jcc::Vec3 t(0.0, 0.1, 0.25);
// const jcc::Vec3 t = jcc::Vec3::Zero();
const SO3 r_vehicle_from_sensor = SO3::exp(jcc::Vec3(0.0, 0.0, 0.0));
const SE3 sensor_from_body(r_vehicle_from_sensor, t);
p.T_imu_from_vehicle = sensor_from_body;
return p;
}
void setup() {
const auto view = viewer::get_window3d("Mr. Filter, filters");
view->set_target_from_world(
SE3(SO3::exp(Eigen::Vector3d(-3.1415 * 0.5, 0.0, 0.0)), Eigen::Vector3d::Zero()));
view->set_continue_time_ms(10);
const auto background = view->add_primitive<viewer::SimpleGeometry>();
const geometry::shapes::Plane ground{jcc::Vec3::UnitZ(), 0.0};
background->add_plane({ground});
background->flip();
}
void draw_states(viewer::SimpleGeometry& geo,
const std::vector<State>& states,
bool truth) {
const int n_states = static_cast<int>(states.size());
for (int k = 0; k < n_states; ++k) {
auto& state = states.at(k);
const SE3 T_world_from_body = state.T_body_from_world.inverse();
if (truth) {
geo.add_axes({T_world_from_body, 0.1});
} else {
geo.add_axes({T_world_from_body, 0.05, 2.0, true});
if (k < n_states - 1) {
const auto& next_state = states.at(k + 1);
const SE3 T_world_from_body_next = next_state.T_body_from_world.inverse();
geo.add_line(
{T_world_from_body.translation(), T_world_from_body_next.translation()});
}
}
}
}
void print_state(const State& x) {
std::cout << "\teps_dot : " << x.eps_dot.transpose() << std::endl;
std::cout << "\teps_ddot : " << x.eps_ddot.transpose() << std::endl;
std::cout << "\taccel_bias: " << x.accel_bias.transpose() << std::endl;
std::cout << "\tgyro_bias : " << x.gyro_bias.transpose() << std::endl;
// const auto res = observe_accel(xp.x, true_params);
// std::cout << "\tExpected Measurement: " << res.transpose() << std::endl;
}
template <int dim, int row, int mat_size>
void set_diag_to_value(MatNd<mat_size, mat_size>& mat, double value) {
mat.template block<dim, dim>(row, row) = (MatNd<dim, dim>::Identity() * value);
}
} // namespace
class JetOptimizer {
public:
JetOptimizer() {
MatNd<AccelMeasurement::DIM, AccelMeasurement::DIM> accel_cov;
accel_cov.setZero();
set_diag_to_value<AccelMeasurementDelta::observed_acceleration_error_dim,
AccelMeasurementDelta::observed_acceleration_error_ind>(accel_cov,
0.01);
MatNd<FiducialMeasurement::DIM, FiducialMeasurement::DIM> fiducial_cov;
fiducial_cov.block<3, 3>(0, 0) = MatNd<3, 3>::Identity() * 0.001;
fiducial_cov.block<3, 3>(3, 3) = MatNd<3, 3>::Identity() * 0.0001;
MatNd<State::DIM, State::DIM> state_cov;
state_cov.setZero();
set_diag_to_value<StateDelta::accel_bias_error_dim, StateDelta::accel_bias_error_ind>(
state_cov, 0.0001);
set_diag_to_value<StateDelta::gyro_bias_error_dim, StateDelta::gyro_bias_error_ind>(
state_cov, 0.0001);
set_diag_to_value<StateDelta::eps_dot_error_dim, StateDelta::eps_dot_error_ind>(
state_cov, 0.1);
set_diag_to_value<StateDelta::eps_ddot_error_dim, StateDelta::eps_ddot_error_ind>(
state_cov, 0.1);
constexpr int T_error_dim = StateDelta::T_body_from_world_error_log_dim;
constexpr int T_error_ind = StateDelta::T_body_from_world_error_log_ind;
set_diag_to_value<T_error_dim, T_error_ind>(state_cov, 0.001);
imu_id_ = pose_opt_.add_error_model<AccelMeasurement>(accel_error_model, accel_cov);
fiducial_id_ = pose_opt_.add_error_model<FiducialMeasurement>(fiducial_error_model,
fiducial_cov);
pose_opt_.set_dynamics_cov(state_cov);
}
void measure_imu(const AccelMeasurement& meas, const TimePoint& t) {
pose_opt_.add_measurement(meas, t, imu_id_);
}
void measure_fiducial(const FiducialMeasurement& meas, const TimePoint& t) {
pose_opt_.add_measurement(meas, t, fiducial_id_);
}
JetPoseOptimizer::Solution solve(const std::vector<State> x, const Parameters& p) {
const auto view = viewer::get_window3d("Mr. Filter, filters");
const auto geo = view->add_primitive<viewer::SimpleGeometry>();
const auto visitor = [&view, &geo](const JetPoseOptimizer::Solution& soln) {
geo->clear();
draw_states(*geo, soln.x, false);
geo->flip();
std::cout << "\tOptimized g: " << soln.p.g_world.transpose() << std::endl;
std::cout << "\tOptimized T_imu_from_vehicle: "
<< soln.p.T_imu_from_vehicle.translation().transpose() << "; "
<< soln.p.T_imu_from_vehicle.so3().log().transpose() << std::endl;
view->spin_until_step();
};
return pose_opt_.solve({x, p}, visitor);
}
private:
JetPoseOptimizer pose_opt_{rk4_integrate};
int imu_id_ = -1;
int fiducial_id_ = -1;
};
void run_filter() {
const Parameters true_params = mock_parameters();
JetOptimizer jet_opt;
FilterState<State> xp0;
xp0.P.setIdentity();
xp0.x.eps_dot[0] = 1.0;
xp0.x.eps_dot[4] = -0.6;
xp0.x.eps_dot[5] = -0.2;
xp0.x.eps_ddot[1] = 0.01;
xp0.x.eps_ddot[5] = 0.01;
xp0.time_of_validity = {};
State true_x = xp0.x;
true_x.eps_dot[4] = 0.1;
JetFilter jf(xp0);
// AccelMeasurement imu_meas;
// imu_meas.observed_acceleration[0] = 2.0;
setup();
const auto view = viewer::get_window3d("Mr. Filter, filters");
const auto obs_geo = view->add_primitive<viewer::SimpleGeometry>();
constexpr double sphere_size_m = 0.05;
std::vector<State> ground_truth;
std::vector<State> est_states;
TimePoint start_time = {};
constexpr auto dt = to_duration(0.1);
constexpr int NUM_SIM_STEPS = 1000;
TimePoint current_time = start_time;
for (int k = 0; k < NUM_SIM_STEPS; ++k) {
if (k > 75 && k < 130) {
true_x.eps_ddot[0] = 0.1;
true_x.eps_ddot[1] = -0.02;
true_x.eps_ddot[2] = -0.03;
true_x.eps_ddot[3] = 0.1;
true_x.eps_ddot[4] = 0.05;
true_x.eps_ddot[5] = -0.01;
} else if (k > 130) {
true_x.eps_ddot.setZero();
}
//
// Accelerometer Observation
//
// if ((k % 10 == 0) && k > 75) {
if (true) {
ground_truth.push_back(true_x);
const AccelMeasurement imu_meas =observe_accel(true_x, true_params;
std::cout << "Accel: " << imu_meas.observed_acceleration.transpose() << std::endl;
jf.measure_imu(imu_meas, current_time);
jet_opt.measure_imu(imu_meas, current_time);
jf.free_run();
est_states.push_back(jf.state().x);
assert(jf.state().time_of_validity == current_time);
const jcc::Vec4 accel_color(0.0, 0.7, 0.7, 0.8);
obs_geo->add_sphere({jf.state().x.T_body_from_world.inverse().translation(),
sphere_size_m, accel_color});
const SE3 world_from_body = jf.state().x.T_body_from_world.inverse();
const jcc::Vec3 observed_accel_body_frame =
(world_from_body.so3() * true_params.T_imu_from_vehicle.so3().inverse() *
imu_meas.observed_acceleration);
obs_geo->add_line(
{world_from_body.translation(),
world_from_body.translation() + (0.25 * observed_accel_body_frame),
accel_color});
}
//
// Gyro Observation
//
if (false) {
ground_truth.push_back(true_x);
const AccelMeasurement imu_meas = observe_accel(true_x, true_params);
std::cout << "Accel: " << imu_meas.observed_acceleration.transpose() << std::endl;
jf.measure_imu(imu_meas, current_time);
jet_opt.measure_imu(imu_meas, current_time);
jf.free_run();
est_states.push_back(jf.state().x);
assert(jf.state().time_of_validity == current_time);
const jcc::Vec4 accel_color(0.0, 0.7, 0.7, 0.8);
obs_geo->add_sphere({jf.state().x.T_body_from_world.inverse().translation(),
sphere_size_m, accel_color});
const SE3 world_from_body = jf.state().x.T_body_from_world.inverse();
const jcc::Vec3 observed_accel_body_frame =
(world_from_body.so3() * true_params.T_imu_from_vehicle.so3().inverse() *
imu_meas.observed_acceleration);
obs_geo->add_line(
{world_from_body.translation(),
world_from_body.translation() + (0.25 * observed_accel_body_frame),
accel_color});
}
//
// Fiducial Measurement
//
{
constexpr auto dt2 = to_duration(0.05);
true_x = rk4_integrate(true_x, true_params, to_seconds(dt2));
current_time += dt2;
ground_truth.push_back(true_x);
const FiducialMeasurement fiducial_meas = observe_fiducial(true_x, true_params);
jf.measure_fiducial(fiducial_meas, current_time);
jet_opt.measure_fiducial(fiducial_meas, current_time);
jf.free_run();
est_states.push_back(jf.state().x);
assert(jf.state().time_of_validity == current_time);
obs_geo->add_sphere({jf.state().x.T_body_from_world.inverse().translation(),
sphere_size_m, jcc::Vec4(1.0, 0.0, 0.0, 1.0)});
}
//
// Printout
//
{
const auto xp = jf.state();
std::cout << "k: " << k << std::endl;
print_state(xp.x);
}
true_x = rk4_integrate(true_x, true_params, to_seconds(dt));
current_time += dt;
}
// Do the optimization
obs_geo->flip();
const auto geo = view->add_primitive<viewer::SimpleGeometry>();
draw_states(*geo, ground_truth, true);
geo->flip();
// const std::vector<State> crap_init(est_states.size(), xp0.x);
// const auto solution = jet_opt.solve(crap_init, jf.parameters());
const auto solution = jet_opt.solve(est_states, jf.parameters());
// const auto solution = jet_opt.solve(ground_truth, jf.parameters());
for (std::size_t k = 0; k < solution.x.size(); ++k) {
const auto& state = solution.x.at(k);
std::cout << "----- " << k << std::endl;
print_state(state);
std::cout << "\\\\\\\\\\\\" << std::endl;
print_state(ground_truth.at(k));
}
std::cout << "Optimized g: " << solution.p.g_world.transpose() << std::endl;
std::cout << "Optimized T_imu_from_vehicle: "
<< solution.p.T_imu_from_vehicle.translation().transpose() << "; "
<< solution.p.T_imu_from_vehicle.so3().log().transpose() << std::endl;
draw_states(*geo, solution.x, false);
view->spin_until_step();
}
} // namespace jet_filter
} // namespace estimation
int main() {
// estimation::jet_filter::go();
estimation::jet_filter::run_filter();
}<commit_msg>Stopping point for filter demo -- working<commit_after>#include "viewer/primitives/simple_geometry.hh"
#include "viewer/window_3d.hh"
#include "estimation/jet/jet_filter.hh"
#include "estimation/jet/jet_pose_opt.hh"
#include "estimation/jet/jet_rk4.hh"
#include "util/environment.hh"
#include "eigen.hh"
#include "sophus.hh"
namespace estimation {
namespace jet_filter {
namespace {
Parameters mock_parameters() {
Parameters p;
const jcc::Vec3 g(0.0, 0.0, -1.3);
p.g_world = g;
// const jcc::Vec3 t(0.1, 0.5, 0.1);
const jcc::Vec3 t(0.0, 0.1, 0.25);
// const jcc::Vec3 t = jcc::Vec3::Zero();
const SO3 r_vehicle_from_sensor = SO3::exp(jcc::Vec3(0.0, 0.0, 0.0));
const SE3 sensor_from_body(r_vehicle_from_sensor, t);
p.T_imu_from_vehicle = sensor_from_body;
return p;
}
void setup() {
const auto view = viewer::get_window3d("Mr. Filter, filters");
view->set_target_from_world(
SE3(SO3::exp(Eigen::Vector3d(-3.1415 * 0.5, 0.0, 0.0)), Eigen::Vector3d::Zero()));
view->set_continue_time_ms(10);
const auto background = view->add_primitive<viewer::SimpleGeometry>();
const geometry::shapes::Plane ground{jcc::Vec3::UnitZ(), 0.0};
background->add_plane({ground});
background->flip();
}
void draw_states(viewer::SimpleGeometry& geo,
const std::vector<State>& states,
bool truth) {
const int n_states = static_cast<int>(states.size());
for (int k = 0; k < n_states; ++k) {
auto& state = states.at(k);
const SE3 T_world_from_body = state.T_body_from_world.inverse();
if (truth) {
geo.add_axes({T_world_from_body, 0.1});
} else {
geo.add_axes({T_world_from_body, 0.05, 2.0, true});
if (k < n_states - 1) {
const auto& next_state = states.at(k + 1);
const SE3 T_world_from_body_next = next_state.T_body_from_world.inverse();
geo.add_line(
{T_world_from_body.translation(), T_world_from_body_next.translation()});
}
}
}
}
void print_state(const State& x) {
std::cout << "\teps_dot : " << x.eps_dot.transpose() << std::endl;
std::cout << "\teps_ddot : " << x.eps_ddot.transpose() << std::endl;
std::cout << "\taccel_bias: " << x.accel_bias.transpose() << std::endl;
std::cout << "\tgyro_bias : " << x.gyro_bias.transpose() << std::endl;
// const auto res = observe_accel(xp.x, true_params);
// std::cout << "\tExpected Measurement: " << res.transpose() << std::endl;
}
template <int dim, int row, int mat_size>
void set_diag_to_value(MatNd<mat_size, mat_size>& mat, double value) {
mat.template block<dim, dim>(row, row) = (MatNd<dim, dim>::Identity() * value);
}
} // namespace
class JetOptimizer {
public:
JetOptimizer() {
MatNd<AccelMeasurement::DIM, AccelMeasurement::DIM> accel_cov;
accel_cov.setZero();
{
set_diag_to_value<AccelMeasurementDelta::observed_acceleration_error_dim,
AccelMeasurementDelta::observed_acceleration_error_ind>(accel_cov,
0.01);
}
MatNd<FiducialMeasurement::DIM, FiducialMeasurement::DIM> fiducial_cov;
{
fiducial_cov.block<3, 3>(0, 0) = MatNd<3, 3>::Identity() * 0.001;
fiducial_cov.block<3, 3>(3, 3) = MatNd<3, 3>::Identity() * 0.0001;
}
MatNd<State::DIM, State::DIM> state_cov;
{
state_cov.setZero();
set_diag_to_value<StateDelta::accel_bias_error_dim,
StateDelta::accel_bias_error_ind>(state_cov, 0.0001);
set_diag_to_value<StateDelta::gyro_bias_error_dim, StateDelta::gyro_bias_error_ind>(
state_cov, 0.0001);
set_diag_to_value<StateDelta::eps_dot_error_dim, StateDelta::eps_dot_error_ind>(
state_cov, 0.1);
set_diag_to_value<StateDelta::eps_ddot_error_dim, StateDelta::eps_ddot_error_ind>(
state_cov, 0.1);
constexpr int T_error_dim = StateDelta::T_body_from_world_error_log_dim;
constexpr int T_error_ind = StateDelta::T_body_from_world_error_log_ind;
set_diag_to_value<T_error_dim, T_error_ind>(state_cov, 0.001);
}
const MatNd<GyroMeasurement::DIM, GyroMeasurement::DIM> gyro_cov = accel_cov;
imu_id_ =
pose_opt_.add_error_model<AccelMeasurement>(observe_accel_error_model, accel_cov);
gyro_id_ =
pose_opt_.add_error_model<GyroMeasurement>(observe_gyro_error_model, gyro_cov);
fiducial_id_ = pose_opt_.add_error_model<FiducialMeasurement>(fiducial_error_model,
fiducial_cov);
pose_opt_.set_dynamics_cov(state_cov);
}
void measure_imu(const AccelMeasurement& meas, const TimePoint& t) {
pose_opt_.add_measurement(meas, t, imu_id_);
}
void measure_fiducial(const FiducialMeasurement& meas, const TimePoint& t) {
pose_opt_.add_measurement(meas, t, fiducial_id_);
}
void measure_gyro(const GyroMeasurement& meas, const TimePoint& t) {
pose_opt_.add_measurement(meas, t, gyro_id_);
}
JetPoseOptimizer::Solution solve(const std::vector<State> x, const Parameters& p) {
const auto view = viewer::get_window3d("Mr. Filter, filters");
const auto geo = view->add_primitive<viewer::SimpleGeometry>();
const auto visitor = [&view, &geo](const JetPoseOptimizer::Solution& soln) {
geo->clear();
draw_states(*geo, soln.x, false);
geo->flip();
std::cout << "\tOptimized g: " << soln.p.g_world.transpose() << std::endl;
std::cout << "\tOptimized T_imu_from_vehicle: "
<< soln.p.T_imu_from_vehicle.translation().transpose() << "; "
<< soln.p.T_imu_from_vehicle.so3().log().transpose() << std::endl;
view->spin_until_step();
};
return pose_opt_.solve({x, p}, visitor);
}
private:
JetPoseOptimizer pose_opt_{rk4_integrate};
int imu_id_ = -1;
int gyro_id_ = -1;
int fiducial_id_ = -1;
};
void run_filter() {
const Parameters true_params = mock_parameters();
JetOptimizer jet_opt;
FilterState<State> xp0;
{
MatNd<State::DIM, State::DIM> state_cov;
state_cov.setZero();
set_diag_to_value<StateDelta::accel_bias_error_dim, StateDelta::accel_bias_error_ind>(
state_cov, 0.0001);
set_diag_to_value<StateDelta::gyro_bias_error_dim, StateDelta::gyro_bias_error_ind>(
state_cov, 0.0001);
set_diag_to_value<StateDelta::eps_dot_error_dim, StateDelta::eps_dot_error_ind>(
state_cov, 0.01);
set_diag_to_value<StateDelta::eps_ddot_error_dim, StateDelta::eps_ddot_error_ind>(
state_cov, 0.1);
xp0.P = state_cov;
}
// xp0.x.eps_dot[0] = 1.0;
// xp0.x.eps_dot[4] = -0.6;
// xp0.x.eps_dot[5] = -0.2;
// xp0.x.eps_ddot[1] = 0.01;
// xp0.x.eps_ddot[5] = 0.01;
// xp0.x.eps_ddot[3] = 0.02;
xp0.time_of_validity = {};
State true_x = xp0.x;
true_x.eps_dot[4] = 0.1;
true_x.eps_dot[0] = 1.0;
true_x.eps_dot[4] = -0.6;
true_x.eps_dot[5] = -0.2;
true_x.eps_ddot[1] = 0.01;
true_x.eps_ddot[5] = 0.01;
true_x.eps_ddot[3] = 0.02;
JetFilter jf(xp0);
// AccelMeasurement imu_meas;
// imu_meas.observed_acceleration[0] = 2.0;
setup();
const auto view = viewer::get_window3d("Mr. Filter, filters");
const auto obs_geo = view->add_primitive<viewer::SimpleGeometry>();
constexpr double sphere_size_m = 0.05;
std::vector<State> ground_truth;
std::vector<State> est_states;
TimePoint start_time = {};
constexpr auto dt = to_duration(0.1);
constexpr int NUM_SIM_STEPS = 300;
TimePoint current_time = start_time;
for (int k = 0; k < NUM_SIM_STEPS; ++k) {
if (k > 75 && k < 130) {
// true_x.eps_ddot[0] = 0.1;
// true_x.eps_ddot[1] = -0.02;
// true_x.eps_ddot[2] = -0.03;
// true_x.eps_ddot[3] = 0.1;
// true_x.eps_ddot[4] = 0.05;
// true_x.eps_ddot[5] = -0.01;
} else if (k > 130) {
// true_x.eps_ddot.setZero();
}
//
// Accelerometer Observation
//
// if ((k % 10 == 0) && k > 75) {
if (true) {
ground_truth.push_back(true_x);
const AccelMeasurement imu_meas = observe_accel(true_x, true_params);
std::cout << "Accel: " << imu_meas.observed_acceleration.transpose() << std::endl;
jf.measure_imu(imu_meas, current_time);
jet_opt.measure_imu(imu_meas, current_time);
jf.free_run();
est_states.push_back(jf.state().x);
assert(jf.state().time_of_validity == current_time);
const jcc::Vec4 accel_color(0.0, 0.7, 0.7, 0.8);
obs_geo->add_sphere({jf.state().x.T_body_from_world.inverse().translation(),
sphere_size_m, accel_color});
const SE3 world_from_body = jf.state().x.T_body_from_world.inverse();
const jcc::Vec3 observed_accel_world_frame =
(world_from_body.so3() * true_params.T_imu_from_vehicle.so3().inverse() *
imu_meas.observed_acceleration);
obs_geo->add_line(
{world_from_body.translation(),
world_from_body.translation() + (0.25 * observed_accel_world_frame),
accel_color});
}
//
// Gyro Observation
//
if (true) {
constexpr auto dt2 = to_duration(0.01);
true_x = rk4_integrate(true_x, true_params, to_seconds(dt2));
current_time += dt2;
ground_truth.push_back(true_x);
const GyroMeasurement gyro_meas = observe_gyro(true_x, true_params);
std::cout << "Gyro: " << gyro_meas.observed_w.transpose() << std::endl;
jf.measure_gyro(gyro_meas, current_time);
jet_opt.measure_gyro(gyro_meas, current_time);
jf.free_run();
est_states.push_back(jf.state().x);
assert(jf.state().time_of_validity == current_time);
const jcc::Vec4 gyro_color(0.7, 0.1, 0.7, 0.8);
obs_geo->add_sphere({jf.state().x.T_body_from_world.inverse().translation(),
sphere_size_m, gyro_color});
const SE3 world_from_body = jf.state().x.T_body_from_world.inverse();
const jcc::Vec3 observed_w_world_frame =
(world_from_body.so3() * true_params.T_imu_from_vehicle.so3().inverse() *
gyro_meas.observed_w);
obs_geo->add_line({world_from_body.translation(),
world_from_body.translation() + (0.25 * observed_w_world_frame),
gyro_color});
}
//
// Fiducial Measurement
//
{
constexpr auto dt2 = to_duration(0.05);
true_x = rk4_integrate(true_x, true_params, to_seconds(dt2));
current_time += dt2;
ground_truth.push_back(true_x);
const FiducialMeasurement fiducial_meas = observe_fiducial(true_x, true_params);
jf.measure_fiducial(fiducial_meas, current_time);
jet_opt.measure_fiducial(fiducial_meas, current_time);
jf.free_run();
est_states.push_back(jf.state().x);
assert(jf.state().time_of_validity == current_time);
obs_geo->add_sphere({jf.state().x.T_body_from_world.inverse().translation(),
sphere_size_m, jcc::Vec4(1.0, 0.0, 0.0, 1.0)});
}
//
// Printout
//
{
const auto xp = jf.state();
std::cout << "k: " << k << std::endl;
print_state(xp.x);
}
true_x = rk4_integrate(true_x, true_params, to_seconds(dt));
current_time += dt;
}
// Do the optimization
obs_geo->flip();
const auto geo = view->add_primitive<viewer::SimpleGeometry>();
draw_states(*geo, ground_truth, true);
geo->flip();
// const std::vector<State> crap_init(est_states.size(), xp0.x);
// const auto solution = jet_opt.solve(crap_init, jf.parameters());
const auto solution = jet_opt.solve(est_states, jf.parameters());
// const auto solution = jet_opt.solve(ground_truth, jf.parameters());
for (std::size_t k = 0; k < solution.x.size(); ++k) {
const auto& state = solution.x.at(k);
std::cout << "----- " << k << std::endl;
print_state(state);
std::cout << "\\\\\\\\\\\\" << std::endl;
print_state(ground_truth.at(k));
}
std::cout << "Optimized g: " << solution.p.g_world.transpose() << std::endl;
std::cout << "Optimized T_imu_from_vehicle: "
<< solution.p.T_imu_from_vehicle.translation().transpose() << "; "
<< solution.p.T_imu_from_vehicle.so3().log().transpose() << std::endl;
draw_states(*geo, solution.x, false);
view->spin_until_step();
}
} // namespace jet_filter
} // namespace estimation
int main() {
// estimation::jet_filter::go();
estimation::jet_filter::run_filter();
}<|endoftext|> |
<commit_before>#include <cnoid/Plugin>
#include <boost/bind.hpp>
using namespace cnoid;
using namespace boost;
class ProtoPlugin : public Plugin
{
public:
ProtoPlugin() : Plugin("ProtoPlugin")
{
}
/* virtual functions can be overridden by child functions */
virtual bool initialize()
{
// make things happen
}
private:
void onProtoTriggered()
{
// make things binded to ProtoPlugin() happen
// must return true (good way to test functionality)
}
};
/* generate associated .cnoid file ( i think ) */
CNOID_IMPLEMENT_PLUGIN_ENTRY(ProtoPlugin)
<commit_msg>Update ProtoPlugin.cpp<commit_after>#include <cnoid/Plugin>
#include <boost/bind.hpp>
using namespace cnoid;
using namespace boost;
class ProtoPlugin : public Plugin
{
public:
ProtoPlugin() : Plugin("ProtoPlugin")
{
}
/* virtual functions can be overridden by child functions */
virtual bool initialize()
{
// make things happen
}
private:
void onProtoTriggered()
{
// make things binded to ProtoPlugin() happen
}
};
/* generate associated .cnoid file ( i think ) */
CNOID_IMPLEMENT_PLUGIN_ENTRY(ProtoPlugin)
<|endoftext|> |
<commit_before>#include <memory>
#include <archive.h>
#include <archive_entry.h>
#include "main.h"
static bool
care_about(struct archive_entry *entry)
{
mode_t mode = archive_entry_mode(entry);
#if 0
if (AE_IFLNK == (mode & AE_IFLNK)) {
// ignoring symlinks for now
return false;
}
#endif
if (AE_IFREG != (mode & AE_IFREG)) {
// not a regular file
return false;
}
if (!archive_entry_size_is_set(entry)) {
// ignore files which have no size...
return false;
}
return true;
}
// because isspace(3) is locale dependent
static bool
c_isspace(const char c) {
return (c == ' ' || c == '\t' ||
c == '\n' || c == '\r' ||
c == '\v' || c == '\f');
}
static bool
ends_word(const char c) {
return c_isspace(c) || c == '=';
}
// NOTE:
// Judgding from pacman/libalpm source code this function
// is way less strict about the formatting, as we skip whitespace
// between every word, whereas pacman matches /^(\w+) = (.*)$/ exactly.
static bool
read_info(Package *pkg, struct archive *tar, size_t size)
{
std::vector<char> data(size);
ssize_t rc = archive_read_data(tar, &data[0], size);
if ((size_t)rc != size) {
log(Error, "failed to read .PKGINFO");
return false;
}
std::string str(&data[0], data.size());
size_t pos = 0;
auto skipwhite = [&]() {
while (pos < size && c_isspace(str[pos]))
++pos;
};
auto skipline = [&]() {
while (pos < size && str[pos] != '\n')
++pos;
};
auto getvalue = [&](const char *entryname, std::string &out) -> bool {
skipwhite();
if (str[pos] != '=') {
log(Error, "Error in .PKGINFO");
return false;
}
++pos;
skipwhite();
if (pos >= size) {
log(Error, "invalid %s entry in .PKGINFO", entryname);
return false;
}
size_t to = str.find_first_of(" \n\r\t", pos);
out = str.substr(pos, to-pos);
skipline();
return true;
};
auto isentry = [&](const char *what, size_t len) -> bool {
if (size-pos > len &&
str.compare(pos, len, what) == 0 &&
ends_word(str[pos+len]))
{
pos += len;
return true;
}
return false;
};
std::string es;
while (pos < size) {
skipwhite();
if (isentry("pkgname", sizeof("pkgname")-1)) {
if (!getvalue("pkgname", pkg->name))
return false;
continue;
}
if (isentry("pkgver", sizeof("pkgver")-1)) {
if (!getvalue("pkgver", pkg->version))
return false;
continue;
}
if (!opt_package_depends) {
skipline();
continue;
}
if (isentry("depend", sizeof("depend")-1)) {
if (!getvalue("depend", es))
return false;
pkg->depends.push_back(es);
continue;
}
if (isentry("optdepend", sizeof("optdepend")-1)) {
if (!getvalue("optdepend", es))
return false;
es.erase(es.find_first_of(':'));
if (es.length())
pkg->optdepends.push_back(es);
continue;
}
skipline();
}
return true;
}
static inline std::tuple<std::string, std::string>
splitpath(const std::string& path)
{
size_t slash = path.find_last_of('/');
if (slash == std::string::npos)
return std::make_tuple("/", path);
if (path[0] != '/')
return std::make_tuple(std::move(std::string("/") + path.substr(0, slash)), path.substr(slash+1));
return std::make_tuple(path.substr(0, slash), path.substr(slash+1));
}
static bool
read_object(Package *pkg, struct archive *tar, std::string &&filename, size_t size)
{
std::vector<char> data;
data.resize(size);
ssize_t rc = archive_read_data(tar, &data[0], size);
if (rc < 0) {
log(Error, "failed to read from archive stream\n");
return false;
}
else if ((size_t)rc != size) {
log(Error, "file was short: %s\n", filename.c_str());
return false;
}
bool err = false;
rptr<Elf> object(Elf::open(&data[0], data.size(), &err, filename.c_str()));
if (!object.get()) {
if (err)
log(Error, "error in: %s\n", filename.c_str());
return !err;
}
auto split(std::move(splitpath(filename)));
object->dirname = std::move(std::get<0>(split));
object->basename = std::move(std::get<1>(split));
object->solve_paths(object->dirname);
pkg->objects.push_back(object);
return true;
}
static bool
add_entry(Package *pkg, struct archive *tar, struct archive_entry *entry)
{
std::string filename(archive_entry_pathname(entry));
bool isinfo = filename == ".PKGINFO";
// for now we only care about files named lib.*\.so(\.|$)
if (!isinfo && !care_about(entry))
{
archive_read_data_skip(tar);
return true;
}
mode_t mode = archive_entry_mode(entry);
if (AE_IFLNK == (mode & AE_IFLNK)) {
// it's a symlink...
const char *link = archive_entry_symlink(entry);
if (!link) {
log(Error, "error reading symlink");
return false;
}
archive_read_data_skip(tar);
pkg->load.symlinks[filename] = link;
return true;
}
// Check the size
size_t size = archive_entry_size(entry);
if (!size)
return true;
if (isinfo)
return read_info(pkg, tar, size);
return read_object(pkg, tar, std::move(filename), size);
}
Elf*
Package::find(const std::string& dirname, const std::string& basename) const
{
for (auto &obj : objects) {
if (obj->dirname == dirname && obj->basename == basename)
return const_cast<Elf*>(obj.get());
}
return nullptr;
}
void
Package::guess(const std::string& path)
{
// extract the basename:
size_t at = path.find_last_of('/');
std::string base(at == std::string::npos ? path : path.substr(at+1));
// at least N.tgz
if (base.length() < 5)
return;
// ArchLinux scheme:
// ${name}-${pkgver}-${pkgrel}-${CARCH}.pkg.tar.*
// Slackware:
// ${name}-${pkgver}-${CARCH}-${build}.t{gz,bz2,xz}
// so the first part up to the first /-\d/ is part of the name
size_t to = base.find_first_of("-.");
// sanity:
if (!to || to == std::string::npos)
return;
while (to+1 < base.length() && // gonna check [to+1]
base[to] != '.' && // a dot ends the name
!(base[to+1] >= '0' && base[to+1] <= '9'))
{
// name can have dashes, let's move to the next one
to = base.find_first_of("-.", to+1);
}
name = base.substr(0, to);
if (base[to] != '-' || !(base[to+1] >= '0' && base[to+1] <= '9')) {
// no version
return;
}
// version
size_t from = to+1;
to = base.find_first_of('-', from);
if (to == std::string::npos) {
// we'll take it...
version = base.substr(from);
return;
}
bool slack = true;
// check for a pkgrel (Arch scheme)
if (base[to] == '-' &&
to+1 < base.length() &&
(base[to+1] >= '0' && base[to+1] <= '9'))
{
slack = false;
to = base.find_first_of("-.", to+1);
}
version = base.substr(from, to-from);
if (!slack || to == std::string::npos)
return;
// slackware build-name comes right before the extension
to = base.find_last_of('.');
if (!to || to == std::string::npos)
return;
from = base.find_last_of("-.", to-1);
if (from && from != std::string::npos) {
version.append(1, '-');
version.append(base.substr(from+1, to-from-1));
}
}
Package*
Package::open(const std::string& path)
{
std::unique_ptr<Package> package(new Package);
struct archive *tar = archive_read_new();
archive_read_support_filter_all(tar);
archive_read_support_format_all(tar);
struct archive_entry *entry;
if (ARCHIVE_OK != archive_read_open_filename(tar, path.c_str(), 10240)) {
return 0;
}
while (ARCHIVE_OK == archive_read_next_header(tar, &entry)) {
if (!add_entry(package.get(), tar, entry))
return 0;
}
archive_read_free(tar);
if (!package->name.length() && !package->version.length())
package->guess(path);
bool changed;
do {
changed = false;
for (auto link = package->load.symlinks.begin(); link != package->load.symlinks.end();)
{
auto linkfrom = splitpath(link->first);
decltype(linkfrom) linkto;
// handle relative as well as absolute symlinks
if (!link->second.length()) {
// illegal
++link;
continue;
}
if (link->second[0] == '/') // absolute
linkto = splitpath(link->second);
else // relative
{
std::string fullpath = std::get<0>(linkfrom) + "/" + link->second;
linkto = splitpath(fullpath);
}
Elf *obj = package->find(std::get<0>(linkto), std::get<1>(linkto));
if (!obj) {
++link;
continue;
}
changed = true;
Elf *copy = new Elf(*obj);
copy->dirname = std::move(std::get<0>(linkfrom));
copy->basename = std::move(std::get<1>(linkfrom));
copy->solve_paths(obj->dirname);
package->objects.push_back(copy);
package->load.symlinks.erase(link++);
}
} while (changed);
package->load.symlinks.clear();
return package.release();
}
void
Package::show_needed()
{
const char *name = this->name.c_str();
for (auto &obj : objects) {
std::string path = obj->dirname + "/" + obj->basename;
const char *objname = path.c_str();
for (auto &need : obj->needed) {
printf("%s: %s NEEDS %s\n", name, objname, need.c_str());
}
}
}
<commit_msg>fix a bug in reading of optdepend entries<commit_after>#include <memory>
#include <archive.h>
#include <archive_entry.h>
#include "main.h"
static bool
care_about(struct archive_entry *entry)
{
mode_t mode = archive_entry_mode(entry);
#if 0
if (AE_IFLNK == (mode & AE_IFLNK)) {
// ignoring symlinks for now
return false;
}
#endif
if (AE_IFREG != (mode & AE_IFREG)) {
// not a regular file
return false;
}
if (!archive_entry_size_is_set(entry)) {
// ignore files which have no size...
return false;
}
return true;
}
// because isspace(3) is locale dependent
static bool
c_isspace(const char c) {
return (c == ' ' || c == '\t' ||
c == '\n' || c == '\r' ||
c == '\v' || c == '\f');
}
static bool
ends_word(const char c) {
return c_isspace(c) || c == '=';
}
// NOTE:
// Judgding from pacman/libalpm source code this function
// is way less strict about the formatting, as we skip whitespace
// between every word, whereas pacman matches /^(\w+) = (.*)$/ exactly.
static bool
read_info(Package *pkg, struct archive *tar, const size_t size)
{
std::vector<char> data(size);
ssize_t rc = archive_read_data(tar, &data[0], size);
if ((size_t)rc != size) {
log(Error, "failed to read .PKGINFO");
return false;
}
std::string str(&data[0], data.size());
size_t pos = 0;
auto skipwhite = [&]() {
while (pos < size && c_isspace(str[pos]))
++pos;
};
auto skipline = [&]() {
while (pos < size && str[pos] != '\n')
++pos;
};
auto getvalue = [&](const char *entryname, std::string &out) -> bool {
skipwhite();
if (pos >= size) {
log(Error, "invalid %s entry in .PKGINFO", entryname);
return false;
}
if (str[pos] != '=') {
log(Error, "Error in .PKGINFO");
return false;
}
++pos;
skipwhite();
if (pos >= size) {
log(Error, "invalid %s entry in .PKGINFO", entryname);
return false;
}
size_t to = str.find_first_of(" \n\r\t", pos);
out = str.substr(pos, to-pos);
skipline();
return true;
};
auto isentry = [&](const char *what, size_t len) -> bool {
if (size-pos > len &&
str.compare(pos, len, what) == 0 &&
ends_word(str[pos+len]))
{
pos += len;
return true;
}
return false;
};
std::string es;
while (pos < size) {
skipwhite();
if (isentry("pkgname", sizeof("pkgname")-1)) {
if (!getvalue("pkgname", pkg->name))
return false;
continue;
}
if (isentry("pkgver", sizeof("pkgver")-1)) {
if (!getvalue("pkgver", pkg->version))
return false;
continue;
}
if (!opt_package_depends) {
skipline();
continue;
}
if (isentry("depend", sizeof("depend")-1)) {
if (!getvalue("depend", es))
return false;
pkg->depends.push_back(es);
continue;
}
if (isentry("optdepend", sizeof("optdepend")-1)) {
if (!getvalue("optdepend", es))
return false;
size_t c = es.find_first_of(':');
if (c != std::string::npos)
es.erase(c);
if (es.length())
pkg->optdepends.push_back(es);
continue;
}
skipline();
}
return true;
}
static inline std::tuple<std::string, std::string>
splitpath(const std::string& path)
{
size_t slash = path.find_last_of('/');
if (slash == std::string::npos)
return std::make_tuple("/", path);
if (path[0] != '/')
return std::make_tuple(std::move(std::string("/") + path.substr(0, slash)), path.substr(slash+1));
return std::make_tuple(path.substr(0, slash), path.substr(slash+1));
}
static bool
read_object(Package *pkg, struct archive *tar, std::string &&filename, size_t size)
{
std::vector<char> data;
data.resize(size);
ssize_t rc = archive_read_data(tar, &data[0], size);
if (rc < 0) {
log(Error, "failed to read from archive stream\n");
return false;
}
else if ((size_t)rc != size) {
log(Error, "file was short: %s\n", filename.c_str());
return false;
}
bool err = false;
rptr<Elf> object(Elf::open(&data[0], data.size(), &err, filename.c_str()));
if (!object.get()) {
if (err)
log(Error, "error in: %s\n", filename.c_str());
return !err;
}
auto split(std::move(splitpath(filename)));
object->dirname = std::move(std::get<0>(split));
object->basename = std::move(std::get<1>(split));
object->solve_paths(object->dirname);
pkg->objects.push_back(object);
return true;
}
static bool
add_entry(Package *pkg, struct archive *tar, struct archive_entry *entry)
{
std::string filename(archive_entry_pathname(entry));
bool isinfo = filename == ".PKGINFO";
// for now we only care about files named lib.*\.so(\.|$)
if (!isinfo && !care_about(entry))
{
archive_read_data_skip(tar);
return true;
}
mode_t mode = archive_entry_mode(entry);
if (AE_IFLNK == (mode & AE_IFLNK)) {
// it's a symlink...
const char *link = archive_entry_symlink(entry);
if (!link) {
log(Error, "error reading symlink");
return false;
}
archive_read_data_skip(tar);
pkg->load.symlinks[filename] = link;
return true;
}
// Check the size
size_t size = archive_entry_size(entry);
if (!size)
return true;
if (isinfo)
return read_info(pkg, tar, size);
return read_object(pkg, tar, std::move(filename), size);
}
Elf*
Package::find(const std::string& dirname, const std::string& basename) const
{
for (auto &obj : objects) {
if (obj->dirname == dirname && obj->basename == basename)
return const_cast<Elf*>(obj.get());
}
return nullptr;
}
void
Package::guess(const std::string& path)
{
// extract the basename:
size_t at = path.find_last_of('/');
std::string base(at == std::string::npos ? path : path.substr(at+1));
// at least N.tgz
if (base.length() < 5)
return;
// ArchLinux scheme:
// ${name}-${pkgver}-${pkgrel}-${CARCH}.pkg.tar.*
// Slackware:
// ${name}-${pkgver}-${CARCH}-${build}.t{gz,bz2,xz}
// so the first part up to the first /-\d/ is part of the name
size_t to = base.find_first_of("-.");
// sanity:
if (!to || to == std::string::npos)
return;
while (to+1 < base.length() && // gonna check [to+1]
base[to] != '.' && // a dot ends the name
!(base[to+1] >= '0' && base[to+1] <= '9'))
{
// name can have dashes, let's move to the next one
to = base.find_first_of("-.", to+1);
}
name = base.substr(0, to);
if (base[to] != '-' || !(base[to+1] >= '0' && base[to+1] <= '9')) {
// no version
return;
}
// version
size_t from = to+1;
to = base.find_first_of('-', from);
if (to == std::string::npos) {
// we'll take it...
version = base.substr(from);
return;
}
bool slack = true;
// check for a pkgrel (Arch scheme)
if (base[to] == '-' &&
to+1 < base.length() &&
(base[to+1] >= '0' && base[to+1] <= '9'))
{
slack = false;
to = base.find_first_of("-.", to+1);
}
version = base.substr(from, to-from);
if (!slack || to == std::string::npos)
return;
// slackware build-name comes right before the extension
to = base.find_last_of('.');
if (!to || to == std::string::npos)
return;
from = base.find_last_of("-.", to-1);
if (from && from != std::string::npos) {
version.append(1, '-');
version.append(base.substr(from+1, to-from-1));
}
}
Package*
Package::open(const std::string& path)
{
std::unique_ptr<Package> package(new Package);
struct archive *tar = archive_read_new();
archive_read_support_filter_all(tar);
archive_read_support_format_all(tar);
struct archive_entry *entry;
if (ARCHIVE_OK != archive_read_open_filename(tar, path.c_str(), 10240)) {
return 0;
}
while (ARCHIVE_OK == archive_read_next_header(tar, &entry)) {
if (!add_entry(package.get(), tar, entry))
return 0;
}
archive_read_free(tar);
if (!package->name.length() && !package->version.length())
package->guess(path);
bool changed;
do {
changed = false;
for (auto link = package->load.symlinks.begin(); link != package->load.symlinks.end();)
{
auto linkfrom = splitpath(link->first);
decltype(linkfrom) linkto;
// handle relative as well as absolute symlinks
if (!link->second.length()) {
// illegal
++link;
continue;
}
if (link->second[0] == '/') // absolute
linkto = splitpath(link->second);
else // relative
{
std::string fullpath = std::get<0>(linkfrom) + "/" + link->second;
linkto = splitpath(fullpath);
}
Elf *obj = package->find(std::get<0>(linkto), std::get<1>(linkto));
if (!obj) {
++link;
continue;
}
changed = true;
Elf *copy = new Elf(*obj);
copy->dirname = std::move(std::get<0>(linkfrom));
copy->basename = std::move(std::get<1>(linkfrom));
copy->solve_paths(obj->dirname);
package->objects.push_back(copy);
package->load.symlinks.erase(link++);
}
} while (changed);
package->load.symlinks.clear();
return package.release();
}
void
Package::show_needed()
{
const char *name = this->name.c_str();
for (auto &obj : objects) {
std::string path = obj->dirname + "/" + obj->basename;
const char *objname = path.c_str();
for (auto &need : obj->needed) {
printf("%s: %s NEEDS %s\n", name, objname, need.c_str());
}
}
}
<|endoftext|> |
<commit_before>// Copyright (c) 2013, German Neuroinformatics Node (G-Node)
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted under the terms of the BSD License. See
// LICENSE file in the root of the Project.
#ifndef NIX_PSIZE_H
#define NIX_PSIZE_H
#include <nix/Platform.hpp>
#include <nix/Exception.hpp>
#include <cstdint>
#include <stdexcept>
#include <algorithm>
#include <initializer_list>
#include <iostream>
namespace nix {
#ifdef _WIN32
//TODO: consider reimplementing NDSizeBase using std::vector (cf. issue #449)
#pragma warning(disable: 4996)
#endif
template<typename T>
class NDSizeBase {
public:
typedef T value_type;
typedef T *iterator;
typedef const T *const_iterator;
typedef T &reference;
typedef const T const_reference;
typedef T *pointer;
typedef size_t difference_type;
typedef size_t size_type;
NDSizeBase()
: rank(0), dims(nullptr)
{
}
explicit NDSizeBase(size_t rank)
: rank(rank), dims(nullptr)
{
allocate();
}
explicit NDSizeBase(size_t rank, T fill_value)
: rank(rank), dims(nullptr)
{
allocate();
fill(fill_value);
}
template<typename U>
NDSizeBase(std::initializer_list<U> args)
: rank(args.size())
{
allocate();
std::transform(args.begin(), args.end(), dims, [](const U& val) { return static_cast<T>(val);});
}
//copy
NDSizeBase(const NDSizeBase &other)
: rank(other.rank), dims(nullptr)
{
allocate();
std::copy(other.dims, other.dims + rank, dims);
}
//move (not tested due to: http://llvm.org/bugs/show_bug.cgi?id=12208)
NDSizeBase(NDSizeBase &&other)
: rank(other.rank), dims(other.dims)
{
other.dims = nullptr;
other.rank = 0;
}
//copy and move assignment operator (not tested, see above)
NDSizeBase& operator=(NDSizeBase other) {
swap(other);
return *this;
}
// safe bool of the future (i.e. C++11)
explicit operator bool() const {
return rank > 0;
}
T& operator[] (const size_t index) {
const NDSizeBase *this_const = const_cast<const NDSizeBase*>(this);
return const_cast<T&>(this_const->operator[](index));
}
const T& operator[] (const size_t index) const {
if (index + 1 > rank) {
throw std::out_of_range ("Index out of bounds");
}
return dims[index];
}
NDSizeBase<T>& operator++() {
std::for_each(begin(), end(), [](T &val) {
val++;
});
return *this;
}
NDSizeBase<T> operator++(int) {
NDSizeBase<T> snapshot(*this);
operator++();
return snapshot;
}
NDSizeBase<T>& operator+=(const NDSizeBase<T> &rhs) {
if(size() != rhs.size()) {
throw std::out_of_range (""); //fixme: use different exception
}
for (size_t i = 0; i < rank; i++) {
dims[i] += rhs.dims[i];
}
return *this;
}
NDSizeBase<T>& operator+=(T val) {
for (size_t i = 0; i < rank; i++) {
dims[i] += val;
}
return *this;
}
NDSizeBase<T>& operator+=(int val) {
return operator+=(static_cast<T>(val));
}
NDSizeBase<T>& operator--() {
std::for_each(begin(), end(), [](T &val) {
val--;
});
return *this;
}
NDSizeBase<T> operator--(int) {
NDSizeBase<T> snapshot(*this);
operator--();
return snapshot;
}
NDSizeBase<T>& operator-=(const NDSizeBase<T> &rhs) {
if(size() != rhs.size()) {
throw std::out_of_range (""); //fixme: use different exception
}
for (size_t i = 0; i < rank; i++) {
dims[i] -= rhs.dims[i];
}
return *this;
}
NDSizeBase<T>& operator-=(T val) {
for (size_t i = 0; i < rank; i++) {
dims[i] -= val;
}
return *this;
}
NDSizeBase<T>& operator-=(int val) {
return operator-=(static_cast<T>(val));
}
void swap(NDSizeBase &other) {
using std::swap;
swap(dims, other.dims);
rank = other.rank;
}
NDSizeBase<T>& operator*=(const NDSizeBase<T> &rhs) {
if(size() != rhs.size()) {
throw std::out_of_range (""); //fixme: use different exception
}
for (size_t i = 0; i < rank; i++) {
dims[i] *= rhs.dims[i];
}
return *this;
}
NDSizeBase<T>& operator/=(const NDSizeBase<T> &rhs) {
if(size() != rhs.size()) {
throw std::out_of_range (""); //fixme: use different exception
}
for (size_t i = 0; i < rank; i++) {
dims[i] /= rhs.dims[i];
}
return *this;
}
size_t size() const { return rank; }
size_t nelms() const {
T product = 1;
std::for_each(begin(), end(), [&](T val) {
product *= val;
});
//FIXME: check overflow before casting
return static_cast<size_t>(product);
}
T dot(const NDSizeBase<T> &other) const {
if(size() != other.size()) {
throw std::out_of_range ("Dimensions do not match"); //fixme: use different exception
}
T res = 0;
for (size_t i = 0; i < rank; i++) {
res += dims[i] * other.dims[i];
}
return res;
}
T* data() { return dims; }
const T* data() const {return dims; }
void fill(T value) {
std::fill_n(dims, rank, value);
}
~NDSizeBase() {
delete[] dims;
}
//we are modelling a boost::Collection
iterator begin() { return dims; }
iterator end() { return dims + rank; }
const_iterator begin() const { return dims; }
const_iterator end() const { return dims + rank; }
bool empty() const { return rank == 0; }
private:
void allocate() {
if (rank > 0) {
dims = new T[rank];
}
}
size_t rank;
T *dims;
};
template<typename T>
NDSizeBase<T> operator-(NDSizeBase<T> lhs, const NDSizeBase<T> &rhs)
{
lhs -= rhs;
return lhs;
}
template<typename T>
NDSizeBase<T> operator+(NDSizeBase<T> lhs, const NDSizeBase<T> &rhs)
{
lhs += rhs;
return lhs;
}
template<typename T>
NDSizeBase<T> operator+(NDSizeBase<T> lhs, T rhs)
{
lhs += rhs;
return lhs;
}
template<typename T>
NDSizeBase<T> operator+(T lhs, const NDSizeBase<T> &rhs)
{
return operator+(rhs, lhs);
}
template<typename T>
NDSizeBase<T> operator+(NDSizeBase<T> lhs, int rhs)
{
lhs += rhs;
return lhs;
}
template<typename T>
NDSizeBase<T> operator+(int lhs, const NDSizeBase<T> &rhs)
{
return operator+(rhs, lhs);
}
template<typename T>
NDSizeBase<T> operator*(NDSizeBase<T> lhs, const NDSizeBase<T> &rhs)
{
lhs *= rhs;
return lhs;
}
template<typename T>
NDSizeBase<T> operator*(NDSizeBase<T> lhs, T rhs)
{
lhs *= rhs;
return lhs;
}
template<typename T>
NDSizeBase<T> operator*(T lhs, const NDSizeBase<T> &rhs)
{
return operator*(rhs, lhs);
}
template<typename T>
NDSizeBase<T> operator/(NDSizeBase<T> lhs, const NDSizeBase<T> &rhs)
{
lhs /= rhs;
return lhs;
}
template<typename T>
NDSizeBase<T> operator/(NDSizeBase<T> lhs, T rhs)
{
lhs /= rhs;
return lhs;
}
template<typename T>
NDSizeBase<T> operator/(T lhs, const NDSizeBase<T> &rhs)
{
return operator/(rhs, lhs);
}
template<typename T>
inline bool operator==(const NDSizeBase<T> &lhs, const NDSizeBase<T> &rhs)
{
if (lhs.size() != rhs.size())
return false;
for (size_t i = 0; i < lhs.size(); i++) {
if (lhs[i] != rhs[i])
return false;
}
return true;
}
template<typename T>
inline bool operator!=(const NDSizeBase<T> &lhs, const NDSizeBase<T> &rhs)
{
return !operator==(lhs, rhs);
}
template<typename T>
inline bool operator<(const NDSizeBase<T> &lhs, const NDSizeBase<T> &rhs)
{
if (lhs.size() != rhs.size()) {
throw IncompatibleDimensions("size must agree to compare",
"NDSizeBase < NDSizeBase ");
}
const size_t size = lhs.size();
for (size_t i = 0; i < size; i++) {
if (lhs[i] >= rhs[i]) {
return false;
}
}
return true;
}
template<typename T>
inline bool operator<=(const NDSizeBase<T> &lhs, const NDSizeBase<T> &rhs)
{
if (lhs.size() != rhs.size()) {
throw IncompatibleDimensions("size must agree to compare",
"NDSizeBase < NDSizeBase ");
}
const size_t size = lhs.size();
for (size_t i = 0; i < size; i++) {
if (lhs[i] > rhs[i]) {
return false;
}
}
return true;
}
template<typename T>
inline bool operator>(const NDSizeBase<T> &lhs, const NDSizeBase<T> &rhs)
{
return !(lhs <= rhs);
}
template<typename T>
inline bool operator>=(const NDSizeBase<T> &lhs, const NDSizeBase<T> &rhs)
{
return !(lhs < rhs);
}
template<typename T>
inline std::ostream& operator<<(std::ostream &os, const NDSizeBase<T> &ndsize)
{
os << "NDSize {";
for(size_t i = 0; i < ndsize.size(); i++) {
if (i != 0) {
os << ", ";
}
os << ndsize[i];
}
os << "}\n";
return os;
}
/* ***** */
//Ideally we would use unit64_t (and int64_t) here to directly specify
//the size we want, but for now we stick with how the hdf5 library
//defines hsize_t, otherwise we will run into issues when on plaforms
// where unit64_t is an incompatible type to the type of hsize_t
//(e.g. Ubuntu 12.04 LTS Server Edition 64 bit.)
typedef NDSizeBase<unsigned long long int> NDSize;
typedef NDSizeBase<long long int> NDSSize;
} // namespace nix
#endif // NIX_PSIZE_H
<commit_msg>NDSize: define ndsize_t and ndssize_t<commit_after>// Copyright (c) 2013, German Neuroinformatics Node (G-Node)
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted under the terms of the BSD License. See
// LICENSE file in the root of the Project.
#ifndef NIX_PSIZE_H
#define NIX_PSIZE_H
#include <nix/Platform.hpp>
#include <nix/Exception.hpp>
#include <cstdint>
#include <stdexcept>
#include <algorithm>
#include <initializer_list>
#include <iostream>
namespace nix {
//Ideally we would use unit64_t (and int64_t) here to directly specify
//the size we want, but for now we stick with how the hdf5 library
//defines hsize_t, otherwise we will run into issues when on plaforms
// where unit64_t is an incompatible type to the type of hsize_t
//(e.g. Ubuntu 12.04 LTS Server Edition 64 bit.)
typedef unsigned long long int ndsize_t;
typedef long long int ndssize_t;
#endif
template<typename T>
class NDSizeBase {
public:
typedef T value_type;
typedef T *iterator;
typedef const T *const_iterator;
typedef T &reference;
typedef const T const_reference;
typedef T *pointer;
typedef size_t difference_type;
typedef size_t size_type;
NDSizeBase()
: rank(0), dims(nullptr)
{
}
explicit NDSizeBase(size_t rank)
: rank(rank), dims(nullptr)
{
allocate();
}
explicit NDSizeBase(size_t rank, T fill_value)
: rank(rank), dims(nullptr)
{
allocate();
fill(fill_value);
}
template<typename U>
NDSizeBase(std::initializer_list<U> args)
: rank(args.size())
{
allocate();
std::transform(args.begin(), args.end(), dims, [](const U& val) { return static_cast<T>(val);});
}
//copy
NDSizeBase(const NDSizeBase &other)
: rank(other.rank), dims(nullptr)
{
allocate();
std::copy(other.dims, other.dims + rank, dims);
}
//move (not tested due to: http://llvm.org/bugs/show_bug.cgi?id=12208)
NDSizeBase(NDSizeBase &&other)
: rank(other.rank), dims(other.dims)
{
other.dims = nullptr;
other.rank = 0;
}
//copy and move assignment operator (not tested, see above)
NDSizeBase& operator=(NDSizeBase other) {
swap(other);
return *this;
}
// safe bool of the future (i.e. C++11)
explicit operator bool() const {
return rank > 0;
}
T& operator[] (const size_t index) {
const NDSizeBase *this_const = const_cast<const NDSizeBase*>(this);
return const_cast<T&>(this_const->operator[](index));
}
const T& operator[] (const size_t index) const {
if (index + 1 > rank) {
throw std::out_of_range ("Index out of bounds");
}
return dims[index];
}
NDSizeBase<T>& operator++() {
std::for_each(begin(), end(), [](T &val) {
val++;
});
return *this;
}
NDSizeBase<T> operator++(int) {
NDSizeBase<T> snapshot(*this);
operator++();
return snapshot;
}
NDSizeBase<T>& operator+=(const NDSizeBase<T> &rhs) {
if(size() != rhs.size()) {
throw std::out_of_range (""); //fixme: use different exception
}
for (size_t i = 0; i < rank; i++) {
dims[i] += rhs.dims[i];
}
return *this;
}
NDSizeBase<T>& operator+=(T val) {
for (size_t i = 0; i < rank; i++) {
dims[i] += val;
}
return *this;
}
NDSizeBase<T>& operator+=(int val) {
return operator+=(static_cast<T>(val));
}
NDSizeBase<T>& operator--() {
std::for_each(begin(), end(), [](T &val) {
val--;
});
return *this;
}
NDSizeBase<T> operator--(int) {
NDSizeBase<T> snapshot(*this);
operator--();
return snapshot;
}
NDSizeBase<T>& operator-=(const NDSizeBase<T> &rhs) {
if(size() != rhs.size()) {
throw std::out_of_range (""); //fixme: use different exception
}
for (size_t i = 0; i < rank; i++) {
dims[i] -= rhs.dims[i];
}
return *this;
}
NDSizeBase<T>& operator-=(T val) {
for (size_t i = 0; i < rank; i++) {
dims[i] -= val;
}
return *this;
}
NDSizeBase<T>& operator-=(int val) {
return operator-=(static_cast<T>(val));
}
void swap(NDSizeBase &other) {
using std::swap;
swap(dims, other.dims);
rank = other.rank;
}
NDSizeBase<T>& operator*=(const NDSizeBase<T> &rhs) {
if(size() != rhs.size()) {
throw std::out_of_range (""); //fixme: use different exception
}
for (size_t i = 0; i < rank; i++) {
dims[i] *= rhs.dims[i];
}
return *this;
}
NDSizeBase<T>& operator/=(const NDSizeBase<T> &rhs) {
if(size() != rhs.size()) {
throw std::out_of_range (""); //fixme: use different exception
}
for (size_t i = 0; i < rank; i++) {
dims[i] /= rhs.dims[i];
}
return *this;
}
size_t size() const { return rank; }
size_t nelms() const {
T product = 1;
std::for_each(begin(), end(), [&](T val) {
product *= val;
});
//FIXME: check overflow before casting
return static_cast<size_t>(product);
}
T dot(const NDSizeBase<T> &other) const {
if(size() != other.size()) {
throw std::out_of_range ("Dimensions do not match"); //fixme: use different exception
}
T res = 0;
for (size_t i = 0; i < rank; i++) {
res += dims[i] * other.dims[i];
}
return res;
}
T* data() { return dims; }
const T* data() const {return dims; }
void fill(T value) {
std::fill_n(dims, rank, value);
}
~NDSizeBase() {
delete[] dims;
}
//we are modelling a boost::Collection
iterator begin() { return dims; }
iterator end() { return dims + rank; }
const_iterator begin() const { return dims; }
const_iterator end() const { return dims + rank; }
bool empty() const { return rank == 0; }
private:
void allocate() {
if (rank > 0) {
dims = new T[rank];
}
}
size_t rank;
T *dims;
};
template<typename T>
NDSizeBase<T> operator-(NDSizeBase<T> lhs, const NDSizeBase<T> &rhs)
{
lhs -= rhs;
return lhs;
}
template<typename T>
NDSizeBase<T> operator+(NDSizeBase<T> lhs, const NDSizeBase<T> &rhs)
{
lhs += rhs;
return lhs;
}
template<typename T>
NDSizeBase<T> operator+(NDSizeBase<T> lhs, T rhs)
{
lhs += rhs;
return lhs;
}
template<typename T>
NDSizeBase<T> operator+(T lhs, const NDSizeBase<T> &rhs)
{
return operator+(rhs, lhs);
}
template<typename T>
NDSizeBase<T> operator+(NDSizeBase<T> lhs, int rhs)
{
lhs += rhs;
return lhs;
}
template<typename T>
NDSizeBase<T> operator+(int lhs, const NDSizeBase<T> &rhs)
{
return operator+(rhs, lhs);
}
template<typename T>
NDSizeBase<T> operator*(NDSizeBase<T> lhs, const NDSizeBase<T> &rhs)
{
lhs *= rhs;
return lhs;
}
template<typename T>
NDSizeBase<T> operator*(NDSizeBase<T> lhs, T rhs)
{
lhs *= rhs;
return lhs;
}
template<typename T>
NDSizeBase<T> operator*(T lhs, const NDSizeBase<T> &rhs)
{
return operator*(rhs, lhs);
}
template<typename T>
NDSizeBase<T> operator/(NDSizeBase<T> lhs, const NDSizeBase<T> &rhs)
{
lhs /= rhs;
return lhs;
}
template<typename T>
NDSizeBase<T> operator/(NDSizeBase<T> lhs, T rhs)
{
lhs /= rhs;
return lhs;
}
template<typename T>
NDSizeBase<T> operator/(T lhs, const NDSizeBase<T> &rhs)
{
return operator/(rhs, lhs);
}
template<typename T>
inline bool operator==(const NDSizeBase<T> &lhs, const NDSizeBase<T> &rhs)
{
if (lhs.size() != rhs.size())
return false;
for (size_t i = 0; i < lhs.size(); i++) {
if (lhs[i] != rhs[i])
return false;
}
return true;
}
template<typename T>
inline bool operator!=(const NDSizeBase<T> &lhs, const NDSizeBase<T> &rhs)
{
return !operator==(lhs, rhs);
}
template<typename T>
inline bool operator<(const NDSizeBase<T> &lhs, const NDSizeBase<T> &rhs)
{
if (lhs.size() != rhs.size()) {
throw IncompatibleDimensions("size must agree to compare",
"NDSizeBase < NDSizeBase ");
}
const size_t size = lhs.size();
for (size_t i = 0; i < size; i++) {
if (lhs[i] >= rhs[i]) {
return false;
}
}
return true;
}
template<typename T>
inline bool operator<=(const NDSizeBase<T> &lhs, const NDSizeBase<T> &rhs)
{
if (lhs.size() != rhs.size()) {
throw IncompatibleDimensions("size must agree to compare",
"NDSizeBase < NDSizeBase ");
}
const size_t size = lhs.size();
for (size_t i = 0; i < size; i++) {
if (lhs[i] > rhs[i]) {
return false;
}
}
return true;
}
template<typename T>
inline bool operator>(const NDSizeBase<T> &lhs, const NDSizeBase<T> &rhs)
{
return !(lhs <= rhs);
}
template<typename T>
inline bool operator>=(const NDSizeBase<T> &lhs, const NDSizeBase<T> &rhs)
{
return !(lhs < rhs);
}
template<typename T>
inline std::ostream& operator<<(std::ostream &os, const NDSizeBase<T> &ndsize)
{
os << "NDSize {";
for(size_t i = 0; i < ndsize.size(); i++) {
if (i != 0) {
os << ", ";
}
os << ndsize[i];
}
os << "}\n";
return os;
}
/* ***** */
//Ideally we would use unit64_t (and int64_t) here to directly specify
//the size we want, but for now we stick with how the hdf5 library
//defines hsize_t, otherwise we will run into issues when on plaforms
// where unit64_t is an incompatible type to the type of hsize_t
//(e.g. Ubuntu 12.04 LTS Server Edition 64 bit.)
typedef NDSizeBase<unsigned long long int> NDSize;
typedef NDSizeBase<long long int> NDSSize;
} // namespace nix
#endif // NIX_PSIZE_H
<|endoftext|> |
<commit_before>
/*
* Copyright 2006 The Android Open Source Project
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "SkComposeShader.h"
#include "SkColorFilter.h"
#include "SkColorPriv.h"
#include "SkXfermode.h"
///////////////////////////////////////////////////////////////////////////////
SkComposeShader::SkComposeShader(SkShader* sA, SkShader* sB, SkXfermode* mode) {
fShaderA = sA; sA->ref();
fShaderB = sB; sB->ref();
// mode may be null
fMode = mode;
SkSafeRef(mode);
}
SkComposeShader::SkComposeShader(SkFlattenableReadBuffer& buffer) :
INHERITED(buffer) {
fShaderA = static_cast<SkShader*>(buffer.readFlattenable());
fShaderB = static_cast<SkShader*>(buffer.readFlattenable());
fMode = static_cast<SkXfermode*>(buffer.readFlattenable());
}
SkComposeShader::~SkComposeShader() {
SkSafeUnref(fMode);
fShaderB->unref();
fShaderA->unref();
}
void SkComposeShader::beginSession() {
this->INHERITED::beginSession();
fShaderA->beginSession();
fShaderB->beginSession();
}
void SkComposeShader::endSession() {
fShaderA->endSession();
fShaderB->endSession();
this->INHERITED::endSession();
}
class SkAutoAlphaRestore {
public:
SkAutoAlphaRestore(SkPaint* paint, uint8_t newAlpha) {
fAlpha = paint->getAlpha();
fPaint = paint;
paint->setAlpha(newAlpha);
}
~SkAutoAlphaRestore() {
fPaint->setAlpha(fAlpha);
}
private:
SkPaint* fPaint;
uint8_t fAlpha;
};
void SkComposeShader::flatten(SkFlattenableWriteBuffer& buffer) {
this->INHERITED::flatten(buffer);
buffer.writeFlattenable(fShaderA);
buffer.writeFlattenable(fShaderB);
buffer.writeFlattenable(fMode);
}
/* We call setContext on our two worker shaders. However, we
always let them see opaque alpha, and if the paint really
is translucent, then we apply that after the fact.
*/
bool SkComposeShader::setContext(const SkBitmap& device,
const SkPaint& paint,
const SkMatrix& matrix) {
if (!this->INHERITED::setContext(device, paint, matrix)) {
return false;
}
// we preconcat our localMatrix (if any) with the device matrix
// before calling our sub-shaders
SkMatrix tmpM;
(void)this->getLocalMatrix(&tmpM);
tmpM.setConcat(matrix, tmpM);
SkAutoAlphaRestore restore(const_cast<SkPaint*>(&paint), 0xFF);
return fShaderA->setContext(device, paint, tmpM) &&
fShaderB->setContext(device, paint, tmpM);
}
// larger is better (fewer times we have to loop), but we shouldn't
// take up too much stack-space (each element is 4 bytes)
#define TMP_COLOR_COUNT 64
void SkComposeShader::shadeSpan(int x, int y, SkPMColor result[], int count) {
SkShader* shaderA = fShaderA;
SkShader* shaderB = fShaderB;
SkXfermode* mode = fMode;
unsigned scale = SkAlpha255To256(this->getPaintAlpha());
SkPMColor tmp[TMP_COLOR_COUNT];
if (NULL == mode) { // implied SRC_OVER
// TODO: when we have a good test-case, should use SkBlitRow::Proc32
// for these loops
do {
int n = count;
if (n > TMP_COLOR_COUNT) {
n = TMP_COLOR_COUNT;
}
shaderA->shadeSpan(x, y, result, n);
shaderB->shadeSpan(x, y, tmp, n);
if (256 == scale) {
for (int i = 0; i < n; i++) {
result[i] = SkPMSrcOver(tmp[i], result[i]);
}
} else {
for (int i = 0; i < n; i++) {
result[i] = SkAlphaMulQ(SkPMSrcOver(tmp[i], result[i]),
scale);
}
}
result += n;
x += n;
count -= n;
} while (count > 0);
} else { // use mode for the composition
do {
int n = count;
if (n > TMP_COLOR_COUNT) {
n = TMP_COLOR_COUNT;
}
shaderA->shadeSpan(x, y, result, n);
shaderB->shadeSpan(x, y, tmp, n);
mode->xfer32(result, tmp, n, NULL);
if (256 == scale) {
for (int i = 0; i < n; i++) {
result[i] = SkAlphaMulQ(result[i], scale);
}
}
result += n;
x += n;
count -= n;
} while (count > 0);
}
}
<commit_msg>handle if unflattening returned a null shader<commit_after>
/*
* Copyright 2006 The Android Open Source Project
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "SkComposeShader.h"
#include "SkColorFilter.h"
#include "SkColorPriv.h"
#include "SkColorShader.h"
#include "SkXfermode.h"
///////////////////////////////////////////////////////////////////////////////
SkComposeShader::SkComposeShader(SkShader* sA, SkShader* sB, SkXfermode* mode) {
fShaderA = sA; sA->ref();
fShaderB = sB; sB->ref();
// mode may be null
fMode = mode;
SkSafeRef(mode);
}
SkComposeShader::SkComposeShader(SkFlattenableReadBuffer& buffer) :
INHERITED(buffer) {
fShaderA = static_cast<SkShader*>(buffer.readFlattenable());
if (NULL == fShaderA) {
fShaderA = SkNEW_ARGS(SkColorShader, (0));
}
fShaderB = static_cast<SkShader*>(buffer.readFlattenable());
if (NULL == fShaderB) {
fShaderB = SkNEW_ARGS(SkColorShader, (0));
}
fMode = static_cast<SkXfermode*>(buffer.readFlattenable());
}
SkComposeShader::~SkComposeShader() {
SkSafeUnref(fMode);
fShaderB->unref();
fShaderA->unref();
}
void SkComposeShader::beginSession() {
this->INHERITED::beginSession();
fShaderA->beginSession();
fShaderB->beginSession();
}
void SkComposeShader::endSession() {
fShaderA->endSession();
fShaderB->endSession();
this->INHERITED::endSession();
}
class SkAutoAlphaRestore {
public:
SkAutoAlphaRestore(SkPaint* paint, uint8_t newAlpha) {
fAlpha = paint->getAlpha();
fPaint = paint;
paint->setAlpha(newAlpha);
}
~SkAutoAlphaRestore() {
fPaint->setAlpha(fAlpha);
}
private:
SkPaint* fPaint;
uint8_t fAlpha;
};
void SkComposeShader::flatten(SkFlattenableWriteBuffer& buffer) {
this->INHERITED::flatten(buffer);
buffer.writeFlattenable(fShaderA);
buffer.writeFlattenable(fShaderB);
buffer.writeFlattenable(fMode);
}
/* We call setContext on our two worker shaders. However, we
always let them see opaque alpha, and if the paint really
is translucent, then we apply that after the fact.
*/
bool SkComposeShader::setContext(const SkBitmap& device,
const SkPaint& paint,
const SkMatrix& matrix) {
if (!this->INHERITED::setContext(device, paint, matrix)) {
return false;
}
// we preconcat our localMatrix (if any) with the device matrix
// before calling our sub-shaders
SkMatrix tmpM;
(void)this->getLocalMatrix(&tmpM);
tmpM.setConcat(matrix, tmpM);
SkAutoAlphaRestore restore(const_cast<SkPaint*>(&paint), 0xFF);
return fShaderA->setContext(device, paint, tmpM) &&
fShaderB->setContext(device, paint, tmpM);
}
// larger is better (fewer times we have to loop), but we shouldn't
// take up too much stack-space (each element is 4 bytes)
#define TMP_COLOR_COUNT 64
void SkComposeShader::shadeSpan(int x, int y, SkPMColor result[], int count) {
SkShader* shaderA = fShaderA;
SkShader* shaderB = fShaderB;
SkXfermode* mode = fMode;
unsigned scale = SkAlpha255To256(this->getPaintAlpha());
SkPMColor tmp[TMP_COLOR_COUNT];
if (NULL == mode) { // implied SRC_OVER
// TODO: when we have a good test-case, should use SkBlitRow::Proc32
// for these loops
do {
int n = count;
if (n > TMP_COLOR_COUNT) {
n = TMP_COLOR_COUNT;
}
shaderA->shadeSpan(x, y, result, n);
shaderB->shadeSpan(x, y, tmp, n);
if (256 == scale) {
for (int i = 0; i < n; i++) {
result[i] = SkPMSrcOver(tmp[i], result[i]);
}
} else {
for (int i = 0; i < n; i++) {
result[i] = SkAlphaMulQ(SkPMSrcOver(tmp[i], result[i]),
scale);
}
}
result += n;
x += n;
count -= n;
} while (count > 0);
} else { // use mode for the composition
do {
int n = count;
if (n > TMP_COLOR_COUNT) {
n = TMP_COLOR_COUNT;
}
shaderA->shadeSpan(x, y, result, n);
shaderB->shadeSpan(x, y, tmp, n);
mode->xfer32(result, tmp, n, NULL);
if (256 == scale) {
for (int i = 0; i < n; i++) {
result[i] = SkAlphaMulQ(result[i], scale);
}
}
result += n;
x += n;
count -= n;
} while (count > 0);
}
}
<|endoftext|> |
<commit_before>#ifndef PICOLIB_STREAM_H_
#define PICOLIB_STREAM_H_
namespace Pico {
class IO
{
public:
VIRTUAL_METHOD IO& in(void *, size_t) = 0;
VIRTUAL_METHOD IO& out(const void *, size_t) = 0;
METHOD IO& read(void *ptr, size_t count) {
return in(ptr, count);
}
METHOD IO& write(const void *ptr, size_t count) {
return out(ptr, count);
}
METHOD IO& read(Memory::Buffer const& buffer) {
return read(buffer.pointer(), buffer.size());
}
METHOD IO& write(Memory::Buffer const& buffer) {
return write(buffer.pointer(), buffer.size());
}
METHOD friend IO& operator <<(IO &io, Memory::Buffer const& buffer)
{
return io.write(buffer);
}
METHOD friend IO& operator >>(IO &io, Memory::Buffer const& buffer)
{
return io.read(buffer);
}
METHOD friend IO& operator <<(Memory::Buffer const& buffer, IO &io)
{
return io >> buffer;
}
METHOD friend IO& operator >>(Memory::Buffer const& buffer, IO &io)
{
return io << buffer;
}
};
class Stream : public IO
{
public:
FUNCTION Stream standard_input();
FUNCTION Stream standard_output();
FUNCTION Stream standard_error();
CONSTRUCTOR Stream() = default;
CONSTRUCTOR Stream(int fd) : fd(fd) {}
METHOD Stream& in(void *ptr, size_t count);
METHOD Stream& out(const void *ptr, size_t count);
METHOD Stream duplicate();
METHOD void replace(Stream const&);
METHOD int file_desc() const { return fd; }
METHOD int close();
protected:
int fd = -1;
};
template <class Rx, class Tx = Rx>
class BiStream : public IO
{
public:
CONSTRUCTOR BiStream() = default;
CONSTRUCTOR BiStream(Rx rx, Tx tx) : rx(rx), tx(tx) {}
CONSTRUCTOR BiStream(int rfd, int wfd) : rx(Stream(rfd)), tx(Stream(wfd)) {}
METHOD BiStream& in(void *ptr, size_t count) {
rx.read(ptr, count);
return *this;
}
METHOD BiStream& out(const void *ptr, size_t count) {
tx.write(ptr, count);
return *this;
}
protected:
Rx rx;
Tx tx;
};
}
#endif
<commit_msg>pico/stream: close method<commit_after>#ifndef PICOLIB_STREAM_H_
#define PICOLIB_STREAM_H_
namespace Pico {
class IO
{
public:
VIRTUAL_METHOD IO& in(void *, size_t) = 0;
VIRTUAL_METHOD IO& out(const void *, size_t) = 0;
VIRTUAL_METHOD int close() = 0;
METHOD IO& read(void *ptr, size_t count) {
return in(ptr, count);
}
METHOD IO& write(const void *ptr, size_t count) {
return out(ptr, count);
}
METHOD IO& read(Memory::Buffer const& buffer) {
return read(buffer.pointer(), buffer.size());
}
METHOD IO& write(Memory::Buffer const& buffer) {
return write(buffer.pointer(), buffer.size());
}
METHOD friend IO& operator <<(IO &io, Memory::Buffer const& buffer)
{
return io.write(buffer);
}
METHOD friend IO& operator >>(IO &io, Memory::Buffer const& buffer)
{
return io.read(buffer);
}
METHOD friend IO& operator <<(Memory::Buffer const& buffer, IO &io)
{
return io >> buffer;
}
METHOD friend IO& operator >>(Memory::Buffer const& buffer, IO &io)
{
return io << buffer;
}
};
class Stream : public IO
{
public:
FUNCTION Stream standard_input();
FUNCTION Stream standard_output();
FUNCTION Stream standard_error();
CONSTRUCTOR Stream() = default;
CONSTRUCTOR Stream(int fd) : fd(fd) {}
METHOD Stream& in(void *ptr, size_t count);
METHOD Stream& out(const void *ptr, size_t count);
METHOD Stream duplicate();
METHOD void replace(Stream const&);
METHOD int file_desc() const { return fd; }
METHOD int close();
protected:
int fd = -1;
};
template <class Rx, class Tx = Rx>
class BiStream : public IO
{
public:
CONSTRUCTOR BiStream() = default;
CONSTRUCTOR BiStream(Rx rx, Tx tx) : rx(rx), tx(tx) {}
CONSTRUCTOR BiStream(int rfd, int wfd) : rx(Stream(rfd)), tx(Stream(wfd)) {}
METHOD BiStream& in(void *ptr, size_t count) {
rx.read(ptr, count);
return *this;
}
METHOD BiStream& out(const void *ptr, size_t count) {
tx.write(ptr, count);
return *this;
}
METHOD int close() {
return rx.close() | tx.close();
}
protected:
Rx rx;
Tx tx;
};
}
#endif
<|endoftext|> |
<commit_before>// festus/algebraic-path-test.cc
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Copyright 2016 Google, Inc.
// Author: [email protected] (Martin Jansche)
//
// \file
// Unit test for algebraic path computation.
#include "festus/algebraic-path.h"
#include <cmath>
#include <fst/compat.h>
#include <fst/fstlib.h>
#include <gtest/gtest.h>
#include "festus/arc.h"
#include "festus/float-weight-star.h"
#include "festus/max-times-semiring.h"
#include "festus/modular-int-semiring.h"
#include "festus/quaternion-semiring.h"
#include "festus/real-weight.h"
#include "festus/value-weight-static.h"
DEFINE_double(delta, fst::kDelta,
"Convergence threshold for ShortestDistance");
DEFINE_bool(modular_int, false,
"Try to compute ShortestDistance in modular int semiring");
DEFINE_bool(quaternion, false,
"Try to compute ShortestDistance in quaternion semiring");
namespace {
template <class Arc>
void TestOneStateLoop(
typename Arc::Weight loop_weight,
typename Arc::Weight final_weight,
typename Arc::Weight expected_sum_total,
float comparison_delta,
int power_series_terms,
bool use_shortest_distance,
const char *msg) {
typedef typename Arc::Weight Weight;
// One-state FST with a loop at its only (initial and final) state.
fst::VectorFst<Arc> fst;
const auto state = fst.AddState();
fst.SetStart(state);
fst.AddArc(state, Arc(0, 0, loop_weight, state));
fst.SetFinal(state, final_weight);
const Weight sum_total = festus::SumTotalWeight(fst);
EXPECT_TRUE(ApproxEqual(sum_total, expected_sum_total, comparison_delta));
VLOG(0) << "sum total = " << sum_total << " ~= " << expected_sum_total;
if (power_series_terms) {
Weight power = Weight::One();
Weight series = Weight::One();
VLOG(0) << "\\sum_{n=0}^0 loop_weight^n = " << series;
VLOG(0) << " sum x final = " << Times(series, final_weight);
for (int n = 1; n <= power_series_terms; ++n) {
power = Times(power, loop_weight);
series = Plus(series, power);
VLOG(0) << "\\sum_{n=0}^" << n << " loop_weight^n = " << series;
VLOG(0) << " sum x final = " << Times(series, final_weight);
}
}
if (use_shortest_distance) {
VLOG(0) << msg;
VLOG(0) << "shortest distance = "
<< fst::ShortestDistance(fst, FLAGS_delta);
}
}
TEST(AlgebraicPathTest, Log) {
typedef fst::LogArc Arc;
typedef Arc::Weight Weight;
constexpr float q = 1.0f / 32768.0f;
TestOneStateLoop<Arc>(
Weight(-std::log1p(-q)), Weight(-std::log(q)), Weight::One(), 1e-9, 9,
true, "shortest distance computation will be slow and imprecise");
// Internal implementation detail:
EXPECT_EQ(0, festus::internal::SemiringFor<Weight>::IsSpecialized());
}
TEST(AlgebraicPathTest, LimitedMaxTimes) {
// Note that this semiring is not k-closed.
typedef festus::LimitedMaxTimesSemiring<int8, 3, 2> SemiringType;
typedef festus::ValueWeightStatic<SemiringType> Weight;
typedef festus::ValueArcTpl<Weight> Arc;
TestOneStateLoop<Arc>(
Weight::From(1), Weight::From(1), Weight::From(2), 1e-30, 3,
true, "shortest distance computation will be fast and different");
// Internal implementation detail:
EXPECT_EQ(1, festus::internal::SemiringFor<Weight>::IsSpecialized());
}
TEST(AlgebraicPathTest, IntegersMod13) {
// Note that this semiring is not k-closed.
typedef festus::IntegersMod<13> SemiringType;
typedef festus::ValueWeightStatic<SemiringType> Weight;
typedef festus::ValueArcTpl<Weight> Arc;
TestOneStateLoop<Arc>(
Weight::From(3), Weight::From(11), Weight::One(), 1e-30, 5,
FLAGS_modular_int, "shortest distance computation will not terminate");
// Internal implementation detail:
EXPECT_EQ(1, festus::internal::SemiringFor<Weight>::IsSpecialized());
}
TEST(AlgebraicPathTest, Quaternion) {
// Note that this semiring is not k-closed.
typedef festus::QuaternionWeightTpl<festus::RealSemiring<float>> Weight;
typedef festus::ValueArcTpl<Weight> Arc;
const Weight p = Weight::From(-0.5f, 0.5f, 0.5f, 0.5f);
const Weight q = Minus(Weight::One(), p);
TestOneStateLoop<Arc>(
p, q, Weight::One(), 1e-9, 5,
FLAGS_quaternion, "shortest distance computation will not terminate");
// Internal implementation detail:
EXPECT_EQ(1, festus::internal::SemiringFor<Weight>::IsSpecialized());
}
} // namespace
int main(int argc, char *argv[]) {
testing::InitGoogleTest(&argc, argv);
SET_FLAGS(argv[0], &argc, &argv, true);
return RUN_ALL_TESTS();
}
<commit_msg>Documentation for algebraic path test.<commit_after>// festus/algebraic-path-test.cc
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Copyright 2016 Google, Inc.
// Author: [email protected] (Martin Jansche)
//
// \file
// Unit test for algebraic path computation.
//
// This also illustrates the different behaviors of fst::ShortestDistance(fst)
// vs. festus::SumTotalWeight(fst):
//
// * ShortestDistance() requires, but cannot check, that the weight semiring
// is (approximately) k-closed. It uses this assumption to compute an
// implicitly defined Star() closure of the semiring by expanding out a
// power series until (approximate) convergence.
//
// * SumTotalWeight() requires that a Star() operation has been explicitly
// defined which satisfies the Star axiom. It makes no assumptions about
// Star() being equivalent to a convergent power series.
//
// The behavior of these two functions differs in at least the following
// situations:
//
// * The power series for all observed cycles converge; the limit of a
// convergent power series is also provided by the corresponding Star()
// operation. This means that, for all practical purposes and with only minor
// hand-waving, the semiring is approximately k-closed. This is the case,
// inter alia, for the log semiring and graphs/FSTs without negative weight
// cycles, i.e. all real weights fall into [0;1), so the geometric power
// series converges.
//
// In this situation SumTotalWeight() and ShortestDistance() will eventually
// give approximately the same answer. However, there are differences in
// terms of speed and quality.
//
// SumTotalWeight() will give a generally more precise answer in terms of
// Star(), which is quick to compute by itself, but uses an algorithm with
// worst-case cubic running time in the number of state/vertices
// (TODO: cubic in the size of the largest strongly connected component).
//
// ShortestDistance() will give an answer in terms of the limit of a
// convergent power series, but in order to do so it has to expand out the
// terms of the power series one-by-one (without acceleration) until
// approximate convergence. For high-probability cycles (whose real
// probabilities are close to 1), convergence can be slow. The quality of the
// answer also depends on the configured convergence threshold.
//
// * A cycle weight can be computed via a convergent power series, but its
// limit differs from the result of the defined Star() operation. This is
// the case for the particular instance of LimitedMaxTimesSemiring below,
// where 2 == Star(1) != max(1^0, 1^1, 1^2, 1^3, ...) == 1.
//
// In this situation SumTotalWeight() will give an answer in terms of Star(),
// and ShortestDistance() will give a different answer in terms of the limit
// of the convergent power series.
//
// * The power series for a cycle weight diverges, but the corresponding Star()
// value is well-defined. This is the case, inter alia, for the finite field
// of integers modulo a prime, and for the division ring of quaternions. In
// all division rings (and hence all fields), whenever Star(x) is defined, it
// must be defined as Star(x) := (1 - x)^{-1}; and in all rings, Star(x) must
// be undefined when 1 - x == 0.
//
// In this situation SumTotalWeight() will give an answer in terms of Star(),
// and ShortestDistance() will not terminate.
#include "festus/algebraic-path.h"
#include <cmath>
#include <fst/compat.h>
#include <fst/fstlib.h>
#include <gtest/gtest.h>
#include "festus/arc.h"
#include "festus/float-weight-star.h"
#include "festus/max-times-semiring.h"
#include "festus/modular-int-semiring.h"
#include "festus/quaternion-semiring.h"
#include "festus/real-weight.h"
#include "festus/value-weight-static.h"
DEFINE_double(delta, fst::kDelta,
"Convergence threshold for ShortestDistance");
DEFINE_bool(modular_int, false,
"Try to compute ShortestDistance in modular int semiring");
DEFINE_bool(quaternion, false,
"Try to compute ShortestDistance in quaternion semiring");
namespace {
template <class Arc>
void TestOneStateLoop(
typename Arc::Weight loop_weight,
typename Arc::Weight final_weight,
typename Arc::Weight expected_sum_total,
float comparison_delta,
int power_series_terms,
bool use_shortest_distance,
const char *msg) {
typedef typename Arc::Weight Weight;
// One-state FST with a loop at its only (initial and final) state.
fst::VectorFst<Arc> fst;
const auto state = fst.AddState();
fst.SetStart(state);
fst.AddArc(state, Arc(0, 0, loop_weight, state));
fst.SetFinal(state, final_weight);
const Weight sum_total = festus::SumTotalWeight(fst);
EXPECT_TRUE(ApproxEqual(sum_total, expected_sum_total, comparison_delta));
VLOG(0) << "sum total = " << sum_total << " ~= " << expected_sum_total;
if (power_series_terms) {
Weight power = Weight::One();
Weight series = Weight::One();
VLOG(0) << "\\sum_{n=0}^0 loop_weight^n = " << series;
VLOG(0) << " sum x final = " << Times(series, final_weight);
for (int n = 1; n <= power_series_terms; ++n) {
power = Times(power, loop_weight);
series = Plus(series, power);
VLOG(0) << "\\sum_{n=0}^" << n << " loop_weight^n = " << series;
VLOG(0) << " sum x final = " << Times(series, final_weight);
}
}
if (use_shortest_distance) {
VLOG(0) << msg;
VLOG(0) << "shortest distance = "
<< fst::ShortestDistance(fst, FLAGS_delta);
}
}
TEST(AlgebraicPathTest, Log) {
typedef fst::LogArc Arc;
typedef Arc::Weight Weight;
constexpr float q = 1.0f / 32768.0f;
TestOneStateLoop<Arc>(
Weight(-std::log1p(-q)), Weight(-std::log(q)), Weight::One(), 1e-9, 9,
true, "shortest distance computation will be slow and imprecise");
// Internal implementation detail:
EXPECT_EQ(0, festus::internal::SemiringFor<Weight>::IsSpecialized());
}
TEST(AlgebraicPathTest, LimitedMaxTimes) {
// Note that this semiring is not k-closed.
typedef festus::LimitedMaxTimesSemiring<int8, 3, 2> SemiringType;
typedef festus::ValueWeightStatic<SemiringType> Weight;
typedef festus::ValueArcTpl<Weight> Arc;
TestOneStateLoop<Arc>(
Weight::From(1), Weight::From(1), Weight::From(2), 1e-30, 3,
true, "shortest distance computation will be fast and different");
// Internal implementation detail:
EXPECT_EQ(1, festus::internal::SemiringFor<Weight>::IsSpecialized());
}
TEST(AlgebraicPathTest, IntegersMod13) {
// Note that this semiring is not k-closed.
typedef festus::IntegersMod<13> SemiringType;
typedef festus::ValueWeightStatic<SemiringType> Weight;
typedef festus::ValueArcTpl<Weight> Arc;
TestOneStateLoop<Arc>(
Weight::From(3), Weight::From(11), Weight::One(), 1e-30, 5,
FLAGS_modular_int, "shortest distance computation will not terminate");
// Internal implementation detail:
EXPECT_EQ(1, festus::internal::SemiringFor<Weight>::IsSpecialized());
}
TEST(AlgebraicPathTest, Quaternion) {
// Note that this semiring is not k-closed.
typedef festus::QuaternionWeightTpl<festus::RealSemiring<float>> Weight;
typedef festus::ValueArcTpl<Weight> Arc;
const Weight p = Weight::From(-0.5f, 0.5f, 0.5f, 0.5f);
const Weight q = Minus(Weight::One(), p);
TestOneStateLoop<Arc>(
p, q, Weight::One(), 1e-9, 5,
FLAGS_quaternion, "shortest distance computation will not terminate");
// Internal implementation detail:
EXPECT_EQ(1, festus::internal::SemiringFor<Weight>::IsSpecialized());
}
} // namespace
int main(int argc, char *argv[]) {
testing::InitGoogleTest(&argc, argv);
SET_FLAGS(argv[0], &argc, &argv, true);
return RUN_ALL_TESTS();
}
<|endoftext|> |
<commit_before>///
/// @file primecount.hpp
///
/// Copyright (C) 2014 Kim Walisch, <[email protected]>
///
/// This file is distributed under the BSD License. See the COPYING
/// file in the top level directory.
///
#ifndef PRIMECOUNT_HPP
#define PRIMECOUNT_HPP
#include <stdexcept>
#include <string>
#include <stdint.h>
#define PRIMECOUNT_VERSION "1.1"
#define PRIMECOUNT_VERSION_MAJOR 1
#define PRIMECOUNT_VERSION_MINOR 1
namespace primecount {
class primecount_error : public std::runtime_error
{
public:
primecount_error(const std::string& msg)
: std::runtime_error(msg)
{ }
};
/// Alias for the fastest prime counting function in primecount.
int64_t pi(int64_t x);
/// Alias for the fastest prime counting function in primecount.
/// @param x integer or arithmetic expression like 10^12.
/// @pre x <= primecount::max().
///
std::string pi(const std::string& x);
/// Calculate the number of primes below x using the
/// Deleglise-Rivat algorithm.
/// Run time: O(x^(2/3) / (log x)^2) operations, O(x^(1/3) * (log x)^3) space.
///
int64_t pi_deleglise_rivat(int64_t x);
/// Calculate the number of primes below x using Legendre's formula.
/// Run time: O(x) operations, O(x^(1/2)) space.
///
int64_t pi_legendre(int64_t x);
/// Calculate the number of primes below x using Lehmer's formula.
/// Run time: O(x/(log x)^4) operations, O(x^(1/2)) space.
///
int64_t pi_lehmer(int64_t x);
/// Calculate the number of primes below x using the
/// Lagarias-Miller-Odlyzko algorithm.
/// Run time: O(x^(2/3) / log x) operations, O(x^(1/3) * (log x)^2) space.
///
int64_t pi_lmo(int64_t x);
/// Calculate the number of primes below x using Meissel's formula.
/// Run time: O(x/(log x)^3) operations, O(x^(1/2) / log x) space.
///
int64_t pi_meissel(int64_t x);
/// Calculate the number of primes below x using an optimized
/// segmented sieve of Eratosthenes implementation.
/// Run time: O(x log log x) operations, O(x^(1/2)) space.
///
int64_t pi_primesieve(int64_t x);
/// Calculate the nth prime using a combination of an efficient prime
/// counting function implementation and the sieve of Eratosthenes.
/// Run time: O(x^(2/3) / (log x)^2) operations, O(x^(1/2)) space.
///
int64_t nth_prime(int64_t n);
/// Partial sieve function (a.k.a. Legendre-sum).
/// phi(x, a) counts the numbers <= x that are not divisible
/// by any of the first a primes.
///
int64_t phi(int64_t x, int64_t a);
/// Calculate the offset logarithmic integral which is a very
/// accurate approximation of the number of primes below x.
/// @post Li(x) > pi(x) for 24 <= x <= ~ 10^316
///
int64_t Li(int64_t x);
/// Calculate the inverse logarithmic integral Li^-1(x) which is
/// a very accurate approximation of the nth prime.
/// @post Li_inverse(x) < nth_prime(x) for 7 <= x <= ~ 10^316
///
int64_t Li_inverse(int64_t x);
// Set the number of threads.
void set_num_threads(int num_threads);
// Get the currently set number of threads.
int get_num_threads();
/// Returns the largest integer that can be used with
/// pi(std::string x). The return type is a string as max may be a
/// 128-bit integer which is not supported by all compilers.
///
std::string max();
/// Test all prime counting function implementations.
/// @return true if success else false.
///
bool test();
} // namespace primecount
#endif
<commit_msg>Update documentation<commit_after>///
/// @file primecount.hpp
///
/// Copyright (C) 2014 Kim Walisch, <[email protected]>
///
/// This file is distributed under the BSD License. See the COPYING
/// file in the top level directory.
///
#ifndef PRIMECOUNT_HPP
#define PRIMECOUNT_HPP
#include <stdexcept>
#include <string>
#include <stdint.h>
#define PRIMECOUNT_VERSION "1.1"
#define PRIMECOUNT_VERSION_MAJOR 1
#define PRIMECOUNT_VERSION_MINOR 1
namespace primecount {
class primecount_error : public std::runtime_error
{
public:
primecount_error(const std::string& msg)
: std::runtime_error(msg)
{ }
};
/// Alias for the fastest prime counting function in primecount.
int64_t pi(int64_t x);
/// 128-bit prime counting function.
/// Run time: O(x^(2/3) / (log x)^2) operations, O(x^(1/3) * (log x)^3) space.
/// @param expr Integer arithmetic expression e.g. "1000", "10^22"
/// @pre expr <= primecount::max()
///
std::string pi(const std::string& x);
/// Calculate the number of primes below x using the
/// Deleglise-Rivat algorithm.
/// Run time: O(x^(2/3) / (log x)^2) operations, O(x^(1/3) * (log x)^3) space.
///
int64_t pi_deleglise_rivat(int64_t x);
/// Calculate the number of primes below x using Legendre's formula.
/// Run time: O(x) operations, O(x^(1/2)) space.
///
int64_t pi_legendre(int64_t x);
/// Calculate the number of primes below x using Lehmer's formula.
/// Run time: O(x/(log x)^4) operations, O(x^(1/2)) space.
///
int64_t pi_lehmer(int64_t x);
/// Calculate the number of primes below x using the
/// Lagarias-Miller-Odlyzko algorithm.
/// Run time: O(x^(2/3) / log x) operations, O(x^(1/3) * (log x)^2) space.
///
int64_t pi_lmo(int64_t x);
/// Calculate the number of primes below x using Meissel's formula.
/// Run time: O(x/(log x)^3) operations, O(x^(1/2) / log x) space.
///
int64_t pi_meissel(int64_t x);
/// Calculate the number of primes below x using an optimized
/// segmented sieve of Eratosthenes implementation.
/// Run time: O(x log log x) operations, O(x^(1/2)) space.
///
int64_t pi_primesieve(int64_t x);
/// Calculate the nth prime using a combination of an efficient prime
/// counting function implementation and the sieve of Eratosthenes.
/// Run time: O(x^(2/3) / (log x)^2) operations, O(x^(1/2)) space.
///
int64_t nth_prime(int64_t n);
/// Partial sieve function (a.k.a. Legendre-sum).
/// phi(x, a) counts the numbers <= x that are not divisible
/// by any of the first a primes.
///
int64_t phi(int64_t x, int64_t a);
/// Calculate the offset logarithmic integral which is a very
/// accurate approximation of the number of primes below x.
/// @post Li(x) > pi(x) for 24 <= x <= ~ 10^316
///
int64_t Li(int64_t x);
/// Calculate the inverse logarithmic integral Li^-1(x) which is
/// a very accurate approximation of the nth prime.
/// @post Li_inverse(x) < nth_prime(x) for 7 <= x <= ~ 10^316
///
int64_t Li_inverse(int64_t x);
/// Set the number of threads.
void set_num_threads(int num_threads);
/// Get the currently set number of threads.
int get_num_threads();
/// Largest integer supported by pi(const std::string& x).
/// The return type is a string as max may be a 128-bit integer
/// which is not supported by all compilers.
/// @return 2^63-1 for 32-bit CPUs, 10^27 for 64-bit CPUs
///
std::string max();
/// Test all prime counting function implementations.
/// @return true if success else false.
///
bool test();
} // namespace primecount
#endif
<|endoftext|> |
<commit_before>/***************************************************
This is a library for the HDC1000 Humidity & Temp Sensor
Designed specifically to work with the HDC1008 sensor from Adafruit
----> https://www.adafruit.com/products/2635
These sensors use I2C to communicate, 2 pins are required to
interface
Adafruit invests time and resources providing this open source code,
please support Adafruit and open-source hardware by purchasing
products from Adafruit!
Written by Limor Fried/Ladyada for Adafruit Industries.
BSD license, all text above must be included in any redistribution
Modified for Photon needs application.h for types RMB
****************************************************/
#include "application.h"
#include "Adafruit_HDC1000/Adafruit_HDC1000.h"
Adafruit_HDC1000::Adafruit_HDC1000() {
}
boolean Adafruit_HDC1000::begin(uint8_t addr) {
_i2caddr = addr;
Wire.begin();
reset();
if (read16(HDC1000_MANUFID) != 0x5449) return false;
if (read16(HDC1000_DEVICEID) != 0x1000) return false;
return true;
}
void Adafruit_HDC1000::reset(void) {
// reset,combined temp/humidity measurement,and select 14 bit temp & humidity resolution
uint16_t config = HDC1000_CONFIG_RST | HDC1000_CONFIG_MODE | HDC1000_CONFIG_TRES_14 | HDC1000_CONFIG_HRES_14;
Wire.beginTransmission(_i2caddr);
Wire.write(HDC1000_CONFIG); // set pointer register to configuration register RMB
Wire.write(config>>8); // now write out 2 bytes MSB first RMB
Wire.write(config&0xFF);
Wire.endTransmission();
delay(15);
}
float Adafruit_HDC1000::readTemperature(void) {
float temp = (read32(HDC1000_TEMP, 20) >> 16);
temp /= 65536;
temp *= 165;
temp -= 40;
return temp;
}
float Adafruit_HDC1000::readHumidity(void) {
// reads both temp and humidity but masks out temp in highest 16 bits
// originally used hum but humidity declared in private section of class
float humidity = (read32(HDC1000_TEMP, 20) & 0xFFFF);
humidity /= 65536;
humidity *= 100;
return humidity;
}
void Adafruit_HDC1000::ReadTempHumidity(void) {
// HDC1008 setup to measure both temperature and humidity in one conversion
// this is a different way to access data in ONE read
// this sets internal private variables that can be accessed by Get() functions
uint32_t rt,rh ; // working variables
rt = read32(HDC1000_TEMP, 20); // get temp and humidity reading together
rh = rt; // save a copy for humidity processing
float temp = (rt >> 16); // convert to temp first
temp /= 65536;
temp *= 165;
temp -= 40;
float humidity = (rh & 0xFFFF); // now convert to humidity
humidity /= 65536;
humidity *= 100;
}
float Adafruit_HDC1000::GetTemperature(void) {
// getter function to access private temp variable
return temp ;
}
float Adafruit_HDC1000::GetHumidity(void) {
// getter function to access private humidity variable
return humidity ;
}
// Add ability to test battery voltage, useful in remote monitoring, TRUE if <2.8V
// usually called after Temp/Humid reading RMB
// Thanks to KFricke for micropython-hdc1008 example on GitHub
boolean Adafruit_HDC1000::batteryLOW(void) {
uint16_t battLOW = (read16(HDC1000_CONFIG_BATT, 20));
battLOW &= HDC1000_CONFIG_BATT; // mask off other bits, bit 11 will be 1 if voltage < 2.8V
if (battLOW> 0) return true;
return false;
}
/*********************************************************************/
uint16_t Adafruit_HDC1000::read16(uint8_t a, uint8_t d) {
Wire.beginTransmission(_i2caddr);
Wire.write(a);
Wire.endTransmission();
delay(d);
Wire.requestFrom((uint8_t)_i2caddr, (uint8_t)2);
uint16_t r = Wire.read();
r <<= 8;
r |= Wire.read();
//Serial.println(r, HEX);
return r;
}
uint32_t Adafruit_HDC1000::read32(uint8_t a, uint8_t d) {
Wire.beginTransmission(_i2caddr);
Wire.write(a);
Wire.endTransmission();
// delay was hardcoded as 50, should use d RMB
delay(d);
Wire.requestFrom((uint8_t)_i2caddr, (uint8_t)4);
uint32_t r = Wire.read();
// assembles temp into highest 16 bits, humidity into lowest 16 bits
r <<= 8;
r |= Wire.read();
r <<= 8;
r |= Wire.read();
r <<= 8;
r |= Wire.read();
//Serial.println(r, HEX);
return r;
}
<commit_msg>problems with private variables temp and humidity<commit_after>/***************************************************
This is a library for the HDC1000 Humidity & Temp Sensor
Designed specifically to work with the HDC1008 sensor from Adafruit
----> https://www.adafruit.com/products/2635
These sensors use I2C to communicate, 2 pins are required to
interface
Adafruit invests time and resources providing this open source code,
please support Adafruit and open-source hardware by purchasing
products from Adafruit!
Written by Limor Fried/Ladyada for Adafruit Industries.
BSD license, all text above must be included in any redistribution
Modified for Photon needs application.h for types RMB
****************************************************/
#include "application.h"
#include "Adafruit_HDC1000/Adafruit_HDC1000.h"
Adafruit_HDC1000::Adafruit_HDC1000() {
}
boolean Adafruit_HDC1000::begin(uint8_t addr) {
_i2caddr = addr;
Wire.begin();
reset();
if (read16(HDC1000_MANUFID) != 0x5449) return false;
if (read16(HDC1000_DEVICEID) != 0x1000) return false;
return true;
}
void Adafruit_HDC1000::reset(void) {
// reset,combined temp/humidity measurement,and select 14 bit temp & humidity resolution
uint16_t config = HDC1000_CONFIG_RST | HDC1000_CONFIG_MODE | HDC1000_CONFIG_TRES_14 | HDC1000_CONFIG_HRES_14;
Wire.beginTransmission(_i2caddr);
Wire.write(HDC1000_CONFIG); // set pointer register to configuration register RMB
Wire.write(config>>8); // now write out 2 bytes MSB first RMB
Wire.write(config&0xFF);
Wire.endTransmission();
delay(15);
}
float Adafruit_HDC1000::readTemperature(void) {
float temp = (read32(HDC1000_TEMP, 20) >> 16);
temp /= 65536;
temp *= 165;
temp -= 40;
return temp;
}
float Adafruit_HDC1000::readHumidity(void) {
// reads both temp and humidity but masks out temp in highest 16 bits
// originally used hum but humidity declared in private section of class
float humidity = (read32(HDC1000_TEMP, 20) & 0xFFFF);
humidity /= 65536;
humidity *= 100;
return humidity;
}
void Adafruit_HDC1000::ReadTempHumidity(void) {
// HDC1008 setup to measure both temperature and humidity in one conversion
// this is a different way to access data in ONE read
// this sets internal private variables that can be accessed by Get() functions
uint32_t rt,rh ; // working variables
rt = read32(HDC1000_TEMP, 20); // get temp and humidity reading together
rh = rt; // save a copy for humidity processing
float temp = (rt >> 16); // convert to temp first
temp /= 65536;
temp *= 165;
temp -= 40;
Serial.print("temp=",temp);
float humidity = (rh & 0xFFFF); // now convert to humidity
humidity /= 65536;
humidity *= 100;
Serial.println("\thumidity=",humidity);
}
float Adafruit_HDC1000::GetTemperature(void) {
// getter function to access private temp variable
return temp ;
}
float Adafruit_HDC1000::GetHumidity(void) {
// getter function to access private humidity variable
return humidity ;
}
// Add ability to test battery voltage, useful in remote monitoring, TRUE if <2.8V
// usually called after Temp/Humid reading RMB
// Thanks to KFricke for micropython-hdc1008 example on GitHub
boolean Adafruit_HDC1000::batteryLOW(void) {
uint16_t battLOW = (read16(HDC1000_CONFIG_BATT, 20));
battLOW &= HDC1000_CONFIG_BATT; // mask off other bits, bit 11 will be 1 if voltage < 2.8V
if (battLOW> 0) return true;
return false;
}
/*********************************************************************/
uint16_t Adafruit_HDC1000::read16(uint8_t a, uint8_t d) {
Wire.beginTransmission(_i2caddr);
Wire.write(a);
Wire.endTransmission();
delay(d);
Wire.requestFrom((uint8_t)_i2caddr, (uint8_t)2);
uint16_t r = Wire.read();
r <<= 8;
r |= Wire.read();
//Serial.println(r, HEX);
return r;
}
uint32_t Adafruit_HDC1000::read32(uint8_t a, uint8_t d) {
Wire.beginTransmission(_i2caddr);
Wire.write(a);
Wire.endTransmission();
// delay was hardcoded as 50, should use d RMB
delay(d);
Wire.requestFrom((uint8_t)_i2caddr, (uint8_t)4);
uint32_t r = Wire.read();
// assembles temp into highest 16 bits, humidity into lowest 16 bits
r <<= 8;
r |= Wire.read();
r <<= 8;
r |= Wire.read();
r <<= 8;
r |= Wire.read();
//Serial.println(r, HEX);
return r;
}
<|endoftext|> |
<commit_before>/*
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "gameproject.h"
#include "gameprojectprivate.h"
#include "gdlhandler.h"
#include "debughelper.h"
#include <QtCore/QStringList>
#include <QtCore/QFile>
#include <QtCore/QTextStream>
#include <QMetaClassInfo>
REGISTER_OBJECTTYPE(Gluon,GameProject)
Q_DECLARE_METATYPE(Gluon::GameObject*);
using namespace Gluon;
GameProject::GameProject(QObject * parent)
: GluonObject(parent)
{
d = new GameProjectPrivate;
setGameProject(this);
#warning Q_PROPERTY does not currently handle namespaced types - see bugreports.qt.nokia.com/browse/QTBUG-2151
QVariant somethingEmpty;
GameObject * theObject = NULL;
somethingEmpty.setValue<GameObject*>(theObject);
setProperty("entryPoint", somethingEmpty);
}
GameProject::GameProject(const GameProject &other, QObject * parent)
: GluonObject(parent)
, d(other.d)
{
}
GameProject::~GameProject()
{
}
GameProject *
GameProject::instantiate()
{
return new GameProject(this);
}
GluonObject *
GameProject::findItemByName(QString qualifiedName)
{
return d->findItemByNameInObject(qualifiedName.split('.'), this);
}
bool
GameProject::saveToFile() const
{
QFile *projectFile = new QFile(filename().toLocalFile());
if(!projectFile->open(QIODevice::WriteOnly))
return false;
QList<const GluonObject*> thisProject;
thisProject.append(this);
QTextStream projectWriter(projectFile);
projectWriter << GDLHandler::instance()->serializeGDL(thisProject);
projectFile->close();
delete(projectFile);
return true;
}
bool
GameProject::loadFromFile()
{
DEBUG_FUNC_NAME
QFile *projectFile = new QFile(filename().toLocalFile());
if(!projectFile->open(QIODevice::ReadOnly))
return false;
QTextStream projectReader(projectFile);
QString fileContents = projectReader.readAll();
projectFile->close();
if(fileContents.isEmpty())
return false;
QList<GluonObject*> objectList = GDLHandler::instance()->parseGDL(fileContents, this->parent());
if(objectList.count() > 0)
{
if(objectList[0]->metaObject())
{
// If the first object in the list is a GluonProject, then let's
// adapt ourselves to represent that object...
if(objectList[0]->metaObject()->className() == this->metaObject()->className())
{
DEBUG_TEXT("Project successfully parsed - applying to local instance");
GameProject* loadedProject = qobject_cast<GameProject*>(objectList[0]);
// First things first - clean ourselves out, all the children
// and the media info list should be gone-ified
qDeleteAll(this->children());
// Reassign all the children of the newly loaded project to
// ourselves...
foreach(QObject* child, loadedProject->children())
{
GluonObject* theChild = qobject_cast<GluonObject*>(child);
theChild->setParent(this);
}
// Set all the interesting values...
setName(loadedProject->name());
// Copy accross all the properties
const QMetaObject *metaobject = loadedProject->metaObject();
int count = metaobject->propertyCount();
for(int i = 0; i < count; ++i)
{
QMetaProperty metaproperty = metaobject->property(i);
const QString theName(metaproperty.name());
if(theName == "objectName" || theName == "name")
continue;
setProperty(metaproperty.name(), loadedProject->property(metaproperty.name()));
}
// Then get all the dynamic ones (in case any such exist)
QList<QByteArray> propertyNames = loadedProject->dynamicPropertyNames();
foreach(QByteArray propName, propertyNames)
setProperty(propName, loadedProject->property(propName));
// Sanitize me!
this->sanitize();
// Finally, get rid of the left-overs
qDeleteAll(objectList);
DEBUG_TEXT("Project loading successful!");
}
// Otherwise it is not a GluonProject, and should fail!
else
{
DEBUG_TEXT(QString("First object loaded is not a Gluon::GameProject."));
DEBUG_TEXT(QString("Type of loaded object:").arg(objectList[0]->metaObject()->className()));
DEBUG_TEXT(QString("Name of loaded object:").arg(objectList[0]->name()));
return false;
}
}
else
return false;
}
delete(projectFile);
return true;
}
bool
GameProject::loadFromFile(QUrl filename)
{
setFilename(filename);
return loadFromFile();
}
/******************************************************************************
* Property Getter-setters
*****************************************************************************/
QString
GameProject::description() const
{
return d->description;
}
void
GameProject::setDescription(QString newDescription)
{
d->description = newDescription;
}
QUrl
GameProject::homepage() const
{
return d->homepage;
}
void
GameProject::setHomepage(QUrl newHomepage)
{
d->homepage = newHomepage;
}
QList<QUrl>
GameProject::mediaInfo() const
{
return d->mediaInfo;
}
void
GameProject::setMediaInfo(QList<QUrl> newMediaInfo)
{
d->mediaInfo = newMediaInfo;
}
QUrl
GameProject::filename() const
{
return d->filename;
}
void
GameProject::setFilename(QUrl newFilename)
{
d->filename = newFilename;
}
GameObject *
GameProject::entryPoint() const
{
// return d->entryPoint;
return property("entryPoint").value<GameObject*>();
}
void
GameProject::setEntryPoint(GameObject * newEntryPoint)
{
//d->entryPoint = newEntryPoint;
QVariant theNewValue;
theNewValue.setValue<GameObject*>(newEntryPoint);
setProperty("entryPoint", theNewValue);
}
#include "gameproject.moc"
<commit_msg>copy the dynamic property value<commit_after>/*
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "gameproject.h"
#include "gameprojectprivate.h"
#include "gdlhandler.h"
#include "debughelper.h"
#include <QtCore/QStringList>
#include <QtCore/QFile>
#include <QtCore/QTextStream>
#include <QMetaClassInfo>
REGISTER_OBJECTTYPE(Gluon,GameProject)
Q_DECLARE_METATYPE(Gluon::GameObject*);
using namespace Gluon;
GameProject::GameProject(QObject * parent)
: GluonObject(parent)
{
d = new GameProjectPrivate;
setGameProject(this);
#warning Q_PROPERTY does not currently handle namespaced types - see bugreports.qt.nokia.com/browse/QTBUG-2151
QVariant somethingEmpty;
GameObject * theObject = NULL;
somethingEmpty.setValue<GameObject*>(theObject);
setProperty("entryPoint", somethingEmpty);
}
GameProject::GameProject(const GameProject &other, QObject * parent)
: GluonObject(parent)
, d(other.d)
{
setProperty("entryPoint", other.property("entryPoint"));
}
GameProject::~GameProject()
{
}
GameProject *
GameProject::instantiate()
{
return new GameProject(this);
}
GluonObject *
GameProject::findItemByName(QString qualifiedName)
{
return d->findItemByNameInObject(qualifiedName.split('.'), this);
}
bool
GameProject::saveToFile() const
{
QFile *projectFile = new QFile(filename().toLocalFile());
if(!projectFile->open(QIODevice::WriteOnly))
return false;
QList<const GluonObject*> thisProject;
thisProject.append(this);
QTextStream projectWriter(projectFile);
projectWriter << GDLHandler::instance()->serializeGDL(thisProject);
projectFile->close();
delete(projectFile);
return true;
}
bool
GameProject::loadFromFile()
{
DEBUG_FUNC_NAME
QFile *projectFile = new QFile(filename().toLocalFile());
if(!projectFile->open(QIODevice::ReadOnly))
return false;
QTextStream projectReader(projectFile);
QString fileContents = projectReader.readAll();
projectFile->close();
if(fileContents.isEmpty())
return false;
QList<GluonObject*> objectList = GDLHandler::instance()->parseGDL(fileContents, this->parent());
if(objectList.count() > 0)
{
if(objectList[0]->metaObject())
{
// If the first object in the list is a GluonProject, then let's
// adapt ourselves to represent that object...
if(objectList[0]->metaObject()->className() == this->metaObject()->className())
{
DEBUG_TEXT("Project successfully parsed - applying to local instance");
GameProject* loadedProject = qobject_cast<GameProject*>(objectList[0]);
// First things first - clean ourselves out, all the children
// and the media info list should be gone-ified
qDeleteAll(this->children());
// Reassign all the children of the newly loaded project to
// ourselves...
foreach(QObject* child, loadedProject->children())
{
GluonObject* theChild = qobject_cast<GluonObject*>(child);
theChild->setParent(this);
}
// Set all the interesting values...
setName(loadedProject->name());
// Copy accross all the properties
const QMetaObject *metaobject = loadedProject->metaObject();
int count = metaobject->propertyCount();
for(int i = 0; i < count; ++i)
{
QMetaProperty metaproperty = metaobject->property(i);
const QString theName(metaproperty.name());
if(theName == "objectName" || theName == "name")
continue;
setProperty(metaproperty.name(), loadedProject->property(metaproperty.name()));
}
// Then get all the dynamic ones (in case any such exist)
QList<QByteArray> propertyNames = loadedProject->dynamicPropertyNames();
foreach(QByteArray propName, propertyNames)
setProperty(propName, loadedProject->property(propName));
// Sanitize me!
this->sanitize();
// Finally, get rid of the left-overs
qDeleteAll(objectList);
DEBUG_TEXT("Project loading successful!");
}
// Otherwise it is not a GluonProject, and should fail!
else
{
DEBUG_TEXT(QString("First object loaded is not a Gluon::GameProject."));
DEBUG_TEXT(QString("Type of loaded object:").arg(objectList[0]->metaObject()->className()));
DEBUG_TEXT(QString("Name of loaded object:").arg(objectList[0]->name()));
return false;
}
}
else
return false;
}
delete(projectFile);
return true;
}
bool
GameProject::loadFromFile(QUrl filename)
{
setFilename(filename);
return loadFromFile();
}
/******************************************************************************
* Property Getter-setters
*****************************************************************************/
QString
GameProject::description() const
{
return d->description;
}
void
GameProject::setDescription(QString newDescription)
{
d->description = newDescription;
}
QUrl
GameProject::homepage() const
{
return d->homepage;
}
void
GameProject::setHomepage(QUrl newHomepage)
{
d->homepage = newHomepage;
}
QList<QUrl>
GameProject::mediaInfo() const
{
return d->mediaInfo;
}
void
GameProject::setMediaInfo(QList<QUrl> newMediaInfo)
{
d->mediaInfo = newMediaInfo;
}
QUrl
GameProject::filename() const
{
return d->filename;
}
void
GameProject::setFilename(QUrl newFilename)
{
d->filename = newFilename;
}
GameObject *
GameProject::entryPoint() const
{
// return d->entryPoint;
return property("entryPoint").value<GameObject*>();
}
void
GameProject::setEntryPoint(GameObject * newEntryPoint)
{
//d->entryPoint = newEntryPoint;
QVariant theNewValue;
theNewValue.setValue<GameObject*>(newEntryPoint);
setProperty("entryPoint", theNewValue);
}
#include "gameproject.moc"
<|endoftext|> |
<commit_before>// PythonStuff.cpp
// Copyright 2011, Dan Heeks
// This program is released under the BSD license. See the file COPYING for details.
#include "PythonStuff.h"
#include "Area.h"
#include "Point.h"
#include "AreaDxf.h"
#include "kurve/geometry.h"
#if _DEBUG
#undef _DEBUG
#include <Python.h>
#define _DEBUG
#else
#include <Python.h>
#endif
#ifdef __GNUG__
#pragma implementation
#endif
#include <boost/progress.hpp>
#include <boost/timer.hpp>
#include <boost/foreach.hpp>
#include <boost/python.hpp>
#include <boost/python/module.hpp>
#include <boost/python/class.hpp>
#include <boost/python/wrapper.hpp>
#include <boost/python/call.hpp>
#include "clipper.hpp"
using namespace clipper;
namespace bp = boost::python;
boost::python::list getVertices(const CCurve& curve) {
boost::python::list vlist;
BOOST_FOREACH(const CVertex& vertex, curve.m_vertices) {
vlist.append(vertex);
}
return vlist;
}
boost::python::list getCurves(const CArea& area) {
boost::python::list clist;
BOOST_FOREACH(const CCurve& curve, area.m_curves) {
clist.append(curve);
}
return clist;
}
boost::python::tuple transformed_point(const geoff_geometry::Matrix &matrix, double x, double y, double z)
{
geoff_geometry::Point3d p(x,y,z);
p = p.Transform(matrix);
return bp::make_tuple(p.x,p.y,p.z);
}
static void print_curve(const CCurve& c)
{
unsigned int nvertices = c.m_vertices.size();
printf("number of vertices = %d\n", nvertices);
int i = 0;
for(std::list<CVertex>::const_iterator It = c.m_vertices.begin(); It != c.m_vertices.end(); It++, i++)
{
const CVertex& vertex = *It;
printf("vertex %d type = %d, x = %g, y = %g", i+1, vertex.m_type, vertex.m_p.x / CArea::m_units, vertex.m_p.y / CArea::m_units);
if(vertex.m_type)printf(", xc = %g, yc = %g", vertex.m_c.x / CArea::m_units, vertex.m_c.y / CArea::m_units);
printf("\n");
}
}
static void print_area(const CArea &a)
{
for(std::list<CCurve>::const_iterator It = a.m_curves.begin(); It != a.m_curves.end(); It++)
{
const CCurve& curve = *It;
print_curve(curve);
}
}
static unsigned int num_vertices(const CCurve& curve)
{
return curve.m_vertices.size();
}
static CVertex FirstVertex(const CCurve& curve)
{
return curve.m_vertices.front();
}
static CVertex LastVertex(const CCurve& curve)
{
return curve.m_vertices.back();
}
static void set_units(double units)
{
CArea::m_units = units;
}
static double get_units()
{
return CArea::m_units;
}
static bool holes_linked()
{
return CArea::HolesLinked();
}
static CArea AreaFromDxf(const char* filepath)
{
CArea area;
AreaDxfRead dxf(&area, filepath);
dxf.DoRead();
return area;
}
static void append_point(CCurve& c, const Point& p)
{
c.m_vertices.push_back(CVertex(p));
}
static boost::python::tuple nearest_point_to_curve(CCurve& c1, const CCurve& c2)
{
double dist;
Point p = c1.NearestPoint(c2, &dist);
return bp::make_tuple(p, dist);
}
boost::python::list MakePocketToolpath(const CArea& a, double tool_radius, double extra_offset, double stepover, bool from_center, bool use_zig_zag, double zig_angle)
{
std::list<CCurve> toolpath;
CAreaPocketParams params(tool_radius, extra_offset, stepover, from_center, use_zig_zag ? ZigZagPocketMode : SpiralPocketMode, zig_angle);
a.SplitAndMakePocketToolpath(toolpath, params);
boost::python::list clist;
BOOST_FOREACH(const CCurve& c, toolpath) {
clist.append(c);
}
return clist;
}
boost::python::list SplitArea(const CArea& a)
{
std::list<CArea> areas;
a.Split(areas);
boost::python::list alist;
BOOST_FOREACH(const CArea& a, areas) {
alist.append(a);
}
return alist;
}
void dxfArea(CArea& area, const char* str)
{
area = CArea();
}
boost::python::list getCurveSpans(const CCurve& c)
{
boost::python::list span_list;
const Point *prev_p = NULL;
for(std::list<CVertex>::const_iterator VIt = c.m_vertices.begin(); VIt != c.m_vertices.end(); VIt++)
{
const CVertex& vertex = *VIt;
if(prev_p)
{
span_list.append(Span(*prev_p, vertex));
}
prev_p = &(vertex.m_p);
}
return span_list;
}
Span getFirstCurveSpan(const CCurve& c)
{
if(c.m_vertices.size() < 2)return Span();
std::list<CVertex>::const_iterator VIt = c.m_vertices.begin();
const Point &p = (*VIt).m_p;
VIt++;
return Span(p, *VIt, true);
}
Span getLastCurveSpan(const CCurve& c)
{
if(c.m_vertices.size() < 2)return Span();
std::list<CVertex>::const_reverse_iterator VIt = c.m_vertices.rbegin();
const CVertex &v = (*VIt);
VIt++;
return Span((*VIt).m_p, v, c.m_vertices.size() == 2);
}
bp::tuple TangentialArc(const Point &p0, const Point &p1, const Point &v0)
{
Point c;
int dir;
tangential_arc(p0, p1, v0, c, dir);
return bp::make_tuple(c, dir);
}
boost::python::list spanIntersect(const Span& span1, const Span& span2) {
boost::python::list plist;
std::list<Point> pts;
span1.Intersect(span2, pts);
BOOST_FOREACH(const Point& p, pts) {
plist.append(p);
}
return plist;
}
//Matrix(boost::python::list &l){}
boost::shared_ptr<geoff_geometry::Matrix> matrix_constructor(const boost::python::list& lst) {
double m[16] = {1,0,0,0,0,1,0,0, 0,0,1,0, 0,0,0,1};
boost::python::ssize_t n = boost::python::len(lst);
int j = 0;
for(boost::python::ssize_t i=0;i<n;i++) {
boost::python::object elem = lst[i];
m[j] = boost::python::extract<double>(elem.attr("__float__")());
j++;
if(j>=16)break;
}
return boost::shared_ptr<geoff_geometry::Matrix>( new geoff_geometry::Matrix(m) );
}
boost::python::list InsideCurves(const CArea& a, const CCurve& curve) {
boost::python::list plist;
std::list<CCurve> curves_inside;
a.InsideCurves(curve, curves_inside);
BOOST_FOREACH(const CCurve& c, curves_inside) {
plist.append(c);
}
return plist;
}
BOOST_PYTHON_MODULE(area) {
bp::class_<Point>("Point")
.def(bp::init<double, double>())
.def(bp::init<Point>())
.def(bp::other<double>() * bp::self)
.def(bp::self * bp::other<double>())
.def(bp::self / bp::other<double>())
.def(bp::self * bp::other<Point>())
.def(bp::self - bp::other<Point>())
.def(bp::self + bp::other<Point>())
.def(bp::self ^ bp::other<Point>())
.def(bp::self == bp::other<Point>())
.def(bp::self != bp::other<Point>())
.def(-bp::self)
.def(~bp::self)
.def("dist", &Point::dist)
.def("length", &Point::length)
.def("normalize", &Point::normalize)
.def("Rotate", static_cast< void (Point::*)(double, double) >(&Point::Rotate))
.def("Rotate", static_cast< void (Point::*)(double) >(&Point::Rotate))
.def_readwrite("x", &Point::x)
.def_readwrite("y", &Point::y)
.def("Transform", &Point::Transform)
;
bp::class_<CVertex>("Vertex")
.def(bp::init<CVertex>())
.def(bp::init<int, Point, Point>())
.def(bp::init<Point>())
.def(bp::init<int, Point, Point, int>())
.def_readwrite("type", &CVertex::m_type)
.def_readwrite("p", &CVertex::m_p)
.def_readwrite("c", &CVertex::m_c)
.def_readwrite("user_data", &CVertex::m_user_data)
;
bp::class_<Span>("Span")
.def(bp::init<Span>())
.def(bp::init<Point, CVertex, bool>())
.def("NearestPoint", static_cast< Point (Span::*)(const Point& p)const >(&Span::NearestPoint))
.def("NearestPoint", static_cast< Point (Span::*)(const Span& p, double *d)const >(&Span::NearestPoint))
.def("GetBox", &Span::GetBox)
.def("IncludedAngle", &Span::IncludedAngle)
.def("GetArea", &Span::GetArea)
.def("On", &Span::On)
.def("MidPerim", &Span::MidPerim)
.def("MidParam", &Span::MidParam)
.def("Length", &Span::Length)
.def("GetVector", &Span::GetVector)
.def("Intersect", &spanIntersect)
.def_readwrite("p", &Span::m_p)
.def_readwrite("v", &Span::m_v)
;
bp::class_<CCurve>("Curve")
.def(bp::init<CCurve>())
.def("getVertices", &getVertices)
.def("append",&CCurve::append)
.def("append",&append_point)
.def("text", &print_curve)
.def("NearestPoint", static_cast< Point (CCurve::*)(const Point& p)const >(&CCurve::NearestPoint))
.def("NearestPoint", &nearest_point_to_curve)
.def("Reverse", &CCurve::Reverse)
.def("getNumVertices", &num_vertices)
.def("FirstVertex", &FirstVertex)
.def("LastVertex", &LastVertex)
.def("GetArea", &CCurve::GetArea)
.def("IsClockwise", &CCurve::IsClockwise)
.def("IsClosed", &CCurve::IsClosed)
.def("ChangeStart",&CCurve::ChangeStart)
.def("ChangeEnd",&CCurve::ChangeEnd)
.def("Offset",&CCurve::Offset)
.def("OffsetForward",&CCurve::OffsetForward)
.def("GetSpans",&getCurveSpans)
.def("GetFirstSpan",&getFirstCurveSpan)
.def("GetLastSpan",&getLastCurveSpan)
.def("Break",&CCurve::Break)
.def("Perim",&CCurve::Perim)
.def("PerimToPoint",&CCurve::PerimToPoint)
.def("PointToPerim",&CCurve::PointToPerim)
.def("FitArcs",&CCurve::FitArcs)
.def("UnFitArcs",&CCurve::UnFitArcs)
;
bp::class_<CBox2D>("Box")
.def(bp::init<CBox2D>())
.def("MinX", &CBox2D::MinX)
.def("MaxX", &CBox2D::MaxX)
.def("MinY", &CBox2D::MinY)
.def("MaxY", &CBox2D::MaxY)
;
bp::class_<CArea>("Area")
.def(bp::init<CArea>())
.def("getCurves", &getCurves)
.def("append",&CArea::append)
.def("Subtract",&CArea::Subtract)
.def("Intersect",&CArea::Intersect)
.def("Union",&CArea::Union)
.def("Offset",&CArea::Offset)
.def("FitArcs",&CArea::FitArcs)
.def("text", &print_area)
.def("num_curves", &CArea::num_curves)
.def("NearestPoint", &CArea::NearestPoint)
.def("GetBox", &CArea::GetBox)
.def("Reorder", &CArea::Reorder)
.def("MakePocketToolpath", &MakePocketToolpath)
.def("Split", &SplitArea)
.def("InsideCurves", &InsideCurves)
;
bp::class_<geoff_geometry::Matrix, boost::shared_ptr<geoff_geometry::Matrix> > ("Matrix")
.def(bp::init<geoff_geometry::Matrix>())
.def("__init__", bp::make_constructor(&matrix_constructor))
.def("TransformedPoint", &transformed_point)
.def("Multiply", &geoff_geometry::Matrix::Multiply)
;
bp::def("set_units", set_units);
bp::def("get_units", get_units);
bp::def("holes_linked", holes_linked);
bp::def("AreaFromDxf", AreaFromDxf);
bp::def("TangentialArc", TangentialArc);
}
<commit_msg>I exported the CArea::Thicken function to Python<commit_after>// PythonStuff.cpp
// Copyright 2011, Dan Heeks
// This program is released under the BSD license. See the file COPYING for details.
#include "PythonStuff.h"
#include "Area.h"
#include "Point.h"
#include "AreaDxf.h"
#include "kurve/geometry.h"
#if _DEBUG
#undef _DEBUG
#include <Python.h>
#define _DEBUG
#else
#include <Python.h>
#endif
#ifdef __GNUG__
#pragma implementation
#endif
#include <boost/progress.hpp>
#include <boost/timer.hpp>
#include <boost/foreach.hpp>
#include <boost/python.hpp>
#include <boost/python/module.hpp>
#include <boost/python/class.hpp>
#include <boost/python/wrapper.hpp>
#include <boost/python/call.hpp>
#include "clipper.hpp"
using namespace clipper;
namespace bp = boost::python;
boost::python::list getVertices(const CCurve& curve) {
boost::python::list vlist;
BOOST_FOREACH(const CVertex& vertex, curve.m_vertices) {
vlist.append(vertex);
}
return vlist;
}
boost::python::list getCurves(const CArea& area) {
boost::python::list clist;
BOOST_FOREACH(const CCurve& curve, area.m_curves) {
clist.append(curve);
}
return clist;
}
boost::python::tuple transformed_point(const geoff_geometry::Matrix &matrix, double x, double y, double z)
{
geoff_geometry::Point3d p(x,y,z);
p = p.Transform(matrix);
return bp::make_tuple(p.x,p.y,p.z);
}
static void print_curve(const CCurve& c)
{
unsigned int nvertices = c.m_vertices.size();
printf("number of vertices = %d\n", nvertices);
int i = 0;
for(std::list<CVertex>::const_iterator It = c.m_vertices.begin(); It != c.m_vertices.end(); It++, i++)
{
const CVertex& vertex = *It;
printf("vertex %d type = %d, x = %g, y = %g", i+1, vertex.m_type, vertex.m_p.x / CArea::m_units, vertex.m_p.y / CArea::m_units);
if(vertex.m_type)printf(", xc = %g, yc = %g", vertex.m_c.x / CArea::m_units, vertex.m_c.y / CArea::m_units);
printf("\n");
}
}
static void print_area(const CArea &a)
{
for(std::list<CCurve>::const_iterator It = a.m_curves.begin(); It != a.m_curves.end(); It++)
{
const CCurve& curve = *It;
print_curve(curve);
}
}
static unsigned int num_vertices(const CCurve& curve)
{
return curve.m_vertices.size();
}
static CVertex FirstVertex(const CCurve& curve)
{
return curve.m_vertices.front();
}
static CVertex LastVertex(const CCurve& curve)
{
return curve.m_vertices.back();
}
static void set_units(double units)
{
CArea::m_units = units;
}
static double get_units()
{
return CArea::m_units;
}
static bool holes_linked()
{
return CArea::HolesLinked();
}
static CArea AreaFromDxf(const char* filepath)
{
CArea area;
AreaDxfRead dxf(&area, filepath);
dxf.DoRead();
return area;
}
static void append_point(CCurve& c, const Point& p)
{
c.m_vertices.push_back(CVertex(p));
}
static boost::python::tuple nearest_point_to_curve(CCurve& c1, const CCurve& c2)
{
double dist;
Point p = c1.NearestPoint(c2, &dist);
return bp::make_tuple(p, dist);
}
boost::python::list MakePocketToolpath(const CArea& a, double tool_radius, double extra_offset, double stepover, bool from_center, bool use_zig_zag, double zig_angle)
{
std::list<CCurve> toolpath;
CAreaPocketParams params(tool_radius, extra_offset, stepover, from_center, use_zig_zag ? ZigZagPocketMode : SpiralPocketMode, zig_angle);
a.SplitAndMakePocketToolpath(toolpath, params);
boost::python::list clist;
BOOST_FOREACH(const CCurve& c, toolpath) {
clist.append(c);
}
return clist;
}
boost::python::list SplitArea(const CArea& a)
{
std::list<CArea> areas;
a.Split(areas);
boost::python::list alist;
BOOST_FOREACH(const CArea& a, areas) {
alist.append(a);
}
return alist;
}
void dxfArea(CArea& area, const char* str)
{
area = CArea();
}
boost::python::list getCurveSpans(const CCurve& c)
{
boost::python::list span_list;
const Point *prev_p = NULL;
for(std::list<CVertex>::const_iterator VIt = c.m_vertices.begin(); VIt != c.m_vertices.end(); VIt++)
{
const CVertex& vertex = *VIt;
if(prev_p)
{
span_list.append(Span(*prev_p, vertex));
}
prev_p = &(vertex.m_p);
}
return span_list;
}
Span getFirstCurveSpan(const CCurve& c)
{
if(c.m_vertices.size() < 2)return Span();
std::list<CVertex>::const_iterator VIt = c.m_vertices.begin();
const Point &p = (*VIt).m_p;
VIt++;
return Span(p, *VIt, true);
}
Span getLastCurveSpan(const CCurve& c)
{
if(c.m_vertices.size() < 2)return Span();
std::list<CVertex>::const_reverse_iterator VIt = c.m_vertices.rbegin();
const CVertex &v = (*VIt);
VIt++;
return Span((*VIt).m_p, v, c.m_vertices.size() == 2);
}
bp::tuple TangentialArc(const Point &p0, const Point &p1, const Point &v0)
{
Point c;
int dir;
tangential_arc(p0, p1, v0, c, dir);
return bp::make_tuple(c, dir);
}
boost::python::list spanIntersect(const Span& span1, const Span& span2) {
boost::python::list plist;
std::list<Point> pts;
span1.Intersect(span2, pts);
BOOST_FOREACH(const Point& p, pts) {
plist.append(p);
}
return plist;
}
//Matrix(boost::python::list &l){}
boost::shared_ptr<geoff_geometry::Matrix> matrix_constructor(const boost::python::list& lst) {
double m[16] = {1,0,0,0,0,1,0,0, 0,0,1,0, 0,0,0,1};
boost::python::ssize_t n = boost::python::len(lst);
int j = 0;
for(boost::python::ssize_t i=0;i<n;i++) {
boost::python::object elem = lst[i];
m[j] = boost::python::extract<double>(elem.attr("__float__")());
j++;
if(j>=16)break;
}
return boost::shared_ptr<geoff_geometry::Matrix>( new geoff_geometry::Matrix(m) );
}
boost::python::list InsideCurves(const CArea& a, const CCurve& curve) {
boost::python::list plist;
std::list<CCurve> curves_inside;
a.InsideCurves(curve, curves_inside);
BOOST_FOREACH(const CCurve& c, curves_inside) {
plist.append(c);
}
return plist;
}
BOOST_PYTHON_MODULE(area) {
bp::class_<Point>("Point")
.def(bp::init<double, double>())
.def(bp::init<Point>())
.def(bp::other<double>() * bp::self)
.def(bp::self * bp::other<double>())
.def(bp::self / bp::other<double>())
.def(bp::self * bp::other<Point>())
.def(bp::self - bp::other<Point>())
.def(bp::self + bp::other<Point>())
.def(bp::self ^ bp::other<Point>())
.def(bp::self == bp::other<Point>())
.def(bp::self != bp::other<Point>())
.def(-bp::self)
.def(~bp::self)
.def("dist", &Point::dist)
.def("length", &Point::length)
.def("normalize", &Point::normalize)
.def("Rotate", static_cast< void (Point::*)(double, double) >(&Point::Rotate))
.def("Rotate", static_cast< void (Point::*)(double) >(&Point::Rotate))
.def_readwrite("x", &Point::x)
.def_readwrite("y", &Point::y)
.def("Transform", &Point::Transform)
;
bp::class_<CVertex>("Vertex")
.def(bp::init<CVertex>())
.def(bp::init<int, Point, Point>())
.def(bp::init<Point>())
.def(bp::init<int, Point, Point, int>())
.def_readwrite("type", &CVertex::m_type)
.def_readwrite("p", &CVertex::m_p)
.def_readwrite("c", &CVertex::m_c)
.def_readwrite("user_data", &CVertex::m_user_data)
;
bp::class_<Span>("Span")
.def(bp::init<Span>())
.def(bp::init<Point, CVertex, bool>())
.def("NearestPoint", static_cast< Point (Span::*)(const Point& p)const >(&Span::NearestPoint))
.def("NearestPoint", static_cast< Point (Span::*)(const Span& p, double *d)const >(&Span::NearestPoint))
.def("GetBox", &Span::GetBox)
.def("IncludedAngle", &Span::IncludedAngle)
.def("GetArea", &Span::GetArea)
.def("On", &Span::On)
.def("MidPerim", &Span::MidPerim)
.def("MidParam", &Span::MidParam)
.def("Length", &Span::Length)
.def("GetVector", &Span::GetVector)
.def("Intersect", &spanIntersect)
.def_readwrite("p", &Span::m_p)
.def_readwrite("v", &Span::m_v)
;
bp::class_<CCurve>("Curve")
.def(bp::init<CCurve>())
.def("getVertices", &getVertices)
.def("append",&CCurve::append)
.def("append",&append_point)
.def("text", &print_curve)
.def("NearestPoint", static_cast< Point (CCurve::*)(const Point& p)const >(&CCurve::NearestPoint))
.def("NearestPoint", &nearest_point_to_curve)
.def("Reverse", &CCurve::Reverse)
.def("getNumVertices", &num_vertices)
.def("FirstVertex", &FirstVertex)
.def("LastVertex", &LastVertex)
.def("GetArea", &CCurve::GetArea)
.def("IsClockwise", &CCurve::IsClockwise)
.def("IsClosed", &CCurve::IsClosed)
.def("ChangeStart",&CCurve::ChangeStart)
.def("ChangeEnd",&CCurve::ChangeEnd)
.def("Offset",&CCurve::Offset)
.def("OffsetForward",&CCurve::OffsetForward)
.def("GetSpans",&getCurveSpans)
.def("GetFirstSpan",&getFirstCurveSpan)
.def("GetLastSpan",&getLastCurveSpan)
.def("Break",&CCurve::Break)
.def("Perim",&CCurve::Perim)
.def("PerimToPoint",&CCurve::PerimToPoint)
.def("PointToPerim",&CCurve::PointToPerim)
.def("FitArcs",&CCurve::FitArcs)
.def("UnFitArcs",&CCurve::UnFitArcs)
;
bp::class_<CBox2D>("Box")
.def(bp::init<CBox2D>())
.def("MinX", &CBox2D::MinX)
.def("MaxX", &CBox2D::MaxX)
.def("MinY", &CBox2D::MinY)
.def("MaxY", &CBox2D::MaxY)
;
bp::class_<CArea>("Area")
.def(bp::init<CArea>())
.def("getCurves", &getCurves)
.def("append",&CArea::append)
.def("Subtract",&CArea::Subtract)
.def("Intersect",&CArea::Intersect)
.def("Union",&CArea::Union)
.def("Offset",&CArea::Offset)
.def("FitArcs",&CArea::FitArcs)
.def("text", &print_area)
.def("num_curves", &CArea::num_curves)
.def("NearestPoint", &CArea::NearestPoint)
.def("GetBox", &CArea::GetBox)
.def("Reorder", &CArea::Reorder)
.def("MakePocketToolpath", &MakePocketToolpath)
.def("Split", &SplitArea)
.def("InsideCurves", &InsideCurves)
.def("Thicken"), &CArea::Thicken)
;
bp::class_<geoff_geometry::Matrix, boost::shared_ptr<geoff_geometry::Matrix> > ("Matrix")
.def(bp::init<geoff_geometry::Matrix>())
.def("__init__", bp::make_constructor(&matrix_constructor))
.def("TransformedPoint", &transformed_point)
.def("Multiply", &geoff_geometry::Matrix::Multiply)
;
bp::def("set_units", set_units);
bp::def("get_units", get_units);
bp::def("holes_linked", holes_linked);
bp::def("AreaFromDxf", AreaFromDxf);
bp::def("TangentialArc", TangentialArc);
}
<|endoftext|> |
<commit_before>#include "dynet/nodes.h"
#include "dynet/dynet.h"
#include "dynet/training.h"
#include "dynet/timing.h"
#include "dynet/rnn.h"
#include "dynet/gru.h"
#include "dynet/lstm.h"
#include "dynet/dict.h"
#include "dynet/expr.h"
#include "dynet/cfsm-builder.h"
#include "dynet/hsm-builder.h"
#include "dynet/globals.h"
#include "dynet/io.h"
#include "../utils/getpid.h"
#include "../utils/cl-args.h"
#include <iostream>
#include <fstream>
#include <sstream>
using namespace std;
using namespace dynet;
unsigned LAYERS = 0;
unsigned INPUT_DIM = 0;
unsigned HIDDEN_DIM = 0;
unsigned VOCAB_SIZE = 0;
float DROPOUT = 0;
bool SAMPLE = false;
SoftmaxBuilder* cfsm = nullptr;
dynet::Dict d;
int kSOS;
int kEOS;
volatile bool INTERRUPTED = false;
template <class Builder>
struct RNNLanguageModel {
LookupParameter p_c;
Parameter p_R;
Parameter p_bias;
Builder builder;
explicit RNNLanguageModel(ParameterCollection& model) : builder(LAYERS, INPUT_DIM, HIDDEN_DIM, model) {
p_c = model.add_lookup_parameters(VOCAB_SIZE, {INPUT_DIM});
p_R = model.add_parameters({VOCAB_SIZE, HIDDEN_DIM});
p_bias = model.add_parameters({VOCAB_SIZE});
}
// return Expression of total loss
Expression BuildLMGraph(const vector<int>& sent, ComputationGraph& cg, bool apply_dropout) {
const unsigned slen = sent.size();
if (apply_dropout) {
builder.set_dropout(DROPOUT);
} else {
builder.disable_dropout();
}
builder.new_graph(cg); // reset RNN builder for new graph
builder.start_new_sequence();
if (cfsm) cfsm->new_graph(cg);
Expression R = parameter(cg, p_R); // hidden -> word rep parameter
Expression bias = parameter(cg, p_bias); // word bias
vector<Expression> errs(slen + 1);
Expression h_t = builder.add_input(lookup(cg, p_c, kSOS)); // read <s>
for (unsigned t = 0; t < slen; ++t) { // h_t = RNN(x_0,...,x_t)
if (cfsm) { // class-factored softmax
errs[t] = cfsm->neg_log_softmax(h_t, sent[t]);
} else { // regular softmax
Expression u_t = affine_transform({bias, R, h_t});
errs[t] = pickneglogsoftmax(u_t, sent[t]);
}
Expression x_t = lookup(cg, p_c, sent[t]);
h_t = builder.add_input(x_t);
}
// it reamins to deal predict </s>
if (cfsm) {
errs.back() = cfsm->neg_log_softmax(h_t, kEOS);
} else {
Expression u_last = affine_transform({bias, R, h_t});
errs.back() = pickneglogsoftmax(u_last, kEOS); // predict </s>
}
return sum(errs);
}
void RandomSample(int max_len = 200) {
ComputationGraph cg;
builder.new_graph(cg); // reset RNN builder for new graph
builder.start_new_sequence();
if (cfsm) cfsm->new_graph(cg);
Expression R = parameter(cg, p_R); // hidden -> word rep parameter
Expression bias = parameter(cg, p_bias); // word bias
Expression h_t = builder.add_input(lookup(cg, p_c, kSOS)); // read <s>
int cur = kSOS;
int len = 0;
while (len < max_len) {
if (cfsm) { // class-factored softmax
cur = cfsm->sample(h_t);
} else { // regular softmax
Expression u_t = affine_transform({bias, R, h_t});
Expression dist_expr = softmax(u_t);
auto dist = as_vector(cg.incremental_forward(dist_expr));
double p = rand01();
cur = 0;
for (; cur < dist.size(); ++cur) {
p -= dist[cur];
if (p < 0.0) { break; }
}
if (cur == dist.size()) cur = kEOS;
}
if (cur == kEOS) break;
++len;
cerr << (len == 1 ? "" : " ") << d.convert(cur);
Expression x_t = lookup(cg, p_c, cur);
h_t = builder.add_input(x_t);
}
cerr << endl;
}
};
void inline read_fields(string line, vector<string>& fields, string delimiter = "|||") {
string field;
int start = 0, end = 0, delim_size = delimiter.size();
while (true) {
end = line.find(delimiter, start);
fields.push_back(line.substr(start, end - start));
if (end == std::string::npos) break;
start = end + delim_size;
}
}
int main(int argc, char** argv) {
cerr << "COMMAND LINE:";
for (unsigned i = 0; i < static_cast<unsigned>(argc); ++i) cerr << ' ' << argv[i];
cerr << endl;
// Fetch dynet params ----------------------------------------------------------------------------
auto dyparams = dynet::extract_dynet_params(argc, argv);
dynet::initialize(dyparams);
// Fetch program specific parameters (see ../utils/cl-args.h) ------------------------------------
Params params;
get_args(argc, argv, params, TRAIN);
kSOS = d.convert("<s>");
kEOS = d.convert("</s>");
LAYERS = params.LAYERS;
INPUT_DIM = params.INPUT_DIM;
HIDDEN_DIM = params.HIDDEN_DIM;
SAMPLE = params.sample;
if (params.dropout_rate)
DROPOUT = params.dropout_rate;
Model model;
if (params.clusters_file != "")
cfsm = new ClassFactoredSoftmaxBuilder(HIDDEN_DIM, params.clusters_file, d, model);
else if (params.paths_file != "")
cfsm = new HierarchicalSoftmaxBuilder(HIDDEN_DIM, params.paths_file, d, model);
float eta_decay_rate = params.eta_decay_rate;
unsigned eta_decay_onset_epoch = params.eta_decay_onset_epoch;
vector<vector<int>> training, dev, test;
string line;
int tlc = 0;
int ttoks = 0;
{
string trainf = params.train_file;
cerr << "Reading training data from " << trainf << " ...\n";
ifstream in(trainf);
assert(in);
while (getline(in, line)) {
++tlc;
training.push_back(read_sentence(line, d));
ttoks += training.back().size();
if (training.back().front() == kSOS || training.back().back() == kEOS) {
cerr << "Training sentence in " << argv[1] << ":" << tlc << " started with <s> or ended with </s>\n";
abort();
}
}
cerr << tlc << " lines, " << ttoks << " tokens, " << d.size() << " types\n";
}
d.freeze(); // no new word types allowed
d.set_unk("<unk>");
VOCAB_SIZE = d.size();
if (!cfsm)
cfsm = new StandardSoftmaxBuilder(HIDDEN_DIM, VOCAB_SIZE, model);
if (params.test_file != "") {
string testf = params.test_file;
cerr << "Reading test data from " << testf << " ...\n";
ifstream in(testf);
assert(in);
while (getline(in, line)) {
test.push_back(read_sentence(line, d));
if (test.back().front() == kSOS || test.back().back() == kEOS) {
cerr << "Test sentence in " << argv[2] << ":" << tlc << " started with <s> or ended with </s>\n";
abort();
}
}
}
Trainer* sgd = new SimpleSGDTrainer(model);
sgd->eta0 = sgd->eta = params.eta0;
RNNLanguageModel<LSTMBuilder> lm(model);
bool has_model_to_load = params.model_file != "";
if (has_model_to_load) {
string fname = params.model_file;
cerr << "Reading parameters from " << fname << "...\n";
TextFileSaver saver(fname);
saver.save(model);
}
bool TRAIN = (params.train_file != "");
if (TRAIN) {
int dlc = 0;
int dtoks = 0;
if (params.dev_file == "") {
cerr << "You must specify a development set (--dev file.txt) with --train" << endl;
abort();
} else {
string devf = params.dev_file;
cerr << "Reading dev data from " << devf << " ...\n";
ifstream in(devf);
assert(in);
while (getline(in, line)) {
++dlc;
dev.push_back(read_sentence(line, d));
dtoks += dev.back().size();
if (dev.back().front() == kSOS || dev.back().back() == kEOS) {
cerr << "Dev sentence in " << argv[2] << ":" << tlc << " started with <s> or ended with </s>\n";
abort();
}
}
cerr << dlc << " lines, " << dtoks << " tokens\n";
}
ostringstream os;
os << "lm"
<< '_' << DROPOUT
<< '_' << LAYERS
<< '_' << INPUT_DIM
<< '_' << HIDDEN_DIM
<< "-pid" << getpid() << ".params";
const string fname = os.str();
cerr << "Parameters will be written to: " << fname << endl;
double best = 9e+99;
unsigned report_every_i = 100;
unsigned dev_every_i_reports = 25;
unsigned si = training.size();
if (report_every_i > si) report_every_i = si;
vector<unsigned> order(training.size());
for (unsigned i = 0; i < order.size(); ++i) order[i] = i;
bool first = true;
int report = 0;
double lines = 0;
int completed_epoch = -1;
while (!INTERRUPTED) {
if (SAMPLE) lm.RandomSample();
Timer iteration("completed in");
double loss = 0;
unsigned chars = 0;
for (unsigned i = 0; i < report_every_i; ++i) {
if (si == training.size()) {
si = 0;
if (first) { first = false; } else { sgd->update_epoch(); }
cerr << "**SHUFFLE\n";
completed_epoch++;
if (eta_decay_onset_epoch && completed_epoch >= (int)eta_decay_onset_epoch)
sgd->eta *= eta_decay_rate;
shuffle(order.begin(), order.end(), *rndeng);
}
// build graph for this instance
ComputationGraph cg;
auto& sent = training[order[si]];
chars += sent.size();
++si;
Expression loss_expr = lm.BuildLMGraph(sent, cg, DROPOUT > 0.f);
loss += as_scalar(cg.forward(loss_expr));
cg.backward(loss_expr);
sgd->update();
++lines;
}
report++;
cerr << '#' << report << " [epoch=" << (lines / training.size()) << " eta=" << sgd->eta << "] E = " << (loss / chars) << " ppl=" << exp(loss / chars) << ' ';
// show score on dev data?
if (report % dev_every_i_reports == 0) {
double dloss = 0;
int dchars = 0;
for (auto& sent : dev) {
ComputationGraph cg;
Expression loss_expr = lm.BuildLMGraph(sent, cg, false);
dloss += as_scalar(cg.forward(loss_expr));
dchars += sent.size();
}
if (dloss < best) {
best = dloss;
TextFileSaver saver(fname);
saver.save(model);
}
cerr << "\n***DEV [epoch=" << (lines / training.size()) << "] E = " << (dloss / dchars) << " ppl=" << exp(dloss / dchars) << ' ';
}
}
} // train?
if (params.test_file != "") {
cerr << "Evaluating test data...\n";
double tloss = 0;
int tchars = 0;
for (auto& sent : test) {
ComputationGraph cg;
Expression loss_expr = lm.BuildLMGraph(sent, cg, false);
tloss += as_scalar(cg.forward(loss_expr));
tchars += sent.size();
}
cerr << "TEST -LLH = " << tloss << endl;
cerr << "TEST CROSS ENTOPY (NATS) = " << (tloss / tchars) << endl;
cerr << "TEST PPL = " << exp(tloss / tchars) << endl;
}
// N-best scoring
if (params.nbest_file != "") {
// cdec: index ||| hypothesis ||| feature=val ... ||| ...
// Moses: index ||| hypothesis ||| feature= val(s) ... ||| ...
const int HYP_FIELD = 1;
const int FEAT_FIELD = 2;
const string FEAT_NAME = "RNNLM";
// Input
string nbestf = params.nbest_file;
cerr << "Scoring N-best list " << nbestf << " ..." << endl;
shared_ptr<istream> in;
if (nbestf == "-") {
in.reset(&cin, [](...) {});
} else {
in.reset(new ifstream(nbestf));
}
// Match spacing of input file
string sep = "=";
bool sep_detected = false;
// Input lines
while (getline(*in, line)) {
vector<string> fields;
read_fields(line, fields);
// Check sep if needed
if (!sep_detected) {
sep_detected = true;
int i = fields[FEAT_FIELD].find("=");
if (fields[FEAT_FIELD].substr(i + 1, 1) == " ") {
sep = "= ";
}
}
// Score hypothesis
ComputationGraph cg;
Expression loss_expr = lm.BuildLMGraph(read_sentence(fields[HYP_FIELD], d), cg, false);
double loss = as_scalar(cg.forward(loss_expr));
// Add score
ostringstream os;
os << fields[FEAT_FIELD] << " " << FEAT_NAME << sep << loss;
fields[FEAT_FIELD] = os.str();
// Write augmented line
for (unsigned f = 0; f < fields.size(); ++f) {
if (f > 0)
cout << " ||| ";
cout << fields[f];
}
cout << endl;
}
}
delete sgd;
}
<commit_msg>Fixed compile error in example<commit_after>#include "dynet/nodes.h"
#include "dynet/dynet.h"
#include "dynet/training.h"
#include "dynet/timing.h"
#include "dynet/rnn.h"
#include "dynet/gru.h"
#include "dynet/lstm.h"
#include "dynet/dict.h"
#include "dynet/expr.h"
#include "dynet/cfsm-builder.h"
#include "dynet/hsm-builder.h"
#include "dynet/globals.h"
#include "dynet/io.h"
#include "../utils/getpid.h"
#include "../utils/cl-args.h"
#include <iostream>
#include <fstream>
#include <sstream>
#include <memory>
using namespace std;
using namespace dynet;
unsigned LAYERS = 0;
unsigned INPUT_DIM = 0;
unsigned HIDDEN_DIM = 0;
unsigned VOCAB_SIZE = 0;
float DROPOUT = 0;
bool SAMPLE = false;
SoftmaxBuilder* cfsm = nullptr;
dynet::Dict d;
int kSOS;
int kEOS;
volatile bool INTERRUPTED = false;
template <class Builder>
struct RNNLanguageModel {
LookupParameter p_c;
Parameter p_R;
Parameter p_bias;
Builder builder;
explicit RNNLanguageModel(ParameterCollection& model) : builder(LAYERS, INPUT_DIM, HIDDEN_DIM, model) {
p_c = model.add_lookup_parameters(VOCAB_SIZE, {INPUT_DIM});
p_R = model.add_parameters({VOCAB_SIZE, HIDDEN_DIM});
p_bias = model.add_parameters({VOCAB_SIZE});
}
// return Expression of total loss
Expression BuildLMGraph(const vector<int>& sent, ComputationGraph& cg, bool apply_dropout) {
const unsigned slen = sent.size();
if (apply_dropout) {
builder.set_dropout(DROPOUT);
} else {
builder.disable_dropout();
}
builder.new_graph(cg); // reset RNN builder for new graph
builder.start_new_sequence();
if (cfsm) cfsm->new_graph(cg);
Expression R = parameter(cg, p_R); // hidden -> word rep parameter
Expression bias = parameter(cg, p_bias); // word bias
vector<Expression> errs(slen + 1);
Expression h_t = builder.add_input(lookup(cg, p_c, kSOS)); // read <s>
for (unsigned t = 0; t < slen; ++t) { // h_t = RNN(x_0,...,x_t)
if (cfsm) { // class-factored softmax
errs[t] = cfsm->neg_log_softmax(h_t, sent[t]);
} else { // regular softmax
Expression u_t = affine_transform({bias, R, h_t});
errs[t] = pickneglogsoftmax(u_t, sent[t]);
}
Expression x_t = lookup(cg, p_c, sent[t]);
h_t = builder.add_input(x_t);
}
// it reamins to deal predict </s>
if (cfsm) {
errs.back() = cfsm->neg_log_softmax(h_t, kEOS);
} else {
Expression u_last = affine_transform({bias, R, h_t});
errs.back() = pickneglogsoftmax(u_last, kEOS); // predict </s>
}
return sum(errs);
}
void RandomSample(int max_len = 200) {
ComputationGraph cg;
builder.new_graph(cg); // reset RNN builder for new graph
builder.start_new_sequence();
if (cfsm) cfsm->new_graph(cg);
Expression R = parameter(cg, p_R); // hidden -> word rep parameter
Expression bias = parameter(cg, p_bias); // word bias
Expression h_t = builder.add_input(lookup(cg, p_c, kSOS)); // read <s>
int cur = kSOS;
int len = 0;
while (len < max_len) {
if (cfsm) { // class-factored softmax
cur = cfsm->sample(h_t);
} else { // regular softmax
Expression u_t = affine_transform({bias, R, h_t});
Expression dist_expr = softmax(u_t);
auto dist = as_vector(cg.incremental_forward(dist_expr));
double p = rand01();
cur = 0;
for (; cur < dist.size(); ++cur) {
p -= dist[cur];
if (p < 0.0) { break; }
}
if (cur == dist.size()) cur = kEOS;
}
if (cur == kEOS) break;
++len;
cerr << (len == 1 ? "" : " ") << d.convert(cur);
Expression x_t = lookup(cg, p_c, cur);
h_t = builder.add_input(x_t);
}
cerr << endl;
}
};
void inline read_fields(string line, vector<string>& fields, string delimiter = "|||") {
string field;
int start = 0, end = 0, delim_size = delimiter.size();
while (true) {
end = line.find(delimiter, start);
fields.push_back(line.substr(start, end - start));
if (end == (int)std::string::npos) break;
start = end + delim_size;
}
}
int main(int argc, char** argv) {
cerr << "COMMAND LINE:";
for (unsigned i = 0; i < static_cast<unsigned>(argc); ++i) cerr << ' ' << argv[i];
cerr << endl;
// Fetch dynet params ----------------------------------------------------------------------------
auto dyparams = dynet::extract_dynet_params(argc, argv);
dynet::initialize(dyparams);
// Fetch program specific parameters (see ../utils/cl-args.h) ------------------------------------
Params params;
get_args(argc, argv, params, TRAIN);
kSOS = d.convert("<s>");
kEOS = d.convert("</s>");
LAYERS = params.LAYERS;
INPUT_DIM = params.INPUT_DIM;
HIDDEN_DIM = params.HIDDEN_DIM;
SAMPLE = params.sample;
if (params.dropout_rate)
DROPOUT = params.dropout_rate;
Model model;
if (params.clusters_file != "")
cfsm = new ClassFactoredSoftmaxBuilder(HIDDEN_DIM, params.clusters_file, d, model);
else if (params.paths_file != "")
cfsm = new HierarchicalSoftmaxBuilder(HIDDEN_DIM, params.paths_file, d, model);
float eta_decay_rate = params.eta_decay_rate;
unsigned eta_decay_onset_epoch = params.eta_decay_onset_epoch;
vector<vector<int>> training, dev, test;
string line;
int tlc = 0;
int ttoks = 0;
{
string trainf = params.train_file;
cerr << "Reading training data from " << trainf << " ...\n";
ifstream in(trainf);
assert(in);
while (getline(in, line)) {
++tlc;
training.push_back(read_sentence(line, d));
ttoks += training.back().size();
if (training.back().front() == kSOS || training.back().back() == kEOS) {
cerr << "Training sentence in " << argv[1] << ":" << tlc << " started with <s> or ended with </s>\n";
abort();
}
}
cerr << tlc << " lines, " << ttoks << " tokens, " << d.size() << " types\n";
}
d.freeze(); // no new word types allowed
d.set_unk("<unk>");
VOCAB_SIZE = d.size();
if (!cfsm)
cfsm = new StandardSoftmaxBuilder(HIDDEN_DIM, VOCAB_SIZE, model);
if (params.test_file != "") {
string testf = params.test_file;
cerr << "Reading test data from " << testf << " ...\n";
ifstream in(testf);
assert(in);
while (getline(in, line)) {
test.push_back(read_sentence(line, d));
if (test.back().front() == kSOS || test.back().back() == kEOS) {
cerr << "Test sentence in " << argv[2] << ":" << tlc << " started with <s> or ended with </s>\n";
abort();
}
}
}
Trainer* sgd = new SimpleSGDTrainer(model);
sgd->eta0 = sgd->eta = params.eta0;
RNNLanguageModel<LSTMBuilder> lm(model);
bool has_model_to_load = params.model_file != "";
if (has_model_to_load) {
string fname = params.model_file;
cerr << "Reading parameters from " << fname << "...\n";
TextFileSaver saver(fname);
saver.save(model);
}
bool TRAIN = (params.train_file != "");
if (TRAIN) {
int dlc = 0;
int dtoks = 0;
if (params.dev_file == "") {
cerr << "You must specify a development set (--dev file.txt) with --train" << endl;
abort();
} else {
string devf = params.dev_file;
cerr << "Reading dev data from " << devf << " ...\n";
ifstream in(devf);
assert(in);
while (getline(in, line)) {
++dlc;
dev.push_back(read_sentence(line, d));
dtoks += dev.back().size();
if (dev.back().front() == kSOS || dev.back().back() == kEOS) {
cerr << "Dev sentence in " << argv[2] << ":" << tlc << " started with <s> or ended with </s>\n";
abort();
}
}
cerr << dlc << " lines, " << dtoks << " tokens\n";
}
ostringstream os;
os << "lm"
<< '_' << DROPOUT
<< '_' << LAYERS
<< '_' << INPUT_DIM
<< '_' << HIDDEN_DIM
<< "-pid" << getpid() << ".params";
const string fname = os.str();
cerr << "Parameters will be written to: " << fname << endl;
double best = 9e+99;
unsigned report_every_i = 100;
unsigned dev_every_i_reports = 25;
unsigned si = training.size();
if (report_every_i > si) report_every_i = si;
vector<unsigned> order(training.size());
for (unsigned i = 0; i < order.size(); ++i) order[i] = i;
bool first = true;
int report = 0;
double lines = 0;
int completed_epoch = -1;
while (!INTERRUPTED) {
if (SAMPLE) lm.RandomSample();
Timer iteration("completed in");
double loss = 0;
unsigned chars = 0;
for (unsigned i = 0; i < report_every_i; ++i) {
if (si == training.size()) {
si = 0;
if (first) { first = false; } else { sgd->update_epoch(); }
cerr << "**SHUFFLE\n";
completed_epoch++;
if (eta_decay_onset_epoch && completed_epoch >= (int)eta_decay_onset_epoch)
sgd->eta *= eta_decay_rate;
shuffle(order.begin(), order.end(), *rndeng);
}
// build graph for this instance
ComputationGraph cg;
auto& sent = training[order[si]];
chars += sent.size();
++si;
Expression loss_expr = lm.BuildLMGraph(sent, cg, DROPOUT > 0.f);
loss += as_scalar(cg.forward(loss_expr));
cg.backward(loss_expr);
sgd->update();
++lines;
}
report++;
cerr << '#' << report << " [epoch=" << (lines / training.size()) << " eta=" << sgd->eta << "] E = " << (loss / chars) << " ppl=" << exp(loss / chars) << ' ';
// show score on dev data?
if (report % dev_every_i_reports == 0) {
double dloss = 0;
int dchars = 0;
for (auto& sent : dev) {
ComputationGraph cg;
Expression loss_expr = lm.BuildLMGraph(sent, cg, false);
dloss += as_scalar(cg.forward(loss_expr));
dchars += sent.size();
}
if (dloss < best) {
best = dloss;
TextFileSaver saver(fname);
saver.save(model);
}
cerr << "\n***DEV [epoch=" << (lines / training.size()) << "] E = " << (dloss / dchars) << " ppl=" << exp(dloss / dchars) << ' ';
}
}
} // train?
if (params.test_file != "") {
cerr << "Evaluating test data...\n";
double tloss = 0;
int tchars = 0;
for (auto& sent : test) {
ComputationGraph cg;
Expression loss_expr = lm.BuildLMGraph(sent, cg, false);
tloss += as_scalar(cg.forward(loss_expr));
tchars += sent.size();
}
cerr << "TEST -LLH = " << tloss << endl;
cerr << "TEST CROSS ENTOPY (NATS) = " << (tloss / tchars) << endl;
cerr << "TEST PPL = " << exp(tloss / tchars) << endl;
}
// N-best scoring
if (params.nbest_file != "") {
// cdec: index ||| hypothesis ||| feature=val ... ||| ...
// Moses: index ||| hypothesis ||| feature= val(s) ... ||| ...
const int HYP_FIELD = 1;
const int FEAT_FIELD = 2;
const string FEAT_NAME = "RNNLM";
// Input
string nbestf = params.nbest_file;
cerr << "Scoring N-best list " << nbestf << " ..." << endl;
shared_ptr<istream> in;
if (nbestf == "-") {
in.reset(&cin, [](...) {});
} else {
in.reset(new ifstream(nbestf));
}
// Match spacing of input file
string sep = "=";
bool sep_detected = false;
// Input lines
while (getline(*in, line)) {
vector<string> fields;
read_fields(line, fields);
// Check sep if needed
if (!sep_detected) {
sep_detected = true;
int i = fields[FEAT_FIELD].find("=");
if (fields[FEAT_FIELD].substr(i + 1, 1) == " ") {
sep = "= ";
}
}
// Score hypothesis
ComputationGraph cg;
Expression loss_expr = lm.BuildLMGraph(read_sentence(fields[HYP_FIELD], d), cg, false);
double loss = as_scalar(cg.forward(loss_expr));
// Add score
ostringstream os;
os << fields[FEAT_FIELD] << " " << FEAT_NAME << sep << loss;
fields[FEAT_FIELD] = os.str();
// Write augmented line
for (unsigned f = 0; f < fields.size(); ++f) {
if (f > 0)
cout << " ||| ";
cout << fields[f];
}
cout << endl;
}
}
delete sgd;
}
<|endoftext|> |
<commit_before>/* exception_handler.cc
Jeremy Barnes, 26 February 2008
Copyright (c) 2009 Jeremy Barnes. All rights reserved.
*/
#include <cxxabi.h>
#include <cstring>
#include <fstream>
#include "jml/compiler/compiler.h"
#include "jml/utils/environment.h"
#include "backtrace.h"
#include "demangle.h"
#include "exception.h"
#include "exception_hook.h"
#include "format.h"
#include "threads.h"
using namespace std;
namespace ML {
Env_Option<bool> TRACE_EXCEPTIONS("JML_TRACE_EXCEPTIONS", true);
__thread bool trace_exceptions = false;
__thread bool trace_exceptions_initialized = false;
void set_default_trace_exceptions(bool val)
{
TRACE_EXCEPTIONS.set(val);
}
bool get_default_trace_exceptions()
{
return TRACE_EXCEPTIONS;
}
void set_trace_exceptions(bool trace)
{
//cerr << "set_trace_exceptions to " << trace << " at " << &trace_exceptions
// << endl;
trace_exceptions = trace;
trace_exceptions_initialized = true;
}
bool get_trace_exceptions()
{
if (!trace_exceptions_initialized) {
//cerr << "trace_exceptions initialized to = "
// << trace_exceptions << " at " << &trace_exceptions << endl;
set_trace_exceptions(TRACE_EXCEPTIONS);
trace_exceptions_initialized = true;
}
//cerr << "get_trace_exceptions returned " << trace_exceptions
// << " at " << &trace_exceptions << endl;
return trace_exceptions;
}
static const std::exception *
to_std_exception(void* object, const std::type_info * tinfo)
{
/* Check if its a class. If not, we can't see if it's a std::exception.
The abi::__class_type_info is the base class of all types of type
info for types that are classes (of which std::exception is one).
*/
const abi::__class_type_info * ctinfo
= dynamic_cast<const abi::__class_type_info *>(tinfo);
if (!ctinfo) return 0;
/* The thing thrown was an object. Now, check if it is derived from
std::exception. */
const std::type_info * etinfo = &typeid(std::exception);
/* See if the exception could catch this. This is the mechanism
used internally by the compiler in catch {} blocks to see if
the exception matches the catch type.
In the case of success, the object will be adjusted to point to
the start of the std::exception object.
*/
void * obj_ptr = object;
bool can_catch = etinfo->__do_catch(tinfo, &obj_ptr, 0);
if (!can_catch) return 0;
/* obj_ptr points to a std::exception; extract it and get the
exception message.
*/
return (const std::exception *)obj_ptr;
}
/** We install this handler for when an exception is thrown. */
void default_exception_tracer(void * object, const std::type_info * tinfo)
{
//cerr << "trace_exception: trace_exceptions = " << get_trace_exceptions()
// << " at " << &trace_exceptions << endl;
if (!get_trace_exceptions()) return;
const std::exception * exc = to_std_exception(object, tinfo);
// We don't want these exceptions to be printed out.
if (dynamic_cast<const ML::SilentException *>(exc)) return;
/* avoid allocations when std::bad_alloc is thrown */
bool noAlloc = dynamic_cast<const std::bad_alloc *>(exc);
size_t bufferSize(1024*1024);
char buffer[bufferSize];
char datetime[128];
size_t totalWritten(0), written, remaining(bufferSize);
time_t now;
time(&now);
struct tm lt_tm;
strftime(datetime, sizeof(datetime), "%FT%H:%M:%SZ",
gmtime_r(&now, <_tm));
const char * demangled;
char * heapDemangled;
if (noAlloc) {
heapDemangled = nullptr;
demangled = "std::bad_alloc";
}
else {
heapDemangled = char_demangle(tinfo->name());
demangled = heapDemangled;
}
auto pid = getpid();
auto tid = gettid();
written = ::snprintf(buffer, remaining,
"\n"
"--------------------------[Exception thrown]"
"---------------------------\n"
"time: %s\n"
"type: %s\n"
"pid: %d; tid: %d\n",
datetime, demangled, pid, tid);
if (heapDemangled) {
free(heapDemangled);
}
if (written >= remaining) {
goto end;
}
totalWritten += written;
remaining -= written;
if (exc) {
written = snprintf(buffer + totalWritten, remaining,
"what: %s\n", exc->what());
if (written >= remaining) {
goto end;
}
totalWritten += written;
remaining -= written;
}
if (noAlloc) {
goto end;
}
written = snprintf(buffer + totalWritten, remaining, "stack:\n");
if (written >= remaining) {
goto end;
}
totalWritten += written;
remaining -= written;
written = backtrace(buffer + totalWritten, remaining, 3);
if (written >= remaining) {
goto end;
}
totalWritten += written;
if (totalWritten < bufferSize - 1) {
strcpy(buffer + totalWritten, "\n");
}
end:
cerr << buffer;
char const * reports = getenv("ENABLE_EXCEPTION_REPORTS");
if (!noAlloc && reports) {
std::string path = ML::format("%s/exception-report-%s-%d-%d.log",
reports, datetime, pid, tid);
std::ofstream file(path, std::ios_base::app);
if(file) {
file << getenv("_") << endl;
backtrace(file, 3);
file.close();
}
}
}
} // namespace ML
<commit_msg>PLAT-887: include node name in exception message<commit_after>/* exception_handler.cc
Jeremy Barnes, 26 February 2008
Copyright (c) 2009 Jeremy Barnes. All rights reserved.
*/
#include <sys/utsname.h>
#include <cxxabi.h>
#include <cstring>
#include <fstream>
#include "jml/compiler/compiler.h"
#include "jml/utils/environment.h"
#include "backtrace.h"
#include "demangle.h"
#include "exception.h"
#include "exception_hook.h"
#include "format.h"
#include "threads.h"
using namespace std;
namespace ML {
Env_Option<bool> TRACE_EXCEPTIONS("JML_TRACE_EXCEPTIONS", true);
__thread bool trace_exceptions = false;
__thread bool trace_exceptions_initialized = false;
void set_default_trace_exceptions(bool val)
{
TRACE_EXCEPTIONS.set(val);
}
bool get_default_trace_exceptions()
{
return TRACE_EXCEPTIONS;
}
void set_trace_exceptions(bool trace)
{
//cerr << "set_trace_exceptions to " << trace << " at " << &trace_exceptions
// << endl;
trace_exceptions = trace;
trace_exceptions_initialized = true;
}
bool get_trace_exceptions()
{
if (!trace_exceptions_initialized) {
//cerr << "trace_exceptions initialized to = "
// << trace_exceptions << " at " << &trace_exceptions << endl;
set_trace_exceptions(TRACE_EXCEPTIONS);
trace_exceptions_initialized = true;
}
//cerr << "get_trace_exceptions returned " << trace_exceptions
// << " at " << &trace_exceptions << endl;
return trace_exceptions;
}
static const std::exception *
to_std_exception(void* object, const std::type_info * tinfo)
{
/* Check if its a class. If not, we can't see if it's a std::exception.
The abi::__class_type_info is the base class of all types of type
info for types that are classes (of which std::exception is one).
*/
const abi::__class_type_info * ctinfo
= dynamic_cast<const abi::__class_type_info *>(tinfo);
if (!ctinfo) return 0;
/* The thing thrown was an object. Now, check if it is derived from
std::exception. */
const std::type_info * etinfo = &typeid(std::exception);
/* See if the exception could catch this. This is the mechanism
used internally by the compiler in catch {} blocks to see if
the exception matches the catch type.
In the case of success, the object will be adjusted to point to
the start of the std::exception object.
*/
void * obj_ptr = object;
bool can_catch = etinfo->__do_catch(tinfo, &obj_ptr, 0);
if (!can_catch) return 0;
/* obj_ptr points to a std::exception; extract it and get the
exception message.
*/
return (const std::exception *)obj_ptr;
}
/** We install this handler for when an exception is thrown. */
void default_exception_tracer(void * object, const std::type_info * tinfo)
{
//cerr << "trace_exception: trace_exceptions = " << get_trace_exceptions()
// << " at " << &trace_exceptions << endl;
if (!get_trace_exceptions()) return;
const std::exception * exc = to_std_exception(object, tinfo);
// We don't want these exceptions to be printed out.
if (dynamic_cast<const ML::SilentException *>(exc)) return;
/* avoid allocations when std::bad_alloc is thrown */
bool noAlloc = dynamic_cast<const std::bad_alloc *>(exc);
size_t bufferSize(1024*1024);
char buffer[bufferSize];
char datetime[128];
size_t totalWritten(0), written, remaining(bufferSize);
time_t now;
time(&now);
struct tm lt_tm;
strftime(datetime, sizeof(datetime), "%FT%H:%M:%SZ",
gmtime_r(&now, <_tm));
const char * demangled;
char * heapDemangled;
if (noAlloc) {
heapDemangled = nullptr;
demangled = "std::bad_alloc";
}
else {
heapDemangled = char_demangle(tinfo->name());
demangled = heapDemangled;
}
const char *nodeName = "<unknown>";
struct utsname utsName;
if (::uname(&utsName) == 0) {
nodeName = utsName.nodename;
}
else {
cerr << "error calling uname\n";
}
auto pid = getpid();
auto tid = gettid();
written = ::snprintf(buffer, remaining,
"\n"
"--------------------------[Exception thrown]"
"---------------------------\n"
"time: %s\n"
"type: %s\n"
"node: %s\n"
"pid: %d; tid: %d\n",
datetime, demangled, nodeName, pid, tid);
if (heapDemangled) {
free(heapDemangled);
}
if (written >= remaining) {
goto end;
}
totalWritten += written;
remaining -= written;
if (exc) {
written = snprintf(buffer + totalWritten, remaining,
"what: %s\n", exc->what());
if (written >= remaining) {
goto end;
}
totalWritten += written;
remaining -= written;
}
if (noAlloc) {
goto end;
}
written = snprintf(buffer + totalWritten, remaining, "stack:\n");
if (written >= remaining) {
goto end;
}
totalWritten += written;
remaining -= written;
written = backtrace(buffer + totalWritten, remaining, 3);
if (written >= remaining) {
goto end;
}
totalWritten += written;
if (totalWritten < bufferSize - 1) {
strcpy(buffer + totalWritten, "\n");
}
end:
cerr << buffer;
char const * reports = getenv("ENABLE_EXCEPTION_REPORTS");
if (!noAlloc && reports) {
std::string path = ML::format("%s/exception-report-%s-%d-%d.log",
reports, datetime, pid, tid);
std::ofstream file(path, std::ios_base::app);
if(file) {
file << getenv("_") << endl;
backtrace(file, 3);
file.close();
}
}
}
} // namespace ML
<|endoftext|> |
<commit_before>// PythonStuff.cpp
// written by Dan Heeks, February 6th 2009, license: GPL version 3 http://www.gnu.org/licenses/gpl-3.0.txt
#include "PythonStuff.h"
#include <set>
#include "Area.h"
#if _DEBUG
#undef _DEBUG
#include <Python.h>
#define _DEBUG
#else
#include <Python.h>
#endif
#ifdef __GNUG__
#pragma implementation
#endif
#include "kbool/include/_lnk_itr.h"
#include "kbool/include/booleng.h"
std::set<CArea*> valid_areas;
static PyObject* area_new(PyObject* self, PyObject* args)
{
CArea* new_object = new CArea();
valid_areas.insert(new_object);
// return new object cast to an int
PyObject *pValue = PyInt_FromLong((long)new_object);
Py_INCREF(pValue);
return pValue;
}
static PyObject* area_exists(PyObject* self, PyObject* args)
{
int ik;
if (!PyArg_ParseTuple(args, "i", &ik)) return NULL;
CArea* k = (CArea*)ik;
bool exists = (valid_areas.find(k) != valid_areas.end());
// return exists
PyObject *pValue = exists ? Py_True : Py_False;
Py_INCREF(pValue);
return pValue;
}
static PyObject* area_delete(PyObject* self, PyObject* args)
{
int ik;
if (!PyArg_ParseTuple(args, "i", &ik)) return NULL;
CArea* k = (CArea*)ik;
if(valid_areas.find(k) != valid_areas.end())
{
delete k;
valid_areas.erase(k);
}
Py_RETURN_NONE;
}
static int span_number = 1;
static PyObject* area_add_point(PyObject* self, PyObject* args)
{
double x, y, i, j;
int sp, ik;
if (!PyArg_ParseTuple(args, "iidddd", &ik, &sp, &x, &y, &i, &j)) return NULL;
CArea* k = (CArea*)ik;
if(valid_areas.find(k) != valid_areas.end())
{
// add a curve if there isn't one
if(k->m_curves.size() == 0)k->m_curves.push_back(CCurve());
int curve_index = k->m_curves.size() - 1;
// can't add arc as first span
if(sp && k->m_curves[curve_index].m_vertices.size() == 0){ const char* str = "can't add arc to area as first point"; printf(str); throw(str);}
// add the vertex
k->m_curves[curve_index].m_vertices.push_back(CVertex(sp, x, y, i, j, span_number));
span_number++;
}
Py_RETURN_NONE;
}
static PyObject* area_start_new_curve(PyObject* self, PyObject* args)
{
int ik;
if (!PyArg_ParseTuple(args, "i", &ik)) return NULL;
CArea* k = (CArea*)ik;
if(valid_areas.find(k) != valid_areas.end())
{
// add a new curve
k->m_curves.push_back(CCurve());
}
Py_RETURN_NONE;
}
static PyObject* area_offset(PyObject* self, PyObject* args)
{
int ik;
double inwards;
if (!PyArg_ParseTuple(args, "id", &ik, &inwards)) return NULL;
CArea* k = (CArea*)ik;
//int ret = 0;
if(valid_areas.find(k) != valid_areas.end())
{
k->Offset(inwards);
}
Py_RETURN_NONE;
}
static PyObject* area_subtract(PyObject* self, PyObject* args)
{
int a1, a2;
if (!PyArg_ParseTuple(args, "ii", &a1, &a2)) return NULL;
CArea* area1 = (CArea*)a1;
CArea* area2 = (CArea*)a2;
if(valid_areas.find(area1) != valid_areas.end() && valid_areas.find(area2) != valid_areas.end())
{
area1->Subtract(*area2);
}
Py_RETURN_NONE;
}
static PyObject* area_set_round_corner_factor(PyObject* self, PyObject* args)
{
if (!PyArg_ParseTuple(args, "d", &CArea::m_round_corners_factor)) return NULL;
Py_RETURN_NONE;
}
static PyObject* area_copy(PyObject* self, PyObject* args)
{
int ik;
int ik2;
if (!PyArg_ParseTuple(args, "ii", &ik, &ik2)) return NULL;
CArea* k = (CArea*)ik;
CArea* k2 = (CArea*)ik2;
if(valid_areas.find(k) != valid_areas.end())
{
if(valid_areas.find(k2) != valid_areas.end())
{
*k2 = *k;
}
}
Py_RETURN_NONE;
}
static PyObject* area_num_curves(PyObject* self, PyObject* args)
{
int ik;
if (!PyArg_ParseTuple(args, "i", &ik)) return NULL;
CArea* k = (CArea*)ik;
int n = 0;
if(valid_areas.find(k) != valid_areas.end())
{
n = k->m_curves.size();
}
PyObject *pValue = PyInt_FromLong(n);
Py_INCREF(pValue);
return pValue;
}
static PyObject* area_num_vertices(PyObject* self, PyObject* args)
{
int ik, ic;
if (!PyArg_ParseTuple(args, "ii", &ik, &ic)) return NULL;
CArea* k = (CArea*)ik;
int n = 0;
if(valid_areas.find(k) != valid_areas.end())
{
if(ic >= 0 && ic < (int)(k->m_curves.size()))n = k->m_curves[ic].m_vertices.size();
}
PyObject *pValue = PyInt_FromLong(n);
Py_INCREF(pValue);
return pValue;
}
static PyObject* area_get_vertex(PyObject* self, PyObject* args)
{
int ik, ic;
int index; // 0 is first
if (!PyArg_ParseTuple(args, "iii", &ik, &ic, &index)) return NULL;
CArea* k = (CArea*)ik;
int sp = 0;
double x = 0.0, y = 0.0;
double cx = 0.0, cy = 0.0;
if(valid_areas.find(k) != valid_areas.end())
{
if(ic >= 0 && ic < (int)(k->m_curves.size()))
{
CCurve& curve = k->m_curves[ic];
if(index >= 0 && index < (int)(curve.m_vertices.size()))
{
CVertex& vertex = curve.m_vertices[index];
sp = vertex.m_type;
x = vertex.m_p[0];
y = vertex.m_p[1];
cx = vertex.m_c[0];
cy = vertex.m_c[1];
}
}
}
// return span data as a tuple
PyObject *pTuple = PyTuple_New(5);
{
PyObject *pValue = PyInt_FromLong(sp);
if (!pValue){
Py_DECREF(pTuple);return NULL;
}
PyTuple_SetItem(pTuple, 0, pValue);
}
{
PyObject *pValue = PyFloat_FromDouble(x);
if (!pValue){
Py_DECREF(pTuple);return NULL;
}
PyTuple_SetItem(pTuple, 1, pValue);
}
{
PyObject *pValue = PyFloat_FromDouble(y);
if (!pValue){
Py_DECREF(pTuple);return NULL;
}
PyTuple_SetItem(pTuple, 2, pValue);
}
{
PyObject *pValue = PyFloat_FromDouble(cx);
if (!pValue){
Py_DECREF(pTuple);return NULL;
}
PyTuple_SetItem(pTuple, 3, pValue);
}
{
PyObject *pValue = PyFloat_FromDouble(cy);
if (!pValue){
Py_DECREF(pTuple);return NULL;
}
PyTuple_SetItem(pTuple, 4, pValue);
}
Py_INCREF(pTuple);
return pTuple;
}
static PyObject* area_add_curve(PyObject* self, PyObject* args)
{
int ik, ij, ii;
if (!PyArg_ParseTuple(args, "iii", &ik, &ij, &ii)) return NULL;
CArea* k = (CArea*)ik;
CArea* j = (CArea*)ij;
if(valid_areas.find(k) != valid_areas.end() && valid_areas.find(j) != valid_areas.end())
{
if(ii >= 0 && ii < (int)j->m_curves.size()){
// add curve
k->m_curves.push_back(j->m_curves[ii]);
}
}
Py_RETURN_NONE;
}
static PyMethodDef AreaMethods[] = {
{"new", area_new, METH_VARARGS , ""},
{"exists", area_exists, METH_VARARGS , ""},
{"delete", area_delete, METH_VARARGS , ""},
{"add_point", area_add_point, METH_VARARGS , ""},
{"start_new_curve", area_start_new_curve, METH_VARARGS , ""},
{"subtract", area_subtract, METH_VARARGS , ""},
{"offset", area_offset, METH_VARARGS , ""},
{"set_round_corner_factor", area_set_round_corner_factor, METH_VARARGS , ""},
{"copy", area_copy, METH_VARARGS , ""},
{"num_curves", area_num_curves, METH_VARARGS , ""},
{"num_vertices", area_num_vertices, METH_VARARGS , ""},
{"get_vertex", area_get_vertex, METH_VARARGS , ""},
{"add_curve", area_add_curve, METH_VARARGS , ""},
{NULL, NULL, 0, NULL}
};
PyMODINIT_FUNC
initarea(void)
{
Py_InitModule("area", AreaMethods);
}
<commit_msg>added area.print_area(a)<commit_after>// PythonStuff.cpp
// written by Dan Heeks, February 6th 2009, license: GPL version 3 http://www.gnu.org/licenses/gpl-3.0.txt
#include "PythonStuff.h"
#include <set>
#include "Area.h"
#if _DEBUG
#undef _DEBUG
#include <Python.h>
#define _DEBUG
#else
#include <Python.h>
#endif
#ifdef __GNUG__
#pragma implementation
#endif
#include "kbool/include/_lnk_itr.h"
#include "kbool/include/booleng.h"
std::set<CArea*> valid_areas;
static PyObject* area_new(PyObject* self, PyObject* args)
{
CArea* new_object = new CArea();
valid_areas.insert(new_object);
// return new object cast to an int
PyObject *pValue = PyInt_FromLong((long)new_object);
Py_INCREF(pValue);
return pValue;
}
static PyObject* area_exists(PyObject* self, PyObject* args)
{
int ik;
if (!PyArg_ParseTuple(args, "i", &ik)) return NULL;
CArea* k = (CArea*)ik;
bool exists = (valid_areas.find(k) != valid_areas.end());
// return exists
PyObject *pValue = exists ? Py_True : Py_False;
Py_INCREF(pValue);
return pValue;
}
static PyObject* area_delete(PyObject* self, PyObject* args)
{
int ik;
if (!PyArg_ParseTuple(args, "i", &ik)) return NULL;
CArea* k = (CArea*)ik;
if(valid_areas.find(k) != valid_areas.end())
{
delete k;
valid_areas.erase(k);
}
Py_RETURN_NONE;
}
static int span_number = 1;
static PyObject* area_add_point(PyObject* self, PyObject* args)
{
double x, y, i, j;
int sp, ik;
if (!PyArg_ParseTuple(args, "iidddd", &ik, &sp, &x, &y, &i, &j)) return NULL;
CArea* k = (CArea*)ik;
if(valid_areas.find(k) != valid_areas.end())
{
// add a curve if there isn't one
if(k->m_curves.size() == 0)k->m_curves.push_back(CCurve());
int curve_index = k->m_curves.size() - 1;
// can't add arc as first span
if(sp && k->m_curves[curve_index].m_vertices.size() == 0){ const char* str = "can't add arc to area as first point"; printf(str); throw(str);}
// add the vertex
k->m_curves[curve_index].m_vertices.push_back(CVertex(sp, x, y, i, j, span_number));
span_number++;
}
Py_RETURN_NONE;
}
static PyObject* area_start_new_curve(PyObject* self, PyObject* args)
{
int ik;
if (!PyArg_ParseTuple(args, "i", &ik)) return NULL;
CArea* k = (CArea*)ik;
if(valid_areas.find(k) != valid_areas.end())
{
// add a new curve
k->m_curves.push_back(CCurve());
}
Py_RETURN_NONE;
}
static PyObject* area_offset(PyObject* self, PyObject* args)
{
int ik;
double inwards;
if (!PyArg_ParseTuple(args, "id", &ik, &inwards)) return NULL;
CArea* k = (CArea*)ik;
//int ret = 0;
if(valid_areas.find(k) != valid_areas.end())
{
k->Offset(inwards);
}
Py_RETURN_NONE;
}
static PyObject* area_subtract(PyObject* self, PyObject* args)
{
int a1, a2;
if (!PyArg_ParseTuple(args, "ii", &a1, &a2)) return NULL;
CArea* area1 = (CArea*)a1;
CArea* area2 = (CArea*)a2;
if(valid_areas.find(area1) != valid_areas.end() && valid_areas.find(area2) != valid_areas.end())
{
area1->Subtract(*area2);
}
Py_RETURN_NONE;
}
static PyObject* area_set_round_corner_factor(PyObject* self, PyObject* args)
{
if (!PyArg_ParseTuple(args, "d", &CArea::m_round_corners_factor)) return NULL;
Py_RETURN_NONE;
}
static PyObject* area_copy(PyObject* self, PyObject* args)
{
int ik;
int ik2;
if (!PyArg_ParseTuple(args, "ii", &ik, &ik2)) return NULL;
CArea* k = (CArea*)ik;
CArea* k2 = (CArea*)ik2;
if(valid_areas.find(k) != valid_areas.end())
{
if(valid_areas.find(k2) != valid_areas.end())
{
*k2 = *k;
}
}
Py_RETURN_NONE;
}
static PyObject* area_num_curves(PyObject* self, PyObject* args)
{
int ik;
if (!PyArg_ParseTuple(args, "i", &ik)) return NULL;
CArea* k = (CArea*)ik;
int n = 0;
if(valid_areas.find(k) != valid_areas.end())
{
n = k->m_curves.size();
}
PyObject *pValue = PyInt_FromLong(n);
Py_INCREF(pValue);
return pValue;
}
static PyObject* area_num_vertices(PyObject* self, PyObject* args)
{
int ik, ic;
if (!PyArg_ParseTuple(args, "ii", &ik, &ic)) return NULL;
CArea* k = (CArea*)ik;
int n = 0;
if(valid_areas.find(k) != valid_areas.end())
{
if(ic >= 0 && ic < (int)(k->m_curves.size()))n = k->m_curves[ic].m_vertices.size();
}
PyObject *pValue = PyInt_FromLong(n);
Py_INCREF(pValue);
return pValue;
}
static PyObject* area_get_vertex(PyObject* self, PyObject* args)
{
int ik, ic;
int index; // 0 is first
if (!PyArg_ParseTuple(args, "iii", &ik, &ic, &index)) return NULL;
CArea* k = (CArea*)ik;
int sp = 0;
double x = 0.0, y = 0.0;
double cx = 0.0, cy = 0.0;
if(valid_areas.find(k) != valid_areas.end())
{
if(ic >= 0 && ic < (int)(k->m_curves.size()))
{
CCurve& curve = k->m_curves[ic];
if(index >= 0 && index < (int)(curve.m_vertices.size()))
{
CVertex& vertex = curve.m_vertices[index];
sp = vertex.m_type;
x = vertex.m_p[0];
y = vertex.m_p[1];
cx = vertex.m_c[0];
cy = vertex.m_c[1];
}
}
}
// return span data as a tuple
PyObject *pTuple = PyTuple_New(5);
{
PyObject *pValue = PyInt_FromLong(sp);
if (!pValue){
Py_DECREF(pTuple);return NULL;
}
PyTuple_SetItem(pTuple, 0, pValue);
}
{
PyObject *pValue = PyFloat_FromDouble(x);
if (!pValue){
Py_DECREF(pTuple);return NULL;
}
PyTuple_SetItem(pTuple, 1, pValue);
}
{
PyObject *pValue = PyFloat_FromDouble(y);
if (!pValue){
Py_DECREF(pTuple);return NULL;
}
PyTuple_SetItem(pTuple, 2, pValue);
}
{
PyObject *pValue = PyFloat_FromDouble(cx);
if (!pValue){
Py_DECREF(pTuple);return NULL;
}
PyTuple_SetItem(pTuple, 3, pValue);
}
{
PyObject *pValue = PyFloat_FromDouble(cy);
if (!pValue){
Py_DECREF(pTuple);return NULL;
}
PyTuple_SetItem(pTuple, 4, pValue);
}
Py_INCREF(pTuple);
return pTuple;
}
static PyObject* area_add_curve(PyObject* self, PyObject* args)
{
int ik, ij, ii;
if (!PyArg_ParseTuple(args, "iii", &ik, &ij, &ii)) return NULL;
CArea* k = (CArea*)ik;
CArea* j = (CArea*)ij;
if(valid_areas.find(k) != valid_areas.end() && valid_areas.find(j) != valid_areas.end())
{
if(ii >= 0 && ii < (int)j->m_curves.size()){
// add curve
k->m_curves.push_back(j->m_curves[ii]);
}
}
Py_RETURN_NONE;
}
static void print_curve(const CCurve& c)
{
unsigned int nvertices = c.m_vertices.size();
printf("number of vertices = %d\n", nvertices);
for(unsigned int i = 0; i< nvertices; i++)
{
const CVertex &vertex = c.m_vertices[i];
printf("vertex %d type = %d, x = %g, y = %g", i+1, vertex.m_type, vertex.m_p[0], vertex.m_p[1]);
if(vertex.m_type)printf(", xc = %g, yc = %g", vertex.m_c[0], vertex.m_c[1]);
printf("\n");
}
}
static void print_area(const CArea &a)
{
for(unsigned int i = 0; i<a.m_curves.size(); i++)
{
const CCurve& curve = a.m_curves[i];
print_curve(curve);
}
}
static PyObject* area_print_area(PyObject* self, PyObject* args)
{
int ik;
if (!PyArg_ParseTuple(args, "i", &ik)) return NULL;
CArea* k = (CArea*)ik;
if(valid_areas.find(k) != valid_areas.end())
{
print_area(*k);
}
Py_RETURN_NONE;
}
static PyMethodDef AreaMethods[] = {
{"new", area_new, METH_VARARGS , ""},
{"exists", area_exists, METH_VARARGS , ""},
{"delete", area_delete, METH_VARARGS , ""},
{"add_point", area_add_point, METH_VARARGS , ""},
{"start_new_curve", area_start_new_curve, METH_VARARGS , ""},
{"subtract", area_subtract, METH_VARARGS , ""},
{"offset", area_offset, METH_VARARGS , ""},
{"set_round_corner_factor", area_set_round_corner_factor, METH_VARARGS , ""},
{"copy", area_copy, METH_VARARGS , ""},
{"num_curves", area_num_curves, METH_VARARGS , ""},
{"num_vertices", area_num_vertices, METH_VARARGS , ""},
{"get_vertex", area_get_vertex, METH_VARARGS , ""},
{"add_curve", area_add_curve, METH_VARARGS , ""},
{"print_area", area_print_area, METH_VARARGS , ""},
{NULL, NULL, 0, NULL}
};
PyMODINIT_FUNC
initarea(void)
{
Py_InitModule("area", AreaMethods);
}
<|endoftext|> |
<commit_before>#include "ExampleAndroidHandler.h"
#include <AndroidLog.h>
ExampleAndroidHandler::ExampleAndroidHandler()
{
// State variables
m_bShouldQuit = false;
m_bIsVisible = false;
m_bIsPaused = true;
// Egl
m_Display = EGL_NO_DISPLAY;
m_Surface = EGL_NO_SURFACE;
m_Context = NULL;
}
ExampleAndroidHandler::~ExampleAndroidHandler()
{
DestroyOpenGL();
}
void ExampleAndroidHandler::Run()
{
// Example asset read
Android::Asset* pAsset = Android::GetAssetManager().GetAsset( "test.txt" );
if ( pAsset )
{
// Create a buffer to read the content into,
// [ Size() + 1 ] for null terminator character for LOV usage
char* pBuffer = new char[ pAsset->Size() + 1 ];
// Read the buffer
pAsset->Read( pBuffer, pAsset->Size() );
// Delete the asset file
delete pAsset;
// Set null terminating for LOGV
pBuffer[ pAsset->Size() ] = 0;
// Show us the file's content!
LOGV( "File content: %s", pBuffer );
// Delete the buffer
delete [] pBuffer;
}
// Create time measurement
timespec timeNow;
clock_gettime( CLOCK_MONOTONIC, &timeNow );
uint64_t uPreviousTime = timeNow.tv_sec * 1000000000ull + timeNow.tv_nsec;
// While application is alive...
while ( !m_bShouldQuit )
{
// Handle Android events
Android::PollEvents();
// Calculate delta time
clock_gettime( CLOCK_MONOTONIC, &timeNow ); // query time now
uint64_t uNowNano = timeNow.tv_sec * 1000000000ull + timeNow.tv_nsec; // get time in nanoseconds
float fDeltaSeconds = float( uNowNano - uPreviousTime ) * 0.000000001f; // 1 second = 1,000,000,000 nanoseconds
uPreviousTime = uNowNano; // set previous time to new time
// If not paused...
if ( !m_bIsPaused )
{
// Update logic
Update( fDeltaSeconds );
}
// If visible
if ( m_bIsVisible )
{
// Draw
Draw();
}
}
}
void ExampleAndroidHandler::Update( float fDeltaSeconds )
{
// Do stuff here
}
void ExampleAndroidHandler::Draw()
{
// Draw things here
glClearColor( 0.0f, 0.0f, 1.0f, 1.0f );
glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT );
if ( !eglSwapBuffers( m_Display, m_Surface ) )
{
LOGE( "eglSwapBuffers() returned error %d", eglGetError() );
}
}
bool ExampleAndroidHandler::InitOpenGL()
{
const EGLint attribs[] =
{
EGL_SURFACE_TYPE, EGL_WINDOW_BIT,
EGL_BLUE_SIZE, 8,
EGL_GREEN_SIZE, 8,
EGL_RED_SIZE, 8,
EGL_NONE
};
EGLDisplay display;
EGLConfig config;
EGLint numConfigs;
EGLint format;
EGLSurface surface;
EGLContext context;
EGLint width;
EGLint height;
GLfloat ratio;
LOGV( "[Example]: Initializing context" );
if ( ( display = eglGetDisplay( EGL_DEFAULT_DISPLAY ) ) == EGL_NO_DISPLAY )
{
LOGE( "[Example]: eglGetDisplay() returned error %d", eglGetError() );
return false;
}
if ( !eglInitialize( display, 0, 0 ) )
{
LOGE( "[Example]: eglInitialize() returned error %d", eglGetError() );
return false;
}
if ( !eglChooseConfig(display, attribs, &config, 1, &numConfigs) )
{
LOGE( "[Example]: eglChooseConfig() returned error %d", eglGetError() );
DestroyOpenGL();
return false;
}
if ( !eglGetConfigAttrib(display, config, EGL_NATIVE_VISUAL_ID, &format) )
{
LOGE( "[Example]: eglGetConfigAttrib() returned error %d", eglGetError() );
DestroyOpenGL();
return false;
}
// Set buffer geometry using our window which is saved in Android
ANativeWindow_setBuffersGeometry( Android::GetWindow(), 0, 0, format );
if ( !( surface = eglCreateWindowSurface( display, config, Android::GetWindow(), 0 ) ) )
{
LOGE( "[Example]: eglCreateWindowSurface() returned error %d", eglGetError() );
DestroyOpenGL();
return false;
}
if ( !( context = eglCreateContext( display, config, 0, 0 ) ) )
{
LOGE( "[Example]: eglCreateContext() returned error %d", eglGetError() );
DestroyOpenGL();
return false;
}
if ( !eglMakeCurrent(display, surface, surface, context ) )
{
LOGE( "[Example]: eglMakeCurrent() returned error %d", eglGetError() );
DestroyOpenGL();
return false;
}
if ( !eglQuerySurface( display, surface, EGL_WIDTH, &width ) ||
!eglQuerySurface( display, surface, EGL_HEIGHT, &height ) )
{
LOGE( "[Example]: eglQuerySurface() returned error %d", eglGetError() );
DestroyOpenGL();
return false;
}
m_Display = display;
m_Surface = surface;
m_Context = context;
glDisable( GL_DITHER );
glHint( GL_PERSPECTIVE_CORRECTION_HINT, GL_FASTEST );
glClearColor(0, 0, 0, 0);
glEnable( GL_CULL_FACE );
glEnable( GL_DEPTH_TEST );
return true;
}
void ExampleAndroidHandler::DestroyOpenGL()
{
if ( m_Display )
{
LOGV( "[Example]: Shutting down OpenGL" );
eglMakeCurrent( m_Display, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT );
eglDestroyContext( m_Display, m_Context );
eglDestroySurface( m_Display, m_Surface);
eglTerminate( m_Display );
m_Display = EGL_NO_DISPLAY;
m_Surface = EGL_NO_SURFACE;
m_Context = NULL;
}
}
// Application
void ExampleAndroidHandler::OnShutdown()
{
LOGV( "[Example]: Shutting down!" );
m_bShouldQuit = true;
}
// Surface
void ExampleAndroidHandler::OnSurfaceCreated()
{
LOGV( "[Example]: Creating surface!" );
if ( InitOpenGL() == false )
{
m_bShouldQuit = true;
}
}
void ExampleAndroidHandler::OnSurfaceChanged( int iPixelFormat, int iWidth, int iHeight )
{
LOGV( "[Example]: Setting viewports!" );
// Set new viewport
glViewport( 0, 0, iWidth, iHeight );
}
void ExampleAndroidHandler::OnSurfaceDestroyed()
{
LOGV( "[Example]: Destroying egl!" );
DestroyOpenGL();
}
// States
void ExampleAndroidHandler::OnPause()
{
LOGV( "[Example]: Paused!" );
m_bIsPaused = true;
}
void ExampleAndroidHandler::OnResume()
{
LOGV( "[Example]: Resumed!" );
m_bIsPaused = false;
}
void ExampleAndroidHandler::OnVisible()
{
LOGV( "[Example]: Visible!" );
m_bIsVisible = true;
}
void ExampleAndroidHandler::OnHidden()
{
LOGV( "[Example]: Hidden!" );
m_bIsVisible = false;
}
void ExampleAndroidHandler::OnLowMemory()
{
LOGV( "[Example]: Clearing some memory to stay alive..." );
// BigMemoryObject->Release();
}
// Input
void ExampleAndroidHandler::OnKey( int iKeyCode, wchar_t iUnicodeChar )
{
LOGV( "[Example]: Got key! %i %c", iKeyCode, iUnicodeChar );
}
void ExampleAndroidHandler::OnTouch( int iPointerID, float fPosX, float fPosY, int iAction )
{
LOGV( "[Example]: Touch: %i, x: %f y:, %f action:, %i.", iPointerID, fPosX, fPosY, iAction );
if ( iAction == 0 )
{
// On touch start show keyboard!
Android::ShowKeyboard();
}
else if ( iAction == 1 )
{
// On touch up, hide keyboard...
Android::HideKeyboard();
}
}
<commit_msg>Added missing log identifiers<commit_after>#include "ExampleAndroidHandler.h"
#include <AndroidLog.h>
ExampleAndroidHandler::ExampleAndroidHandler()
{
// State variables
m_bShouldQuit = false;
m_bIsVisible = false;
m_bIsPaused = true;
// Egl
m_Display = EGL_NO_DISPLAY;
m_Surface = EGL_NO_SURFACE;
m_Context = NULL;
}
ExampleAndroidHandler::~ExampleAndroidHandler()
{
DestroyOpenGL();
}
void ExampleAndroidHandler::Run()
{
// Example asset read
Android::Asset* pAsset = Android::GetAssetManager().GetAsset( "test.txt" );
if ( pAsset )
{
// Create a buffer to read the content into,
// [ Size() + 1 ] for null terminator character for LOV usage
char* pBuffer = new char[ pAsset->Size() + 1 ];
// Read the buffer
pAsset->Read( pBuffer, pAsset->Size() );
// Delete the asset file
delete pAsset;
// Set null terminating for LOGV
pBuffer[ pAsset->Size() ] = 0;
// Show us the file's content!
LOGV( "[Example]: File content: %s", pBuffer );
// Delete the buffer
delete [] pBuffer;
}
// Create time measurement
timespec timeNow;
clock_gettime( CLOCK_MONOTONIC, &timeNow );
uint64_t uPreviousTime = timeNow.tv_sec * 1000000000ull + timeNow.tv_nsec;
// While application is alive...
while ( !m_bShouldQuit )
{
// Handle Android events
Android::PollEvents();
// Calculate delta time
clock_gettime( CLOCK_MONOTONIC, &timeNow ); // query time now
uint64_t uNowNano = timeNow.tv_sec * 1000000000ull + timeNow.tv_nsec; // get time in nanoseconds
float fDeltaSeconds = float( uNowNano - uPreviousTime ) * 0.000000001f; // 1 second = 1,000,000,000 nanoseconds
uPreviousTime = uNowNano; // set previous time to new time
// If not paused...
if ( !m_bIsPaused )
{
// Update logic
Update( fDeltaSeconds );
}
// If visible
if ( m_bIsVisible )
{
// Draw
Draw();
}
}
LOGV( "[Example]: Mainloop terminated." );
}
void ExampleAndroidHandler::Update( float fDeltaSeconds )
{
// Do stuff here
}
void ExampleAndroidHandler::Draw()
{
// Draw things here
glClearColor( 0.0f, 0.0f, 1.0f, 1.0f );
glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT );
if ( !eglSwapBuffers( m_Display, m_Surface ) )
{
LOGE( "[Example]: eglSwapBuffers() returned error %d", eglGetError() );
}
}
bool ExampleAndroidHandler::InitOpenGL()
{
const EGLint attribs[] =
{
EGL_SURFACE_TYPE, EGL_WINDOW_BIT,
EGL_BLUE_SIZE, 8,
EGL_GREEN_SIZE, 8,
EGL_RED_SIZE, 8,
EGL_NONE
};
EGLDisplay display;
EGLConfig config;
EGLint numConfigs;
EGLint format;
EGLSurface surface;
EGLContext context;
EGLint width;
EGLint height;
GLfloat ratio;
LOGV( "[Example]: Initializing context" );
if ( ( display = eglGetDisplay( EGL_DEFAULT_DISPLAY ) ) == EGL_NO_DISPLAY )
{
LOGE( "[Example]: eglGetDisplay() returned error %d", eglGetError() );
return false;
}
if ( !eglInitialize( display, 0, 0 ) )
{
LOGE( "[Example]: eglInitialize() returned error %d", eglGetError() );
return false;
}
if ( !eglChooseConfig(display, attribs, &config, 1, &numConfigs) )
{
LOGE( "[Example]: eglChooseConfig() returned error %d", eglGetError() );
DestroyOpenGL();
return false;
}
if ( !eglGetConfigAttrib(display, config, EGL_NATIVE_VISUAL_ID, &format) )
{
LOGE( "[Example]: eglGetConfigAttrib() returned error %d", eglGetError() );
DestroyOpenGL();
return false;
}
// Set buffer geometry using our window which is saved in Android
ANativeWindow_setBuffersGeometry( Android::GetWindow(), 0, 0, format );
if ( !( surface = eglCreateWindowSurface( display, config, Android::GetWindow(), 0 ) ) )
{
LOGE( "[Example]: eglCreateWindowSurface() returned error %d", eglGetError() );
DestroyOpenGL();
return false;
}
if ( !( context = eglCreateContext( display, config, 0, 0 ) ) )
{
LOGE( "[Example]: eglCreateContext() returned error %d", eglGetError() );
DestroyOpenGL();
return false;
}
if ( !eglMakeCurrent(display, surface, surface, context ) )
{
LOGE( "[Example]: eglMakeCurrent() returned error %d", eglGetError() );
DestroyOpenGL();
return false;
}
if ( !eglQuerySurface( display, surface, EGL_WIDTH, &width ) ||
!eglQuerySurface( display, surface, EGL_HEIGHT, &height ) )
{
LOGE( "[Example]: eglQuerySurface() returned error %d", eglGetError() );
DestroyOpenGL();
return false;
}
m_Display = display;
m_Surface = surface;
m_Context = context;
glDisable( GL_DITHER );
glHint( GL_PERSPECTIVE_CORRECTION_HINT, GL_FASTEST );
glClearColor(0, 0, 0, 0);
glEnable( GL_CULL_FACE );
glEnable( GL_DEPTH_TEST );
return true;
}
void ExampleAndroidHandler::DestroyOpenGL()
{
if ( m_Display )
{
LOGV( "[Example]: Shutting down OpenGL" );
eglMakeCurrent( m_Display, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT );
eglDestroyContext( m_Display, m_Context );
eglDestroySurface( m_Display, m_Surface);
eglTerminate( m_Display );
m_Display = EGL_NO_DISPLAY;
m_Surface = EGL_NO_SURFACE;
m_Context = NULL;
}
}
// Application
void ExampleAndroidHandler::OnShutdown()
{
LOGV( "[Example]: Shutting down!" );
m_bShouldQuit = true;
}
// Surface
void ExampleAndroidHandler::OnSurfaceCreated()
{
LOGV( "[Example]: Creating surface!" );
if ( InitOpenGL() == false )
{
m_bShouldQuit = true;
}
}
void ExampleAndroidHandler::OnSurfaceChanged( int iPixelFormat, int iWidth, int iHeight )
{
LOGV( "[Example]: Setting viewports!" );
// Set new viewport
glViewport( 0, 0, iWidth, iHeight );
}
void ExampleAndroidHandler::OnSurfaceDestroyed()
{
LOGV( "[Example]: Destroying egl!" );
DestroyOpenGL();
}
// States
void ExampleAndroidHandler::OnPause()
{
LOGV( "[Example]: Paused!" );
m_bIsPaused = true;
}
void ExampleAndroidHandler::OnResume()
{
LOGV( "[Example]: Resumed!" );
m_bIsPaused = false;
}
void ExampleAndroidHandler::OnVisible()
{
LOGV( "[Example]: Visible!" );
m_bIsVisible = true;
}
void ExampleAndroidHandler::OnHidden()
{
LOGV( "[Example]: Hidden!" );
m_bIsVisible = false;
}
void ExampleAndroidHandler::OnLowMemory()
{
LOGV( "[Example]: Clearing some memory to stay alive..." );
// BigMemoryObject->Release();
}
// Input
void ExampleAndroidHandler::OnKey( int iKeyCode, wchar_t iUnicodeChar )
{
LOGV( "[Example]: Got key! %i %c", iKeyCode, iUnicodeChar );
}
void ExampleAndroidHandler::OnTouch( int iPointerID, float fPosX, float fPosY, int iAction )
{
LOGV( "[Example]: Touch: %i, x: %f y:, %f action:, %i.", iPointerID, fPosX, fPosY, iAction );
if ( iAction == 0 )
{
// On touch start show keyboard!
Android::ShowKeyboard();
}
else if ( iAction == 1 )
{
// On touch up, hide keyboard...
Android::HideKeyboard();
}
}
<|endoftext|> |
<commit_before>#include <stdio.h>
#include <iostream>
#include "opencv2/highgui/highgui.hpp"
#include "opencv2/features2d/features2d.hpp"
#include "opencv2/nonfree/nonfree.hpp"
#include "opencv2/video/video.hpp"
#include <utils.h>
#include <vector>
#include "types.h"
using namespace std;
using namespace visual_odometry;
using namespace visual_odometry::utils;
#define LOG(...) printf(__VA_ARGS__)
//void CalcProjectionMatrix(const vector<cv::Point3f>& pt_3d, const vector<cv::Point2f>& pt_2d, cv::Mat pM);
class Frame {
public:
Frame(int n) {
squareFeatures.resize(n);
triangleFeatures.resize(n);
projMatrix.create(cv::Size(4, 3), CV_64FC1);
}
Frame(const Frame& other) {
squareFeatures = other.squareFeatures;
triangleFeatures = other.triangleFeatures;
projMatrix = other.projMatrix.clone();
intrinsic = other.intrinsic;
distortion = other.distortion;
image = other.image;
keypoints = other.keypoints;
descriptors = other.descriptors.clone();
}
vector<Feature> squareFeatures;
vector<Feature> triangleFeatures;
cv::Mat projMatrix;
// Intrinsics params
cv::Mat intrinsic; // intrinsic parameters
cv::Mat distortion; // lens distortion coefficients
cv::Mat image;
vector<cv::KeyPoint> keypoints;
cv::Mat descriptors;
void calcProjMatrix() {
vector<cv::Point3f> points3d;
vector<cv::Point2f> points2d;
for (int i = 0; i < squareFeatures.size(); i++) {
points3d.push_back(squareFeatures[i].p3D_);
points2d.push_back(squareFeatures[i].kp_.pt);
}
// bool cv::solvePnPRansac ( InputArray objectPoints,
// InputArray imagePoints,
// InputArray cameraMatrix,
// InputArray distCoeffs,
// OutputArray rvec,
// OutputArray tvec,
// bool useExtrinsicGuess = false,
// int iterationsCount = 100,
// float reprojectionError = 8.0,
// double confidence = 0.99,
// OutputArray inliers = noArray(),
// int flags = SOLVEPNP_ITERATIVE
// )
LOG("Number of Points %d\n", points3d.size());
cv::Mat tvec, rvec;
cv::solvePnPRansac(points3d, points2d, intrinsic, distortion, rvec, tvec, false, 100, 8.0, 0.99);
cv::Mat R;
cv::Rodrigues(rvec, R);
cv::Mat Pose(3,4, R.type());
R.copyTo(Pose(cv::Rect(0, 0, 3, 3)));
tvec.copyTo(Pose(cv::Rect(3, 0, 1, 3)));
projMatrix = intrinsic*Pose;
//CalcProjectionMatrix(points3d, points2d, projMatrix);
printProjMatrix();
}
void detectAndDescribe() {
char algorithm[] = "SIFT";
cv::Ptr<cv::FeatureDetector> detector = cv::FeatureDetector::create(algorithm);
cv::Ptr<cv::DescriptorExtractor> descriptor = cv::DescriptorExtractor::create(algorithm);
keypoints.clear();
detector->detect(image, keypoints);
descriptor->compute(image, keypoints, descriptors);
}
void loadIntrinsicsFromFile(const std::string& filename){
cv::FileStorage cvfs(filename.c_str(),CV_STORAGE_READ);
if( cvfs.isOpened() ){
cvfs["mat_intrinsicMat"] >> intrinsic;
cvfs["mat_distortionMat"] >> distortion;
}
}
void loadKpFromFile(const std::string& filename){
FILE *f = fopen(filename.c_str(), "r");
float x, y;
int index = 0;
while (fscanf(f, "%f,%f", &x, &y) == 2){
squareFeatures[index].kp_ = cv::KeyPoint(x, y, 1);
squareFeatures[index].type_ = Feature::SQUARE;
index++;
}
fclose(f);
}
void load3DPointsFromFile(const std::string& filename){
FILE *f = fopen(filename.c_str(), "r");
cv::Point3f p;
int index = 0;
while (fscanf(f, "%f,%f,%f", &p.x, &p.y, &p.z) == 3){
squareFeatures[index].p3D_ = p;
index++;
}
fclose(f);
}
void printProjMatrix() {
static int projIndex = 0;
LOG("Proj Matrix #%d:", projIndex++);
for (int i = 0; i < 12; i++) {
LOG("%s%lf\t", (i % 4 == 0) ? "\n" : "", projMatrix.at<double>(i / 4, i % 4));
}
LOG("\n");
projectAndShow();
}
void readNextFrame() {
static int findex = 0;
char buf[256];
sprintf(buf, "S01L03_VGA/S01L03_VGA_%04d.png", findex++);
image = cv::imread(buf);
if (image.empty()) {
exit(0);
}
}
void updateUsingKLT(Frame& previousFrame) {
squareFeatures.clear();
vector<cv::Point2f> previousPoints;
vector<cv::Point2f> currentPoints;
vector<uchar> status;
cv::Mat errors;
for (int i = 0; i < previousFrame.squareFeatures.size(); i++) {
previousPoints.push_back(previousFrame.squareFeatures[i].kp_.pt);
}
cv::calcOpticalFlowPyrLK(previousFrame.image, image, previousPoints, currentPoints, status, errors);
for (int i = 0; i < previousPoints.size(); i++) {
if (status[i] != 0 /*&& errors.at<float>(i) < 4*/) { // klt ok!
Feature f;
f.kp_ = cv::KeyPoint(currentPoints[i].x, currentPoints[i].y, 1);
f.p3D_ = previousFrame.squareFeatures[i].p3D_;
squareFeatures.push_back(f);
}
}
}
void projectAndShow() {
cv::Mat point3D;
point3D.create(cv::Size(1, 4), CV_64FC1);
point3D.at<double>(0) = 140;
point3D.at<double>(1) = -264;
point3D.at<double>(2) = 300;
point3D.at<double>(3) = 1;
cv::Mat result;
result.create(cv::Size(1, 3), CV_64FC1);
cv::gemm(projMatrix, point3D, 1, 0, 0, result);
//printf("%lf %lf %lf\n", result.at<double>(0), result.at<double>(1), result.at<double>(2));
//printf("%lf %lf\n", result.at<double>(0) / result.at<double>(2), result.at<double>(1) / result.at<double>(2));
cv::Mat imcopy = image.clone();
cv::circle(imcopy, cv::Point(result.at<double>(0) / result.at<double>(2), result.at<double>(1) / result.at<double>(2)),4,cv::Scalar(0,0,255),-1);
cv::circle(imcopy, cv::Point(result.at<double>(0) / result.at<double>(2), result.at<double>(1) / result.at<double>(2)), 3, cv::Scalar(255, 255, 255), -1);
cv::circle(imcopy, cv::Point(result.at<double>(0) / result.at<double>(2), result.at<double>(1) / result.at<double>(2)), 2, cv::Scalar(0, 0, 255), -1);
for(int i = 0; i < squareFeatures.size(); i++){
point3D.at<double>(0) = squareFeatures[i].p3D_.x;
point3D.at<double>(1) = squareFeatures[i].p3D_.y;
point3D.at<double>(2) = squareFeatures[i].p3D_.z;
point3D.at<double>(3) = 1;
cv::gemm(projMatrix, point3D , 1, 0, 0, result);
cv::circle(imcopy, cv::Point(result.at<double>(0) / result.at<double>(2), result.at<double>(1) / result.at<double>(2)),4,cv::Scalar(0,0,255),-1);
cv::circle(imcopy, cv::Point(result.at<double>(0) / result.at<double>(2), result.at<double>(1) / result.at<double>(2)), 3, cv::Scalar(255, 255, 255), -1);
cv::circle(imcopy, cv::Point(result.at<double>(0) / result.at<double>(2), result.at<double>(1) / result.at<double>(2)), 2, cv::Scalar(0, 0, 255), -1);
}
for(int i = 0; i < triangleFeatures.size(); i++){
cv::circle(imcopy, cv::Point(triangleFeatures[i].kp_.pt.x,triangleFeatures[i].kp_.pt.y), 4,cv::Scalar(0,125,255),-1);
cv::circle(imcopy, cv::Point(triangleFeatures[i].kp_.pt.x,triangleFeatures[i].kp_.pt.y), 3, cv::Scalar(125, 255, 255), -1);
cv::circle(imcopy, cv::Point(triangleFeatures[i].kp_.pt.x,triangleFeatures[i].kp_.pt.y) , 2, cv::Scalar(125, 125, 255), -1);
}
cv::imshow("frame", imcopy);
if (cv::waitKey(0) == 27) exit(0);
}
};
void matchAndTriangulate(Frame& previousFrame, Frame& currentFrame, cv::Mat intrinsics, cv::Mat distortion) {
static GenericMatcher matcher;
vector<cv::DMatch> matches;
matcher.match(currentFrame.descriptors, previousFrame.descriptors, matches, currentFrame.keypoints, previousFrame.keypoints);
vector<cv::Point2f> previousTriangulate, currentTriangulate;
cv::Mat outputTriangulate;
outputTriangulate.create(cv::Size(4, matches.size()), CV_32FC1);
for (int i = 0; i < matches.size(); i++) {
cv::Point pt1 = previousFrame.keypoints[matches[i].trainIdx].pt;
cv::Point pt2 = currentFrame.keypoints[matches[i].queryIdx].pt;
previousTriangulate.push_back(pt1);
currentTriangulate.push_back(pt2);
}
// undistort
std::vector<cv::Point2f> previousTriangulateUnd, currentTriangulateUnd;
cv::undistortPoints(previousTriangulate, previousTriangulateUnd, intrinsics, distortion);
cv::undistortPoints(currentTriangulate, currentTriangulateUnd, intrinsics, distortion);
cv::triangulatePoints(intrinsics.inv()*previousFrame.projMatrix, intrinsics.inv()*currentFrame.projMatrix, previousTriangulateUnd, currentTriangulateUnd, outputTriangulate);
for (int i = 0; i < matches.size(); i++) {
Feature f;
f.kp_ = cv::KeyPoint(currentTriangulate[i].x, currentTriangulate[i].y, 1);
f.p3D_ = cv::Point3f(outputTriangulate.at<float>(0, i) / outputTriangulate.at<float>(3, i),
outputTriangulate.at<float>(1, i) / outputTriangulate.at<float>(3, i),
outputTriangulate.at<float>(2, i) / outputTriangulate.at<float>(3, i));
currentFrame.squareFeatures.push_back(f);
}
}
bool has_enough_baseline(cv::Mat pose1, cv::Mat pose2, double thr_baseline){
cv::Mat R1 = pose1(cv::Range::all(), cv::Range(0, 3));
cv::Mat T1 = pose1(cv::Range::all(), cv::Range(3, 4));
cv::Mat R2 = pose2(cv::Range::all(), cv::Range(0, 3));
cv::Mat T2 = pose2(cv::Range::all(), cv::Range(3, 4));
cv::Mat pos1, pos2;
pos1 = -R1.inv() * T1;
pos2 = -R2.inv() * T2;
double baseline = cv::norm(pos1 - pos2);
LOG("Baseline %f\n", baseline);
return baseline >= thr_baseline;
}
int main() {
//cvNamedWindow("frame", CV_WINDOW_NORMAL);
//cvSetWindowProperty("frame", CV_WND_PROP_FULLSCREEN, CV_WINDOW_FULLSCREEN);
Frame previousFrame(40);
Frame currentFrame(40);
Frame keyFrame(40);
cv::initModule_nonfree();
previousFrame.loadKpFromFile("S01_2Ddata_dst_init.csv");
previousFrame.load3DPointsFromFile("S01_3Ddata_dst_init.csv");
previousFrame.loadIntrinsicsFromFile("intrinsics.xml");
currentFrame.loadIntrinsicsFromFile("intrinsics.xml");
previousFrame.readNextFrame();
previousFrame.calcProjMatrix();
previousFrame.detectAndDescribe();
keyFrame = previousFrame;
int counter = 1;
while (true) {
currentFrame.readNextFrame();
currentFrame.updateUsingKLT(previousFrame);
currentFrame.calcProjMatrix();
bool enough_baseline = has_enough_baseline(keyFrame.intrinsic.inv()*keyFrame.projMatrix, currentFrame.intrinsic.inv()*currentFrame.projMatrix, 150);
if (enough_baseline /*counter % 20 == 0*/) { // keyframe interval // change here from 5 to any other number
currentFrame.detectAndDescribe();
LOG("BEFORE: %d\t", currentFrame.squareFeatures.size());
matchAndTriangulate(keyFrame, currentFrame, currentFrame.intrinsic, currentFrame.distortion);
LOG("AFTER: %d\n", currentFrame.squareFeatures.size());
keyFrame = currentFrame;
// This is extremely important (otherwise all Frames will have a common projMatrix in the memory)
keyFrame.projMatrix = currentFrame.projMatrix.clone();
}
previousFrame = currentFrame;
counter++;
}
}
<commit_msg>fixed triangulation assert error and optimised params<commit_after>#include <stdio.h>
#include <iostream>
#include "opencv2/highgui/highgui.hpp"
#include "opencv2/features2d/features2d.hpp"
#include "opencv2/nonfree/nonfree.hpp"
#include "opencv2/video/video.hpp"
#include <utils.h>
#include <vector>
#include "types.h"
#include <algorithm>
using namespace std;
using namespace visual_odometry;
using namespace visual_odometry::utils;
#define LOG(...) printf(__VA_ARGS__)
//void CalcProjectionMatrix(const vector<cv::Point3f>& pt_3d, const vector<cv::Point2f>& pt_2d, cv::Mat pM);
class Frame {
public:
Frame(int n) {
squareFeatures.resize(n);
triangleFeatures.resize(n);
projMatrix.create(cv::Size(4, 3), CV_64FC1);
}
Frame(const Frame& other) {
squareFeatures = other.squareFeatures;
triangleFeatures = other.triangleFeatures;
projMatrix = other.projMatrix.clone();
intrinsic = other.intrinsic;
distortion = other.distortion;
image = other.image;
keypoints = other.keypoints;
descriptors = other.descriptors.clone();
}
vector<Feature> squareFeatures;
vector<Feature> triangleFeatures;
cv::Mat projMatrix;
// Intrinsics params
cv::Mat intrinsic; // intrinsic parameters
cv::Mat distortion; // lens distortion coefficients
cv::Mat image;
vector<cv::KeyPoint> keypoints;
cv::Mat descriptors;
void calcProjMatrix() {
vector<cv::Point3f> points3d;
vector<cv::Point2f> points2d;
for (int i = std::max<int>(0,(squareFeatures.size()-100)); i < squareFeatures.size(); i++) {
points3d.push_back(squareFeatures[i].p3D_);
points2d.push_back(squareFeatures[i].kp_.pt);
}
// bool cv::solvePnPRansac ( InputArray objectPoints,
// InputArray imagePoints,
// InputArray cameraMatrix,
// InputArray distCoeffs,
// OutputArray rvec,
// OutputArray tvec,
// bool useExtrinsicGuess = false,
// int iterationsCount = 100,
// float reprojectionError = 8.0,
// double confidence = 0.99,
// OutputArray inliers = noArray(),
// int flags = SOLVEPNP_ITERATIVE
// )
LOG("Number of Points %d\n", points3d.size());
cv::Mat tvec, rvec;
cv::solvePnPRansac(points3d, points2d, intrinsic, distortion, rvec, tvec, false, 300, 8.0, 0.99);
cv::Mat R;
cv::Rodrigues(rvec, R);
cv::Mat Pose(3,4, R.type());
R.copyTo(Pose(cv::Rect(0, 0, 3, 3)));
tvec.copyTo(Pose(cv::Rect(3, 0, 1, 3)));
projMatrix = intrinsic*Pose;
//CalcProjectionMatrix(points3d, points2d, projMatrix);
printProjMatrix();
}
void detectAndDescribe() {
char algorithm[] = "SIFT";
cv::Ptr<cv::FeatureDetector> detector = cv::FeatureDetector::create(algorithm);
cv::Ptr<cv::DescriptorExtractor> descriptor = cv::DescriptorExtractor::create(algorithm);
keypoints.clear();
detector->detect(image, keypoints);
descriptor->compute(image, keypoints, descriptors);
}
void loadIntrinsicsFromFile(const std::string& filename){
cv::FileStorage cvfs(filename.c_str(),CV_STORAGE_READ);
if( cvfs.isOpened() ){
cvfs["mat_intrinsicMat"] >> intrinsic;
cvfs["mat_distortionMat"] >> distortion;
}
}
void loadKpFromFile(const std::string& filename){
FILE *f = fopen(filename.c_str(), "r");
float x, y;
int index = 0;
while (fscanf(f, "%f,%f", &x, &y) == 2){
squareFeatures[index].kp_ = cv::KeyPoint(x, y, 1);
squareFeatures[index].type_ = Feature::SQUARE;
index++;
}
fclose(f);
}
void load3DPointsFromFile(const std::string& filename){
FILE *f = fopen(filename.c_str(), "r");
cv::Point3f p;
int index = 0;
while (fscanf(f, "%f,%f,%f", &p.x, &p.y, &p.z) == 3){
squareFeatures[index].p3D_ = p;
index++;
}
fclose(f);
}
void printProjMatrix() {
static int projIndex = 0;
LOG("Proj Matrix #%d:", projIndex++);
for (int i = 0; i < 12; i++) {
LOG("%s%lf\t", (i % 4 == 0) ? "\n" : "", projMatrix.at<double>(i / 4, i % 4));
}
LOG("\n");
projectAndShow();
}
void readNextFrame() {
static int findex = 0;
char buf[256];
sprintf(buf, "S01L03_VGA/S01L03_VGA_%04d.png", findex++);
image = cv::imread(buf);
if (image.empty()) {
exit(0);
}
}
void updateUsingKLT(Frame& previousFrame) {
squareFeatures.clear();
vector<cv::Point2f> previousPoints;
vector<cv::Point2f> currentPoints;
vector<uchar> status;
cv::Mat errors;
for (int i = 0; i < previousFrame.squareFeatures.size(); i++) {
previousPoints.push_back(previousFrame.squareFeatures[i].kp_.pt);
}
cv::calcOpticalFlowPyrLK(previousFrame.image, image, previousPoints, currentPoints, status, errors);
for (int i = 0; i < previousPoints.size(); i++) {
if (status[i] != 0 /*&& errors.at<float>(i) < 4*/) { // klt ok!
Feature f;
f.kp_ = cv::KeyPoint(currentPoints[i].x, currentPoints[i].y, 1);
f.p3D_ = previousFrame.squareFeatures[i].p3D_;
squareFeatures.push_back(f);
}
}
}
void projectAndShow() {
cv::Mat point3D;
point3D.create(cv::Size(1, 4), CV_64FC1);
point3D.at<double>(0) = 140;
point3D.at<double>(1) = -264;
point3D.at<double>(2) = 300;
point3D.at<double>(3) = 1;
cv::Mat result;
result.create(cv::Size(1, 3), CV_64FC1);
cv::gemm(projMatrix, point3D, 1, 0, 0, result);
//printf("%lf %lf %lf\n", result.at<double>(0), result.at<double>(1), result.at<double>(2));
//printf("%lf %lf\n", result.at<double>(0) / result.at<double>(2), result.at<double>(1) / result.at<double>(2));
cv::Mat imcopy = image.clone();
cv::circle(imcopy, cv::Point(result.at<double>(0) / result.at<double>(2), result.at<double>(1) / result.at<double>(2)),4,cv::Scalar(0,0,255),-1);
cv::circle(imcopy, cv::Point(result.at<double>(0) / result.at<double>(2), result.at<double>(1) / result.at<double>(2)), 3, cv::Scalar(255, 255, 255), -1);
cv::circle(imcopy, cv::Point(result.at<double>(0) / result.at<double>(2), result.at<double>(1) / result.at<double>(2)), 2, cv::Scalar(0, 0, 255), -1);
for(int i = 0; i < squareFeatures.size(); i++){
point3D.at<double>(0) = squareFeatures[i].p3D_.x;
point3D.at<double>(1) = squareFeatures[i].p3D_.y;
point3D.at<double>(2) = squareFeatures[i].p3D_.z;
point3D.at<double>(3) = 1;
cv::gemm(projMatrix, point3D , 1, 0, 0, result);
cv::circle(imcopy, cv::Point(result.at<double>(0) / result.at<double>(2), result.at<double>(1) / result.at<double>(2)),4,cv::Scalar(0,0,255),-1);
cv::circle(imcopy, cv::Point(result.at<double>(0) / result.at<double>(2), result.at<double>(1) / result.at<double>(2)), 3, cv::Scalar(255, 255, 255), -1);
cv::circle(imcopy, cv::Point(result.at<double>(0) / result.at<double>(2), result.at<double>(1) / result.at<double>(2)), 2, cv::Scalar(0, 0, 255), -1);
}
for(int i = 0; i < triangleFeatures.size(); i++){
cv::circle(imcopy, cv::Point(triangleFeatures[i].kp_.pt.x,triangleFeatures[i].kp_.pt.y), 4,cv::Scalar(0,125,255),-1);
cv::circle(imcopy, cv::Point(triangleFeatures[i].kp_.pt.x,triangleFeatures[i].kp_.pt.y), 3, cv::Scalar(125, 255, 255), -1);
cv::circle(imcopy, cv::Point(triangleFeatures[i].kp_.pt.x,triangleFeatures[i].kp_.pt.y) , 2, cv::Scalar(125, 125, 255), -1);
}
cv::imshow("frame", imcopy);
if (cv::waitKey(0) == 27) exit(0);
}
};
void matchAndTriangulate(Frame& previousFrame, Frame& currentFrame, cv::Mat intrinsics, cv::Mat distortion) {
static GenericMatcher matcher;
vector<cv::DMatch> matches;
matcher.match(currentFrame.descriptors, previousFrame.descriptors, matches, currentFrame.keypoints, previousFrame.keypoints);
LOG("NMatches %d\n",matches.size());
vector<cv::Point2f> previousTriangulate, currentTriangulate;
cv::Mat outputTriangulate;
outputTriangulate.create(cv::Size(4, matches.size()), CV_32FC1);
for (int i = 0; i < matches.size(); i++) {
cv::Point pt1 = previousFrame.keypoints[matches[i].trainIdx].pt;
cv::Point pt2 = currentFrame.keypoints[matches[i].queryIdx].pt;
previousTriangulate.push_back(pt1);
currentTriangulate.push_back(pt2);
}
if( previousTriangulate.size() == 0 || currentTriangulate.size() == 0 ){
//LOG("Triangulation Points %d %d\n",previousTriangulate.size(),currentTriangulate.size());
return;
}
// undistort
std::vector<cv::Point2f> previousTriangulateUnd, currentTriangulateUnd;
cv::undistortPoints(previousTriangulate, previousTriangulateUnd, intrinsics, distortion);
cv::undistortPoints(currentTriangulate, currentTriangulateUnd, intrinsics, distortion);
cv::triangulatePoints(intrinsics.inv()*previousFrame.projMatrix, intrinsics.inv()*currentFrame.projMatrix, previousTriangulateUnd, currentTriangulateUnd, outputTriangulate);
for (int i = 0; i < matches.size(); i++) {
Feature f;
f.kp_ = cv::KeyPoint(currentTriangulate[i].x, currentTriangulate[i].y, 1);
f.p3D_ = cv::Point3f(outputTriangulate.at<float>(0, i) / outputTriangulate.at<float>(3, i),
outputTriangulate.at<float>(1, i) / outputTriangulate.at<float>(3, i),
outputTriangulate.at<float>(2, i) / outputTriangulate.at<float>(3, i));
currentFrame.squareFeatures.push_back(f);
}
}
bool has_enough_baseline(cv::Mat pose1, cv::Mat pose2, double thr_baseline){
cv::Mat R1 = pose1(cv::Range::all(), cv::Range(0, 3));
cv::Mat T1 = pose1(cv::Range::all(), cv::Range(3, 4));
cv::Mat R2 = pose2(cv::Range::all(), cv::Range(0, 3));
cv::Mat T2 = pose2(cv::Range::all(), cv::Range(3, 4));
cv::Mat pos1, pos2;
pos1 = -R1.inv() * T1;
pos2 = -R2.inv() * T2;
double baseline = cv::norm(pos1 - pos2);
LOG("Baseline %f\n", baseline);
return baseline >= thr_baseline;
}
int main() {
//cvNamedWindow("frame", CV_WINDOW_NORMAL);
//cvSetWindowProperty("frame", CV_WND_PROP_FULLSCREEN, CV_WINDOW_FULLSCREEN);
Frame previousFrame(40);
Frame currentFrame(40);
Frame keyFrame(40);
cv::initModule_nonfree();
previousFrame.loadKpFromFile("S01_2Ddata_dst_init.csv");
previousFrame.load3DPointsFromFile("S01_3Ddata_dst_init.csv");
previousFrame.loadIntrinsicsFromFile("intrinsics.xml");
currentFrame.loadIntrinsicsFromFile("intrinsics.xml");
previousFrame.readNextFrame();
previousFrame.calcProjMatrix();
previousFrame.detectAndDescribe();
keyFrame = previousFrame;
int counter = 1;
while (true) {
currentFrame.readNextFrame();
currentFrame.updateUsingKLT(previousFrame);
currentFrame.calcProjMatrix();
bool enough_baseline = has_enough_baseline(keyFrame.intrinsic.inv()*keyFrame.projMatrix, currentFrame.intrinsic.inv()*currentFrame.projMatrix, 150);
if (enough_baseline /*counter % 20 == 0*/) { // keyframe interval // change here from 5 to any other number
currentFrame.detectAndDescribe();
LOG("BEFORE: %d\t", currentFrame.squareFeatures.size());
matchAndTriangulate(keyFrame, currentFrame, currentFrame.intrinsic, currentFrame.distortion);
LOG("AFTER: %d\n", currentFrame.squareFeatures.size());
keyFrame = currentFrame;
// This is extremely important (otherwise all Frames will have a common projMatrix in the memory)
keyFrame.projMatrix = currentFrame.projMatrix.clone();
}
previousFrame = currentFrame;
counter++;
}
}
<|endoftext|> |
<commit_before>/*
* Copyright 2014 Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "folly/Subprocess.h"
#include <unistd.h>
#include <sys/types.h>
#include <dirent.h>
#include <boost/container/flat_set.hpp>
#include <glog/logging.h>
#include <gtest/gtest.h>
#include "folly/Exception.h"
#include "folly/Format.h"
#include "folly/FileUtil.h"
#include "folly/String.h"
#include "folly/gen/Base.h"
#include "folly/gen/File.h"
#include "folly/gen/String.h"
#include "folly/experimental/io/FsUtil.h"
using namespace folly;
TEST(SimpleSubprocessTest, ExitsSuccessfully) {
Subprocess proc(std::vector<std::string>{ "/bin/true" });
EXPECT_EQ(0, proc.wait().exitStatus());
}
TEST(SimpleSubprocessTest, ExitsSuccessfullyChecked) {
Subprocess proc(std::vector<std::string>{ "/bin/true" });
proc.waitChecked();
}
TEST(SimpleSubprocessTest, ExitsWithError) {
Subprocess proc(std::vector<std::string>{ "/bin/false" });
EXPECT_EQ(1, proc.wait().exitStatus());
}
TEST(SimpleSubprocessTest, ExitsWithErrorChecked) {
Subprocess proc(std::vector<std::string>{ "/bin/false" });
EXPECT_THROW(proc.waitChecked(), CalledProcessError);
}
#define EXPECT_SPAWN_ERROR(err, errMsg, cmd, ...) \
do { \
try { \
Subprocess proc(std::vector<std::string>{ (cmd), ## __VA_ARGS__ }); \
ADD_FAILURE() << "expected an error when running " << (cmd); \
} catch (const SubprocessSpawnError& ex) { \
EXPECT_EQ((err), ex.errnoValue()); \
if (StringPiece(ex.what()).find(errMsg) == StringPiece::npos) { \
ADD_FAILURE() << "failed to find \"" << (errMsg) << \
"\" in exception: \"" << ex.what() << "\""; \
} \
} \
} while (0)
TEST(SimpleSubprocessTest, ExecFails) {
EXPECT_SPAWN_ERROR(ENOENT, "failed to execute /no/such/file:",
"/no/such/file");
EXPECT_SPAWN_ERROR(EACCES, "failed to execute /etc/passwd:",
"/etc/passwd");
EXPECT_SPAWN_ERROR(ENOTDIR, "failed to execute /etc/passwd/not/a/file:",
"/etc/passwd/not/a/file");
}
TEST(SimpleSubprocessTest, ShellExitsSuccesssfully) {
Subprocess proc("true");
EXPECT_EQ(0, proc.wait().exitStatus());
}
TEST(SimpleSubprocessTest, ShellExitsWithError) {
Subprocess proc("false");
EXPECT_EQ(1, proc.wait().exitStatus());
}
TEST(SimpleSubprocessTest, ChangeChildDirectorySuccessfully) {
// The filesystem root normally lacks a 'true' binary
EXPECT_EQ(0, chdir("/"));
EXPECT_SPAWN_ERROR(ENOENT, "failed to execute ./true", "./true");
// The child can fix that by moving to /bin before exec().
Subprocess proc("./true", Subprocess::Options().chdir("/bin"));
EXPECT_EQ(0, proc.wait().exitStatus());
}
TEST(SimpleSubprocessTest, ChangeChildDirectoryWithError) {
try {
Subprocess proc(
std::vector<std::string>{"/bin/true"},
Subprocess::Options().chdir("/usually/this/is/not/a/valid/directory/")
);
ADD_FAILURE() << "expected to fail when changing the child's directory";
} catch (const SubprocessSpawnError& ex) {
EXPECT_EQ(ENOENT, ex.errnoValue());
const std::string expectedError =
"error preparing to execute /bin/true: No such file or directory";
if (StringPiece(ex.what()).find(expectedError) == StringPiece::npos) {
ADD_FAILURE() << "failed to find \"" << expectedError <<
"\" in exception: \"" << ex.what() << "\"";
}
}
}
namespace {
boost::container::flat_set<int> getOpenFds() {
auto pid = getpid();
auto dirname = to<std::string>("/proc/", pid, "/fd");
boost::container::flat_set<int> fds;
for (fs::directory_iterator it(dirname);
it != fs::directory_iterator();
++it) {
int fd = to<int>(it->path().filename().native());
fds.insert(fd);
}
return fds;
}
template<class Runnable>
void checkFdLeak(const Runnable& r) {
// Get the currently open fds. Check that they are the same both before and
// after calling the specified function. We read the open fds from /proc.
// (If we wanted to work even on systems that don't have /proc, we could
// perhaps create and immediately close a socket both before and after
// running the function, and make sure we got the same fd number both times.)
auto fdsBefore = getOpenFds();
r();
auto fdsAfter = getOpenFds();
EXPECT_EQ(fdsAfter.size(), fdsBefore.size());
}
}
// Make sure Subprocess doesn't leak any file descriptors
TEST(SimpleSubprocessTest, FdLeakTest) {
// Normal execution
checkFdLeak([] {
Subprocess proc("true");
EXPECT_EQ(0, proc.wait().exitStatus());
});
// Normal execution with pipes
checkFdLeak([] {
Subprocess proc("echo foo; echo bar >&2",
Subprocess::pipeStdout() | Subprocess::pipeStderr());
auto p = proc.communicate();
EXPECT_EQ("foo\n", p.first);
EXPECT_EQ("bar\n", p.second);
proc.waitChecked();
});
// Test where the exec call fails()
checkFdLeak([] {
EXPECT_SPAWN_ERROR(ENOENT, "failed to execute", "/no/such/file");
});
// Test where the exec call fails() with pipes
checkFdLeak([] {
try {
Subprocess proc(std::vector<std::string>({"/no/such/file"}),
Subprocess::pipeStdout().stderr(Subprocess::PIPE));
ADD_FAILURE() << "expected an error when running /no/such/file";
} catch (const SubprocessSpawnError& ex) {
EXPECT_EQ(ENOENT, ex.errnoValue());
}
});
}
TEST(ParentDeathSubprocessTest, ParentDeathSignal) {
// Find out where we are.
static constexpr size_t pathLength = 2048;
char buf[pathLength + 1];
int r = readlink("/proc/self/exe", buf, pathLength);
CHECK_ERR(r);
buf[r] = '\0';
fs::path helper(buf);
helper.remove_filename();
helper /= "subprocess_test_parent_death_helper";
fs::path tempFile(fs::temp_directory_path() / fs::unique_path());
std::vector<std::string> args {helper.string(), tempFile.string()};
Subprocess proc(args);
// The helper gets killed by its child, see details in
// SubprocessTestParentDeathHelper.cpp
ASSERT_EQ(SIGKILL, proc.wait().killSignal());
// Now wait for the file to be created, see details in
// SubprocessTestParentDeathHelper.cpp
while (!fs::exists(tempFile)) {
usleep(20000); // 20ms
}
fs::remove(tempFile);
}
TEST(PopenSubprocessTest, PopenRead) {
Subprocess proc("ls /", Subprocess::pipeStdout());
int found = 0;
gen::byLine(File(proc.stdout())) |
[&] (StringPiece line) {
if (line == "etc" || line == "bin" || line == "usr") {
++found;
}
};
EXPECT_EQ(3, found);
proc.waitChecked();
}
TEST(CommunicateSubprocessTest, SimpleRead) {
Subprocess proc(std::vector<std::string>{ "/bin/echo", "-n", "foo", "bar"},
Subprocess::pipeStdout());
auto p = proc.communicate();
EXPECT_EQ("foo bar", p.first);
proc.waitChecked();
}
TEST(CommunicateSubprocessTest, BigWrite) {
const int numLines = 1 << 20;
std::string line("hello\n");
std::string data;
data.reserve(numLines * line.size());
for (int i = 0; i < numLines; ++i) {
data.append(line);
}
Subprocess proc("wc -l", Subprocess::pipeStdin() | Subprocess::pipeStdout());
auto p = proc.communicate(data);
EXPECT_EQ(folly::format("{}\n", numLines).str(), p.first);
proc.waitChecked();
}
TEST(CommunicateSubprocessTest, Duplex) {
// Take 10MB of data and pass them through a filter.
// One line, as tr is line-buffered
const int bytes = 10 << 20;
std::string line(bytes, 'x');
Subprocess proc("tr a-z A-Z",
Subprocess::pipeStdin() | Subprocess::pipeStdout());
auto p = proc.communicate(line);
EXPECT_EQ(bytes, p.first.size());
EXPECT_EQ(std::string::npos, p.first.find_first_not_of('X'));
proc.waitChecked();
}
TEST(CommunicateSubprocessTest, Duplex2) {
checkFdLeak([] {
// Pipe 200,000 lines through sed
const size_t numCopies = 100000;
auto iobuf = IOBuf::copyBuffer("this is a test\nanother line\n");
IOBufQueue input;
for (int n = 0; n < numCopies; ++n) {
input.append(iobuf->clone());
}
std::vector<std::string> cmd({
"sed", "-u",
"-e", "s/a test/a successful test/",
"-e", "/^another line/w/dev/stderr",
});
auto options = Subprocess::pipeStdin().pipeStdout().pipeStderr().usePath();
Subprocess proc(cmd, options);
auto out = proc.communicateIOBuf(std::move(input));
proc.waitChecked();
// Convert stdout and stderr to strings so we can call split() on them.
fbstring stdoutStr;
if (out.first.front()) {
stdoutStr = out.first.move()->moveToFbString();
}
fbstring stderrStr;
if (out.second.front()) {
stderrStr = out.second.move()->moveToFbString();
}
// stdout should be a copy of stdin, with "a test" replaced by
// "a successful test"
std::vector<StringPiece> stdoutLines;
split('\n', stdoutStr, stdoutLines);
EXPECT_EQ(numCopies * 2 + 1, stdoutLines.size());
// Strip off the trailing empty line
if (!stdoutLines.empty()) {
EXPECT_EQ("", stdoutLines.back());
stdoutLines.pop_back();
}
size_t linenum = 0;
for (const auto& line : stdoutLines) {
if ((linenum & 1) == 0) {
EXPECT_EQ("this is a successful test", line);
} else {
EXPECT_EQ("another line", line);
}
++linenum;
}
// stderr should only contain the lines containing "another line"
std::vector<StringPiece> stderrLines;
split('\n', stderrStr, stderrLines);
EXPECT_EQ(numCopies + 1, stderrLines.size());
// Strip off the trailing empty line
if (!stderrLines.empty()) {
EXPECT_EQ("", stderrLines.back());
stderrLines.pop_back();
}
for (const auto& line : stderrLines) {
EXPECT_EQ("another line", line);
}
});
}
namespace {
bool readToString(int fd, std::string& buf, size_t maxSize) {
size_t bytesRead = 0;
buf.resize(maxSize);
char* dest = &buf.front();
size_t remaining = maxSize;
ssize_t n = -1;
while (remaining) {
n = ::read(fd, dest, remaining);
if (n == -1) {
if (errno == EINTR) {
continue;
}
if (errno == EAGAIN) {
break;
}
PCHECK("read failed");
} else if (n == 0) {
break;
}
dest += n;
remaining -= n;
}
buf.resize(dest - buf.data());
return (n == 0);
}
} // namespace
TEST(CommunicateSubprocessTest, Chatty) {
checkFdLeak([] {
const int lineCount = 1000;
int wcount = 0;
int rcount = 0;
auto options = Subprocess::pipeStdin().pipeStdout().pipeStderr().usePath();
std::vector<std::string> cmd {
"sed",
"-u",
"-e",
"s/a test/a successful test/",
};
Subprocess proc(cmd, options);
auto writeCallback = [&] (int pfd, int cfd) -> bool {
EXPECT_EQ(0, cfd); // child stdin
EXPECT_EQ(rcount, wcount); // chatty, one read for every write
auto msg = folly::to<std::string>("a test ", wcount, "\n");
// Not entirely kosher, we should handle partial writes, but this is
// fine for writes <= PIPE_BUF
EXPECT_EQ(msg.size(), writeFull(pfd, msg.data(), msg.size()));
++wcount;
proc.enableNotifications(0, false);
return (wcount == lineCount);
};
auto readCallback = [&] (int pfd, int cfd) -> bool {
EXPECT_EQ(1, cfd); // child stdout
EXPECT_EQ(wcount, rcount + 1);
auto expected =
folly::to<std::string>("a successful test ", rcount, "\n");
std::string lineBuf;
// Not entirely kosher, we should handle partial reads, but this is
// fine for reads <= PIPE_BUF
bool r = readToString(pfd, lineBuf, expected.size() + 1);
EXPECT_EQ((rcount == lineCount), r); // EOF iff at lineCount
EXPECT_EQ(expected, lineBuf);
++rcount;
if (rcount != lineCount) {
proc.enableNotifications(0, true);
}
return (rcount == lineCount);
};
proc.communicate(readCallback, writeCallback);
EXPECT_EQ(lineCount, wcount);
EXPECT_EQ(lineCount, rcount);
EXPECT_EQ(0, proc.wait().exitStatus());
});
}
<commit_msg>Fix apparent race in SubprocessTest<commit_after>/*
* Copyright 2014 Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "folly/Subprocess.h"
#include <unistd.h>
#include <sys/types.h>
#include <dirent.h>
#include <boost/container/flat_set.hpp>
#include <glog/logging.h>
#include <gtest/gtest.h>
#include "folly/Exception.h"
#include "folly/Format.h"
#include "folly/FileUtil.h"
#include "folly/String.h"
#include "folly/gen/Base.h"
#include "folly/gen/File.h"
#include "folly/gen/String.h"
#include "folly/experimental/io/FsUtil.h"
using namespace folly;
TEST(SimpleSubprocessTest, ExitsSuccessfully) {
Subprocess proc(std::vector<std::string>{ "/bin/true" });
EXPECT_EQ(0, proc.wait().exitStatus());
}
TEST(SimpleSubprocessTest, ExitsSuccessfullyChecked) {
Subprocess proc(std::vector<std::string>{ "/bin/true" });
proc.waitChecked();
}
TEST(SimpleSubprocessTest, ExitsWithError) {
Subprocess proc(std::vector<std::string>{ "/bin/false" });
EXPECT_EQ(1, proc.wait().exitStatus());
}
TEST(SimpleSubprocessTest, ExitsWithErrorChecked) {
Subprocess proc(std::vector<std::string>{ "/bin/false" });
EXPECT_THROW(proc.waitChecked(), CalledProcessError);
}
#define EXPECT_SPAWN_ERROR(err, errMsg, cmd, ...) \
do { \
try { \
Subprocess proc(std::vector<std::string>{ (cmd), ## __VA_ARGS__ }); \
ADD_FAILURE() << "expected an error when running " << (cmd); \
} catch (const SubprocessSpawnError& ex) { \
EXPECT_EQ((err), ex.errnoValue()); \
if (StringPiece(ex.what()).find(errMsg) == StringPiece::npos) { \
ADD_FAILURE() << "failed to find \"" << (errMsg) << \
"\" in exception: \"" << ex.what() << "\""; \
} \
} \
} while (0)
TEST(SimpleSubprocessTest, ExecFails) {
EXPECT_SPAWN_ERROR(ENOENT, "failed to execute /no/such/file:",
"/no/such/file");
EXPECT_SPAWN_ERROR(EACCES, "failed to execute /etc/passwd:",
"/etc/passwd");
EXPECT_SPAWN_ERROR(ENOTDIR, "failed to execute /etc/passwd/not/a/file:",
"/etc/passwd/not/a/file");
}
TEST(SimpleSubprocessTest, ShellExitsSuccesssfully) {
Subprocess proc("true");
EXPECT_EQ(0, proc.wait().exitStatus());
}
TEST(SimpleSubprocessTest, ShellExitsWithError) {
Subprocess proc("false");
EXPECT_EQ(1, proc.wait().exitStatus());
}
TEST(SimpleSubprocessTest, ChangeChildDirectorySuccessfully) {
// The filesystem root normally lacks a 'true' binary
EXPECT_EQ(0, chdir("/"));
EXPECT_SPAWN_ERROR(ENOENT, "failed to execute ./true", "./true");
// The child can fix that by moving to /bin before exec().
Subprocess proc("./true", Subprocess::Options().chdir("/bin"));
EXPECT_EQ(0, proc.wait().exitStatus());
}
TEST(SimpleSubprocessTest, ChangeChildDirectoryWithError) {
try {
Subprocess proc(
std::vector<std::string>{"/bin/true"},
Subprocess::Options().chdir("/usually/this/is/not/a/valid/directory/")
);
ADD_FAILURE() << "expected to fail when changing the child's directory";
} catch (const SubprocessSpawnError& ex) {
EXPECT_EQ(ENOENT, ex.errnoValue());
const std::string expectedError =
"error preparing to execute /bin/true: No such file or directory";
if (StringPiece(ex.what()).find(expectedError) == StringPiece::npos) {
ADD_FAILURE() << "failed to find \"" << expectedError <<
"\" in exception: \"" << ex.what() << "\"";
}
}
}
namespace {
boost::container::flat_set<int> getOpenFds() {
auto pid = getpid();
auto dirname = to<std::string>("/proc/", pid, "/fd");
boost::container::flat_set<int> fds;
for (fs::directory_iterator it(dirname);
it != fs::directory_iterator();
++it) {
int fd = to<int>(it->path().filename().native());
fds.insert(fd);
}
return fds;
}
template<class Runnable>
void checkFdLeak(const Runnable& r) {
// Get the currently open fds. Check that they are the same both before and
// after calling the specified function. We read the open fds from /proc.
// (If we wanted to work even on systems that don't have /proc, we could
// perhaps create and immediately close a socket both before and after
// running the function, and make sure we got the same fd number both times.)
auto fdsBefore = getOpenFds();
r();
auto fdsAfter = getOpenFds();
EXPECT_EQ(fdsAfter.size(), fdsBefore.size());
}
}
// Make sure Subprocess doesn't leak any file descriptors
TEST(SimpleSubprocessTest, FdLeakTest) {
// Normal execution
checkFdLeak([] {
Subprocess proc("true");
EXPECT_EQ(0, proc.wait().exitStatus());
});
// Normal execution with pipes
checkFdLeak([] {
Subprocess proc("echo foo; echo bar >&2",
Subprocess::pipeStdout() | Subprocess::pipeStderr());
auto p = proc.communicate();
EXPECT_EQ("foo\n", p.first);
EXPECT_EQ("bar\n", p.second);
proc.waitChecked();
});
// Test where the exec call fails()
checkFdLeak([] {
EXPECT_SPAWN_ERROR(ENOENT, "failed to execute", "/no/such/file");
});
// Test where the exec call fails() with pipes
checkFdLeak([] {
try {
Subprocess proc(std::vector<std::string>({"/no/such/file"}),
Subprocess::pipeStdout().stderr(Subprocess::PIPE));
ADD_FAILURE() << "expected an error when running /no/such/file";
} catch (const SubprocessSpawnError& ex) {
EXPECT_EQ(ENOENT, ex.errnoValue());
}
});
}
TEST(ParentDeathSubprocessTest, ParentDeathSignal) {
// Find out where we are.
static constexpr size_t pathLength = 2048;
char buf[pathLength + 1];
int r = readlink("/proc/self/exe", buf, pathLength);
CHECK_ERR(r);
buf[r] = '\0';
fs::path helper(buf);
helper.remove_filename();
helper /= "subprocess_test_parent_death_helper";
fs::path tempFile(fs::temp_directory_path() / fs::unique_path());
std::vector<std::string> args {helper.string(), tempFile.string()};
Subprocess proc(args);
// The helper gets killed by its child, see details in
// SubprocessTestParentDeathHelper.cpp
ASSERT_EQ(SIGKILL, proc.wait().killSignal());
// Now wait for the file to be created, see details in
// SubprocessTestParentDeathHelper.cpp
while (!fs::exists(tempFile)) {
usleep(20000); // 20ms
}
fs::remove(tempFile);
}
TEST(PopenSubprocessTest, PopenRead) {
Subprocess proc("ls /", Subprocess::pipeStdout());
int found = 0;
gen::byLine(File(proc.stdout())) |
[&] (StringPiece line) {
if (line == "etc" || line == "bin" || line == "usr") {
++found;
}
};
EXPECT_EQ(3, found);
proc.waitChecked();
}
TEST(CommunicateSubprocessTest, SimpleRead) {
Subprocess proc(std::vector<std::string>{ "/bin/echo", "-n", "foo", "bar"},
Subprocess::pipeStdout());
auto p = proc.communicate();
EXPECT_EQ("foo bar", p.first);
proc.waitChecked();
}
TEST(CommunicateSubprocessTest, BigWrite) {
const int numLines = 1 << 20;
std::string line("hello\n");
std::string data;
data.reserve(numLines * line.size());
for (int i = 0; i < numLines; ++i) {
data.append(line);
}
Subprocess proc("wc -l", Subprocess::pipeStdin() | Subprocess::pipeStdout());
auto p = proc.communicate(data);
EXPECT_EQ(folly::format("{}\n", numLines).str(), p.first);
proc.waitChecked();
}
TEST(CommunicateSubprocessTest, Duplex) {
// Take 10MB of data and pass them through a filter.
// One line, as tr is line-buffered
const int bytes = 10 << 20;
std::string line(bytes, 'x');
Subprocess proc("tr a-z A-Z",
Subprocess::pipeStdin() | Subprocess::pipeStdout());
auto p = proc.communicate(line);
EXPECT_EQ(bytes, p.first.size());
EXPECT_EQ(std::string::npos, p.first.find_first_not_of('X'));
proc.waitChecked();
}
TEST(CommunicateSubprocessTest, Duplex2) {
checkFdLeak([] {
// Pipe 200,000 lines through sed
const size_t numCopies = 100000;
auto iobuf = IOBuf::copyBuffer("this is a test\nanother line\n");
IOBufQueue input;
for (int n = 0; n < numCopies; ++n) {
input.append(iobuf->clone());
}
std::vector<std::string> cmd({
"sed", "-u",
"-e", "s/a test/a successful test/",
"-e", "/^another line/w/dev/stderr",
});
auto options = Subprocess::pipeStdin().pipeStdout().pipeStderr().usePath();
Subprocess proc(cmd, options);
auto out = proc.communicateIOBuf(std::move(input));
proc.waitChecked();
// Convert stdout and stderr to strings so we can call split() on them.
fbstring stdoutStr;
if (out.first.front()) {
stdoutStr = out.first.move()->moveToFbString();
}
fbstring stderrStr;
if (out.second.front()) {
stderrStr = out.second.move()->moveToFbString();
}
// stdout should be a copy of stdin, with "a test" replaced by
// "a successful test"
std::vector<StringPiece> stdoutLines;
split('\n', stdoutStr, stdoutLines);
EXPECT_EQ(numCopies * 2 + 1, stdoutLines.size());
// Strip off the trailing empty line
if (!stdoutLines.empty()) {
EXPECT_EQ("", stdoutLines.back());
stdoutLines.pop_back();
}
size_t linenum = 0;
for (const auto& line : stdoutLines) {
if ((linenum & 1) == 0) {
EXPECT_EQ("this is a successful test", line);
} else {
EXPECT_EQ("another line", line);
}
++linenum;
}
// stderr should only contain the lines containing "another line"
std::vector<StringPiece> stderrLines;
split('\n', stderrStr, stderrLines);
EXPECT_EQ(numCopies + 1, stderrLines.size());
// Strip off the trailing empty line
if (!stderrLines.empty()) {
EXPECT_EQ("", stderrLines.back());
stderrLines.pop_back();
}
for (const auto& line : stderrLines) {
EXPECT_EQ("another line", line);
}
});
}
namespace {
bool readToString(int fd, std::string& buf, size_t maxSize) {
size_t bytesRead = 0;
buf.resize(maxSize);
char* dest = &buf.front();
size_t remaining = maxSize;
ssize_t n = -1;
while (remaining) {
n = ::read(fd, dest, remaining);
if (n == -1) {
if (errno == EINTR) {
continue;
}
if (errno == EAGAIN) {
break;
}
PCHECK("read failed");
} else if (n == 0) {
break;
}
dest += n;
remaining -= n;
}
buf.resize(dest - buf.data());
return (n == 0);
}
} // namespace
TEST(CommunicateSubprocessTest, Chatty) {
checkFdLeak([] {
const int lineCount = 1000;
int wcount = 0;
int rcount = 0;
auto options = Subprocess::pipeStdin().pipeStdout().pipeStderr().usePath();
std::vector<std::string> cmd {
"sed",
"-u",
"-e",
"s/a test/a successful test/",
};
Subprocess proc(cmd, options);
auto writeCallback = [&] (int pfd, int cfd) -> bool {
EXPECT_EQ(0, cfd); // child stdin
EXPECT_EQ(rcount, wcount); // chatty, one read for every write
auto msg = folly::to<std::string>("a test ", wcount, "\n");
// Not entirely kosher, we should handle partial writes, but this is
// fine for writes <= PIPE_BUF
EXPECT_EQ(msg.size(), writeFull(pfd, msg.data(), msg.size()));
++wcount;
proc.enableNotifications(0, false);
return (wcount == lineCount);
};
auto readCallback = [&] (int pfd, int cfd) -> bool {
EXPECT_EQ(1, cfd); // child stdout
EXPECT_EQ(wcount, rcount + 1);
auto expected =
folly::to<std::string>("a successful test ", rcount, "\n");
std::string lineBuf;
// Not entirely kosher, we should handle partial reads, but this is
// fine for reads <= PIPE_BUF
bool r = readToString(pfd, lineBuf, expected.size() + 1);
EXPECT_TRUE(!r || (rcount + 1 == lineCount)); // may read EOF at end
EXPECT_EQ(expected, lineBuf);
++rcount;
if (rcount != lineCount) {
proc.enableNotifications(0, true);
}
return (rcount == lineCount);
};
proc.communicate(readCallback, writeCallback);
EXPECT_EQ(lineCount, wcount);
EXPECT_EQ(lineCount, rcount);
EXPECT_EQ(0, proc.wait().exitStatus());
});
}
<|endoftext|> |
<commit_before>/******************************************************************************
* Copyright (c) 2011, Howard Butler, [email protected]
*
* 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 Hobu, Inc. or Flaxen Geo Consulting 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 <pdal/drivers/oci/Iterator.hpp>
#include <pdal/PointBuffer.hpp>
#include <pdal/drivers/oci/Reader.hpp>
#include <pdal/Vector.hpp>
#include <boost/algorithm/string.hpp>
#include <sstream>
#include <map>
#include <algorithm>
namespace pdal { namespace drivers { namespace oci {
IteratorBase::IteratorBase(const Reader& reader)
: m_statement(Statement())
, m_at_end(false)
, m_cloud(reader.getCloud())
, m_reader(reader)
{
std::ostringstream select_blocks;
select_blocks
<< "select T.OBJ_ID, T.BLK_ID, T.BLK_EXTENT, T.NUM_POINTS, T.POINTS from "
<< m_cloud->blk_table << " T WHERE T.OBJ_ID = "
<< m_cloud->pc_id;
m_statement = Statement(m_cloud->connection->CreateStatement(select_blocks.str().c_str()));
m_statement->Execute(0);
m_block = defineBlock(m_statement);
return;
}
IteratorBase::~IteratorBase()
{
}
const Reader& IteratorBase::getReader() const
{
return m_reader;
}
void IteratorBase::read(PointBuffer& data,
boost::uint32_t howMany,
boost::uint32_t whichPoint,
boost::uint32_t whichBlobPosition)
{
boost::uint32_t nAmountRead = 0;
boost::uint32_t blob_length = m_statement->GetBlobLength(m_block->locator);
if (m_block->chunk->size() < blob_length)
{
m_block->chunk->resize(blob_length);
}
// std::cout << "blob_length: " << blob_len// gth << std::endl;
bool read_all_data = m_statement->ReadBlob( m_block->locator,
(void*)(&(*m_block->chunk)[0]),
m_block->chunk->size() ,
&nAmountRead);
if (!read_all_data) throw pdal_error("Did not read all blob data!");
// std::cout << "nAmountRead: " << nAmountRead << std::endl;
data.getSchema().getByteSize();
boost::uint32_t howMuchToRead = howMany * data.getSchema().getByteSize();
data.setDataStride(&(*m_block->chunk)[whichBlobPosition], whichPoint, howMuchToRead);
data.setNumPoints(data.getNumPoints() + howMany);
}
boost::uint32_t IteratorBase::myReadBuffer(PointBuffer& data)
{
boost::uint32_t numPointsRead = 0;
data.setNumPoints(0);
bool bDidRead = false;
// std::cout << "m_block->num_points: " << m_block->num_points << std::endl;
// std::cout << "data.getCapacity(): " << data.getCapacity() << std::endl;
if (!m_block->num_points)
{
// We still have a block of data from the last readBuffer call
// that was partially read.
// std::cout << "reading because we have no points" << std::endl;
bDidRead = m_statement->Fetch();
if (!bDidRead)
{
m_at_end = true;
return 0;
}
if (m_block->num_points > static_cast<boost::int32_t>(data.getCapacity()))
{
throw buffer_too_small("The PointBuffer is too small to contain this block.");
}
} else
{
// Our read was already "done" last readBuffer call, but if we're done,
// we're done
if (m_at_end) return 0;
bDidRead = true;
}
while (bDidRead)
{
boost::uint32_t numReadThisBlock = m_block->num_points;
boost::uint32_t numSpaceLeftThisBlock = data.getCapacity() - data.getNumPoints();
if (numReadThisBlock > numSpaceLeftThisBlock)
{
// We're done. We still have more data, but the
// user is going to have to request another buffer.
// We're not going to fill the buffer up to *exactly*
// the number of points the user requested.
// If the buffer's capacity isn't large enough to hold
// an oracle block, they're just not going to get anything
// back right now (FIXME)
break;
}
numPointsRead = numPointsRead + numReadThisBlock;
read(data, numReadThisBlock, data.getNumPoints(), 0);
bDidRead = m_statement->Fetch();
if (!bDidRead)
{
m_at_end = true;
return numPointsRead;
}
}
pdal::Vector<double> mins;
pdal::Vector<double> maxs;
boost::int32_t bounds_length = m_statement->GetArrayLength(&(m_block->blk_extent->sdo_ordinates));
for (boost::int32_t i = 0; i < bounds_length; i = i + 2)
{
double v;
m_statement->GetElement(&(m_block->blk_extent->sdo_ordinates), i, &v);
mins.add(v);
m_statement->GetElement(&(m_block->blk_extent->sdo_ordinates), i+1, &v);
maxs.add(v);
}
pdal::Bounds<double> block_bounds(mins, maxs);
data.setSpatialBounds(block_bounds);
return numPointsRead;
}
//---------------------------------------------------------------------------
//
// SequentialIterator
//
//---------------------------------------------------------------------------
SequentialIterator::SequentialIterator(const Reader& reader)
: IteratorBase(reader)
, pdal::StageSequentialIterator(reader)
{
return;
}
SequentialIterator::~SequentialIterator()
{
return;
}
boost::uint64_t SequentialIterator::skipImpl(boost::uint64_t count)
{
// const boost::uint64_t newPos64 = getIndex() + count;
//
// // The liblas reader's seek() call only supports size_t, so we might
// // not be able to satisfy this request...
//
// if (newPos64 > std::numeric_limits<size_t>::max())
// {
// throw pdal_error("cannot support seek offsets greater than 32-bits");
// }
//
// // safe cast, since we just handled the overflow case
// size_t newPos = static_cast<size_t>(newPos64);
//
// getExternalReader().Seek(newPos);
return 0;
}
BlockPtr IteratorBase::defineBlock(Statement statement)
{
int iCol = 0;
char szFieldName[OWNAME];
int hType = 0;
int nSize = 0;
int nPrecision = 0;
signed short nScale = 0;
char szTypeName[OWNAME];
BlockPtr block = BlockPtr(new Block(m_cloud->connection));
m_cloud->connection->CreateType(&(block->blk_extent));
while( statement->GetNextField(iCol, szFieldName, &hType, &nSize, &nPrecision, &nScale, szTypeName) )
{
std::string name = boost::to_upper_copy(std::string(szFieldName));
if (boost::iequals(szFieldName, "OBJ_ID"))
{
statement->Define(&(block->obj_id));
}
if (boost::iequals(szFieldName, "BLK_ID"))
{
statement->Define(&(block->blk_id));
}
if (boost::iequals(szFieldName, "BLK_EXTENT"))
{
statement->Define(&(block->blk_extent));
}
if (boost::iequals(szFieldName, "BLK_DOMAIN"))
{
statement->Define(&(block->blk_domain));
}
if (boost::iequals(szFieldName, "PCBLK_MIN_RES"))
{
statement->Define(&(block->pcblk_min_res));
}
if (boost::iequals(szFieldName, "PCBLK_MAX_RES"))
{
statement->Define(&(block->pcblk_max_res));
}
if (boost::iequals(szFieldName, "NUM_POINTS"))
{
statement->Define(&(block->num_points));
}
if (boost::iequals(szFieldName, "NUM_UNSORTED_POINTS"))
{
statement->Define(&(block->num_unsorted_points));
}
if (boost::iequals(szFieldName, "PT_SORT_DIM"))
{
statement->Define(&(block->pt_sort_dim));
}
if (boost::iequals(szFieldName, "POINTS"))
{
statement->Define( &(block->locator) );
}
iCol++;
}
return block;
}
bool SequentialIterator::atEndImpl() const
{
return m_at_end;
// return getIndex() >= getStage().getNumPoints();
}
boost::uint32_t SequentialIterator::readBufferImpl(PointBuffer& data)
{
return myReadBuffer(data);
}
//---------------------------------------------------------------------------
//
// RandomIterator
//
//---------------------------------------------------------------------------
} } } // namespaces
<commit_msg>decruft<commit_after>/******************************************************************************
* Copyright (c) 2011, Howard Butler, [email protected]
*
* 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 Hobu, Inc. or Flaxen Geo Consulting 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 <pdal/drivers/oci/Iterator.hpp>
#include <pdal/PointBuffer.hpp>
#include <pdal/drivers/oci/Reader.hpp>
#include <pdal/Vector.hpp>
#include <boost/algorithm/string.hpp>
#include <sstream>
#include <map>
#include <algorithm>
namespace pdal { namespace drivers { namespace oci {
IteratorBase::IteratorBase(const Reader& reader)
: m_statement(Statement())
, m_at_end(false)
, m_cloud(reader.getCloud())
, m_reader(reader)
{
std::ostringstream select_blocks;
select_blocks
<< "select T.OBJ_ID, T.BLK_ID, T.BLK_EXTENT, T.NUM_POINTS, T.POINTS from "
<< m_cloud->blk_table << " T WHERE T.OBJ_ID = "
<< m_cloud->pc_id;
m_statement = Statement(m_cloud->connection->CreateStatement(select_blocks.str().c_str()));
m_statement->Execute(0);
m_block = defineBlock(m_statement);
return;
}
IteratorBase::~IteratorBase()
{
}
const Reader& IteratorBase::getReader() const
{
return m_reader;
}
void IteratorBase::read(PointBuffer& data,
boost::uint32_t howMany,
boost::uint32_t whichPoint,
boost::uint32_t whichBlobPosition)
{
boost::uint32_t nAmountRead = 0;
boost::uint32_t blob_length = m_statement->GetBlobLength(m_block->locator);
if (m_block->chunk->size() < blob_length)
{
m_block->chunk->resize(blob_length);
}
// std::cout << "blob_length: " << blob_len// gth << std::endl;
bool read_all_data = m_statement->ReadBlob( m_block->locator,
(void*)(&(*m_block->chunk)[0]),
m_block->chunk->size() ,
&nAmountRead);
if (!read_all_data) throw pdal_error("Did not read all blob data!");
// std::cout << "nAmountRead: " << nAmountRead << std::endl;
data.getSchema().getByteSize();
boost::uint32_t howMuchToRead = howMany * data.getSchema().getByteSize();
data.setDataStride(&(*m_block->chunk)[whichBlobPosition], whichPoint, howMuchToRead);
data.setNumPoints(data.getNumPoints() + howMany);
}
boost::uint32_t IteratorBase::myReadBuffer(PointBuffer& data)
{
boost::uint32_t numPointsRead = 0;
data.setNumPoints(0);
bool bDidRead = false;
// std::cout << "m_block->num_points: " << m_block->num_points << std::endl;
// std::cout << "data.getCapacity(): " << data.getCapacity() << std::endl;
if (!m_block->num_points)
{
// We still have a block of data from the last readBuffer call
// that was partially read.
// std::cout << "reading because we have no points" << std::endl;
bDidRead = m_statement->Fetch();
if (!bDidRead)
{
m_at_end = true;
return 0;
}
if (m_block->num_points > static_cast<boost::int32_t>(data.getCapacity()))
{
throw buffer_too_small("The PointBuffer is too small to contain this block.");
}
} else
{
// Our read was already "done" last readBuffer call, but if we're done,
// we're done
if (m_at_end) return 0;
bDidRead = true;
}
while (bDidRead)
{
boost::uint32_t numReadThisBlock = m_block->num_points;
boost::uint32_t numSpaceLeftThisBlock = data.getCapacity() - data.getNumPoints();
if (numReadThisBlock > numSpaceLeftThisBlock)
{
// We're done. We still have more data, but the
// user is going to have to request another buffer.
// We're not going to fill the buffer up to *exactly*
// the number of points the user requested.
// If the buffer's capacity isn't large enough to hold
// an oracle block, they're just not going to get anything
// back right now (FIXME)
break;
}
numPointsRead = numPointsRead + numReadThisBlock;
read(data, numReadThisBlock, data.getNumPoints(), 0);
bDidRead = m_statement->Fetch();
if (!bDidRead)
{
m_at_end = true;
return numPointsRead;
}
}
pdal::Vector<double> mins;
pdal::Vector<double> maxs;
boost::int32_t bounds_length = m_statement->GetArrayLength(&(m_block->blk_extent->sdo_ordinates));
for (boost::int32_t i = 0; i < bounds_length; i = i + 2)
{
double v;
m_statement->GetElement(&(m_block->blk_extent->sdo_ordinates), i, &v);
mins.add(v);
m_statement->GetElement(&(m_block->blk_extent->sdo_ordinates), i+1, &v);
maxs.add(v);
}
pdal::Bounds<double> block_bounds(mins, maxs);
data.setSpatialBounds(block_bounds);
return numPointsRead;
}
//---------------------------------------------------------------------------
//
// SequentialIterator
//
//---------------------------------------------------------------------------
SequentialIterator::SequentialIterator(const Reader& reader)
: IteratorBase(reader)
, pdal::StageSequentialIterator(reader)
{
return;
}
SequentialIterator::~SequentialIterator()
{
return;
}
boost::uint64_t SequentialIterator::skipImpl(boost::uint64_t count)
{
// const boost::uint64_t newPos64 = getIndex() + count;
//
// // The liblas reader's seek() call only supports size_t, so we might
// // not be able to satisfy this request...
//
// if (newPos64 > std::numeric_limits<size_t>::max())
// {
// throw pdal_error("cannot support seek offsets greater than 32-bits");
// }
//
// // safe cast, since we just handled the overflow case
// size_t newPos = static_cast<size_t>(newPos64);
//
// getExternalReader().Seek(newPos);
return 0;
}
BlockPtr IteratorBase::defineBlock(Statement statement)
{
int iCol = 0;
char szFieldName[OWNAME];
int hType = 0;
int nSize = 0;
int nPrecision = 0;
signed short nScale = 0;
char szTypeName[OWNAME];
BlockPtr block = BlockPtr(new Block(m_cloud->connection));
m_cloud->connection->CreateType(&(block->blk_extent));
while( statement->GetNextField(iCol, szFieldName, &hType, &nSize, &nPrecision, &nScale, szTypeName) )
{
std::string name = boost::to_upper_copy(std::string(szFieldName));
if (boost::iequals(szFieldName, "OBJ_ID"))
{
statement->Define(&(block->obj_id));
}
if (boost::iequals(szFieldName, "BLK_ID"))
{
statement->Define(&(block->blk_id));
}
if (boost::iequals(szFieldName, "BLK_EXTENT"))
{
statement->Define(&(block->blk_extent));
}
if (boost::iequals(szFieldName, "BLK_DOMAIN"))
{
statement->Define(&(block->blk_domain));
}
if (boost::iequals(szFieldName, "PCBLK_MIN_RES"))
{
statement->Define(&(block->pcblk_min_res));
}
if (boost::iequals(szFieldName, "PCBLK_MAX_RES"))
{
statement->Define(&(block->pcblk_max_res));
}
if (boost::iequals(szFieldName, "NUM_POINTS"))
{
statement->Define(&(block->num_points));
}
if (boost::iequals(szFieldName, "NUM_UNSORTED_POINTS"))
{
statement->Define(&(block->num_unsorted_points));
}
if (boost::iequals(szFieldName, "PT_SORT_DIM"))
{
statement->Define(&(block->pt_sort_dim));
}
if (boost::iequals(szFieldName, "POINTS"))
{
statement->Define( &(block->locator) );
}
iCol++;
}
return block;
}
bool SequentialIterator::atEndImpl() const
{
return m_at_end;
}
boost::uint32_t SequentialIterator::readBufferImpl(PointBuffer& data)
{
return myReadBuffer(data);
}
//---------------------------------------------------------------------------
//
// RandomIterator
//
//---------------------------------------------------------------------------
} } } // namespaces
<|endoftext|> |
<commit_before>/*
* Copyright 2011 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "GrInOrderDrawBuffer.h"
// We will use the reordering buffer, unless we have NVPR.
// TODO move NVPR to batch so we can reorder
static inline bool allow_reordering(const GrCaps* caps) {
return !caps->shaderCaps()->pathRenderingSupport();
}
GrInOrderDrawBuffer::GrInOrderDrawBuffer(GrContext* context)
: INHERITED(context)
, fCommands(GrCommandBuilder::Create(context->getGpu(), allow_reordering(context->caps())))
, fPathIndexBuffer(kPathIdxBufferMinReserve * sizeof(char)/4)
, fPathTransformBuffer(kPathXformBufferMinReserve * sizeof(float)/4)
, fPipelineBuffer(kPipelineBufferMinReserve)
, fDrawID(0) {
}
GrInOrderDrawBuffer::~GrInOrderDrawBuffer() {
this->reset();
}
void GrInOrderDrawBuffer::onDrawBatch(GrBatch* batch,
const PipelineInfo& pipelineInfo) {
State* state = this->setupPipelineAndShouldDraw(batch, pipelineInfo);
if (!state) {
return;
}
GrTargetCommands::Cmd* cmd = fCommands->recordDrawBatch(state, batch);
this->recordTraceMarkersIfNecessary(cmd);
}
void GrInOrderDrawBuffer::onStencilPath(const GrPipelineBuilder& pipelineBuilder,
const GrPathProcessor* pathProc,
const GrPath* path,
const GrScissorState& scissorState,
const GrStencilSettings& stencilSettings) {
GrTargetCommands::Cmd* cmd = fCommands->recordStencilPath(pipelineBuilder,
pathProc, path, scissorState,
stencilSettings);
this->recordTraceMarkersIfNecessary(cmd);
}
void GrInOrderDrawBuffer::onDrawPath(const GrPathProcessor* pathProc,
const GrPath* path,
const GrStencilSettings& stencilSettings,
const PipelineInfo& pipelineInfo) {
State* state = this->setupPipelineAndShouldDraw(pathProc, pipelineInfo);
if (!state) {
return;
}
GrTargetCommands::Cmd* cmd = fCommands->recordDrawPath(state, pathProc, path, stencilSettings);
this->recordTraceMarkersIfNecessary(cmd);
}
void GrInOrderDrawBuffer::onDrawPaths(const GrPathProcessor* pathProc,
const GrPathRange* pathRange,
const void* indices,
PathIndexType indexType,
const float transformValues[],
PathTransformType transformType,
int count,
const GrStencilSettings& stencilSettings,
const PipelineInfo& pipelineInfo) {
State* state = this->setupPipelineAndShouldDraw(pathProc, pipelineInfo);
if (!state) {
return;
}
GrTargetCommands::Cmd* cmd = fCommands->recordDrawPaths(state, this, pathProc, pathRange,
indices, indexType, transformValues,
transformType, count,
stencilSettings, pipelineInfo);
this->recordTraceMarkersIfNecessary(cmd);
}
void GrInOrderDrawBuffer::onClear(const SkIRect* rect, GrColor color,
bool canIgnoreRect, GrRenderTarget* renderTarget) {
GrTargetCommands::Cmd* cmd = fCommands->recordClear(rect, color, canIgnoreRect, renderTarget);
this->recordTraceMarkersIfNecessary(cmd);
}
void GrInOrderDrawBuffer::clearStencilClip(const SkIRect& rect,
bool insideClip,
GrRenderTarget* renderTarget) {
GrTargetCommands::Cmd* cmd = fCommands->recordClearStencilClip(rect, insideClip, renderTarget);
this->recordTraceMarkersIfNecessary(cmd);
}
void GrInOrderDrawBuffer::discard(GrRenderTarget* renderTarget) {
if (!this->caps()->discardRenderTargetSupport()) {
return;
}
GrTargetCommands::Cmd* cmd = fCommands->recordDiscard(renderTarget);
this->recordTraceMarkersIfNecessary(cmd);
}
void GrInOrderDrawBuffer::onReset() {
fCommands->reset();
fPathIndexBuffer.rewind();
fPathTransformBuffer.rewind();
fGpuCmdMarkers.reset();
fPrevState.reset(NULL);
// Note, fPrevState points into fPipelineBuffer's allocation, so we have to reset first.
// Furthermore, we have to reset fCommands before fPipelineBuffer too.
if (fDrawID % kPipelineBufferHighWaterMark) {
fPipelineBuffer.rewind();
} else {
fPipelineBuffer.reset();
}
}
void GrInOrderDrawBuffer::onFlush() {
fCommands->flush(this);
++fDrawID;
}
void GrInOrderDrawBuffer::onCopySurface(GrSurface* dst,
GrSurface* src,
const SkIRect& srcRect,
const SkIPoint& dstPoint) {
GrTargetCommands::Cmd* cmd = fCommands->recordCopySurface(dst, src, srcRect, dstPoint);
this->recordTraceMarkersIfNecessary(cmd);
}
void GrInOrderDrawBuffer::recordTraceMarkersIfNecessary(GrTargetCommands::Cmd* cmd) {
if (!cmd) {
return;
}
const GrTraceMarkerSet& activeTraceMarkers = this->getActiveTraceMarkers();
if (activeTraceMarkers.count() > 0) {
if (cmd->isTraced()) {
fGpuCmdMarkers[cmd->markerID()].addSet(activeTraceMarkers);
} else {
cmd->setMarkerID(fGpuCmdMarkers.count());
fGpuCmdMarkers.push_back(activeTraceMarkers);
}
}
}
GrTargetCommands::State*
GrInOrderDrawBuffer::setupPipelineAndShouldDraw(const GrPrimitiveProcessor* primProc,
const GrDrawTarget::PipelineInfo& pipelineInfo) {
State* state = this->allocState(primProc);
this->setupPipeline(pipelineInfo, state->pipelineLocation());
if (state->getPipeline()->mustSkip()) {
this->unallocState(state);
return NULL;
}
state->fPrimitiveProcessor->initBatchTracker(&state->fBatchTracker,
state->getPipeline()->getInitBatchTracker());
if (fPrevState && fPrevState->fPrimitiveProcessor.get() &&
fPrevState->fPrimitiveProcessor->canMakeEqual(fPrevState->fBatchTracker,
*state->fPrimitiveProcessor,
state->fBatchTracker) &&
fPrevState->getPipeline()->isEqual(*state->getPipeline())) {
this->unallocState(state);
} else {
fPrevState.reset(state);
}
this->recordTraceMarkersIfNecessary(
fCommands->recordXferBarrierIfNecessary(*fPrevState->getPipeline(), *this->caps()));
return fPrevState;
}
GrTargetCommands::State*
GrInOrderDrawBuffer::setupPipelineAndShouldDraw(GrBatch* batch,
const GrDrawTarget::PipelineInfo& pipelineInfo) {
State* state = this->allocState();
this->setupPipeline(pipelineInfo, state->pipelineLocation());
if (state->getPipeline()->mustSkip()) {
this->unallocState(state);
return NULL;
}
batch->initBatchTracker(state->getPipeline()->getInitBatchTracker());
if (fPrevState && !fPrevState->fPrimitiveProcessor.get() &&
fPrevState->getPipeline()->isEqual(*state->getPipeline())) {
this->unallocState(state);
} else {
fPrevState.reset(state);
}
this->recordTraceMarkersIfNecessary(
fCommands->recordXferBarrierIfNecessary(*fPrevState->getPipeline(), *this->caps()));
return fPrevState;
}
<commit_msg>fix dm crash<commit_after>/*
* Copyright 2011 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "GrInOrderDrawBuffer.h"
// We will use the reordering buffer, unless we have NVPR.
// TODO move NVPR to batch so we can reorder
static inline bool allow_reordering(const GrCaps* caps) {
return caps && caps->shaderCaps() && !caps->shaderCaps()->pathRenderingSupport();
}
GrInOrderDrawBuffer::GrInOrderDrawBuffer(GrContext* context)
: INHERITED(context)
, fCommands(GrCommandBuilder::Create(context->getGpu(), allow_reordering(context->caps())))
, fPathIndexBuffer(kPathIdxBufferMinReserve * sizeof(char)/4)
, fPathTransformBuffer(kPathXformBufferMinReserve * sizeof(float)/4)
, fPipelineBuffer(kPipelineBufferMinReserve)
, fDrawID(0) {
}
GrInOrderDrawBuffer::~GrInOrderDrawBuffer() {
this->reset();
}
void GrInOrderDrawBuffer::onDrawBatch(GrBatch* batch,
const PipelineInfo& pipelineInfo) {
State* state = this->setupPipelineAndShouldDraw(batch, pipelineInfo);
if (!state) {
return;
}
GrTargetCommands::Cmd* cmd = fCommands->recordDrawBatch(state, batch);
this->recordTraceMarkersIfNecessary(cmd);
}
void GrInOrderDrawBuffer::onStencilPath(const GrPipelineBuilder& pipelineBuilder,
const GrPathProcessor* pathProc,
const GrPath* path,
const GrScissorState& scissorState,
const GrStencilSettings& stencilSettings) {
GrTargetCommands::Cmd* cmd = fCommands->recordStencilPath(pipelineBuilder,
pathProc, path, scissorState,
stencilSettings);
this->recordTraceMarkersIfNecessary(cmd);
}
void GrInOrderDrawBuffer::onDrawPath(const GrPathProcessor* pathProc,
const GrPath* path,
const GrStencilSettings& stencilSettings,
const PipelineInfo& pipelineInfo) {
State* state = this->setupPipelineAndShouldDraw(pathProc, pipelineInfo);
if (!state) {
return;
}
GrTargetCommands::Cmd* cmd = fCommands->recordDrawPath(state, pathProc, path, stencilSettings);
this->recordTraceMarkersIfNecessary(cmd);
}
void GrInOrderDrawBuffer::onDrawPaths(const GrPathProcessor* pathProc,
const GrPathRange* pathRange,
const void* indices,
PathIndexType indexType,
const float transformValues[],
PathTransformType transformType,
int count,
const GrStencilSettings& stencilSettings,
const PipelineInfo& pipelineInfo) {
State* state = this->setupPipelineAndShouldDraw(pathProc, pipelineInfo);
if (!state) {
return;
}
GrTargetCommands::Cmd* cmd = fCommands->recordDrawPaths(state, this, pathProc, pathRange,
indices, indexType, transformValues,
transformType, count,
stencilSettings, pipelineInfo);
this->recordTraceMarkersIfNecessary(cmd);
}
void GrInOrderDrawBuffer::onClear(const SkIRect* rect, GrColor color,
bool canIgnoreRect, GrRenderTarget* renderTarget) {
GrTargetCommands::Cmd* cmd = fCommands->recordClear(rect, color, canIgnoreRect, renderTarget);
this->recordTraceMarkersIfNecessary(cmd);
}
void GrInOrderDrawBuffer::clearStencilClip(const SkIRect& rect,
bool insideClip,
GrRenderTarget* renderTarget) {
GrTargetCommands::Cmd* cmd = fCommands->recordClearStencilClip(rect, insideClip, renderTarget);
this->recordTraceMarkersIfNecessary(cmd);
}
void GrInOrderDrawBuffer::discard(GrRenderTarget* renderTarget) {
if (!this->caps()->discardRenderTargetSupport()) {
return;
}
GrTargetCommands::Cmd* cmd = fCommands->recordDiscard(renderTarget);
this->recordTraceMarkersIfNecessary(cmd);
}
void GrInOrderDrawBuffer::onReset() {
fCommands->reset();
fPathIndexBuffer.rewind();
fPathTransformBuffer.rewind();
fGpuCmdMarkers.reset();
fPrevState.reset(NULL);
// Note, fPrevState points into fPipelineBuffer's allocation, so we have to reset first.
// Furthermore, we have to reset fCommands before fPipelineBuffer too.
if (fDrawID % kPipelineBufferHighWaterMark) {
fPipelineBuffer.rewind();
} else {
fPipelineBuffer.reset();
}
}
void GrInOrderDrawBuffer::onFlush() {
fCommands->flush(this);
++fDrawID;
}
void GrInOrderDrawBuffer::onCopySurface(GrSurface* dst,
GrSurface* src,
const SkIRect& srcRect,
const SkIPoint& dstPoint) {
GrTargetCommands::Cmd* cmd = fCommands->recordCopySurface(dst, src, srcRect, dstPoint);
this->recordTraceMarkersIfNecessary(cmd);
}
void GrInOrderDrawBuffer::recordTraceMarkersIfNecessary(GrTargetCommands::Cmd* cmd) {
if (!cmd) {
return;
}
const GrTraceMarkerSet& activeTraceMarkers = this->getActiveTraceMarkers();
if (activeTraceMarkers.count() > 0) {
if (cmd->isTraced()) {
fGpuCmdMarkers[cmd->markerID()].addSet(activeTraceMarkers);
} else {
cmd->setMarkerID(fGpuCmdMarkers.count());
fGpuCmdMarkers.push_back(activeTraceMarkers);
}
}
}
GrTargetCommands::State*
GrInOrderDrawBuffer::setupPipelineAndShouldDraw(const GrPrimitiveProcessor* primProc,
const GrDrawTarget::PipelineInfo& pipelineInfo) {
State* state = this->allocState(primProc);
this->setupPipeline(pipelineInfo, state->pipelineLocation());
if (state->getPipeline()->mustSkip()) {
this->unallocState(state);
return NULL;
}
state->fPrimitiveProcessor->initBatchTracker(&state->fBatchTracker,
state->getPipeline()->getInitBatchTracker());
if (fPrevState && fPrevState->fPrimitiveProcessor.get() &&
fPrevState->fPrimitiveProcessor->canMakeEqual(fPrevState->fBatchTracker,
*state->fPrimitiveProcessor,
state->fBatchTracker) &&
fPrevState->getPipeline()->isEqual(*state->getPipeline())) {
this->unallocState(state);
} else {
fPrevState.reset(state);
}
this->recordTraceMarkersIfNecessary(
fCommands->recordXferBarrierIfNecessary(*fPrevState->getPipeline(), *this->caps()));
return fPrevState;
}
GrTargetCommands::State*
GrInOrderDrawBuffer::setupPipelineAndShouldDraw(GrBatch* batch,
const GrDrawTarget::PipelineInfo& pipelineInfo) {
State* state = this->allocState();
this->setupPipeline(pipelineInfo, state->pipelineLocation());
if (state->getPipeline()->mustSkip()) {
this->unallocState(state);
return NULL;
}
batch->initBatchTracker(state->getPipeline()->getInitBatchTracker());
if (fPrevState && !fPrevState->fPrimitiveProcessor.get() &&
fPrevState->getPipeline()->isEqual(*state->getPipeline())) {
this->unallocState(state);
} else {
fPrevState.reset(state);
}
this->recordTraceMarkersIfNecessary(
fCommands->recordXferBarrierIfNecessary(*fPrevState->getPipeline(), *this->caps()));
return fPrevState;
}
<|endoftext|> |
<commit_before>#include "dialogrender.h"
#include <math.h>
#include <QVBoxLayout>
#include <QImage>
#include <QColor>
#include <QPainter>
#include <QMessageBox>
#include <QFileDialog>
#include <QMessageBox>
#include <QListWidget>
#include <QPushButton>
#include "tools.h"
#include "rendering/scenery.h"
#include "rendering/auto.h"
static DialogRender* _current_dialog;
static void _renderStart(int width, int height, Color background)
{
_current_dialog->pixbuf_lock->lock();
delete _current_dialog->pixbuf;
_current_dialog->pixbuf = new QImage(width, height, QImage::Format_ARGB32);
_current_dialog->pixbuf->fill(colorToQColor(background).rgb());
_current_dialog->pixbuf_lock->unlock();
_current_dialog->tellRenderSize(width, height);
}
static void _renderDraw(int x, int y, Color col)
{
_current_dialog->pixbuf->setPixel(x, _current_dialog->pixbuf->height() - 1 - y, colorToQColor(col).rgb());
}
static void _renderUpdate(double progress)
{
_current_dialog->area->update();
_current_dialog->tellProgressChange(progress);
}
class RenderThread:public QThread
{
public:
RenderThread(DialogRender* dialog, Renderer* renderer, RenderParams params):QThread()
{
_dialog = dialog;
_renderer = renderer;
_params = params;
}
void run()
{
rendererStart(_renderer, _params);
_dialog->tellRenderEnded();
}
private:
DialogRender* _dialog;
Renderer* _renderer;
RenderParams _params;
};
class RenderArea:public QWidget
{
public:
RenderArea(QWidget* parent):
QWidget(parent)
{
setMinimumSize(800, 600);
}
void paintEvent(QPaintEvent*)
{
QPainter painter(this);
_current_dialog->pixbuf_lock->lock();
painter.drawImage(0, 0, *_current_dialog->pixbuf);
_current_dialog->pixbuf_lock->unlock();
}
};
DialogRender::DialogRender(QWidget *parent, Renderer* renderer):
QDialog(parent, Qt::WindowTitleHint | Qt::WindowMaximizeButtonHint | Qt::WindowMinimizeButtonHint | Qt::WindowCloseButtonHint)
{
pixbuf_lock = new QMutex();
pixbuf = new QImage(1, 1, QImage::Format_ARGB32);
_current_dialog = this;
_render_thread = NULL;
_renderer = renderer;
setModal(true);
setWindowTitle(tr("Paysages 3D - Render"));
setLayout(new QVBoxLayout());
_scroll = new QScrollArea(this);
_scroll->setAlignment(Qt::AlignCenter);
area = new RenderArea(_scroll);
_scroll->setWidget(area);
layout()->addWidget(_scroll);
// Status bar
_info = new QWidget(this);
_info->setLayout(new QHBoxLayout());
layout()->addWidget(_info);
_timer = new QLabel(QString("0:00.00"), _info);
_info->layout()->addWidget(_timer);
_progress = new QProgressBar(_info);
_progress->setMaximumHeight(12);
_progress->setMinimum(0);
_progress->setMaximum(1000);
_progress->setValue(0);
_info->layout()->addWidget(_progress);
// Action bar
_actions = new QWidget(this);
_actions->setLayout(new QHBoxLayout());
layout()->addWidget(_actions);
_actions->layout()->addWidget(new QLabel(tr("Tone-mapping: "), _actions));
_tonemapping_control = new QComboBox(_actions);
_tonemapping_control->addItems(QStringList(tr("Uncharted")) << tr("Reinhard"));
_actions->layout()->addWidget(_tonemapping_control);
_actions->layout()->addWidget(new QLabel(tr("Exposure: "), _actions));
_actions->hide();
_exposure_control = new QSlider(Qt::Horizontal, _actions);
_exposure_control->setMinimumWidth(200);
_exposure_control->setRange(0, 1000);
_exposure_control->setValue(200);
_actions->layout()->addWidget(_exposure_control);
_save_button = new QPushButton(QIcon(getDataPath("images/save.png")), tr("Save picture"), _actions);
_actions->layout()->addWidget(_save_button);
// Connections
//connect(this, SIGNAL(renderSizeChanged(int, int)), this, SLOT(applyRenderSize(int, int)));
connect(this, SIGNAL(progressChanged(double)), this, SLOT(applyProgress(double)));
connect(this, SIGNAL(renderEnded()), this, SLOT(applyRenderEnded()));
connect(_save_button, SIGNAL(clicked()), this, SLOT(saveRender()));
connect(_tonemapping_control, SIGNAL(currentIndexChanged(int)), this, SLOT(toneMappingChanged()));
connect(_exposure_control, SIGNAL(valueChanged(int)), this, SLOT(toneMappingChanged()));
}
DialogRender::~DialogRender()
{
if (_render_thread)
{
rendererInterrupt(_renderer);
_render_thread->wait();
delete _render_thread;
}
delete pixbuf;
delete pixbuf_lock;
}
void DialogRender::tellRenderSize(int width, int height)
{
emit renderSizeChanged(width, height);
}
void DialogRender::tellProgressChange(double value)
{
emit progressChanged(value);
}
void DialogRender::tellRenderEnded()
{
emit renderEnded();
}
void DialogRender::startRender(RenderParams params)
{
_started = time(NULL);
applyRenderSize(params.width, params.height);
rendererSetPreviewCallbacks(_renderer, _renderStart, _renderDraw, _renderUpdate);
_render_thread = new RenderThread(this, _renderer, params);
_render_thread->start();
exec();
}
void DialogRender::applyRenderEnded()
{
_info->hide();
_actions->show();
}
void DialogRender::saveRender()
{
QString filepath;
filepath = QFileDialog::getSaveFileName(this, tr("Paysages 3D - Choose a filename to save the last render"), QString(), tr("Images (*.png *.jpg)"));
if (!filepath.isNull())
{
if (!filepath.toLower().endsWith(".jpg") && !filepath.toLower().endsWith(".jpeg") && !filepath.toLower().endsWith(".png"))
{
filepath = filepath.append(".png");
}
if (renderSaveToFile(_renderer->render_area, (char*)filepath.toStdString().c_str()))
{
QMessageBox::information(this, "Message", QString(tr("The picture %1 has been saved.")).arg(filepath));
}
else
{
QMessageBox::critical(this, "Message", QString(tr("Can't write to file : %1")).arg(filepath));
}
}
}
void DialogRender::toneMappingChanged()
{
renderSetToneMapping(_renderer->render_area, (ToneMappingOperator)_tonemapping_control->currentIndex(), ((double)_exposure_control->value()) * 0.01);
}
void DialogRender::loadLastRender()
{
applyRenderSize(_renderer->render_width, _renderer->render_height);
rendererSetPreviewCallbacks(_renderer, _renderStart, _renderDraw, _renderUpdate);
renderEnded();
toneMappingChanged();
exec();
}
void DialogRender::applyRenderSize(int width, int height)
{
area->setMinimumSize(width, height);
area->setMaximumSize(width, height);
area->resize(width, height);
_scroll->setMinimumSize(width > 800 ? 820 : width + 20, height > 600 ? 620 : height + 20);
}
void DialogRender::applyProgress(double value)
{
double diff = difftime(time(NULL), _started);
int hours = (int)floor(diff / 3600.0);
int minutes = (int)floor((diff - 3600.0 * hours) / 60.0);
int seconds = (int)floor(diff - 3600.0 * hours - 60.0 * minutes);
_timer->setText(tr("%1:%2.%3").arg(hours).arg(minutes, 2, 10, QLatin1Char('0')).arg(seconds, 2, 10, QLatin1Char('0')));
_progress->setValue((int)(value * 1000.0));
_progress->update();
}
<commit_msg>Partially fixed black widget after render.<commit_after>#include "dialogrender.h"
#include <math.h>
#include <QVBoxLayout>
#include <QImage>
#include <QColor>
#include <QPainter>
#include <QMessageBox>
#include <QFileDialog>
#include <QMessageBox>
#include <QListWidget>
#include <QPushButton>
#include "tools.h"
#include "rendering/scenery.h"
#include "rendering/auto.h"
static DialogRender* _current_dialog;
static void _renderStart(int width, int height, Color background)
{
_current_dialog->pixbuf_lock->lock();
delete _current_dialog->pixbuf;
_current_dialog->pixbuf = new QImage(width, height, QImage::Format_ARGB32);
_current_dialog->pixbuf->fill(colorToQColor(background).rgb());
_current_dialog->pixbuf_lock->unlock();
_current_dialog->tellRenderSize(width, height);
}
static void _renderDraw(int x, int y, Color col)
{
_current_dialog->pixbuf->setPixel(x, _current_dialog->pixbuf->height() - 1 - y, colorToQColor(col).rgb());
}
static void _renderUpdate(double progress)
{
_current_dialog->area->update();
_current_dialog->tellProgressChange(progress);
}
class RenderThread:public QThread
{
public:
RenderThread(DialogRender* dialog, Renderer* renderer, RenderParams params):QThread()
{
_dialog = dialog;
_renderer = renderer;
_params = params;
}
void run()
{
rendererStart(_renderer, _params);
_dialog->tellRenderEnded();
}
private:
DialogRender* _dialog;
Renderer* _renderer;
RenderParams _params;
};
class RenderArea:public QWidget
{
public:
RenderArea(QWidget* parent):
QWidget(parent)
{
setMinimumSize(800, 600);
}
void paintEvent(QPaintEvent*)
{
QPainter painter(this);
_current_dialog->pixbuf_lock->lock();
painter.drawImage(0, 0, *_current_dialog->pixbuf);
_current_dialog->pixbuf_lock->unlock();
}
};
DialogRender::DialogRender(QWidget *parent, Renderer* renderer):
QDialog(parent, Qt::WindowTitleHint | Qt::WindowMaximizeButtonHint | Qt::WindowMinimizeButtonHint | Qt::WindowCloseButtonHint)
{
pixbuf_lock = new QMutex();
pixbuf = new QImage(1, 1, QImage::Format_ARGB32);
_current_dialog = this;
_render_thread = NULL;
_renderer = renderer;
setModal(true);
setWindowTitle(tr("Paysages 3D - Render"));
setLayout(new QVBoxLayout());
_scroll = new QScrollArea(this);
_scroll->setAlignment(Qt::AlignCenter);
area = new RenderArea(_scroll);
_scroll->setWidget(area);
layout()->addWidget(_scroll);
// Status bar
_info = new QWidget(this);
_info->setLayout(new QHBoxLayout());
layout()->addWidget(_info);
_timer = new QLabel(QString("0:00.00"), _info);
_info->layout()->addWidget(_timer);
_progress = new QProgressBar(_info);
_progress->setMaximumHeight(12);
_progress->setMinimum(0);
_progress->setMaximum(1000);
_progress->setValue(0);
_info->layout()->addWidget(_progress);
// Action bar
_actions = new QWidget(this);
_actions->setLayout(new QHBoxLayout());
layout()->addWidget(_actions);
_actions->layout()->addWidget(new QLabel(tr("Tone-mapping: "), _actions));
_tonemapping_control = new QComboBox(_actions);
_tonemapping_control->addItems(QStringList(tr("Uncharted")) << tr("Reinhard"));
_actions->layout()->addWidget(_tonemapping_control);
_actions->layout()->addWidget(new QLabel(tr("Exposure: "), _actions));
_actions->hide();
_exposure_control = new QSlider(Qt::Horizontal, _actions);
_exposure_control->setMinimumWidth(200);
_exposure_control->setRange(0, 1000);
_exposure_control->setValue(200);
_actions->layout()->addWidget(_exposure_control);
_save_button = new QPushButton(QIcon(getDataPath("images/save.png")), tr("Save picture"), _actions);
_actions->layout()->addWidget(_save_button);
// Connections
//connect(this, SIGNAL(renderSizeChanged(int, int)), this, SLOT(applyRenderSize(int, int)));
connect(this, SIGNAL(progressChanged(double)), this, SLOT(applyProgress(double)));
connect(this, SIGNAL(renderEnded()), this, SLOT(applyRenderEnded()));
connect(_save_button, SIGNAL(clicked()), this, SLOT(saveRender()));
connect(_tonemapping_control, SIGNAL(currentIndexChanged(int)), this, SLOT(toneMappingChanged()));
connect(_exposure_control, SIGNAL(valueChanged(int)), this, SLOT(toneMappingChanged()));
}
DialogRender::~DialogRender()
{
if (_render_thread)
{
rendererInterrupt(_renderer);
_render_thread->wait();
delete _render_thread;
}
delete pixbuf;
delete pixbuf_lock;
}
void DialogRender::tellRenderSize(int width, int height)
{
emit renderSizeChanged(width, height);
}
void DialogRender::tellProgressChange(double value)
{
emit progressChanged(value);
}
void DialogRender::tellRenderEnded()
{
emit renderEnded();
}
void DialogRender::startRender(RenderParams params)
{
_started = time(NULL);
applyRenderSize(params.width, params.height);
rendererSetPreviewCallbacks(_renderer, _renderStart, _renderDraw, _renderUpdate);
_render_thread = new RenderThread(this, _renderer, params);
_render_thread->start();
exec();
}
void DialogRender::applyRenderEnded()
{
_info->hide();
_actions->show();
area->update();
}
void DialogRender::saveRender()
{
QString filepath;
filepath = QFileDialog::getSaveFileName(this, tr("Paysages 3D - Choose a filename to save the last render"), QString(), tr("Images (*.png *.jpg)"));
if (!filepath.isNull())
{
if (!filepath.toLower().endsWith(".jpg") && !filepath.toLower().endsWith(".jpeg") && !filepath.toLower().endsWith(".png"))
{
filepath = filepath.append(".png");
}
if (renderSaveToFile(_renderer->render_area, (char*)filepath.toStdString().c_str()))
{
QMessageBox::information(this, "Message", QString(tr("The picture %1 has been saved.")).arg(filepath));
}
else
{
QMessageBox::critical(this, "Message", QString(tr("Can't write to file : %1")).arg(filepath));
}
}
}
void DialogRender::toneMappingChanged()
{
renderSetToneMapping(_renderer->render_area, (ToneMappingOperator)_tonemapping_control->currentIndex(), ((double)_exposure_control->value()) * 0.01);
}
void DialogRender::loadLastRender()
{
applyRenderSize(_renderer->render_width, _renderer->render_height);
rendererSetPreviewCallbacks(_renderer, _renderStart, _renderDraw, _renderUpdate);
renderEnded();
toneMappingChanged();
exec();
}
void DialogRender::applyRenderSize(int width, int height)
{
area->setMinimumSize(width, height);
area->setMaximumSize(width, height);
area->resize(width, height);
_scroll->setMinimumSize(width > 800 ? 820 : width + 20, height > 600 ? 620 : height + 20);
}
void DialogRender::applyProgress(double value)
{
double diff = difftime(time(NULL), _started);
int hours = (int)floor(diff / 3600.0);
int minutes = (int)floor((diff - 3600.0 * hours) / 60.0);
int seconds = (int)floor(diff - 3600.0 * hours - 60.0 * minutes);
_timer->setText(tr("%1:%2.%3").arg(hours).arg(minutes, 2, 10, QLatin1Char('0')).arg(seconds, 2, 10, QLatin1Char('0')));
_progress->setValue((int)(value * 1000.0));
_progress->update();
}
<|endoftext|> |
<commit_before>//=- llvm/CodeGen/DFAPacketizer.cpp - DFA Packetizer for VLIW -*- C++ -*-=====//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
// This class implements a deterministic finite automaton (DFA) based
// packetizing mechanism for VLIW architectures. It provides APIs to
// determine whether there exists a legal mapping of instructions to
// functional unit assignments in a packet. The DFA is auto-generated from
// the target's Schedule.td file.
//
// A DFA consists of 3 major elements: states, inputs, and transitions. For
// the packetizing mechanism, the input is the set of instruction classes for
// a target. The state models all possible combinations of functional unit
// consumption for a given set of instructions in a packet. A transition
// models the addition of an instruction to a packet. In the DFA constructed
// by this class, if an instruction can be added to a packet, then a valid
// transition exists from the corresponding state. Invalid transitions
// indicate that the instruction cannot be added to the current packet.
//
//===----------------------------------------------------------------------===//
#define DEBUG_TYPE "packets"
#include "llvm/CodeGen/DFAPacketizer.h"
#include "llvm/CodeGen/MachineInstr.h"
#include "llvm/CodeGen/MachineInstrBundle.h"
#include "llvm/CodeGen/ScheduleDAGInstrs.h"
#include "llvm/MC/MCInstrItineraries.h"
#include "llvm/Target/TargetInstrInfo.h"
using namespace llvm;
// --------------------------------------------------------------------
// Definitions shared between DFAPacketizer.cpp and DFAPacketizerEmitter.cpp
namespace {
DFAInput addDFAFuncUnits(DFAInput Inp, unsigned FuncUnits) {
return (Inp << DFA_MAX_RESOURCES) | FuncUnits;
}
/// Return the DFAInput for an instruction class input vector.
/// This function is used in both DFAPacketizer.cpp and in
/// DFAPacketizerEmitter.cpp.
DFAInput getDFAInsnInput(const std::vector<unsigned> &InsnClass) {
DFAInput InsnInput = 0;
assert((InsnClass.size() <= DFA_MAX_RESTERMS) &&
"Exceeded maximum number of DFA terms");
for (auto U : InsnClass)
InsnInput = addDFAFuncUnits(InsnInput, U);
return InsnInput;
}
}
// --------------------------------------------------------------------
DFAPacketizer::DFAPacketizer(const InstrItineraryData *I,
const DFAStateInput (*SIT)[2],
const unsigned *SET):
InstrItins(I), CurrentState(0), DFAStateInputTable(SIT),
DFAStateEntryTable(SET) {
// Make sure DFA types are large enough for the number of terms & resources.
static_assert((DFA_MAX_RESTERMS * DFA_MAX_RESOURCES) <=
(8 * sizeof(DFAInput)),
"(DFA_MAX_RESTERMS * DFA_MAX_RESOURCES) too big for DFAInput");
static_assert(
(DFA_MAX_RESTERMS * DFA_MAX_RESOURCES) <= (8 * sizeof(DFAStateInput)),
"(DFA_MAX_RESTERMS * DFA_MAX_RESOURCES) too big for DFAStateInput");
}
// Read the DFA transition table and update CachedTable.
//
// Format of the transition tables:
// DFAStateInputTable[][2] = pairs of <Input, Transition> for all valid
// transitions
// DFAStateEntryTable[i] = Index of the first entry in DFAStateInputTable
// for the ith state
//
void DFAPacketizer::ReadTable(unsigned int state) {
unsigned ThisState = DFAStateEntryTable[state];
unsigned NextStateInTable = DFAStateEntryTable[state+1];
// Early exit in case CachedTable has already contains this
// state's transitions.
if (CachedTable.count(UnsignPair(state, DFAStateInputTable[ThisState][0])))
return;
for (unsigned i = ThisState; i < NextStateInTable; i++)
CachedTable[UnsignPair(state, DFAStateInputTable[i][0])] =
DFAStateInputTable[i][1];
}
// Return the DFAInput for an instruction class.
DFAInput DFAPacketizer::getInsnInput(unsigned InsnClass) {
// Note: this logic must match that in DFAPacketizerDefs.h for input vectors.
DFAInput InsnInput = 0;
unsigned i = 0;
(void)i;
for (const InstrStage *IS = InstrItins->beginStage(InsnClass),
*IE = InstrItins->endStage(InsnClass); IS != IE; ++IS) {
InsnInput = addDFAFuncUnits(InsnInput, IS->getUnits());
assert((i++ < DFA_MAX_RESTERMS) && "Exceeded maximum number of DFA inputs");
}
return InsnInput;
}
// Return the DFAInput for an instruction class input vector.
DFAInput DFAPacketizer::getInsnInput(const std::vector<unsigned> &InsnClass) {
return getDFAInsnInput(InsnClass);
}
// Check if the resources occupied by a MCInstrDesc are available in the
// current state.
bool DFAPacketizer::canReserveResources(const llvm::MCInstrDesc *MID) {
unsigned InsnClass = MID->getSchedClass();
DFAInput InsnInput = getInsnInput(InsnClass);
UnsignPair StateTrans = UnsignPair(CurrentState, InsnInput);
ReadTable(CurrentState);
return CachedTable.count(StateTrans) != 0;
}
// Reserve the resources occupied by a MCInstrDesc and change the current
// state to reflect that change.
void DFAPacketizer::reserveResources(const llvm::MCInstrDesc *MID) {
unsigned InsnClass = MID->getSchedClass();
DFAInput InsnInput = getInsnInput(InsnClass);
UnsignPair StateTrans = UnsignPair(CurrentState, InsnInput);
ReadTable(CurrentState);
assert(CachedTable.count(StateTrans) != 0);
CurrentState = CachedTable[StateTrans];
}
// Check if the resources occupied by a machine instruction are available
// in the current state.
bool DFAPacketizer::canReserveResources(llvm::MachineInstr &MI) {
const llvm::MCInstrDesc &MID = MI.getDesc();
return canReserveResources(&MID);
}
// Reserve the resources occupied by a machine instruction and change the
// current state to reflect that change.
void DFAPacketizer::reserveResources(llvm::MachineInstr &MI) {
const llvm::MCInstrDesc &MID = MI.getDesc();
reserveResources(&MID);
}
namespace llvm {
// This class extends ScheduleDAGInstrs and overrides the schedule method
// to build the dependence graph.
class DefaultVLIWScheduler : public ScheduleDAGInstrs {
private:
AliasAnalysis *AA;
/// Ordered list of DAG postprocessing steps.
std::vector<std::unique_ptr<ScheduleDAGMutation>> Mutations;
public:
DefaultVLIWScheduler(MachineFunction &MF, MachineLoopInfo &MLI,
AliasAnalysis *AA);
// Actual scheduling work.
void schedule() override;
/// DefaultVLIWScheduler takes ownership of the Mutation object.
void addMutation(std::unique_ptr<ScheduleDAGMutation> Mutation) {
Mutations.push_back(std::move(Mutation));
}
protected:
void postprocessDAG();
};
}
DefaultVLIWScheduler::DefaultVLIWScheduler(MachineFunction &MF,
MachineLoopInfo &MLI,
AliasAnalysis *AA)
: ScheduleDAGInstrs(MF, &MLI), AA(AA) {
CanHandleTerminators = true;
}
/// Apply each ScheduleDAGMutation step in order.
void DefaultVLIWScheduler::postprocessDAG() {
for (auto &M : Mutations)
M->apply(this);
}
void DefaultVLIWScheduler::schedule() {
// Build the scheduling graph.
buildSchedGraph(AA);
postprocessDAG();
}
VLIWPacketizerList::VLIWPacketizerList(MachineFunction &mf,
MachineLoopInfo &mli, AliasAnalysis *aa)
: MF(mf), TII(mf.getSubtarget().getInstrInfo()), AA(aa) {
ResourceTracker = TII->CreateTargetScheduleState(MF.getSubtarget());
VLIWScheduler = new DefaultVLIWScheduler(MF, mli, AA);
}
VLIWPacketizerList::~VLIWPacketizerList() {
if (VLIWScheduler)
delete VLIWScheduler;
if (ResourceTracker)
delete ResourceTracker;
}
// End the current packet, bundle packet instructions and reset DFA state.
void VLIWPacketizerList::endPacket(MachineBasicBlock *MBB,
MachineBasicBlock::iterator MI) {
if (CurrentPacketMIs.size() > 1) {
MachineInstr &MIFirst = *CurrentPacketMIs.front();
finalizeBundle(*MBB, MIFirst.getIterator(), MI.getInstrIterator());
}
CurrentPacketMIs.clear();
ResourceTracker->clearResources();
DEBUG(dbgs() << "End packet\n");
}
// Bundle machine instructions into packets.
void VLIWPacketizerList::PacketizeMIs(MachineBasicBlock *MBB,
MachineBasicBlock::iterator BeginItr,
MachineBasicBlock::iterator EndItr) {
assert(VLIWScheduler && "VLIW Scheduler is not initialized!");
VLIWScheduler->startBlock(MBB);
VLIWScheduler->enterRegion(MBB, BeginItr, EndItr,
std::distance(BeginItr, EndItr));
VLIWScheduler->schedule();
DEBUG({
dbgs() << "Scheduling DAG of the packetize region\n";
for (SUnit &SU : VLIWScheduler->SUnits)
SU.dumpAll(VLIWScheduler);
});
// Generate MI -> SU map.
MIToSUnit.clear();
for (SUnit &SU : VLIWScheduler->SUnits)
MIToSUnit[SU.getInstr()] = &SU;
// The main packetizer loop.
for (; BeginItr != EndItr; ++BeginItr) {
MachineInstr &MI = *BeginItr;
initPacketizerState();
// End the current packet if needed.
if (isSoloInstruction(MI)) {
endPacket(MBB, MI);
continue;
}
// Ignore pseudo instructions.
if (ignorePseudoInstruction(MI, MBB))
continue;
SUnit *SUI = MIToSUnit[&MI];
assert(SUI && "Missing SUnit Info!");
// Ask DFA if machine resource is available for MI.
DEBUG(dbgs() << "Checking resources for adding MI to packet " << MI);
bool ResourceAvail = ResourceTracker->canReserveResources(MI);
DEBUG({
if (ResourceAvail)
dbgs() << " Resources are available for adding MI to packet\n";
else
dbgs() << " Resources NOT available\n";
});
if (ResourceAvail && shouldAddToPacket(MI)) {
// Dependency check for MI with instructions in CurrentPacketMIs.
for (auto MJ : CurrentPacketMIs) {
SUnit *SUJ = MIToSUnit[MJ];
assert(SUJ && "Missing SUnit Info!");
DEBUG(dbgs() << " Checking against MJ " << *MJ);
// Is it legal to packetize SUI and SUJ together.
if (!isLegalToPacketizeTogether(SUI, SUJ)) {
DEBUG(dbgs() << " Not legal to add MI, try to prune\n");
// Allow packetization if dependency can be pruned.
if (!isLegalToPruneDependencies(SUI, SUJ)) {
// End the packet if dependency cannot be pruned.
DEBUG(dbgs() << " Could not prune dependencies for adding MI\n");
endPacket(MBB, MI);
break;
}
DEBUG(dbgs() << " Pruned dependence for adding MI\n");
}
}
} else {
DEBUG(if (ResourceAvail)
dbgs() << "Resources are available, but instruction should not be "
"added to packet\n " << MI);
// End the packet if resource is not available, or if the instruction
// shoud not be added to the current packet.
endPacket(MBB, MI);
}
// Add MI to the current packet.
DEBUG(dbgs() << "* Adding MI to packet " << MI << '\n');
BeginItr = addToPacket(MI);
} // For all instructions in the packetization range.
// End any packet left behind.
endPacket(MBB, EndItr);
VLIWScheduler->exitRegion();
VLIWScheduler->finishBlock();
}
// Add a DAG mutation object to the ordered list.
void VLIWPacketizerList::addMutation(
std::unique_ptr<ScheduleDAGMutation> Mutation) {
VLIWScheduler->addMutation(std::move(Mutation));
}
<commit_msg>[Packetizer] Add debugging code to stop packetization after N instructions<commit_after>//=- llvm/CodeGen/DFAPacketizer.cpp - DFA Packetizer for VLIW -*- C++ -*-=====//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
// This class implements a deterministic finite automaton (DFA) based
// packetizing mechanism for VLIW architectures. It provides APIs to
// determine whether there exists a legal mapping of instructions to
// functional unit assignments in a packet. The DFA is auto-generated from
// the target's Schedule.td file.
//
// A DFA consists of 3 major elements: states, inputs, and transitions. For
// the packetizing mechanism, the input is the set of instruction classes for
// a target. The state models all possible combinations of functional unit
// consumption for a given set of instructions in a packet. A transition
// models the addition of an instruction to a packet. In the DFA constructed
// by this class, if an instruction can be added to a packet, then a valid
// transition exists from the corresponding state. Invalid transitions
// indicate that the instruction cannot be added to the current packet.
//
//===----------------------------------------------------------------------===//
#define DEBUG_TYPE "packets"
#include "llvm/CodeGen/DFAPacketizer.h"
#include "llvm/CodeGen/MachineInstr.h"
#include "llvm/CodeGen/MachineInstrBundle.h"
#include "llvm/CodeGen/ScheduleDAGInstrs.h"
#include "llvm/MC/MCInstrItineraries.h"
#include "llvm/Target/TargetInstrInfo.h"
#include "llvm/Support/CommandLine.h"
using namespace llvm;
static cl::opt<unsigned> InstrLimit("dfa-instr-limit", cl::Hidden,
cl::init(0), cl::desc("If present, stops packetizing after N instructions"));
static unsigned InstrCount = 0;
// --------------------------------------------------------------------
// Definitions shared between DFAPacketizer.cpp and DFAPacketizerEmitter.cpp
namespace {
DFAInput addDFAFuncUnits(DFAInput Inp, unsigned FuncUnits) {
return (Inp << DFA_MAX_RESOURCES) | FuncUnits;
}
/// Return the DFAInput for an instruction class input vector.
/// This function is used in both DFAPacketizer.cpp and in
/// DFAPacketizerEmitter.cpp.
DFAInput getDFAInsnInput(const std::vector<unsigned> &InsnClass) {
DFAInput InsnInput = 0;
assert((InsnClass.size() <= DFA_MAX_RESTERMS) &&
"Exceeded maximum number of DFA terms");
for (auto U : InsnClass)
InsnInput = addDFAFuncUnits(InsnInput, U);
return InsnInput;
}
}
// --------------------------------------------------------------------
DFAPacketizer::DFAPacketizer(const InstrItineraryData *I,
const DFAStateInput (*SIT)[2],
const unsigned *SET):
InstrItins(I), CurrentState(0), DFAStateInputTable(SIT),
DFAStateEntryTable(SET) {
// Make sure DFA types are large enough for the number of terms & resources.
static_assert((DFA_MAX_RESTERMS * DFA_MAX_RESOURCES) <=
(8 * sizeof(DFAInput)),
"(DFA_MAX_RESTERMS * DFA_MAX_RESOURCES) too big for DFAInput");
static_assert(
(DFA_MAX_RESTERMS * DFA_MAX_RESOURCES) <= (8 * sizeof(DFAStateInput)),
"(DFA_MAX_RESTERMS * DFA_MAX_RESOURCES) too big for DFAStateInput");
}
// Read the DFA transition table and update CachedTable.
//
// Format of the transition tables:
// DFAStateInputTable[][2] = pairs of <Input, Transition> for all valid
// transitions
// DFAStateEntryTable[i] = Index of the first entry in DFAStateInputTable
// for the ith state
//
void DFAPacketizer::ReadTable(unsigned int state) {
unsigned ThisState = DFAStateEntryTable[state];
unsigned NextStateInTable = DFAStateEntryTable[state+1];
// Early exit in case CachedTable has already contains this
// state's transitions.
if (CachedTable.count(UnsignPair(state, DFAStateInputTable[ThisState][0])))
return;
for (unsigned i = ThisState; i < NextStateInTable; i++)
CachedTable[UnsignPair(state, DFAStateInputTable[i][0])] =
DFAStateInputTable[i][1];
}
// Return the DFAInput for an instruction class.
DFAInput DFAPacketizer::getInsnInput(unsigned InsnClass) {
// Note: this logic must match that in DFAPacketizerDefs.h for input vectors.
DFAInput InsnInput = 0;
unsigned i = 0;
(void)i;
for (const InstrStage *IS = InstrItins->beginStage(InsnClass),
*IE = InstrItins->endStage(InsnClass); IS != IE; ++IS) {
InsnInput = addDFAFuncUnits(InsnInput, IS->getUnits());
assert((i++ < DFA_MAX_RESTERMS) && "Exceeded maximum number of DFA inputs");
}
return InsnInput;
}
// Return the DFAInput for an instruction class input vector.
DFAInput DFAPacketizer::getInsnInput(const std::vector<unsigned> &InsnClass) {
return getDFAInsnInput(InsnClass);
}
// Check if the resources occupied by a MCInstrDesc are available in the
// current state.
bool DFAPacketizer::canReserveResources(const llvm::MCInstrDesc *MID) {
unsigned InsnClass = MID->getSchedClass();
DFAInput InsnInput = getInsnInput(InsnClass);
UnsignPair StateTrans = UnsignPair(CurrentState, InsnInput);
ReadTable(CurrentState);
return CachedTable.count(StateTrans) != 0;
}
// Reserve the resources occupied by a MCInstrDesc and change the current
// state to reflect that change.
void DFAPacketizer::reserveResources(const llvm::MCInstrDesc *MID) {
unsigned InsnClass = MID->getSchedClass();
DFAInput InsnInput = getInsnInput(InsnClass);
UnsignPair StateTrans = UnsignPair(CurrentState, InsnInput);
ReadTable(CurrentState);
assert(CachedTable.count(StateTrans) != 0);
CurrentState = CachedTable[StateTrans];
}
// Check if the resources occupied by a machine instruction are available
// in the current state.
bool DFAPacketizer::canReserveResources(llvm::MachineInstr &MI) {
const llvm::MCInstrDesc &MID = MI.getDesc();
return canReserveResources(&MID);
}
// Reserve the resources occupied by a machine instruction and change the
// current state to reflect that change.
void DFAPacketizer::reserveResources(llvm::MachineInstr &MI) {
const llvm::MCInstrDesc &MID = MI.getDesc();
reserveResources(&MID);
}
namespace llvm {
// This class extends ScheduleDAGInstrs and overrides the schedule method
// to build the dependence graph.
class DefaultVLIWScheduler : public ScheduleDAGInstrs {
private:
AliasAnalysis *AA;
/// Ordered list of DAG postprocessing steps.
std::vector<std::unique_ptr<ScheduleDAGMutation>> Mutations;
public:
DefaultVLIWScheduler(MachineFunction &MF, MachineLoopInfo &MLI,
AliasAnalysis *AA);
// Actual scheduling work.
void schedule() override;
/// DefaultVLIWScheduler takes ownership of the Mutation object.
void addMutation(std::unique_ptr<ScheduleDAGMutation> Mutation) {
Mutations.push_back(std::move(Mutation));
}
protected:
void postprocessDAG();
};
}
DefaultVLIWScheduler::DefaultVLIWScheduler(MachineFunction &MF,
MachineLoopInfo &MLI,
AliasAnalysis *AA)
: ScheduleDAGInstrs(MF, &MLI), AA(AA) {
CanHandleTerminators = true;
}
/// Apply each ScheduleDAGMutation step in order.
void DefaultVLIWScheduler::postprocessDAG() {
for (auto &M : Mutations)
M->apply(this);
}
void DefaultVLIWScheduler::schedule() {
// Build the scheduling graph.
buildSchedGraph(AA);
postprocessDAG();
}
VLIWPacketizerList::VLIWPacketizerList(MachineFunction &mf,
MachineLoopInfo &mli, AliasAnalysis *aa)
: MF(mf), TII(mf.getSubtarget().getInstrInfo()), AA(aa) {
ResourceTracker = TII->CreateTargetScheduleState(MF.getSubtarget());
VLIWScheduler = new DefaultVLIWScheduler(MF, mli, AA);
}
VLIWPacketizerList::~VLIWPacketizerList() {
if (VLIWScheduler)
delete VLIWScheduler;
if (ResourceTracker)
delete ResourceTracker;
}
// End the current packet, bundle packet instructions and reset DFA state.
void VLIWPacketizerList::endPacket(MachineBasicBlock *MBB,
MachineBasicBlock::iterator MI) {
DEBUG({
if (!CurrentPacketMIs.empty()) {
dbgs() << "Finalizing packet:\n";
for (MachineInstr *MI : CurrentPacketMIs)
dbgs() << " * " << *MI;
}
});
if (CurrentPacketMIs.size() > 1) {
MachineInstr &MIFirst = *CurrentPacketMIs.front();
finalizeBundle(*MBB, MIFirst.getIterator(), MI.getInstrIterator());
}
CurrentPacketMIs.clear();
ResourceTracker->clearResources();
DEBUG(dbgs() << "End packet\n");
}
// Bundle machine instructions into packets.
void VLIWPacketizerList::PacketizeMIs(MachineBasicBlock *MBB,
MachineBasicBlock::iterator BeginItr,
MachineBasicBlock::iterator EndItr) {
assert(VLIWScheduler && "VLIW Scheduler is not initialized!");
VLIWScheduler->startBlock(MBB);
VLIWScheduler->enterRegion(MBB, BeginItr, EndItr,
std::distance(BeginItr, EndItr));
VLIWScheduler->schedule();
DEBUG({
dbgs() << "Scheduling DAG of the packetize region\n";
for (SUnit &SU : VLIWScheduler->SUnits)
SU.dumpAll(VLIWScheduler);
});
// Generate MI -> SU map.
MIToSUnit.clear();
for (SUnit &SU : VLIWScheduler->SUnits)
MIToSUnit[SU.getInstr()] = &SU;
bool LimitPresent = InstrLimit.getPosition();
// The main packetizer loop.
for (; BeginItr != EndItr; ++BeginItr) {
if (LimitPresent) {
if (InstrCount >= InstrLimit) {
EndItr = BeginItr;
break;
}
InstrCount++;
}
MachineInstr &MI = *BeginItr;
initPacketizerState();
// End the current packet if needed.
if (isSoloInstruction(MI)) {
endPacket(MBB, MI);
continue;
}
// Ignore pseudo instructions.
if (ignorePseudoInstruction(MI, MBB))
continue;
SUnit *SUI = MIToSUnit[&MI];
assert(SUI && "Missing SUnit Info!");
// Ask DFA if machine resource is available for MI.
DEBUG(dbgs() << "Checking resources for adding MI to packet " << MI);
bool ResourceAvail = ResourceTracker->canReserveResources(MI);
DEBUG({
if (ResourceAvail)
dbgs() << " Resources are available for adding MI to packet\n";
else
dbgs() << " Resources NOT available\n";
});
if (ResourceAvail && shouldAddToPacket(MI)) {
// Dependency check for MI with instructions in CurrentPacketMIs.
for (auto MJ : CurrentPacketMIs) {
SUnit *SUJ = MIToSUnit[MJ];
assert(SUJ && "Missing SUnit Info!");
DEBUG(dbgs() << " Checking against MJ " << *MJ);
// Is it legal to packetize SUI and SUJ together.
if (!isLegalToPacketizeTogether(SUI, SUJ)) {
DEBUG(dbgs() << " Not legal to add MI, try to prune\n");
// Allow packetization if dependency can be pruned.
if (!isLegalToPruneDependencies(SUI, SUJ)) {
// End the packet if dependency cannot be pruned.
DEBUG(dbgs() << " Could not prune dependencies for adding MI\n");
endPacket(MBB, MI);
break;
}
DEBUG(dbgs() << " Pruned dependence for adding MI\n");
}
}
} else {
DEBUG(if (ResourceAvail)
dbgs() << "Resources are available, but instruction should not be "
"added to packet\n " << MI);
// End the packet if resource is not available, or if the instruction
// shoud not be added to the current packet.
endPacket(MBB, MI);
}
// Add MI to the current packet.
DEBUG(dbgs() << "* Adding MI to packet " << MI << '\n');
BeginItr = addToPacket(MI);
} // For all instructions in the packetization range.
// End any packet left behind.
endPacket(MBB, EndItr);
VLIWScheduler->exitRegion();
VLIWScheduler->finishBlock();
}
// Add a DAG mutation object to the ordered list.
void VLIWPacketizerList::addMutation(
std::unique_ptr<ScheduleDAGMutation> Mutation) {
VLIWScheduler->addMutation(std::move(Mutation));
}
<|endoftext|> |
<commit_before>//
// http_client_handler_file.cc
//
#include "plat_os.h"
#include "plat_net.h"
#include <cassert>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <ctime>
#include <cerrno>
#include <csignal>
#include <iostream>
#include <sstream>
#include <string>
#include <vector>
#include <algorithm>
#include <functional>
#include <deque>
#include <map>
#include <atomic>
#include <memory>
#include <thread>
#include <mutex>
#include <condition_variable>
#include "io.h"
#include "url.h"
#include "log.h"
#include "socket.h"
#include "socket_unix.h"
#include "resolver.h"
#include "config_parser.h"
#include "config.h"
#include "pollset.h"
#include "protocol.h"
#include "connection.h"
#include "connection.h"
#include "protocol_thread.h"
#include "protocol_engine.h"
#include "protocol_connection.h"
#include "http_common.h"
#include "http_constants.h"
#include "http_parser.h"
#include "http_request.h"
#include "http_response.h"
#include "http_date.h"
#include "http_client.h"
#include "http_client_handler_file.h"
/* http_client_handler_file */
http_client_handler_file::http_client_handler_file() : file_resource(-1) {}
http_client_handler_file::http_client_handler_file(int fd) : file_resource(fd) {}
http_client_handler_file::~http_client_handler_file() {}
void http_client_handler_file::init()
{
http_version = HTTPVersion11;
status_code = HTTPStatusCodeNone;
request_method = HTTPMethodNone;
content_length = -1;
total_read = 0;
}
bool http_client_handler_file::populate_request()
{
// get request http version and request method
http_version = http_constants::get_version_type(http_conn->request.get_http_version());
request_method = http_constants::get_method_type(http_conn->request.get_request_method());
// set request/response body
switch (request_method) {
case HTTPMethodPOST:
http_conn->request_has_body = true;
http_conn->response_has_body = true;
break;
case HTTPMethodHEAD:
http_conn->request_has_body = false;
http_conn->response_has_body = false;
break;
case HTTPMethodGET:
default:
http_conn->request_has_body = false;
http_conn->response_has_body = true;
break;
}
// TODO - add any additional request headers
return true;
}
io_result http_client_handler_file::write_request_body()
{
return io_result(0);
}
bool http_client_handler_file::handle_response()
{
// set connection close
http_version = http_constants::get_version_type(http_conn->response.get_http_version());
status_code =(HTTPStatusCode)http_conn->response.get_status_code();
const char* connection_str = http_conn->response.get_header_string(kHTTPHeaderConnection);
bool connection_keepalive_present = (connection_str && strcasecmp(connection_str, kHTTPTokenKeepalive) == 0);
bool connection_close_present = (connection_str && strcasecmp(connection_str, kHTTPTokenClose) == 0);
switch (http_version) {
case HTTPVersion10:
http_conn->connection_close = !connection_keepalive_present;
break;
case HTTPVersion11:
http_conn->connection_close = connection_close_present;
break;
default:
http_conn->connection_close = true;
break;
}
// get content length
const char* content_length_str = http_conn->response.get_header_string(kHTTPHeaderContentLength);
content_length = content_length_str ? strtoll(content_length_str, NULL, 10) : -1;
total_read = 0;
return true;
}
io_result http_client_handler_file::read_response_body()
{
auto &buffer = http_conn->buffer;
// handle body fragment in the buffer
if (buffer.bytes_readable() > 0) {
ssize_t bytes_readable = buffer.bytes_readable();
if (file_resource.get_fd() >= 0) {
io_result result = buffer.buffer_write(file_resource);
if (result.has_error()) {
log_error("http_client_handler_file: write: %s", strerror(result.error().errcode));
} else if (result.size() != bytes_readable) {
log_error("http_client_handler_file: short_write");
}
}
total_read += bytes_readable;
buffer.reset();
return io_result(-1);
}
if (total_read == content_length) return io_result(0);
// read data from socket
io_result result = buffer.buffer_read(http_conn->conn);
if (result.has_error()) {
return io_result(io_error(errno));
} else if (buffer.bytes_readable() > 0) {
ssize_t bytes_readable = buffer.bytes_readable();
if (file_resource.get_fd() >= 0) {
io_result result = buffer.buffer_write(file_resource);
if (result.has_error()) {
log_error("http_client_handler_file: write: %s", strerror(result.error().errcode));
} else if (result.size() != bytes_readable) {
log_error("http_client_handler_file: short_write");
}
}
total_read += bytes_readable;
buffer.reset();
}
// return bytes available or -1 if content length not present
if (content_length >= 0) {
return io_result(content_length - total_read);
} else {
return io_result(-1);
}
}
bool http_client_handler_file::end_request()
{
return true;
}
<commit_msg>Fix handling of residual buffer in read_response_body<commit_after>//
// http_client_handler_file.cc
//
#include "plat_os.h"
#include "plat_net.h"
#include <cassert>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <ctime>
#include <cerrno>
#include <csignal>
#include <iostream>
#include <sstream>
#include <string>
#include <vector>
#include <algorithm>
#include <functional>
#include <deque>
#include <map>
#include <atomic>
#include <memory>
#include <thread>
#include <mutex>
#include <condition_variable>
#include "io.h"
#include "url.h"
#include "log.h"
#include "socket.h"
#include "socket_unix.h"
#include "resolver.h"
#include "config_parser.h"
#include "config.h"
#include "pollset.h"
#include "protocol.h"
#include "connection.h"
#include "connection.h"
#include "protocol_thread.h"
#include "protocol_engine.h"
#include "protocol_connection.h"
#include "http_common.h"
#include "http_constants.h"
#include "http_parser.h"
#include "http_request.h"
#include "http_response.h"
#include "http_date.h"
#include "http_client.h"
#include "http_client_handler_file.h"
/* http_client_handler_file */
http_client_handler_file::http_client_handler_file() : file_resource(-1) {}
http_client_handler_file::http_client_handler_file(int fd) : file_resource(fd) {}
http_client_handler_file::~http_client_handler_file() {}
void http_client_handler_file::init()
{
http_version = HTTPVersion11;
status_code = HTTPStatusCodeNone;
request_method = HTTPMethodNone;
content_length = -1;
total_read = 0;
}
bool http_client_handler_file::populate_request()
{
// get request http version and request method
http_version = http_constants::get_version_type(http_conn->request.get_http_version());
request_method = http_constants::get_method_type(http_conn->request.get_request_method());
// set request/response body
switch (request_method) {
case HTTPMethodPOST:
http_conn->request_has_body = true;
http_conn->response_has_body = true;
break;
case HTTPMethodHEAD:
http_conn->request_has_body = false;
http_conn->response_has_body = false;
break;
case HTTPMethodGET:
default:
http_conn->request_has_body = false;
http_conn->response_has_body = true;
break;
}
// TODO - add any additional request headers
return true;
}
io_result http_client_handler_file::write_request_body()
{
return io_result(0);
}
bool http_client_handler_file::handle_response()
{
// set connection close
http_version = http_constants::get_version_type(http_conn->response.get_http_version());
status_code =(HTTPStatusCode)http_conn->response.get_status_code();
const char* connection_str = http_conn->response.get_header_string(kHTTPHeaderConnection);
bool connection_keepalive_present = (connection_str && strcasecmp(connection_str, kHTTPTokenKeepalive) == 0);
bool connection_close_present = (connection_str && strcasecmp(connection_str, kHTTPTokenClose) == 0);
switch (http_version) {
case HTTPVersion10:
http_conn->connection_close = !connection_keepalive_present;
break;
case HTTPVersion11:
http_conn->connection_close = connection_close_present;
break;
default:
http_conn->connection_close = true;
break;
}
// get content length
const char* content_length_str = http_conn->response.get_header_string(kHTTPHeaderContentLength);
content_length = content_length_str ? strtoll(content_length_str, NULL, 10) : -1;
total_read = 0;
return true;
}
io_result http_client_handler_file::read_response_body()
{
auto &buffer = http_conn->buffer;
// handle body fragment in the buffer
if (buffer.bytes_readable() > 0) {
ssize_t bytes_readable = buffer.bytes_readable();
if (file_resource.get_fd() >= 0) {
io_result result = buffer.buffer_write(file_resource);
if (result.has_error()) {
log_error("http_client_handler_file: write: %s", strerror(result.error().errcode));
} else if (result.size() != bytes_readable) {
log_error("http_client_handler_file: short_write");
}
}
total_read += bytes_readable;
buffer.reset();
// return bytes available or -1 if content length not present
if (content_length >= 0) {
return io_result(content_length - total_read);
} else {
return io_result(-1);
}
}
if (total_read == content_length) return io_result(0);
// read data from socket
io_result result = buffer.buffer_read(http_conn->conn);
if (result.has_error()) {
return io_result(io_error(errno));
} else if (buffer.bytes_readable() > 0) {
ssize_t bytes_readable = buffer.bytes_readable();
if (file_resource.get_fd() >= 0) {
io_result result = buffer.buffer_write(file_resource);
if (result.has_error()) {
log_error("http_client_handler_file: write: %s", strerror(result.error().errcode));
} else if (result.size() != bytes_readable) {
log_error("http_client_handler_file: short_write");
}
}
total_read += bytes_readable;
buffer.reset();
}
// return bytes available or -1 if content length not present
if (content_length >= 0) {
return io_result(content_length - total_read);
} else {
return io_result(-1);
}
}
bool http_client_handler_file::end_request()
{
return true;
}
<|endoftext|> |
<commit_before>#include "ofApp.h"
#include "ofxPS3EyeGrabber.h"
#define WIDTH 640
#define HEIGHT 480
//--------------------------------------------------------------
void ofApp::setup(){
// Set the video grabber to the ofxPS3EyeGrabber.
vidGrabber.setGrabber(std::make_shared<ofxPS3EyeGrabber>());
vidGrabber.setup(WIDTH, HEIGHT);
colorImg.allocate(WIDTH, HEIGHT);
grayImage.allocate(WIDTH, HEIGHT);
grayBg.allocate(WIDTH, HEIGHT);
grayDiff.allocate(WIDTH, HEIGHT);
bLearnBakground = true;
threshold = 80;
}
//--------------------------------------------------------------
void ofApp::update(){
vidGrabber.update();
if(vidGrabber.isFrameNew())
{
colorImg.setFromPixels(vidGrabber.getPixels());
grayImage = colorImg;
if (bLearnBakground == true)
{
// the = sign copys the pixels from grayImage into grayBg (operator overloading)
grayBg = grayImage;
bLearnBakground = false;
}
// take the abs value of the difference between background and incoming and then threshold:
grayDiff.absDiff(grayBg, grayImage);
grayDiff.threshold(threshold);
// find contours which are between the size of 20 pixels and 1/3 the w*h pixels.
// also, find holes is set to true so we will get interior contours as well....
//contourFinder.findContours(grayDiff, 20, (WIDTH*HEIGHT)/3, 10, true); // find holes
}
}
//--------------------------------------------------------------
void ofApp::draw(){
ofBackground(0);
ofSetColor(255);
//vidGrabber.draw(0, 0);
grayDiff.draw(0,0);
}
//--------------------------------------------------------------
void ofApp::keyPressed(int key){
switch (key){
case ' ':
bLearnBakground = true;
break;
case '+':
threshold ++;
if (threshold > 255) threshold = 255;
break;
case '-':
threshold --;
if (threshold < 0) threshold = 0;
break;
}
}
//--------------------------------------------------------------
void ofApp::keyReleased(int key){
}
//--------------------------------------------------------------
void ofApp::mouseMoved(int x, int y){
}
//--------------------------------------------------------------
void ofApp::mouseDragged(int x, int y, int button){
}
//--------------------------------------------------------------
void ofApp::mousePressed(int x, int y, int button){
}
//--------------------------------------------------------------
void ofApp::mouseReleased(int x, int y, int button){
}
//--------------------------------------------------------------
void ofApp::mouseEntered(int x, int y){
}
//--------------------------------------------------------------
void ofApp::mouseExited(int x, int y){
}
//--------------------------------------------------------------
void ofApp::windowResized(int w, int h){
}
//--------------------------------------------------------------
void ofApp::gotMessage(ofMessage msg){
}
//--------------------------------------------------------------
void ofApp::dragEvent(ofDragInfo dragInfo){
}
<commit_msg>find and show contours<commit_after>#include "ofApp.h"
#include "ofxPS3EyeGrabber.h"
#define WIDTH 640
#define HEIGHT 480
//--------------------------------------------------------------
void ofApp::setup(){
// Set the video grabber to the ofxPS3EyeGrabber.
vidGrabber.setGrabber(std::make_shared<ofxPS3EyeGrabber>());
vidGrabber.setup(WIDTH, HEIGHT);
colorImg.allocate(WIDTH, HEIGHT);
grayImage.allocate(WIDTH, HEIGHT);
grayBg.allocate(WIDTH, HEIGHT);
grayDiff.allocate(WIDTH, HEIGHT);
bLearnBakground = true;
threshold = 80;
}
//--------------------------------------------------------------
void ofApp::update(){
vidGrabber.update();
if(vidGrabber.isFrameNew())
{
colorImg.setFromPixels(vidGrabber.getPixels());
grayImage = colorImg;
if (bLearnBakground == true)
{
// the = sign copys the pixels from grayImage into grayBg (operator overloading)
grayBg = grayImage;
bLearnBakground = false;
}
// take the abs value of the difference between background and incoming and then threshold:
grayDiff.absDiff(grayBg, grayImage);
grayDiff.threshold(threshold);
// find contours which are between the size of 20 pixels and 1/3 the w*h pixels.
// also, find holes is set to true so we will get interior contours as well....
contourFinder.findContours(grayDiff, 20, (WIDTH*HEIGHT)/3, 10, true); // find holes
}
}
//--------------------------------------------------------------
void ofApp::draw(){
ofBackground(0);
ofSetColor(255);
//vidGrabber.draw(0, 0);
colorImg.draw(0,0);
//grayDiff.draw(0,0);
for(int i = 0; i < contourFinder.nBlobs; i++)
{
contourFinder.blobs[i].draw(0,0);
}
}
//--------------------------------------------------------------
void ofApp::keyPressed(int key){
switch (key){
case ' ':
bLearnBakground = true;
break;
case '+':
threshold ++;
if (threshold > 255) threshold = 255;
break;
case '-':
threshold --;
if (threshold < 0) threshold = 0;
break;
}
}
//--------------------------------------------------------------
void ofApp::keyReleased(int key){
}
//--------------------------------------------------------------
void ofApp::mouseMoved(int x, int y){
}
//--------------------------------------------------------------
void ofApp::mouseDragged(int x, int y, int button){
}
//--------------------------------------------------------------
void ofApp::mousePressed(int x, int y, int button){
}
//--------------------------------------------------------------
void ofApp::mouseReleased(int x, int y, int button){
}
//--------------------------------------------------------------
void ofApp::mouseEntered(int x, int y){
}
//--------------------------------------------------------------
void ofApp::mouseExited(int x, int y){
}
//--------------------------------------------------------------
void ofApp::windowResized(int w, int h){
}
//--------------------------------------------------------------
void ofApp::gotMessage(ofMessage msg){
}
//--------------------------------------------------------------
void ofApp::dragEvent(ofDragInfo dragInfo){
}
<|endoftext|> |
<commit_before>/*******************************************************************************
*
* MIT License
*
* Copyright (c) 2019 Advanced Micro Devices, Inc.
*
* 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 BFLOAT16_H_
#define BFLOAT16_H_
#include <boost/operators.hpp>
#include <iostream>
#include <miopen/config.h>
class bfloat16 : boost::totally_ordered<bfloat16, boost::arithmetic<bfloat16>>
{
public:
bfloat16() : data_{0} {}
explicit bfloat16(float rhs)
{
static union
{
std::uint32_t bf16_st;
float float_st;
} bits_st;
bits_st.float_st = rhs;
// BF16 round and NaN preservation code matches
// https://github.com/ROCmSoftwarePlatform/rocBLAS/blob/develop/library/include/rocblas_bfloat16.h
if((~bits_st.bf16_st & 0x7f800000) == 0) // Inf or NaN
{
// When all of the exponent bits are 1, the value is Inf or NaN.
// Inf is indicated by a zero mantissa. NaN is indicated by any nonzero
// mantissa bit. Quiet NaN is indicated by the most significant mantissa
// bit being 1. Signaling NaN is indicated by the most significant
// mantissa bit being 0 but some other bit(s) being 1. If any of the
// lower 16 bits of the mantissa are 1, we set the least significant bit
// of the bfloat16 mantissa, in order to preserve signaling NaN in case
// the bloat16's mantissa bits are all 0.
if((bits_st.bf16_st & 0xffff) != 0)
{
bits_st.bf16_st |= 0x10000; // Preserve signaling NaN
}
}
else
{
#if MIOPEN_USE_RNE_BFLOAT16 == 1
// When the exponent bits are not all 1s, then the value is zero, normal,
// or subnormal. We round the bfloat16 mantissa up by adding 0x7FFF, plus
// 1 if the least significant bit of the bfloat16 mantissa is 1 (odd).
// This causes the bfloat16's mantissa to be incremented by 1 if the 16
// least significant bits of the float mantissa are greater than 0x8000,
// or if they are equal to 0x8000 and the least significant bit of the
// bfloat16 mantissa is 1 (odd). This causes it to be rounded to even when
// the lower 16 bits are exactly 0x8000. If the bfloat16 mantissa already
// has the value 0x7f, then incrementing it causes it to become 0x00 and
// the exponent is incremented by one, which is the next higher FP value
// to the unrounded bfloat16 value. When the bfloat16 value is subnormal
// with an exponent of 0x00 and a mantissa of 0x7F, it may be rounded up
// to a normal value with an exponent of 0x01 and a mantissa of 0x00.
// When the bfloat16 value has an exponent of 0xFE and a mantissa of 0x7F,
// incrementing it causes it to become an exponent of 0xFF and a mantissa
// of 0x00, which is Inf, the next higher value to the unrounded value.
bits_st.bf16_st +=
(0x7fff + ((bits_st.bf16_st >> 16) & 1)); // Round to nearest, round to even
#else // truncation
// do nothing
#endif
}
data_ = bits_st.bf16_st >> 16;
}
operator float() const
{
static union
{
std::uint32_t bf16_st;
float float_st;
} bits_st;
bits_st.bf16_st = data_;
bits_st.bf16_st = bits_st.bf16_st << 16;
return bits_st.float_st;
}
bfloat16 operator-() const { return bfloat16(-static_cast<float>(*this)); }
bfloat16 operator+() const { return *this; }
bfloat16& operator=(const float rhs)
{
*this = bfloat16(rhs);
return *this;
}
bfloat16& operator+=(bfloat16 rhs)
{
*this = bfloat16(static_cast<float>(*this) + static_cast<float>(rhs));
return *this;
}
bfloat16& operator+=(float rhs)
{
*this = bfloat16(static_cast<float>(*this) + rhs);
return *this;
}
bfloat16& operator-=(bfloat16 rhs)
{
*this += -rhs;
return *this;
}
bfloat16& operator*=(bfloat16 rhs)
{
*this = bfloat16(static_cast<float>(*this) * static_cast<float>(rhs));
return *this;
}
bfloat16& operator*=(float rhs)
{
*this = bfloat16(static_cast<float>(*this) * rhs);
return *this;
}
bfloat16& operator/=(bfloat16 rhs)
{
*this = bfloat16(static_cast<float>(*this) / static_cast<float>(rhs));
return *this;
}
bool operator<(bfloat16 rhs) const
{
return static_cast<float>(*this) < static_cast<float>(rhs);
}
bool operator==(bfloat16 rhs) const { return std::equal_to<float>()(*this, rhs); }
static constexpr bfloat16 generate(uint16_t val) { return bfloat16{val, true}; }
private:
constexpr bfloat16(std::uint16_t val, bool) : data_{val} {}
std::uint16_t data_;
};
namespace std {
template <>
class numeric_limits<bfloat16>
{
public:
static constexpr bool is_specialized = true;
static constexpr bfloat16 min() noexcept { return bfloat16::generate(0x007F); }
static constexpr bfloat16 max() noexcept { return bfloat16::generate(0x7F7F); }
static constexpr bfloat16 lowest() noexcept { return bfloat16::generate(0xFF7F); }
static constexpr bfloat16 epsilon() noexcept { return bfloat16::generate(0x3C00); }
static constexpr bfloat16 infinity() noexcept { return bfloat16::generate(0x7F80); }
static constexpr bfloat16 quiet_NaN() noexcept { return bfloat16::generate(0x7FC0); }
static constexpr bfloat16 signaling_NaN() noexcept { return bfloat16::generate(0x7FC0); }
static constexpr bfloat16 denorm_min() noexcept { return bfloat16::generate(0); }
};
} // namespace std
#endif
<commit_msg>* fix for bfloat16 class (#1908)<commit_after>/*******************************************************************************
*
* MIT License
*
* Copyright (c) 2019 Advanced Micro Devices, Inc.
*
* 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 BFLOAT16_H_
#define BFLOAT16_H_
#include <boost/operators.hpp>
#include <iostream>
#include <miopen/config.h>
class bfloat16 : boost::totally_ordered<bfloat16, boost::arithmetic<bfloat16>>
{
public:
bfloat16() : data_{0} {}
explicit bfloat16(float rhs)
{
union
{
float float_st;
std::uint32_t bf16_st;
} bits_st = {rhs};
// BF16 round and NaN preservation code matches
// https://github.com/ROCmSoftwarePlatform/rocBLAS/blob/develop/library/include/rocblas_bfloat16.h
if((~bits_st.bf16_st & 0x7f800000) == 0) // Inf or NaN
{
// When all of the exponent bits are 1, the value is Inf or NaN.
// Inf is indicated by a zero mantissa. NaN is indicated by any nonzero
// mantissa bit. Quiet NaN is indicated by the most significant mantissa
// bit being 1. Signaling NaN is indicated by the most significant
// mantissa bit being 0 but some other bit(s) being 1. If any of the
// lower 16 bits of the mantissa are 1, we set the least significant bit
// of the bfloat16 mantissa, in order to preserve signaling NaN in case
// the bloat16's mantissa bits are all 0.
if((bits_st.bf16_st & 0xffff) != 0)
{
bits_st.bf16_st |= 0x10000; // Preserve signaling NaN
}
}
else
{
#if MIOPEN_USE_RNE_BFLOAT16 == 1
// When the exponent bits are not all 1s, then the value is zero, normal,
// or subnormal. We round the bfloat16 mantissa up by adding 0x7FFF, plus
// 1 if the least significant bit of the bfloat16 mantissa is 1 (odd).
// This causes the bfloat16's mantissa to be incremented by 1 if the 16
// least significant bits of the float mantissa are greater than 0x8000,
// or if they are equal to 0x8000 and the least significant bit of the
// bfloat16 mantissa is 1 (odd). This causes it to be rounded to even when
// the lower 16 bits are exactly 0x8000. If the bfloat16 mantissa already
// has the value 0x7f, then incrementing it causes it to become 0x00 and
// the exponent is incremented by one, which is the next higher FP value
// to the unrounded bfloat16 value. When the bfloat16 value is subnormal
// with an exponent of 0x00 and a mantissa of 0x7F, it may be rounded up
// to a normal value with an exponent of 0x01 and a mantissa of 0x00.
// When the bfloat16 value has an exponent of 0xFE and a mantissa of 0x7F,
// incrementing it causes it to become an exponent of 0xFF and a mantissa
// of 0x00, which is Inf, the next higher value to the unrounded value.
bits_st.bf16_st +=
(0x7fff + ((bits_st.bf16_st >> 16) & 1)); // Round to nearest, round to even
#else // truncation
// do nothing
#endif
}
data_ = bits_st.bf16_st >> 16;
}
operator float() const
{
union
{
std::uint32_t bf16_st;
float float_st;
} bits_st = {data_};
bits_st.bf16_st = bits_st.bf16_st << 16;
return bits_st.float_st;
}
bfloat16 operator-() const { return bfloat16(-static_cast<float>(*this)); }
bfloat16 operator+() const { return *this; }
bfloat16& operator=(const float rhs)
{
*this = bfloat16(rhs);
return *this;
}
bfloat16& operator+=(bfloat16 rhs)
{
*this = bfloat16(static_cast<float>(*this) + static_cast<float>(rhs));
return *this;
}
bfloat16& operator+=(float rhs)
{
*this = bfloat16(static_cast<float>(*this) + rhs);
return *this;
}
bfloat16& operator-=(bfloat16 rhs)
{
*this += -rhs;
return *this;
}
bfloat16& operator*=(bfloat16 rhs)
{
*this = bfloat16(static_cast<float>(*this) * static_cast<float>(rhs));
return *this;
}
bfloat16& operator*=(float rhs)
{
*this = bfloat16(static_cast<float>(*this) * rhs);
return *this;
}
bfloat16& operator/=(bfloat16 rhs)
{
*this = bfloat16(static_cast<float>(*this) / static_cast<float>(rhs));
return *this;
}
bool operator<(bfloat16 rhs) const
{
return static_cast<float>(*this) < static_cast<float>(rhs);
}
bool operator==(bfloat16 rhs) const { return std::equal_to<float>()(*this, rhs); }
static constexpr bfloat16 generate(uint16_t val) { return bfloat16{val, true}; }
private:
constexpr bfloat16(std::uint16_t val, bool) : data_{val} {}
std::uint16_t data_;
};
namespace std {
template <>
class numeric_limits<bfloat16>
{
public:
static constexpr bool is_specialized = true;
static constexpr bfloat16 min() noexcept { return bfloat16::generate(0x007F); }
static constexpr bfloat16 max() noexcept { return bfloat16::generate(0x7F7F); }
static constexpr bfloat16 lowest() noexcept { return bfloat16::generate(0xFF7F); }
static constexpr bfloat16 epsilon() noexcept { return bfloat16::generate(0x3C00); }
static constexpr bfloat16 infinity() noexcept { return bfloat16::generate(0x7F80); }
static constexpr bfloat16 quiet_NaN() noexcept { return bfloat16::generate(0x7FC0); }
static constexpr bfloat16 signaling_NaN() noexcept { return bfloat16::generate(0x7FC0); }
static constexpr bfloat16 denorm_min() noexcept { return bfloat16::generate(0); }
};
} // namespace std
#endif
<|endoftext|> |
<commit_before>/*
* %injeqt copyright begin%
* Copyright 2014 Rafał Malinowski ([email protected])
* %injeqt copyright end%
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include "implemented-by.h"
#include "extract-interfaces.h"
namespace injeqt { namespace internal {
implemented_by::implemented_by(type interface_type, type implementation_type) :
_interface_type{std::move(interface_type)},
_implementation_type{std::move(implementation_type)}
{
}
type implemented_by::interface_type() const
{
return _interface_type;
}
type implemented_by::implementation_type() const
{
return _implementation_type;
}
void validate(const implemented_by &ib)
{
auto interaces = extract_interfaces(ib.implementation_type());
if (std::find(std::begin(interaces), std::end(interaces), ib.interface_type()) == std::end(interaces))
throw invalid_implemented_by_exception{};
}
bool operator == (const implemented_by &x, const implemented_by &y)
{
if (x.interface_type() != y.interface_type())
return false;
if (x.implementation_type() != y.implementation_type())
return false;
return true;
}
bool operator != (const implemented_by &x, const implemented_by &y)
{
return !(x == y);
}
}}
<commit_msg>add missing checks<commit_after>/*
* %injeqt copyright begin%
* Copyright 2014 Rafał Malinowski ([email protected])
* %injeqt copyright end%
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include "implemented-by.h"
#include "extract-interfaces.h"
namespace injeqt { namespace internal {
implemented_by::implemented_by(type interface_type, type implementation_type) :
_interface_type{std::move(interface_type)},
_implementation_type{std::move(implementation_type)}
{
}
type implemented_by::interface_type() const
{
return _interface_type;
}
type implemented_by::implementation_type() const
{
return _implementation_type;
}
void validate(const implemented_by &ib)
{
validate(ib.interface_type());
validate(ib.implementation_type());
auto interfaces = extract_interfaces(ib.implementation_type());
if (std::find(std::begin(interfaces), std::end(interfaces), ib.interface_type()) == std::end(interfaces))
throw invalid_implemented_by_exception{};
}
bool operator == (const implemented_by &x, const implemented_by &y)
{
if (x.interface_type() != y.interface_type())
return false;
if (x.implementation_type() != y.implementation_type())
return false;
return true;
}
bool operator != (const implemented_by &x, const implemented_by &y)
{
return !(x == y);
}
}}
<|endoftext|> |
<commit_before>/*
* Copyright (C) 2007 Justin Karneges
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
* 02110-1301 USA
*
*/
#include <QtCore>
#include <QHostAddress>
#include "qdnssd.h"
// for ntohl
#ifdef Q_OS_WIN
# include <windows.h>
#else
# include <netinet/in.h>
#endif
class Command
{
public:
enum Type
{
Query,
Browse,
Resolve,
Reg
};
Type type;
QString name; // query, resolve, reg
int rtype; // query
QString stype; // browse, resolve, reg
QString domain; // browse, resolve, reg
int port; // reg
QByteArray txtRecord; // reg
int id;
int dnsId;
bool error;
bool done; // for resolve
Command() :
error(false),
done(false)
{
}
};
static QString nameToString(const QByteArray &in)
{
QStringList parts;
int at = 0;
while(at < in.size())
{
int len = in[at++];
parts += QString::fromUtf8(in.mid(at, len));
at += len;
}
return parts.join(".");
}
static QString recordToDesc(const QDnsSd::Record &rec)
{
QString desc;
if(rec.rrtype == 1) // A
{
quint32 *p = (quint32 *)rec.rdata.data();
desc = QHostAddress(ntohl(*p)).toString();
}
else if(rec.rrtype == 28) // AAAA
{
desc = QHostAddress((quint8 *)rec.rdata.data()).toString();
}
else if(rec.rrtype == 12) // PTR
{
desc = QString("[%1]").arg(nameToString(rec.rdata));
}
else
desc = QString("%1 bytes").arg(rec.rdata.size());
return desc;
}
static QStringList txtRecordToStringList(const QByteArray &rdata)
{
QList<QByteArray> txtEntries = QDnsSd::parseTxtRecord(rdata);
if(txtEntries.isEmpty())
return QStringList();
QStringList out;
foreach(const QByteArray &entry, txtEntries)
out += QString::fromUtf8(entry);
return out;
}
static void printIndentedTxt(const QByteArray &txtRecord)
{
QStringList list = txtRecordToStringList(txtRecord);
if(!list.isEmpty())
{
foreach(const QString &s, list)
printf(" %s\n", qPrintable(s));
}
else
printf(" (TXT parsing error)\n");
}
class App : public QObject
{
Q_OBJECT
public:
QList<Command> commands;
QDnsSd *dns;
App()
{
dns = new QDnsSd(this);
connect(dns, SIGNAL(queryResult(int, const QDnsSd::QueryResult &)), SLOT(dns_queryResult(int, const QDnsSd::QueryResult &)));
connect(dns, SIGNAL(browseResult(int, const QDnsSd::BrowseResult &)), SLOT(dns_browseResult(int, const QDnsSd::BrowseResult &)));
connect(dns, SIGNAL(resolveResult(int, const QDnsSd::ResolveResult &)), SLOT(dns_resolveResult(int, const QDnsSd::ResolveResult &)));
connect(dns, SIGNAL(regResult(int, const QDnsSd::RegResult &)), SLOT(dns_regResult(int, const QDnsSd::RegResult &)));
}
public slots:
void start()
{
for(int n = 0; n < commands.count(); ++n)
{
Command &c = commands[n];
c.id = n;
if(c.type == Command::Query)
{
printf("%2d: Query name=[%s], type=%d ...\n", c.id, qPrintable(c.name), c.rtype);
c.dnsId = dns->query(c.name.toUtf8(), c.rtype);
}
else if(c.type == Command::Browse)
{
printf("%2d: Browse type=[%s]", c.id, qPrintable(c.stype));
if(!c.domain.isEmpty())
printf(", domain=[%s]", qPrintable(c.domain));
printf(" ...\n");
c.dnsId = dns->browse(c.stype.toUtf8(), c.domain.toUtf8());
}
else if(c.type == Command::Resolve)
{
printf("%2d: Resolve name=[%s], type=[%s], domain=[%s] ...\n", c.id, qPrintable(c.name), qPrintable(c.stype), qPrintable(c.domain));
c.dnsId = dns->resolve(c.name.toUtf8(), c.stype.toUtf8(), c.domain.toUtf8());
}
else if(c.type == Command::Reg)
{
printf("%2d: Register name=[%s], type=[%s]", c.id, qPrintable(c.name), qPrintable(c.stype));
if(!c.domain.isEmpty())
printf(", domain=[%s]", qPrintable(c.domain));
printf(", port=%d ...\n", c.port);
if(!c.txtRecord.isEmpty())
printIndentedTxt(c.txtRecord);
c.dnsId = dns->reg(c.name.toUtf8(), c.stype.toUtf8(), c.domain.toUtf8(), c.port, c.txtRecord);
}
}
}
signals:
void quit();
private:
int cmdIdToCmdIndex(int cmdId)
{
for(int n = 0; n < commands.count(); ++n)
{
const Command &c = commands[n];
if(c.id == cmdId)
return n;
}
return -1;
}
int dnsIdToCmdIndex(int dnsId)
{
for(int n = 0; n < commands.count(); ++n)
{
const Command &c = commands[n];
if(c.dnsId == dnsId)
return n;
}
return -1;
}
void tryQuit()
{
// quit if there are nothing but errors or completed resolves
bool doQuit = true;
foreach(const Command &c, commands)
{
if(c.error || (c.type == Command::Resolve && c.done))
continue;
doQuit = false;
break;
}
if(doQuit)
emit quit();
}
private slots:
void dns_queryResult(int id, const QDnsSd::QueryResult &result)
{
int at = dnsIdToCmdIndex(id);
Command &c = commands[at];
if(!result.success)
{
printf("%2d: Error.", c.id);
if(!result.lowLevelError.func.isEmpty())
printf(" (%s, %d)", qPrintable(result.lowLevelError.func), result.lowLevelError.code);
printf("\n");
c.error = true;
tryQuit();
return;
}
foreach(const QDnsSd::Record &rec, result.records)
{
if(rec.added)
{
printf("%2d: Added: %s, ttl=%d\n", c.id, qPrintable(recordToDesc(rec)), rec.ttl);
if(rec.rrtype == 16)
printIndentedTxt(rec.rdata);
}
else
printf("%2d: Removed: %s, ttl=%d\n", c.id, qPrintable(recordToDesc(rec)), rec.ttl);
}
}
void dns_browseResult(int id, const QDnsSd::BrowseResult &result)
{
int at = dnsIdToCmdIndex(id);
Command &c = commands[at];
if(!result.success)
{
printf("%2d: Error.", c.id);
if(!result.lowLevelError.func.isEmpty())
printf(" (%s, %d)", qPrintable(result.lowLevelError.func), result.lowLevelError.code);
printf("\n");
c.error = true;
tryQuit();
return;
}
foreach(const QDnsSd::BrowseEntry &e, result.entries)
{
if(e.added)
printf("%2d: Added: [%s] [%s] [%s]\n", c.id, e.serviceName.data(), e.serviceType.data(), e.replyDomain.data());
else
printf("%2d: Removed: [%s]\n", c.id, e.serviceName.data());
}
}
void dns_resolveResult(int id, const QDnsSd::ResolveResult &result)
{
int at = dnsIdToCmdIndex(id);
Command &c = commands[at];
if(!result.success)
{
printf("%2d: Error.", c.id);
if(!result.lowLevelError.func.isEmpty())
printf(" (%s, %d)", qPrintable(result.lowLevelError.func), result.lowLevelError.code);
printf("\n");
c.error = true;
tryQuit();
return;
}
printf("%2d: Result: host=[%s] port=%d\n", c.id, result.hostTarget.data(), result.port);
if(!result.txtRecord.isEmpty())
printIndentedTxt(result.txtRecord);
c.done = true;
tryQuit();
}
void dns_regResult(int id, const QDnsSd::RegResult &result)
{
int at = dnsIdToCmdIndex(id);
Command &c = commands[at];
if(!result.success)
{
QString errstr;
if(result.errorCode == QDnsSd::RegResult::ErrorConflict)
errstr = "Conflict";
else
errstr = "Generic";
printf("%2d: Error (%s).", c.id, qPrintable(errstr));
if(!result.lowLevelError.func.isEmpty())
printf(" (%s, %d)", qPrintable(result.lowLevelError.func), result.lowLevelError.code);
printf("\n");
c.error = true;
tryQuit();
return;
}
printf("%2d: Registered: domain=[%s]\n", c.id, result.domain.data());
}
};
#include "sdtest.moc"
void usage()
{
printf("usage: sdtest [[command] (command) ...]\n");
printf(" options: --txt=str0,...,strn\n");
printf("\n");
printf(" q=name,type# query for a record\n");
printf(" b=type(,domain) browse for services\n");
printf(" r=name,type,domain resolve a service\n");
printf(" e=name,type,port(,domain) register a service\n");
printf("\n");
}
int main(int argc, char **argv)
{
QCoreApplication qapp(argc, argv);
QStringList args = qapp.arguments();
args.removeFirst();
if(args.count() < 1)
{
usage();
return 1;
}
// options
QStringList txt;
for(int n = 0; n < args.count(); ++n)
{
QString s = args[n];
if(!s.startsWith("--"))
continue;
QString var;
QString val;
int x = s.indexOf('=');
if(x != -1)
{
var = s.mid(2, x - 2);
val = s.mid(x + 1);
}
else
{
var = s.mid(2);
}
bool known = true;
if(var == "txt")
{
txt = val.split(',');
}
else
known = false;
if(known)
{
args.removeAt(n);
--n; // adjust position
}
}
// commands
QList<Command> commands;
for(int n = 0; n < args.count(); ++n)
{
QString str = args[n];
int n = str.indexOf('=');
if(n == -1)
{
printf("Error: bad format of command.\n");
return 1;
}
QString type = str.mid(0, n);
QString rest = str.mid(n + 1);
QStringList parts = rest.split(',');
if(type == "q")
{
if(parts.count() < 2)
{
usage();
return 1;
}
Command c;
c.type = Command::Query;
c.name = parts[0];
c.rtype = parts[1].toInt();
commands += c;
}
else if(type == "b")
{
if(parts.count() < 1)
{
usage();
return 1;
}
Command c;
c.type = Command::Browse;
c.stype = parts[0];
if(parts.count() >= 2)
c.domain = parts[1];
commands += c;
}
else if(type == "r")
{
if(parts.count() < 3)
{
usage();
return 1;
}
Command c;
c.type = Command::Resolve;
c.name = parts[0];
c.stype = parts[1];
c.domain = parts[2];
commands += c;
}
else if(type == "e")
{
if(parts.count() < 3)
{
usage();
return 1;
}
Command c;
c.type = Command::Reg;
c.name = parts[0];
c.stype = parts[1];
c.port = parts[2].toInt();
if(parts.count() >= 4)
c.domain = parts[3];
if(!txt.isEmpty())
{
QList<QByteArray> strings;
foreach(const QString &str, txt)
strings += str.toUtf8();
QByteArray txtRecord = QDnsSd::createTxtRecord(strings);
if(txtRecord.isEmpty())
{
printf("Error: failed to create TXT record, input too large or invalid\n");
return 1;
}
c.txtRecord = txtRecord;
}
commands += c;
}
else
{
printf("Error: unknown command type '%s'.\n", qPrintable(type));
return 1;
}
}
App app;
app.commands = commands;
QObject::connect(&app, SIGNAL(quit()), &qapp, SLOT(quit()));
QTimer::singleShot(0, &app, SLOT(start()));
qapp.exec();
return 0;
}
<commit_msg>more unicode fixes<commit_after>/*
* Copyright (C) 2007 Justin Karneges
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
* 02110-1301 USA
*
*/
#include <QtCore>
#include <QHostAddress>
#include "qdnssd.h"
// for ntohl
#ifdef Q_OS_WIN
# include <windows.h>
#else
# include <netinet/in.h>
#endif
class Command
{
public:
enum Type
{
Query,
Browse,
Resolve,
Reg
};
Type type;
QString name; // query, resolve, reg
int rtype; // query
QString stype; // browse, resolve, reg
QString domain; // browse, resolve, reg
int port; // reg
QByteArray txtRecord; // reg
int id;
int dnsId;
bool error;
bool done; // for resolve
Command() :
error(false),
done(false)
{
}
};
static QString nameToString(const QByteArray &in)
{
QStringList parts;
int at = 0;
while(at < in.size())
{
int len = in[at++];
parts += QString::fromUtf8(in.mid(at, len));
at += len;
}
return parts.join(".");
}
static QString recordToDesc(const QDnsSd::Record &rec)
{
QString desc;
if(rec.rrtype == 1) // A
{
quint32 *p = (quint32 *)rec.rdata.data();
desc = QHostAddress(ntohl(*p)).toString();
}
else if(rec.rrtype == 28) // AAAA
{
desc = QHostAddress((quint8 *)rec.rdata.data()).toString();
}
else if(rec.rrtype == 12) // PTR
{
desc = QString("[%1]").arg(nameToString(rec.rdata));
}
else
desc = QString("%1 bytes").arg(rec.rdata.size());
return desc;
}
static QStringList txtRecordToStringList(const QByteArray &rdata)
{
QList<QByteArray> txtEntries = QDnsSd::parseTxtRecord(rdata);
if(txtEntries.isEmpty())
return QStringList();
QStringList out;
foreach(const QByteArray &entry, txtEntries)
out += QString::fromUtf8(entry);
return out;
}
static void printIndentedTxt(const QByteArray &txtRecord)
{
QStringList list = txtRecordToStringList(txtRecord);
if(!list.isEmpty())
{
foreach(const QString &s, list)
printf(" %s\n", qPrintable(s));
}
else
printf(" (TXT parsing error)\n");
}
class App : public QObject
{
Q_OBJECT
public:
QList<Command> commands;
QDnsSd *dns;
App()
{
dns = new QDnsSd(this);
connect(dns, SIGNAL(queryResult(int, const QDnsSd::QueryResult &)), SLOT(dns_queryResult(int, const QDnsSd::QueryResult &)));
connect(dns, SIGNAL(browseResult(int, const QDnsSd::BrowseResult &)), SLOT(dns_browseResult(int, const QDnsSd::BrowseResult &)));
connect(dns, SIGNAL(resolveResult(int, const QDnsSd::ResolveResult &)), SLOT(dns_resolveResult(int, const QDnsSd::ResolveResult &)));
connect(dns, SIGNAL(regResult(int, const QDnsSd::RegResult &)), SLOT(dns_regResult(int, const QDnsSd::RegResult &)));
}
public slots:
void start()
{
for(int n = 0; n < commands.count(); ++n)
{
Command &c = commands[n];
c.id = n;
if(c.type == Command::Query)
{
printf("%2d: Query name=[%s], type=%d ...\n", c.id, qPrintable(c.name), c.rtype);
c.dnsId = dns->query(c.name.toUtf8(), c.rtype);
}
else if(c.type == Command::Browse)
{
printf("%2d: Browse type=[%s]", c.id, qPrintable(c.stype));
if(!c.domain.isEmpty())
printf(", domain=[%s]", qPrintable(c.domain));
printf(" ...\n");
c.dnsId = dns->browse(c.stype.toUtf8(), c.domain.toUtf8());
}
else if(c.type == Command::Resolve)
{
printf("%2d: Resolve name=[%s], type=[%s], domain=[%s] ...\n", c.id, qPrintable(c.name), qPrintable(c.stype), qPrintable(c.domain));
c.dnsId = dns->resolve(c.name.toUtf8(), c.stype.toUtf8(), c.domain.toUtf8());
}
else if(c.type == Command::Reg)
{
printf("%2d: Register name=[%s], type=[%s]", c.id, qPrintable(c.name), qPrintable(c.stype));
if(!c.domain.isEmpty())
printf(", domain=[%s]", qPrintable(c.domain));
printf(", port=%d ...\n", c.port);
if(!c.txtRecord.isEmpty())
printIndentedTxt(c.txtRecord);
c.dnsId = dns->reg(c.name.toUtf8(), c.stype.toUtf8(), c.domain.toUtf8(), c.port, c.txtRecord);
}
}
}
signals:
void quit();
private:
int cmdIdToCmdIndex(int cmdId)
{
for(int n = 0; n < commands.count(); ++n)
{
const Command &c = commands[n];
if(c.id == cmdId)
return n;
}
return -1;
}
int dnsIdToCmdIndex(int dnsId)
{
for(int n = 0; n < commands.count(); ++n)
{
const Command &c = commands[n];
if(c.dnsId == dnsId)
return n;
}
return -1;
}
void tryQuit()
{
// quit if there are nothing but errors or completed resolves
bool doQuit = true;
foreach(const Command &c, commands)
{
if(c.error || (c.type == Command::Resolve && c.done))
continue;
doQuit = false;
break;
}
if(doQuit)
emit quit();
}
private slots:
void dns_queryResult(int id, const QDnsSd::QueryResult &result)
{
int at = dnsIdToCmdIndex(id);
Command &c = commands[at];
if(!result.success)
{
printf("%2d: Error.", c.id);
if(!result.lowLevelError.func.isEmpty())
printf(" (%s, %d)", qPrintable(result.lowLevelError.func), result.lowLevelError.code);
printf("\n");
c.error = true;
tryQuit();
return;
}
foreach(const QDnsSd::Record &rec, result.records)
{
if(rec.added)
{
printf("%2d: Added: %s, ttl=%d\n", c.id, qPrintable(recordToDesc(rec)), rec.ttl);
if(rec.rrtype == 16)
printIndentedTxt(rec.rdata);
}
else
printf("%2d: Removed: %s, ttl=%d\n", c.id, qPrintable(recordToDesc(rec)), rec.ttl);
}
}
void dns_browseResult(int id, const QDnsSd::BrowseResult &result)
{
int at = dnsIdToCmdIndex(id);
Command &c = commands[at];
if(!result.success)
{
printf("%2d: Error.", c.id);
if(!result.lowLevelError.func.isEmpty())
printf(" (%s, %d)", qPrintable(result.lowLevelError.func), result.lowLevelError.code);
printf("\n");
c.error = true;
tryQuit();
return;
}
foreach(const QDnsSd::BrowseEntry &e, result.entries)
{
if(e.added)
printf("%2d: Added: [%s] [%s] [%s]\n", c.id, qPrintable(QString::fromUtf8(e.serviceName)), qPrintable(QString::fromUtf8(e.serviceType)), qPrintable(QString::fromUtf8(e.replyDomain)));
else
printf("%2d: Removed: [%s]\n", c.id, qPrintable(QString::fromUtf8(e.serviceName)));
}
}
void dns_resolveResult(int id, const QDnsSd::ResolveResult &result)
{
int at = dnsIdToCmdIndex(id);
Command &c = commands[at];
if(!result.success)
{
printf("%2d: Error.", c.id);
if(!result.lowLevelError.func.isEmpty())
printf(" (%s, %d)", qPrintable(result.lowLevelError.func), result.lowLevelError.code);
printf("\n");
c.error = true;
tryQuit();
return;
}
printf("%2d: Result: host=[%s] port=%d\n", c.id, qPrintable(QString::fromUtf8(result.hostTarget)), result.port);
if(!result.txtRecord.isEmpty())
printIndentedTxt(result.txtRecord);
c.done = true;
tryQuit();
}
void dns_regResult(int id, const QDnsSd::RegResult &result)
{
int at = dnsIdToCmdIndex(id);
Command &c = commands[at];
if(!result.success)
{
QString errstr;
if(result.errorCode == QDnsSd::RegResult::ErrorConflict)
errstr = "Conflict";
else
errstr = "Generic";
printf("%2d: Error (%s).", c.id, qPrintable(errstr));
if(!result.lowLevelError.func.isEmpty())
printf(" (%s, %d)", qPrintable(result.lowLevelError.func), result.lowLevelError.code);
printf("\n");
c.error = true;
tryQuit();
return;
}
printf("%2d: Registered: domain=[%s]\n", c.id, qPrintable(QString::fromUtf8(result.domain)));
}
};
#include "sdtest.moc"
void usage()
{
printf("usage: sdtest [[command] (command) ...]\n");
printf(" options: --txt=str0,...,strn\n");
printf("\n");
printf(" q=name,type# query for a record\n");
printf(" b=type(,domain) browse for services\n");
printf(" r=name,type,domain resolve a service\n");
printf(" e=name,type,port(,domain) register a service\n");
printf("\n");
}
int main(int argc, char **argv)
{
QCoreApplication qapp(argc, argv);
QStringList args = qapp.arguments();
args.removeFirst();
if(args.count() < 1)
{
usage();
return 1;
}
// options
QStringList txt;
for(int n = 0; n < args.count(); ++n)
{
QString s = args[n];
if(!s.startsWith("--"))
continue;
QString var;
QString val;
int x = s.indexOf('=');
if(x != -1)
{
var = s.mid(2, x - 2);
val = s.mid(x + 1);
}
else
{
var = s.mid(2);
}
bool known = true;
if(var == "txt")
{
txt = val.split(',');
}
else
known = false;
if(known)
{
args.removeAt(n);
--n; // adjust position
}
}
// commands
QList<Command> commands;
for(int n = 0; n < args.count(); ++n)
{
QString str = args[n];
int n = str.indexOf('=');
if(n == -1)
{
printf("Error: bad format of command.\n");
return 1;
}
QString type = str.mid(0, n);
QString rest = str.mid(n + 1);
QStringList parts = rest.split(',');
if(type == "q")
{
if(parts.count() < 2)
{
usage();
return 1;
}
Command c;
c.type = Command::Query;
c.name = parts[0];
c.rtype = parts[1].toInt();
commands += c;
}
else if(type == "b")
{
if(parts.count() < 1)
{
usage();
return 1;
}
Command c;
c.type = Command::Browse;
c.stype = parts[0];
if(parts.count() >= 2)
c.domain = parts[1];
commands += c;
}
else if(type == "r")
{
if(parts.count() < 3)
{
usage();
return 1;
}
Command c;
c.type = Command::Resolve;
c.name = parts[0];
c.stype = parts[1];
c.domain = parts[2];
commands += c;
}
else if(type == "e")
{
if(parts.count() < 3)
{
usage();
return 1;
}
Command c;
c.type = Command::Reg;
c.name = parts[0];
c.stype = parts[1];
c.port = parts[2].toInt();
if(parts.count() >= 4)
c.domain = parts[3];
if(!txt.isEmpty())
{
QList<QByteArray> strings;
foreach(const QString &str, txt)
strings += str.toUtf8();
QByteArray txtRecord = QDnsSd::createTxtRecord(strings);
if(txtRecord.isEmpty())
{
printf("Error: failed to create TXT record, input too large or invalid\n");
return 1;
}
c.txtRecord = txtRecord;
}
commands += c;
}
else
{
printf("Error: unknown command type '%s'.\n", qPrintable(type));
return 1;
}
}
App app;
app.commands = commands;
QObject::connect(&app, SIGNAL(quit()), &qapp, SLOT(quit()));
QTimer::singleShot(0, &app, SLOT(start()));
qapp.exec();
return 0;
}
<|endoftext|> |
<commit_before>#ifndef MAINSTATE_HPP
#define MAINSTATE_HPP
#include <memory>
#include <SFML/Graphics/RenderTarget.hpp>
#include "gamelib/GameState.hpp"
#include "gamelib/sprite/SpriteSet.hpp"
#include "gamelib/Scene/Scene.hpp"
#include "gamelib/tile/StaticRenderTilemap.hpp"
#include "gamelib/event/SFMLEvent.hpp"
#include "gamelib/utils/DebugGui.hpp"
#include "Player.hpp"
namespace gamelib
{
class Game;
class EventManager;
}
class MainState : public gamelib::GameState
{
public:
MainState();
bool init(gamelib::Game* game);
void quit();
void update(float fps);
void render(sf::RenderTarget& target);
const gamelib::Game& getGame() const;
const gamelib::SpriteSet& getSpriteSet() const;
const gamelib::StaticTilemap<gamelib::SpriteData>& getCollisionMap() const;
private:
static void _eventCallback(MainState* me, gamelib::EventPtr ev);
private:
gamelib::Game* _game;
gamelib::SpriteSet _spriteset;
gamelib::StaticRenderTilemap _map;
Player _player;
};
#endif
<commit_msg>Remove unused include<commit_after>#ifndef MAINSTATE_HPP
#define MAINSTATE_HPP
#include <memory>
#include <SFML/Graphics/RenderTarget.hpp>
#include "gamelib/GameState.hpp"
#include "gamelib/sprite/SpriteSet.hpp"
#include "gamelib/Scene/Scene.hpp"
#include "gamelib/tile/StaticRenderTilemap.hpp"
#include "gamelib/event/SFMLEvent.hpp"
#include "Player.hpp"
namespace gamelib
{
class Game;
class EventManager;
}
class MainState : public gamelib::GameState
{
public:
MainState();
bool init(gamelib::Game* game);
void quit();
void update(float fps);
void render(sf::RenderTarget& target);
const gamelib::Game& getGame() const;
const gamelib::SpriteSet& getSpriteSet() const;
const gamelib::StaticTilemap<gamelib::SpriteData>& getCollisionMap() const;
private:
static void _eventCallback(MainState* me, gamelib::EventPtr ev);
private:
gamelib::Game* _game;
gamelib::SpriteSet _spriteset;
gamelib::StaticRenderTilemap _map;
Player _player;
};
#endif
<|endoftext|> |
<commit_before>#include <engine/ParamQuantity.hpp>
#include <app.hpp>
#include <engine/Engine.hpp>
namespace rack {
namespace engine {
engine::Param *ParamQuantity::getParam() {
assert(module);
return &module->params[paramId];
}
void ParamQuantity::setSmoothValue(float smoothValue) {
if (!module)
return;
smoothValue = math::clampSafe(smoothValue, getMinValue(), getMaxValue());
APP->engine->setSmoothParam(module, paramId, smoothValue);
}
float ParamQuantity::getSmoothValue() {
if (!module)
return 0.f;
return APP->engine->getSmoothParam(module, paramId);
}
void ParamQuantity::setValue(float value) {
if (!module)
return;
value = math::clampSafe(value, getMinValue(), getMaxValue());
APP->engine->setParam(module, paramId, value);
}
float ParamQuantity::getValue() {
if (!module)
return 0.f;
return APP->engine->getParam(module, paramId);
}
float ParamQuantity::getMinValue() {
return minValue;
}
float ParamQuantity::getMaxValue() {
return maxValue;
}
float ParamQuantity::getDefaultValue() {
return defaultValue;
}
float ParamQuantity::getDisplayValue() {
if (!module)
return Quantity::getDisplayValue();
float v = getSmoothValue();
if (displayBase == 0.f) {
// Linear
// v is unchanged
}
else if (displayBase < 0.f) {
// Logarithmic
v = std::log(v) / std::log(-displayBase);
}
else {
// Exponential
v = std::pow(displayBase, v);
}
return v * displayMultiplier + displayOffset;
}
void ParamQuantity::setDisplayValue(float displayValue) {
if (!module)
return;
float v = (displayValue - displayOffset) / displayMultiplier;
if (displayBase == 0.f) {
// Linear
// v is unchanged
}
else if (displayBase < 0.f) {
// Logarithmic
v = std::pow(-displayBase, v);
}
else {
// Exponential
v = std::log(v) / std::log(displayBase);
}
setValue(v);
}
int ParamQuantity::getDisplayPrecision() {
return Quantity::getDisplayPrecision();
}
std::string ParamQuantity::getDisplayValueString() {
return Quantity::getDisplayValueString();
}
void ParamQuantity::setDisplayValueString(std::string s) {
Quantity::setDisplayValueString(s);
}
std::string ParamQuantity::getLabel() {
return label;
}
std::string ParamQuantity::getUnit() {
return unit;
}
} // namespace engine
} // namespace rack
<commit_msg>Allow ParamQuantity::displayMultiplier to be 0.<commit_after>#include <engine/ParamQuantity.hpp>
#include <app.hpp>
#include <engine/Engine.hpp>
namespace rack {
namespace engine {
engine::Param *ParamQuantity::getParam() {
assert(module);
return &module->params[paramId];
}
void ParamQuantity::setSmoothValue(float smoothValue) {
if (!module)
return;
smoothValue = math::clampSafe(smoothValue, getMinValue(), getMaxValue());
APP->engine->setSmoothParam(module, paramId, smoothValue);
}
float ParamQuantity::getSmoothValue() {
if (!module)
return 0.f;
return APP->engine->getSmoothParam(module, paramId);
}
void ParamQuantity::setValue(float value) {
if (!module)
return;
value = math::clampSafe(value, getMinValue(), getMaxValue());
APP->engine->setParam(module, paramId, value);
}
float ParamQuantity::getValue() {
if (!module)
return 0.f;
return APP->engine->getParam(module, paramId);
}
float ParamQuantity::getMinValue() {
return minValue;
}
float ParamQuantity::getMaxValue() {
return maxValue;
}
float ParamQuantity::getDefaultValue() {
return defaultValue;
}
float ParamQuantity::getDisplayValue() {
if (!module)
return Quantity::getDisplayValue();
float v = getSmoothValue();
if (displayBase == 0.f) {
// Linear
// v is unchanged
}
else if (displayBase < 0.f) {
// Logarithmic
v = std::log(v) / std::log(-displayBase);
}
else {
// Exponential
v = std::pow(displayBase, v);
}
return v * displayMultiplier + displayOffset;
}
void ParamQuantity::setDisplayValue(float displayValue) {
if (!module)
return;
float v = displayValue - displayOffset;
if (displayMultiplier == 0.f)
v = 0.f;
else
v /= displayMultiplier;
if (displayBase == 0.f) {
// Linear
// v is unchanged
}
else if (displayBase < 0.f) {
// Logarithmic
v = std::pow(-displayBase, v);
}
else {
// Exponential
v = std::log(v) / std::log(displayBase);
}
setValue(v);
}
int ParamQuantity::getDisplayPrecision() {
return Quantity::getDisplayPrecision();
}
std::string ParamQuantity::getDisplayValueString() {
return Quantity::getDisplayValueString();
}
void ParamQuantity::setDisplayValueString(std::string s) {
Quantity::setDisplayValueString(s);
}
std::string ParamQuantity::getLabel() {
return label;
}
std::string ParamQuantity::getUnit() {
return unit;
}
} // namespace engine
} // namespace rack
<|endoftext|> |
<commit_before>/* This file is part of Ingen.
* Copyright (C) 2007-2009 Dave Robillard <http://drobilla.net>
*
* Ingen is free software; you can redistribute it and/or modify it under the
* terms of the GNU General Public License as published by the Free Software
* Foundation; either version 2 of the License, or (at your option) any later
* version.
*
* Ingen 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 details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include "raul/Maid.hpp"
#include "raul/Path.hpp"
#include "ClientBroadcaster.hpp"
#include "ControlBindings.hpp"
#include "Delete.hpp"
#include "DisconnectAll.hpp"
#include "Driver.hpp"
#include "Engine.hpp"
#include "EngineStore.hpp"
#include "NodeBase.hpp"
#include "PatchImpl.hpp"
#include "PluginImpl.hpp"
#include "PortImpl.hpp"
#include "Request.hpp"
using namespace std;
namespace Ingen {
namespace Events {
using namespace Shared;
Delete::Delete(Engine& engine, SharedPtr<Request> request, FrameTime time, const Raul::Path& path)
: QueuedEvent(engine, request, time, true)
, _path(path)
, _store_iterator(engine.engine_store()->end())
, _driver_port(NULL)
, _patch_node_listnode(NULL)
, _patch_port_listnode(NULL)
, _ports_array(NULL)
, _compiled_patch(NULL)
, _disconnect_event(NULL)
{
assert(request);
assert(request->source());
}
Delete::~Delete()
{
delete _disconnect_event;
}
void
Delete::pre_process()
{
_removed_bindings = _engine.control_bindings()->remove(_path);
_store_iterator = _engine.engine_store()->find(_path);
if (_store_iterator != _engine.engine_store()->end()) {
_node = PtrCast<NodeImpl>(_store_iterator->second);
if (!_node)
_port = PtrCast<PortImpl>(_store_iterator->second);
}
if (_store_iterator != _engine.engine_store()->end()) {
_removed_table = _engine.engine_store()->remove(_store_iterator);
}
if (_node && !_path.is_root()) {
assert(_node->parent_patch());
_patch_node_listnode = _node->parent_patch()->remove_node(_path.symbol());
if (_patch_node_listnode) {
assert(_patch_node_listnode->elem() == _node.get());
_disconnect_event = new DisconnectAll(_engine, _node->parent_patch(), _node.get());
_disconnect_event->pre_process();
if (_node->parent_patch()->enabled()) {
// FIXME: is this called multiple times?
_compiled_patch = _node->parent_patch()->compile();
#ifndef NDEBUG
// Be sure node is removed from process order, so it can be deleted
for (size_t i=0; i < _compiled_patch->size(); ++i) {
assert(_compiled_patch->at(i).node() != _node.get());
// FIXME: check providers/dependants too
}
#endif
}
}
} else if (_port) {
assert(_port->parent_patch());
_patch_port_listnode = _port->parent_patch()->remove_port(_path.symbol());
if (_patch_port_listnode) {
assert(_patch_port_listnode->elem() == _port.get());
_disconnect_event = new DisconnectAll(_engine, _port->parent_patch(), _port.get());
_disconnect_event->pre_process();
if (_port->parent_patch()->enabled()) {
// FIXME: is this called multiple times?
_compiled_patch = _port->parent_patch()->compile();
_ports_array = _port->parent_patch()->build_ports_array();
assert(_ports_array->size() == _port->parent_patch()->num_ports());
}
}
}
QueuedEvent::pre_process();
}
void
Delete::execute(ProcessContext& context)
{
QueuedEvent::execute(context);
if (_patch_node_listnode) {
assert(_node);
if (_disconnect_event)
_disconnect_event->execute(context);
if (_node->parent_patch()->compiled_patch())
_engine.maid()->push(_node->parent_patch()->compiled_patch());
_node->parent_patch()->compiled_patch(_compiled_patch);
} else if (_patch_port_listnode) {
assert(_port);
if (_disconnect_event)
_disconnect_event->execute(context);
if (_port->parent_patch()->compiled_patch())
_engine.maid()->push(_port->parent_patch()->compiled_patch());
_port->parent_patch()->compiled_patch(_compiled_patch);
if (_port->parent_patch()->external_ports())
_engine.maid()->push(_port->parent_patch()->external_ports());
_port->parent_patch()->external_ports(_ports_array);
if ( ! _port->parent_patch()->parent()) {
_driver_port = _engine.driver()->remove_port(_port->path());
}
}
_request->unblock();
}
void
Delete::post_process()
{
_removed_bindings.reset();
if (!_node && !_port) {
if (_path.is_root()) {
_request->respond_error("You can not destroy the root patch (/)");
} else {
string msg = string("Could not find object ") + _path.str() + " to destroy";
_request->respond_error(msg);
}
}
if (_patch_node_listnode) {
assert(_node);
_node->deactivate();
_request->respond_ok();
_engine.broadcaster()->bundle_begin();
if (_disconnect_event)
_disconnect_event->post_process();
_engine.broadcaster()->del(_path);
_engine.broadcaster()->bundle_end();
_engine.maid()->push(_patch_node_listnode);
} else if (_patch_port_listnode) {
assert(_port);
_request->respond_ok();
_engine.broadcaster()->bundle_begin();
if (_disconnect_event)
_disconnect_event->post_process();
_engine.broadcaster()->del(_path);
_engine.broadcaster()->bundle_end();
_engine.maid()->push(_patch_port_listnode);
} else {
_request->respond_error("Unable to destroy object");
}
if (_driver_port) {
_driver_port->elem()->destroy();
_engine.maid()->push(_driver_port);
}
}
} // namespace Ingen
} // namespace Events
<commit_msg>Refuse to delete /control_in or /control_out (fix crashes e.g. select-all + delete).<commit_after>/* This file is part of Ingen.
* Copyright (C) 2007-2009 Dave Robillard <http://drobilla.net>
*
* Ingen is free software; you can redistribute it and/or modify it under the
* terms of the GNU General Public License as published by the Free Software
* Foundation; either version 2 of the License, or (at your option) any later
* version.
*
* Ingen 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 details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include "raul/Maid.hpp"
#include "raul/Path.hpp"
#include "ClientBroadcaster.hpp"
#include "ControlBindings.hpp"
#include "Delete.hpp"
#include "DisconnectAll.hpp"
#include "Driver.hpp"
#include "Engine.hpp"
#include "EngineStore.hpp"
#include "NodeBase.hpp"
#include "PatchImpl.hpp"
#include "PluginImpl.hpp"
#include "PortImpl.hpp"
#include "Request.hpp"
using namespace std;
namespace Ingen {
namespace Events {
using namespace Shared;
Delete::Delete(Engine& engine, SharedPtr<Request> request, FrameTime time, const Raul::Path& path)
: QueuedEvent(engine, request, time, true)
, _path(path)
, _store_iterator(engine.engine_store()->end())
, _driver_port(NULL)
, _patch_node_listnode(NULL)
, _patch_port_listnode(NULL)
, _ports_array(NULL)
, _compiled_patch(NULL)
, _disconnect_event(NULL)
{
assert(request);
assert(request->source());
}
Delete::~Delete()
{
delete _disconnect_event;
}
void
Delete::pre_process()
{
if (_path.is_root() || _path == "path:/control_in" || _path == "path:/control_out") {
QueuedEvent::pre_process();
return;
}
_removed_bindings = _engine.control_bindings()->remove(_path);
_store_iterator = _engine.engine_store()->find(_path);
if (_store_iterator != _engine.engine_store()->end()) {
_node = PtrCast<NodeImpl>(_store_iterator->second);
if (!_node)
_port = PtrCast<PortImpl>(_store_iterator->second);
}
if (_store_iterator != _engine.engine_store()->end()) {
_removed_table = _engine.engine_store()->remove(_store_iterator);
}
if (_node && !_path.is_root()) {
assert(_node->parent_patch());
_patch_node_listnode = _node->parent_patch()->remove_node(_path.symbol());
if (_patch_node_listnode) {
assert(_patch_node_listnode->elem() == _node.get());
_disconnect_event = new DisconnectAll(_engine, _node->parent_patch(), _node.get());
_disconnect_event->pre_process();
if (_node->parent_patch()->enabled()) {
// FIXME: is this called multiple times?
_compiled_patch = _node->parent_patch()->compile();
#ifndef NDEBUG
// Be sure node is removed from process order, so it can be deleted
for (size_t i=0; i < _compiled_patch->size(); ++i) {
assert(_compiled_patch->at(i).node() != _node.get());
// FIXME: check providers/dependants too
}
#endif
}
}
} else if (_port) {
assert(_port->parent_patch());
_patch_port_listnode = _port->parent_patch()->remove_port(_path.symbol());
if (_patch_port_listnode) {
assert(_patch_port_listnode->elem() == _port.get());
_disconnect_event = new DisconnectAll(_engine, _port->parent_patch(), _port.get());
_disconnect_event->pre_process();
if (_port->parent_patch()->enabled()) {
// FIXME: is this called multiple times?
_compiled_patch = _port->parent_patch()->compile();
_ports_array = _port->parent_patch()->build_ports_array();
assert(_ports_array->size() == _port->parent_patch()->num_ports());
}
}
}
QueuedEvent::pre_process();
}
void
Delete::execute(ProcessContext& context)
{
QueuedEvent::execute(context);
if (_patch_node_listnode) {
assert(_node);
if (_disconnect_event)
_disconnect_event->execute(context);
if (_node->parent_patch()->compiled_patch())
_engine.maid()->push(_node->parent_patch()->compiled_patch());
_node->parent_patch()->compiled_patch(_compiled_patch);
} else if (_patch_port_listnode) {
assert(_port);
if (_disconnect_event)
_disconnect_event->execute(context);
if (_port->parent_patch()->compiled_patch())
_engine.maid()->push(_port->parent_patch()->compiled_patch());
_port->parent_patch()->compiled_patch(_compiled_patch);
if (_port->parent_patch()->external_ports())
_engine.maid()->push(_port->parent_patch()->external_ports());
_port->parent_patch()->external_ports(_ports_array);
if ( ! _port->parent_patch()->parent()) {
_driver_port = _engine.driver()->remove_port(_port->path());
}
}
_request->unblock();
}
void
Delete::post_process()
{
_removed_bindings.reset();
if (_path.is_root() || _path == "path:/control_in" || _path == "path:/control_out") {
_request->respond_error(_path.chop_scheme() + " can not be deleted");
} else if (!_node && !_port) {
string msg = string("Could not find object ") + _path.chop_scheme() + " to delete";
_request->respond_error(msg);
} else if (_patch_node_listnode) {
assert(_node);
_node->deactivate();
_request->respond_ok();
_engine.broadcaster()->bundle_begin();
if (_disconnect_event)
_disconnect_event->post_process();
_engine.broadcaster()->del(_path);
_engine.broadcaster()->bundle_end();
_engine.maid()->push(_patch_node_listnode);
} else if (_patch_port_listnode) {
assert(_port);
_request->respond_ok();
_engine.broadcaster()->bundle_begin();
if (_disconnect_event)
_disconnect_event->post_process();
_engine.broadcaster()->del(_path);
_engine.broadcaster()->bundle_end();
_engine.maid()->push(_patch_port_listnode);
} else {
_request->respond_error("Unable to delete object " + _path.chop_scheme());
}
if (_driver_port) {
_driver_port->elem()->destroy();
_engine.maid()->push(_driver_port);
}
}
} // namespace Ingen
} // namespace Events
<|endoftext|> |
<commit_before>#include <glog/logging.h>
#include <util/util.h>
#include <mailer_pool.h>
using namespace std::placeholders;
namespace {
struct mailer_extra {
const std::string server;
const std::string from;
const std::vector<std::string> to;
};
typedef std::pair<std::vector<char>, size_t> payload_t;
size_t payload_source(void *ptr, size_t size, size_t nmemb, void *userp)
{
if((size == 0) || (nmemb == 0) || ((size * nmemb) < 1)) {
return 0;
}
auto payload_data = static_cast<payload_t*>(userp);
size_t copied = payload_data->second;
size_t left = payload_data->first.size() - copied;
size_t to_copy = std::min(size * nmemb, left);
if (to_copy > 0) {
memcpy(ptr, static_cast<void*>(&payload_data->first[copied]), to_copy);
payload_data->second += to_copy;
return to_copy;
} else {
return 0;
}
}
std::vector<char> payload_text(const mailer_extra extra, const Event & e) {
std::string to = "unknown";
if (!extra.to.empty()) {
to = extra.to[0];
}
std::string subject = e.host() + " " + e.service() + " is " + e.state()
+ e.metric_to_str();
std::string payload = "To: " + to + "\r\n" +
"From: " + extra.from + "\r\n" +
"Subject: " + subject + "\r\n" +
"\r\n" +
e.json_str();
return std::vector<char>(payload.begin(), payload.end());
}
}
mailer_pool::mailer_pool(const size_t thread_num, const bool enable_debug)
:
curl_pool_(
thread_num,
std::bind(&mailer_pool::curl_event, this, _1, _2, _3)
),
enable_debug_(enable_debug)
{
}
void mailer_pool::push_event(const std::string server, const std::string from,
const std::vector<std::string> to,
const Event & event)
{
VLOG(3) << "push_event() server: " << server << " from: " << from;
mailer_extra extra = {server, from, to};
curl_pool_.push_event(event, extra);
}
void mailer_pool::curl_event(const queued_event_t queued_event,
const std::shared_ptr<CURL> easy,
std::function<void()> & clean_fn)
{
const auto extra = boost::any_cast<mailer_extra>(queued_event.extra);
const auto & e = queued_event.event;
std::shared_ptr<std::string> server(
new std::string("smtp://" + extra.server));
std::shared_ptr<std::string> from(new std::string(extra.from));
struct curl_slist *recipients = NULL;
for (const auto & to : extra.to) {
recipients = curl_slist_append(recipients, to.c_str());
}
auto payload = std::make_shared<payload_t>(
payload_t({payload_text(extra, e), 0}));
curl_easy_setopt(easy.get(), CURLOPT_URL, server->c_str());
curl_easy_setopt(easy.get(), CURLOPT_MAIL_FROM, from->c_str());
curl_easy_setopt(easy.get(), CURLOPT_MAIL_RCPT, recipients);
curl_easy_setopt(easy.get(), CURLOPT_UPLOAD, 1L);
curl_easy_setopt(easy.get(), CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4);
curl_easy_setopt(easy.get(), CURLOPT_READFUNCTION, payload_source);
curl_easy_setopt(easy.get(), CURLOPT_READDATA, payload.get());
curl_easy_setopt(easy.get(), CURLOPT_VERBOSE, enable_debug_);
clean_fn = [=]()
{
UNUSED_VAR(server);
UNUSED_VAR(from);
UNUSED_VAR(payload);
if (recipients) {
curl_slist_free_all(recipients);
}
};
}
void mailer_pool::stop() {
VLOG(3) << "stop()";
curl_pool_.stop();
}
<commit_msg>Improve email subject<commit_after>#include <glog/logging.h>
#include <util/util.h>
#include <mailer_pool.h>
using namespace std::placeholders;
namespace {
struct mailer_extra {
const std::string server;
const std::string from;
const std::vector<std::string> to;
};
typedef std::pair<std::vector<char>, size_t> payload_t;
size_t payload_source(void *ptr, size_t size, size_t nmemb, void *userp)
{
if((size == 0) || (nmemb == 0) || ((size * nmemb) < 1)) {
return 0;
}
auto payload_data = static_cast<payload_t*>(userp);
size_t copied = payload_data->second;
size_t left = payload_data->first.size() - copied;
size_t to_copy = std::min(size * nmemb, left);
if (to_copy > 0) {
memcpy(ptr, static_cast<void*>(&payload_data->first[copied]), to_copy);
payload_data->second += to_copy;
return to_copy;
} else {
return 0;
}
}
std::vector<char> payload_text(const mailer_extra extra, const Event & e) {
std::string to = "unknown";
if (!extra.to.empty()) {
to = extra.to[0];
}
std::string subject = e.host() + " " + e.service() + " is " + e.state();
if (e.has_metric()) {
subject += " (" + e.metric_to_str() + ")";
}
std::string payload = "To: " + to + "\r\n" +
"From: " + extra.from + "\r\n" +
"Subject: " + subject + "\r\n" +
"\r\n" +
e.json_str();
return std::vector<char>(payload.begin(), payload.end());
}
}
mailer_pool::mailer_pool(const size_t thread_num, const bool enable_debug)
:
curl_pool_(
thread_num,
std::bind(&mailer_pool::curl_event, this, _1, _2, _3)
),
enable_debug_(enable_debug)
{
}
void mailer_pool::push_event(const std::string server, const std::string from,
const std::vector<std::string> to,
const Event & event)
{
VLOG(3) << "push_event() server: " << server << " from: " << from;
mailer_extra extra = {server, from, to};
curl_pool_.push_event(event, extra);
}
void mailer_pool::curl_event(const queued_event_t queued_event,
const std::shared_ptr<CURL> easy,
std::function<void()> & clean_fn)
{
const auto extra = boost::any_cast<mailer_extra>(queued_event.extra);
const auto & e = queued_event.event;
std::shared_ptr<std::string> server(
new std::string("smtp://" + extra.server));
std::shared_ptr<std::string> from(new std::string(extra.from));
struct curl_slist *recipients = NULL;
for (const auto & to : extra.to) {
recipients = curl_slist_append(recipients, to.c_str());
}
auto payload = std::make_shared<payload_t>(
payload_t({payload_text(extra, e), 0}));
curl_easy_setopt(easy.get(), CURLOPT_URL, server->c_str());
curl_easy_setopt(easy.get(), CURLOPT_MAIL_FROM, from->c_str());
curl_easy_setopt(easy.get(), CURLOPT_MAIL_RCPT, recipients);
curl_easy_setopt(easy.get(), CURLOPT_UPLOAD, 1L);
curl_easy_setopt(easy.get(), CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4);
curl_easy_setopt(easy.get(), CURLOPT_READFUNCTION, payload_source);
curl_easy_setopt(easy.get(), CURLOPT_READDATA, payload.get());
curl_easy_setopt(easy.get(), CURLOPT_VERBOSE, enable_debug_);
clean_fn = [=]()
{
UNUSED_VAR(server);
UNUSED_VAR(from);
UNUSED_VAR(payload);
if (recipients) {
curl_slist_free_all(recipients);
}
};
}
void mailer_pool::stop() {
VLOG(3) << "stop()";
curl_pool_.stop();
}
<|endoftext|> |
<commit_before>// Copyright (C) 2012-2015 Leap Motion, Inc. All rights reserved.
#include "stdafx.h"
#include "ProtobufUtil.hpp"
#include "Archive.h"
#include "Descriptor.h"
#include <iomanip>
#include <sstream>
using namespace leap;
using leap::internal::protobuf::WireType;
WireType leap::internal::protobuf::ToWireType(serial_atom atom) {
switch (atom) {
case serial_atom::boolean:
case serial_atom::i8:
case serial_atom::ui8:
case serial_atom::i16:
case serial_atom::ui16:
case serial_atom::i32:
case serial_atom::ui32:
case serial_atom::i64:
case serial_atom::ui64:
return WireType::Varint;
case serial_atom::f32:
return WireType::DoubleWord;
case serial_atom::f64:
return WireType::QuadWord;
case serial_atom::reference:
case serial_atom::array:
return WireType::LenDelimit;
case serial_atom::string:
return WireType::LenDelimit;
case serial_atom::map:
break;
case serial_atom::descriptor:
return WireType::LenDelimit;
case serial_atom::finalized_descriptor:
break;
case serial_atom::ignored:
throw std::invalid_argument("serial_atom::ignored is a utility type and should not be used in ordinary operations");
}
throw std::invalid_argument("Attempted to find a wire type for an unrecognized serial atom type");
}
const char* leap::internal::protobuf::ToProtobufField(serial_atom atom) {
switch (atom) {
case serial_atom::boolean:
return "bool";
case serial_atom::i8:
case serial_atom::i16:
case serial_atom::i32:
return "sint32";
case serial_atom::i64:
return "sint64";
case serial_atom::ui8:
case serial_atom::ui16:
case serial_atom::ui32:
return "int32";
case serial_atom::ui64:
return "int64";
case serial_atom::f32:
return "float";
case serial_atom::f64:
case serial_atom::f80:
return "double";
case serial_atom::reference:
break;
case serial_atom::array:
case serial_atom::string:
return "string";
case serial_atom::map:
break;
case serial_atom::descriptor:
case serial_atom::finalized_descriptor:
break;
case serial_atom::ignored:
throw std::invalid_argument("Invalid serial atom type");
}
throw std::invalid_argument("Attempted to obtain the protobuf field of a non-value type");
}
static std::string FormatError(const descriptor& descriptor) {
std::stringstream ss;
ss << "The OArchiveProtobuf requires that all entries have identifiers" << std::endl
<< "Fields at the following offsets do not have identifiers:" << std::endl;
for (const auto& field_descriptor : descriptor.field_descriptors)
ss << "[ " << std::left << std::setw(8) << ToString(field_descriptor.serializer.type()) << " ] @+" << field_descriptor.offset << std::endl;
return ss.str();
}
internal::protobuf::serialization_error::serialization_error(std::string&& err) :
::leap::serialization_error(std::move(err))
{}
internal::protobuf::serialization_error::serialization_error(const descriptor& descriptor) :
::leap::serialization_error(FormatError(descriptor))
{}
<commit_msg>Add missing `f80` case statement<commit_after>// Copyright (C) 2012-2015 Leap Motion, Inc. All rights reserved.
#include "stdafx.h"
#include "ProtobufUtil.hpp"
#include "Archive.h"
#include "Descriptor.h"
#include <iomanip>
#include <sstream>
using namespace leap;
using leap::internal::protobuf::WireType;
WireType leap::internal::protobuf::ToWireType(serial_atom atom) {
switch (atom) {
case serial_atom::boolean:
case serial_atom::i8:
case serial_atom::ui8:
case serial_atom::i16:
case serial_atom::ui16:
case serial_atom::i32:
case serial_atom::ui32:
case serial_atom::i64:
case serial_atom::ui64:
return WireType::Varint;
case serial_atom::f32:
return WireType::DoubleWord;
case serial_atom::f64:
case serial_atom::f80:
return WireType::QuadWord;
case serial_atom::reference:
case serial_atom::array:
return WireType::LenDelimit;
case serial_atom::string:
return WireType::LenDelimit;
case serial_atom::map:
break;
case serial_atom::descriptor:
return WireType::LenDelimit;
case serial_atom::finalized_descriptor:
break;
case serial_atom::ignored:
throw std::invalid_argument("serial_atom::ignored is a utility type and should not be used in ordinary operations");
}
throw std::invalid_argument("Attempted to find a wire type for an unrecognized serial atom type");
}
const char* leap::internal::protobuf::ToProtobufField(serial_atom atom) {
switch (atom) {
case serial_atom::boolean:
return "bool";
case serial_atom::i8:
case serial_atom::i16:
case serial_atom::i32:
return "sint32";
case serial_atom::i64:
return "sint64";
case serial_atom::ui8:
case serial_atom::ui16:
case serial_atom::ui32:
return "int32";
case serial_atom::ui64:
return "int64";
case serial_atom::f32:
return "float";
case serial_atom::f64:
case serial_atom::f80:
return "double";
case serial_atom::reference:
break;
case serial_atom::array:
case serial_atom::string:
return "string";
case serial_atom::map:
break;
case serial_atom::descriptor:
case serial_atom::finalized_descriptor:
break;
case serial_atom::ignored:
throw std::invalid_argument("Invalid serial atom type");
}
throw std::invalid_argument("Attempted to obtain the protobuf field of a non-value type");
}
static std::string FormatError(const descriptor& descriptor) {
std::stringstream ss;
ss << "The OArchiveProtobuf requires that all entries have identifiers" << std::endl
<< "Fields at the following offsets do not have identifiers:" << std::endl;
for (const auto& field_descriptor : descriptor.field_descriptors)
ss << "[ " << std::left << std::setw(8) << ToString(field_descriptor.serializer.type()) << " ] @+" << field_descriptor.offset << std::endl;
return ss.str();
}
internal::protobuf::serialization_error::serialization_error(std::string&& err) :
::leap::serialization_error(std::move(err))
{}
internal::protobuf::serialization_error::serialization_error(const descriptor& descriptor) :
::leap::serialization_error(FormatError(descriptor))
{}
<|endoftext|> |
<commit_before>// The libMesh Finite Element Library.
// Copyright (C) 2002-2016 Benjamin S. Kirk, John W. Peterson, Roy H. Stogner
// 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
// C++ inlcludes
// Local includes
#include "libmesh/fe.h"
#include "libmesh/elem.h"
#include "libmesh/utility.h"
namespace
{
using namespace libMesh;
// Compute the static coefficients for an element
void hermite_compute_coefs(const Elem * elem, Real & d1xd1x, Real & d2xd2x)
{
const Order mapping_order (elem->default_order());
const ElemType mapping_elem_type (elem->type());
const int n_mapping_shape_functions =
FE<1,LAGRANGE>::n_shape_functions(mapping_elem_type,
mapping_order);
// Degrees of freedom are at vertices and edge midpoints
std::vector<Point> dofpt;
dofpt.push_back(Point(-1));
dofpt.push_back(Point(1));
// Mapping functions - first derivatives at each dofpt
std::vector<Real> dxdxi(2);
std::vector<Real> dxidx(2);
for (int p = 0; p != 2; ++p)
{
dxdxi[p] = 0;
for (int i = 0; i != n_mapping_shape_functions; ++i)
{
const Real ddxi = FE<1,LAGRANGE>::shape_deriv
(mapping_elem_type, mapping_order, i, 0, dofpt[p]);
dxdxi[p] += elem->point(i)(0) * ddxi;
}
}
// Calculate derivative scaling factors
d1xd1x = dxdxi[0];
d2xd2x = dxdxi[1];
}
} // end anonymous namespace
namespace libMesh
{
template<>
Real FEHermite<1>::hermite_raw_shape_second_deriv (const unsigned int i, const Real xi)
{
using Utility::pow;
switch (i)
{
case 0:
return 1.5 * xi;
case 1:
return -1.5 * xi;
case 2:
return 0.5 * (-1. + 3.*xi);
case 3:
return 0.5 * (1. + 3.*xi);
case 4:
return (8.*xi*xi + 4.*(xi*xi-1.))/24.;
case 5:
return (8.*xi*xi*xi + 12.*xi*(xi*xi-1.))/120.;
// case 6:
// return (8.*pow<4>(xi) + 20.*xi*xi*(xi*xi-1.) +
// 2.*(xi*xi-1)*(xi*xi-1))/720.;
default:
Real denominator = 720., xipower = 1.;
for (unsigned n=6; n != i; ++n)
{
xipower *= xi;
denominator *= (n+1);
}
return (8.*pow<4>(xi)*xipower +
(8.*(i-4)+4.)*xi*xi*xipower*(xi*xi-1.) +
(i-4)*(i-5)*xipower*(xi*xi-1.)*(xi*xi-1.))/denominator;
}
libmesh_error_msg("We'll never get here!");
return 0.;
}
template<>
Real FEHermite<1>::hermite_raw_shape_deriv(const unsigned int i, const Real xi)
{
switch (i)
{
case 0:
return 0.75 * (-1. + xi*xi);
case 1:
return 0.75 * (1. - xi*xi);
case 2:
return 0.25 * (-1. - 2.*xi + 3.*xi*xi);
case 3:
return 0.25 * (-1. + 2.*xi + 3.*xi*xi);
case 4:
return 4.*xi * (xi*xi-1.)/24.;
case 5:
return (4*xi*xi*(xi*xi-1.) + (xi*xi-1.)*(xi*xi-1.))/120.;
// case 6:
// return (4*xi*xi*xi*(xi*xi-1.) + 2*xi*(xi*xi-1.)*(xi*xi-1.))/720.;
default:
Real denominator = 720., xipower = 1.;
for (unsigned n=6; n != i; ++n)
{
xipower *= xi;
denominator *= (n+1);
}
return (4*xi*xi*xi*xipower*(xi*xi-1.) +
(i-4)*xi*xipower*(xi*xi-1.)*(xi*xi-1.))/denominator;
}
libmesh_error_msg("We'll never get here!");
return 0.;
}
template<>
Real FEHermite<1>::hermite_raw_shape(const unsigned int i, const Real xi)
{
switch (i)
{
case 0:
return 0.25 * (2. - 3.*xi + xi*xi*xi);
case 1:
return 0.25 * (2. + 3.*xi - xi*xi*xi);
case 2:
return 0.25 * (1. - xi - xi*xi + xi*xi*xi);
case 3:
return 0.25 * (-1. - xi + xi*xi + xi*xi*xi);
// All high order terms have the form x^(p-4)(x^2-1)^2/p!
case 4:
return (xi*xi-1.) * (xi*xi-1.)/24.;
case 5:
return xi * (xi*xi-1.) * (xi*xi-1.)/120.;
// case 6:
// return xi*xi * (xi*xi-1.) * (xi*xi-1.)/720.;
default:
Real denominator = 720., xipower = 1.;
for (unsigned n=6; n != i; ++n)
{
xipower *= xi;
denominator *= (n+1);
}
return (xi*xi*xipower*(xi*xi-1.)*(xi*xi-1.))/denominator;
}
libmesh_error_msg("We'll never get here!");
return 0.;
}
template <>
Real FE<1,HERMITE>::shape(const ElemType,
const Order,
const unsigned int,
const Point &)
{
libmesh_error_msg("Hermite elements require the real element \nto construct gradient-based degrees of freedom.");
return 0.;
}
template <>
Real FE<1,HERMITE>::shape(const Elem * elem,
const Order order,
const unsigned int i,
const Point & p)
{
libmesh_assert(elem);
// Coefficient naming: d(1)d(2n) is the coefficient of the
// global shape function corresponding to value 1 in terms of the
// local shape function corresponding to normal derivative 2
Real d1xd1x, d2xd2x;
hermite_compute_coefs(elem, d1xd1x, d2xd2x);
const ElemType type = elem->type();
const Order totalorder = static_cast<Order>(order + elem->p_level());
switch (totalorder)
{
// Hermite cubic shape functions
case THIRD:
{
switch (type)
{
// C1 functions on the C1 cubic edge
case EDGE2:
case EDGE3:
{
libmesh_assert_less (i, 4);
switch (i)
{
case 0:
return FEHermite<1>::hermite_raw_shape(0, p(0));
case 1:
return d1xd1x * FEHermite<1>::hermite_raw_shape(2, p(0));
case 2:
return FEHermite<1>::hermite_raw_shape(1, p(0));
case 3:
return d2xd2x * FEHermite<1>::hermite_raw_shape(3, p(0));
default:
return FEHermite<1>::hermite_raw_shape(i, p(0));
}
}
default:
libmesh_error_msg("ERROR: Unsupported element type = " << type);
}
}
// by default throw an error
default:
libmesh_error_msg("ERROR: Unsupported polynomial order = " << totalorder);
}
libmesh_error_msg("We'll never get here!");
return 0.;
}
template <>
Real FE<1,HERMITE>::shape_deriv(const ElemType,
const Order,
const unsigned int,
const unsigned int,
const Point &)
{
libmesh_error_msg("Hermite elements require the real element \nto construct gradient-based degrees of freedom.");
return 0.;
}
template <>
Real FE<1,HERMITE>::shape_deriv(const Elem * elem,
const Order order,
const unsigned int i,
const unsigned int,
const Point & p)
{
libmesh_assert(elem);
// Coefficient naming: d(1)d(2n) is the coefficient of the
// global shape function corresponding to value 1 in terms of the
// local shape function corresponding to normal derivative 2
Real d1xd1x, d2xd2x;
hermite_compute_coefs(elem, d1xd1x, d2xd2x);
const ElemType type = elem->type();
const Order totalorder = static_cast<Order>(order + elem->p_level());
switch (totalorder)
{
// Hermite cubic shape functions
case THIRD:
{
switch (type)
{
// C1 functions on the C1 cubic edge
case EDGE2:
case EDGE3:
{
switch (i)
{
case 0:
return FEHermite<1>::hermite_raw_shape_deriv(0, p(0));
case 1:
return d1xd1x * FEHermite<1>::hermite_raw_shape_deriv(2, p(0));
case 2:
return FEHermite<1>::hermite_raw_shape_deriv(1, p(0));
case 3:
return d2xd2x * FEHermite<1>::hermite_raw_shape_deriv(3, p(0));
default:
return FEHermite<1>::hermite_raw_shape_deriv(i, p(0));
}
}
default:
libmesh_error_msg("ERROR: Unsupported element type = " << type);
}
}
// by default throw an error
default:
libmesh_error_msg("ERROR: Unsupported polynomial order = " << totalorder);
}
libmesh_error_msg("We'll never get here!");
return 0.;
}
template <>
Real FE<1,HERMITE>::shape_second_deriv(const Elem * elem,
const Order order,
const unsigned int i,
const unsigned int,
const Point & p)
{
libmesh_assert(elem);
// Coefficient naming: d(1)d(2n) is the coefficient of the
// global shape function corresponding to value 1 in terms of the
// local shape function corresponding to normal derivative 2
Real d1xd1x, d2xd2x;
hermite_compute_coefs(elem, d1xd1x, d2xd2x);
const ElemType type = elem->type();
const Order totalorder = static_cast<Order>(order + elem->p_level());
switch (totalorder)
{
// Hermite cubic shape functions
case THIRD:
{
switch (type)
{
// C1 functions on the C1 cubic edge
case EDGE2:
case EDGE3:
{
switch (i)
{
case 0:
return FEHermite<1>::hermite_raw_shape_second_deriv(0, p(0));
case 1:
return d1xd1x * FEHermite<1>::hermite_raw_shape_second_deriv(2, p(0));
case 2:
return FEHermite<1>::hermite_raw_shape_second_deriv(1, p(0));
case 3:
return d2xd2x * FEHermite<1>::hermite_raw_shape_second_deriv(3, p(0));
default:
return FEHermite<1>::hermite_raw_shape_second_deriv(i, p(0));
}
}
default:
libmesh_error_msg("ERROR: Unsupported element type = " << type);
}
}
// by default throw an error
default:
libmesh_error_msg("ERROR: Unsupported polynomial order = " << totalorder);
}
libmesh_error_msg("We'll never get here!");
return 0.;
}
} // namespace libMesh
<commit_msg>Enable 1D HERMITE elements of arbitrary p<commit_after>// The libMesh Finite Element Library.
// Copyright (C) 2002-2016 Benjamin S. Kirk, John W. Peterson, Roy H. Stogner
// 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
// C++ inlcludes
// Local includes
#include "libmesh/fe.h"
#include "libmesh/elem.h"
#include "libmesh/utility.h"
namespace
{
using namespace libMesh;
// Compute the static coefficients for an element
void hermite_compute_coefs(const Elem * elem, Real & d1xd1x, Real & d2xd2x)
{
const Order mapping_order (elem->default_order());
const ElemType mapping_elem_type (elem->type());
const int n_mapping_shape_functions =
FE<1,LAGRANGE>::n_shape_functions(mapping_elem_type,
mapping_order);
// Degrees of freedom are at vertices and edge midpoints
std::vector<Point> dofpt;
dofpt.push_back(Point(-1));
dofpt.push_back(Point(1));
// Mapping functions - first derivatives at each dofpt
std::vector<Real> dxdxi(2);
std::vector<Real> dxidx(2);
for (int p = 0; p != 2; ++p)
{
dxdxi[p] = 0;
for (int i = 0; i != n_mapping_shape_functions; ++i)
{
const Real ddxi = FE<1,LAGRANGE>::shape_deriv
(mapping_elem_type, mapping_order, i, 0, dofpt[p]);
dxdxi[p] += elem->point(i)(0) * ddxi;
}
}
// Calculate derivative scaling factors
d1xd1x = dxdxi[0];
d2xd2x = dxdxi[1];
}
} // end anonymous namespace
namespace libMesh
{
template<>
Real FEHermite<1>::hermite_raw_shape_second_deriv (const unsigned int i, const Real xi)
{
using Utility::pow;
switch (i)
{
case 0:
return 1.5 * xi;
case 1:
return -1.5 * xi;
case 2:
return 0.5 * (-1. + 3.*xi);
case 3:
return 0.5 * (1. + 3.*xi);
case 4:
return (8.*xi*xi + 4.*(xi*xi-1.))/24.;
case 5:
return (8.*xi*xi*xi + 12.*xi*(xi*xi-1.))/120.;
// case 6:
// return (8.*pow<4>(xi) + 20.*xi*xi*(xi*xi-1.) +
// 2.*(xi*xi-1)*(xi*xi-1))/720.;
default:
Real denominator = 720., xipower = 1.;
for (unsigned n=6; n != i; ++n)
{
xipower *= xi;
denominator *= (n+1);
}
return (8.*pow<4>(xi)*xipower +
(8.*(i-4)+4.)*xi*xi*xipower*(xi*xi-1.) +
(i-4)*(i-5)*xipower*(xi*xi-1.)*(xi*xi-1.))/denominator;
}
libmesh_error_msg("We'll never get here!");
return 0.;
}
template<>
Real FEHermite<1>::hermite_raw_shape_deriv(const unsigned int i, const Real xi)
{
switch (i)
{
case 0:
return 0.75 * (-1. + xi*xi);
case 1:
return 0.75 * (1. - xi*xi);
case 2:
return 0.25 * (-1. - 2.*xi + 3.*xi*xi);
case 3:
return 0.25 * (-1. + 2.*xi + 3.*xi*xi);
case 4:
return 4.*xi * (xi*xi-1.)/24.;
case 5:
return (4*xi*xi*(xi*xi-1.) + (xi*xi-1.)*(xi*xi-1.))/120.;
// case 6:
// return (4*xi*xi*xi*(xi*xi-1.) + 2*xi*(xi*xi-1.)*(xi*xi-1.))/720.;
default:
Real denominator = 720., xipower = 1.;
for (unsigned n=6; n != i; ++n)
{
xipower *= xi;
denominator *= (n+1);
}
return (4*xi*xi*xi*xipower*(xi*xi-1.) +
(i-4)*xi*xipower*(xi*xi-1.)*(xi*xi-1.))/denominator;
}
libmesh_error_msg("We'll never get here!");
return 0.;
}
template<>
Real FEHermite<1>::hermite_raw_shape(const unsigned int i, const Real xi)
{
switch (i)
{
case 0:
return 0.25 * (2. - 3.*xi + xi*xi*xi);
case 1:
return 0.25 * (2. + 3.*xi - xi*xi*xi);
case 2:
return 0.25 * (1. - xi - xi*xi + xi*xi*xi);
case 3:
return 0.25 * (-1. - xi + xi*xi + xi*xi*xi);
// All high order terms have the form x^(p-4)(x^2-1)^2/p!
case 4:
return (xi*xi-1.) * (xi*xi-1.)/24.;
case 5:
return xi * (xi*xi-1.) * (xi*xi-1.)/120.;
// case 6:
// return xi*xi * (xi*xi-1.) * (xi*xi-1.)/720.;
default:
Real denominator = 720., xipower = 1.;
for (unsigned n=6; n != i; ++n)
{
xipower *= xi;
denominator *= (n+1);
}
return (xi*xi*xipower*(xi*xi-1.)*(xi*xi-1.))/denominator;
}
libmesh_error_msg("We'll never get here!");
return 0.;
}
template <>
Real FE<1,HERMITE>::shape(const ElemType,
const Order,
const unsigned int,
const Point &)
{
libmesh_error_msg("Hermite elements require the real element \nto construct gradient-based degrees of freedom.");
return 0.;
}
template <>
Real FE<1,HERMITE>::shape(const Elem * elem,
const Order order,
const unsigned int i,
const Point & p)
{
libmesh_assert(elem);
// Coefficient naming: d(1)d(2n) is the coefficient of the
// global shape function corresponding to value 1 in terms of the
// local shape function corresponding to normal derivative 2
Real d1xd1x, d2xd2x;
hermite_compute_coefs(elem, d1xd1x, d2xd2x);
const ElemType type = elem->type();
#ifndef NDEBUG
const unsigned int totalorder = order + elem->p_level();
#endif
switch (type)
{
// C1 functions on the C1 cubic edge
case EDGE2:
case EDGE3:
{
libmesh_assert_less (i, totalorder+1);
switch (i)
{
case 0:
return FEHermite<1>::hermite_raw_shape(0, p(0));
case 1:
return d1xd1x * FEHermite<1>::hermite_raw_shape(2, p(0));
case 2:
return FEHermite<1>::hermite_raw_shape(1, p(0));
case 3:
return d2xd2x * FEHermite<1>::hermite_raw_shape(3, p(0));
default:
return FEHermite<1>::hermite_raw_shape(i, p(0));
}
}
default:
libmesh_error_msg("ERROR: Unsupported element type = " << type);
}
libmesh_error_msg("We'll never get here!");
return 0.;
}
template <>
Real FE<1,HERMITE>::shape_deriv(const ElemType,
const Order,
const unsigned int,
const unsigned int,
const Point &)
{
libmesh_error_msg("Hermite elements require the real element \nto construct gradient-based degrees of freedom.");
return 0.;
}
template <>
Real FE<1,HERMITE>::shape_deriv(const Elem * elem,
const Order order,
const unsigned int i,
const unsigned int,
const Point & p)
{
libmesh_assert(elem);
// Coefficient naming: d(1)d(2n) is the coefficient of the
// global shape function corresponding to value 1 in terms of the
// local shape function corresponding to normal derivative 2
Real d1xd1x, d2xd2x;
hermite_compute_coefs(elem, d1xd1x, d2xd2x);
const ElemType type = elem->type();
#ifndef NDEBUG
const unsigned int totalorder = order + elem->p_level();
#endif
switch (type)
{
// C1 functions on the C1 cubic edge
case EDGE2:
case EDGE3:
{
libmesh_assert_less (i, totalorder+1);
switch (i)
{
case 0:
return FEHermite<1>::hermite_raw_shape_deriv(0, p(0));
case 1:
return d1xd1x * FEHermite<1>::hermite_raw_shape_deriv(2, p(0));
case 2:
return FEHermite<1>::hermite_raw_shape_deriv(1, p(0));
case 3:
return d2xd2x * FEHermite<1>::hermite_raw_shape_deriv(3, p(0));
default:
return FEHermite<1>::hermite_raw_shape_deriv(i, p(0));
}
}
default:
libmesh_error_msg("ERROR: Unsupported element type = " << type);
}
libmesh_error_msg("We'll never get here!");
return 0.;
}
template <>
Real FE<1,HERMITE>::shape_second_deriv(const Elem * elem,
const Order order,
const unsigned int i,
const unsigned int,
const Point & p)
{
libmesh_assert(elem);
// Coefficient naming: d(1)d(2n) is the coefficient of the
// global shape function corresponding to value 1 in terms of the
// local shape function corresponding to normal derivative 2
Real d1xd1x, d2xd2x;
hermite_compute_coefs(elem, d1xd1x, d2xd2x);
const ElemType type = elem->type();
#ifndef NDEBUG
const unsigned int totalorder = order + elem->p_level();
#endif
switch (type)
{
// C1 functions on the C1 cubic edge
case EDGE2:
case EDGE3:
{
libmesh_assert_less (i, totalorder+1);
switch (i)
{
case 0:
return FEHermite<1>::hermite_raw_shape_second_deriv(0, p(0));
case 1:
return d1xd1x * FEHermite<1>::hermite_raw_shape_second_deriv(2, p(0));
case 2:
return FEHermite<1>::hermite_raw_shape_second_deriv(1, p(0));
case 3:
return d2xd2x * FEHermite<1>::hermite_raw_shape_second_deriv(3, p(0));
default:
return FEHermite<1>::hermite_raw_shape_second_deriv(i, p(0));
}
}
default:
libmesh_error_msg("ERROR: Unsupported element type = " << type);
}
libmesh_error_msg("We'll never get here!");
return 0.;
}
} // namespace libMesh
<|endoftext|> |
<commit_before>/*
Copyright libCellML Contributors
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 "libcellml/types.h"
#include "libcellml/component.h"
#include "libcellml/importsource.h"
#include "libcellml/model.h"
#include "libcellml/reset.h"
#include "libcellml/units.h"
#include "libcellml/variable.h"
#include "anycellmlelement_p.h"
#include "internaltypes.h"
namespace libcellml {
/**
* @brief The UnitsItem::UnitsItemImpl struct.
*
* The private implementation for the UnitsItem class.
*/
struct UnitsItem::UnitsItemImpl
{
UnitsWeakPtr mUnits; /**< Units that owns this units item.*/
size_t mIndex = std::numeric_limits<size_t>::max(); /**< Index of this units item.*/
};
UnitsItem::UnitsItem(const UnitsPtr &units, size_t index)
: mPimpl(new UnitsItemImpl())
{
mPimpl->mUnits = units;
mPimpl->mIndex = index;
}
UnitsItem::~UnitsItem()
{
delete mPimpl;
}
UnitsItemPtr UnitsItem::create(const UnitsPtr &units, size_t index) noexcept
{
return std::shared_ptr<UnitsItem> {new UnitsItem {units, index}};
}
UnitsPtr UnitsItem::units() const
{
return mPimpl->mUnits.lock();
}
size_t UnitsItem::index() const
{
return mPimpl->mIndex;
}
bool UnitsItem::isValid() const
{
return mPimpl->mIndex < mPimpl->mUnits.lock()->unitCount();
}
/**
* @brief The VariablePair::VariablePairImpl struct.
*
* The private implementation for the VariablePair class.
*/
struct VariablePair::VariablePairImpl
{
VariableWeakPtr mVariable1; /**< Variable 1 for the pair.*/
VariableWeakPtr mVariable2; /**< Variable 2 for the pair.*/
};
VariablePair::VariablePair(const VariablePtr &variable1, const VariablePtr &variable2)
: mPimpl(new VariablePairImpl())
{
mPimpl->mVariable1 = variable1;
mPimpl->mVariable2 = variable2;
}
VariablePairPtr VariablePair::create(const VariablePtr &variable1, const VariablePtr &variable2) noexcept
{
return std::shared_ptr<VariablePair> {new VariablePair {variable1, variable2}};
}
VariablePair::~VariablePair()
{
delete mPimpl;
}
VariablePtr VariablePair::variable1() const
{
return mPimpl->mVariable1.lock();
}
VariablePtr VariablePair::variable2() const
{
return mPimpl->mVariable2.lock();
}
bool VariablePair::isValid() const
{
return (mPimpl->mVariable1.lock() != nullptr) && (mPimpl->mVariable2.lock() != nullptr);
}
void AnyCellmlElement::AnyCellmlElementImpl::setComponent(const ComponentPtr &component, CellmlElementType type)
{
mType = type;
mItem = component;
}
void AnyCellmlElement::AnyCellmlElementImpl::setImportSource(const ImportSourcePtr &importSource)
{
mType = CellmlElementType::IMPORT;
mItem = importSource;
}
void AnyCellmlElement::AnyCellmlElementImpl::setModel(const ModelPtr &model, CellmlElementType type)
{
mType = type;
mItem = model;
}
void AnyCellmlElement::AnyCellmlElementImpl::setReset(const ResetPtr &reset, CellmlElementType type)
{
mType = type;
mItem = reset;
}
void AnyCellmlElement::AnyCellmlElementImpl::setUnits(const UnitsPtr &units)
{
mType = CellmlElementType::UNITS;
mItem = units;
}
void AnyCellmlElement::AnyCellmlElementImpl::setUnitsItem(const UnitsItemPtr &unitsItem)
{
mType = CellmlElementType::UNIT;
mItem = unitsItem;
}
void AnyCellmlElement::AnyCellmlElementImpl::setVariable(const VariablePtr &variable)
{
mType = CellmlElementType::VARIABLE;
mItem = variable;
}
void AnyCellmlElement::AnyCellmlElementImpl::setVariablePair(const VariablePairPtr &pair, CellmlElementType type)
{
mType = type;
mItem = pair;
}
void AnyCellmlElement::AnyCellmlElementImpl::setVariablePair(const VariablePtr &variable1, const VariablePtr &variable2, CellmlElementType type)
{
mType = type;
mItem = VariablePair::create(variable1, variable2);
}
AnyCellmlElement::AnyCellmlElement()
: mPimpl(new AnyCellmlElementImpl())
{
}
AnyCellmlElement::~AnyCellmlElement()
{
delete mPimpl;
}
CellmlElementType AnyCellmlElement::type() const
{
return mPimpl->mType;
}
ComponentPtr AnyCellmlElement::component() const
{
if ((mPimpl->mType == CellmlElementType::COMPONENT)
|| (mPimpl->mType == CellmlElementType::COMPONENT_REF)) {
try {
return std::any_cast<ComponentPtr>(mPimpl->mItem);
} catch(const std::bad_any_cast& e) {
return nullptr;
}
}
return nullptr;
}
VariablePairPtr AnyCellmlElement::variablePair() const
{
if ((mPimpl->mType == CellmlElementType::CONNECTION)
|| (mPimpl->mType == CellmlElementType::MAP_VARIABLES)) {
try {
return std::any_cast<VariablePairPtr>(mPimpl->mItem);
} catch(const std::bad_any_cast& e) {
return nullptr;
}
}
return nullptr;
}
ImportSourcePtr AnyCellmlElement::importSource() const
{
if (mPimpl->mType == CellmlElementType::IMPORT) {
try {
return std::any_cast<ImportSourcePtr>(mPimpl->mItem);
} catch(const std::bad_any_cast& e) {
return nullptr;
}
}
return nullptr;
}
ModelPtr AnyCellmlElement::model() const
{
if ((mPimpl->mType == CellmlElementType::ENCAPSULATION)
|| (mPimpl->mType == CellmlElementType::MODEL)) {
try {
return std::any_cast<ModelPtr>(mPimpl->mItem);
} catch(const std::bad_any_cast& e) {
return nullptr;
}
}
return nullptr;
}
ResetPtr AnyCellmlElement::reset() const
{
if (mPimpl->mType == CellmlElementType::RESET) {
try {
return std::any_cast<ResetPtr>(mPimpl->mItem);
} catch(const std::bad_any_cast& e) {
return nullptr;
}
}
return nullptr;
}
ResetPtr AnyCellmlElement::resetValue() const
{
if (mPimpl->mType == CellmlElementType::RESET_VALUE) {
try {
return std::any_cast<ResetPtr>(mPimpl->mItem);
} catch(const std::bad_any_cast& e) {
return nullptr;
}
}
return nullptr;
}
ResetPtr AnyCellmlElement::testValue() const
{
if (mPimpl->mType == CellmlElementType::TEST_VALUE) {
try {
return std::any_cast<ResetPtr>(mPimpl->mItem);
} catch(const std::bad_any_cast& e) {
return nullptr;
}
}
return nullptr;
}
UnitsPtr AnyCellmlElement::units() const
{
if (mPimpl->mType == CellmlElementType::UNITS) {
try {
return std::any_cast<UnitsPtr>(mPimpl->mItem);
} catch(const std::bad_any_cast& e) {
return nullptr;
}
}
return nullptr;
}
UnitsItemPtr AnyCellmlElement::unitsItem() const
{
if (mPimpl->mType == CellmlElementType::UNIT) {
try {
return std::any_cast<UnitsItemPtr>(mPimpl->mItem);
} catch(const std::bad_any_cast& e) {
return nullptr;
}
}
return nullptr;
}
VariablePtr AnyCellmlElement::variable() const
{
if (mPimpl->mType == CellmlElementType::VARIABLE) {
try {
return std::any_cast<VariablePtr>(mPimpl->mItem);
} catch(const std::bad_any_cast& e) {
return nullptr;
}
}
return nullptr;
}
} // namespace libcellml
<commit_msg>Make MSVC and Clang happy.<commit_after>/*
Copyright libCellML Contributors
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 "libcellml/types.h"
#include "libcellml/component.h"
#include "libcellml/importsource.h"
#include "libcellml/model.h"
#include "libcellml/reset.h"
#include "libcellml/units.h"
#include "libcellml/variable.h"
#include "anycellmlelement_p.h"
#include "internaltypes.h"
namespace libcellml {
/**
* @brief The UnitsItem::UnitsItemImpl struct.
*
* The private implementation for the UnitsItem class.
*/
struct UnitsItem::UnitsItemImpl
{
UnitsWeakPtr mUnits; /**< Units that owns this units item.*/
size_t mIndex = std::numeric_limits<size_t>::max(); /**< Index of this units item.*/
};
UnitsItem::UnitsItem(const UnitsPtr &units, size_t index)
: mPimpl(new UnitsItemImpl())
{
mPimpl->mUnits = units;
mPimpl->mIndex = index;
}
UnitsItem::~UnitsItem()
{
delete mPimpl;
}
UnitsItemPtr UnitsItem::create(const UnitsPtr &units, size_t index) noexcept
{
return std::shared_ptr<UnitsItem> {new UnitsItem {units, index}};
}
UnitsPtr UnitsItem::units() const
{
return mPimpl->mUnits.lock();
}
size_t UnitsItem::index() const
{
return mPimpl->mIndex;
}
bool UnitsItem::isValid() const
{
return mPimpl->mIndex < mPimpl->mUnits.lock()->unitCount();
}
/**
* @brief The VariablePair::VariablePairImpl struct.
*
* The private implementation for the VariablePair class.
*/
struct VariablePair::VariablePairImpl
{
VariableWeakPtr mVariable1; /**< Variable 1 for the pair.*/
VariableWeakPtr mVariable2; /**< Variable 2 for the pair.*/
};
VariablePair::VariablePair(const VariablePtr &variable1, const VariablePtr &variable2)
: mPimpl(new VariablePairImpl())
{
mPimpl->mVariable1 = variable1;
mPimpl->mVariable2 = variable2;
}
VariablePairPtr VariablePair::create(const VariablePtr &variable1, const VariablePtr &variable2) noexcept
{
return std::shared_ptr<VariablePair> {new VariablePair {variable1, variable2}};
}
VariablePair::~VariablePair()
{
delete mPimpl;
}
VariablePtr VariablePair::variable1() const
{
return mPimpl->mVariable1.lock();
}
VariablePtr VariablePair::variable2() const
{
return mPimpl->mVariable2.lock();
}
bool VariablePair::isValid() const
{
return (mPimpl->mVariable1.lock() != nullptr) && (mPimpl->mVariable2.lock() != nullptr);
}
void AnyCellmlElement::AnyCellmlElementImpl::setComponent(const ComponentPtr &component, CellmlElementType type)
{
mType = type;
mItem = component;
}
void AnyCellmlElement::AnyCellmlElementImpl::setImportSource(const ImportSourcePtr &importSource)
{
mType = CellmlElementType::IMPORT;
mItem = importSource;
}
void AnyCellmlElement::AnyCellmlElementImpl::setModel(const ModelPtr &model, CellmlElementType type)
{
mType = type;
mItem = model;
}
void AnyCellmlElement::AnyCellmlElementImpl::setReset(const ResetPtr &reset, CellmlElementType type)
{
mType = type;
mItem = reset;
}
void AnyCellmlElement::AnyCellmlElementImpl::setUnits(const UnitsPtr &units)
{
mType = CellmlElementType::UNITS;
mItem = units;
}
void AnyCellmlElement::AnyCellmlElementImpl::setUnitsItem(const UnitsItemPtr &unitsItem)
{
mType = CellmlElementType::UNIT;
mItem = unitsItem;
}
void AnyCellmlElement::AnyCellmlElementImpl::setVariable(const VariablePtr &variable)
{
mType = CellmlElementType::VARIABLE;
mItem = variable;
}
void AnyCellmlElement::AnyCellmlElementImpl::setVariablePair(const VariablePairPtr &pair, CellmlElementType type)
{
mType = type;
mItem = pair;
}
void AnyCellmlElement::AnyCellmlElementImpl::setVariablePair(const VariablePtr &variable1, const VariablePtr &variable2, CellmlElementType type)
{
mType = type;
mItem = VariablePair::create(variable1, variable2);
}
AnyCellmlElement::AnyCellmlElement()
: mPimpl(new AnyCellmlElementImpl())
{
}
AnyCellmlElement::~AnyCellmlElement()
{
delete mPimpl;
}
CellmlElementType AnyCellmlElement::type() const
{
return mPimpl->mType;
}
ComponentPtr AnyCellmlElement::component() const
{
if ((mPimpl->mType == CellmlElementType::COMPONENT)
|| (mPimpl->mType == CellmlElementType::COMPONENT_REF)) {
try {
return std::any_cast<ComponentPtr>(mPimpl->mItem);
} catch (const std::bad_any_cast &) {
return nullptr;
}
}
return nullptr;
}
VariablePairPtr AnyCellmlElement::variablePair() const
{
if ((mPimpl->mType == CellmlElementType::CONNECTION)
|| (mPimpl->mType == CellmlElementType::MAP_VARIABLES)) {
try {
return std::any_cast<VariablePairPtr>(mPimpl->mItem);
} catch (const std::bad_any_cast &) {
return nullptr;
}
}
return nullptr;
}
ImportSourcePtr AnyCellmlElement::importSource() const
{
if (mPimpl->mType == CellmlElementType::IMPORT) {
try {
return std::any_cast<ImportSourcePtr>(mPimpl->mItem);
} catch (const std::bad_any_cast &) {
return nullptr;
}
}
return nullptr;
}
ModelPtr AnyCellmlElement::model() const
{
if ((mPimpl->mType == CellmlElementType::ENCAPSULATION)
|| (mPimpl->mType == CellmlElementType::MODEL)) {
try {
return std::any_cast<ModelPtr>(mPimpl->mItem);
} catch (const std::bad_any_cast &) {
return nullptr;
}
}
return nullptr;
}
ResetPtr AnyCellmlElement::reset() const
{
if (mPimpl->mType == CellmlElementType::RESET) {
try {
return std::any_cast<ResetPtr>(mPimpl->mItem);
} catch (const std::bad_any_cast &) {
return nullptr;
}
}
return nullptr;
}
ResetPtr AnyCellmlElement::resetValue() const
{
if (mPimpl->mType == CellmlElementType::RESET_VALUE) {
try {
return std::any_cast<ResetPtr>(mPimpl->mItem);
} catch (const std::bad_any_cast &) {
return nullptr;
}
}
return nullptr;
}
ResetPtr AnyCellmlElement::testValue() const
{
if (mPimpl->mType == CellmlElementType::TEST_VALUE) {
try {
return std::any_cast<ResetPtr>(mPimpl->mItem);
} catch (const std::bad_any_cast &) {
return nullptr;
}
}
return nullptr;
}
UnitsPtr AnyCellmlElement::units() const
{
if (mPimpl->mType == CellmlElementType::UNITS) {
try {
return std::any_cast<UnitsPtr>(mPimpl->mItem);
} catch (const std::bad_any_cast &) {
return nullptr;
}
}
return nullptr;
}
UnitsItemPtr AnyCellmlElement::unitsItem() const
{
if (mPimpl->mType == CellmlElementType::UNIT) {
try {
return std::any_cast<UnitsItemPtr>(mPimpl->mItem);
} catch (const std::bad_any_cast &) {
return nullptr;
}
}
return nullptr;
}
VariablePtr AnyCellmlElement::variable() const
{
if (mPimpl->mType == CellmlElementType::VARIABLE) {
try {
return std::any_cast<VariablePtr>(mPimpl->mItem);
} catch (const std::bad_any_cast &) {
return nullptr;
}
}
return nullptr;
}
} // namespace libcellml
<|endoftext|> |
<commit_before>//===--- SILGlobalVariable.cpp - Defines SILGlobalVariable structure ------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
#include "swift/SIL/SILGlobalVariable.h"
#include "swift/SIL/SILModule.h"
using namespace swift;
SILGlobalVariable *SILGlobalVariable::create(SILModule &M, SILLinkage linkage,
bool IsFragile,
StringRef name,
SILType loweredType,
Optional<SILLocation> loc,
VarDecl *Decl) {
// Get a StringMapEntry for the variable. As a sop to error cases,
// allow the name to have an empty string.
llvm::StringMapEntry<SILGlobalVariable*> *entry = nullptr;
if (!name.empty()) {
entry = &*M.GlobalVariableTable.insert(std::make_pair(name, nullptr)).first;
assert(!entry->getValue() && "global variable already exists");
name = entry->getKey();
}
auto var = new (M) SILGlobalVariable(M, linkage, IsFragile, name,
loweredType, loc, Decl);
if (entry) entry->setValue(var);
return var;
}
SILGlobalVariable::SILGlobalVariable(SILModule &Module, SILLinkage Linkage,
bool IsFragile,
StringRef Name, SILType LoweredType,
Optional<SILLocation> Loc, VarDecl *Decl)
: Module(Module),
Name(Name),
LoweredType(LoweredType),
Location(Loc),
Linkage(unsigned(Linkage)),
Fragile(IsFragile),
VDecl(Decl) {
IsDeclaration = isAvailableExternally(Linkage);
setLet(Decl ? Decl->isLet() : false);
InitializerF = nullptr;
Module.silGlobals.push_back(this);
}
void SILGlobalVariable::setInitializer(SILFunction *InitF) {
if (InitializerF)
InitializerF->decrementRefCount();
// Increment the ref count to make sure it will not be eliminated.
InitF->incrementRefCount();
InitializerF = InitF;
}
SILGlobalVariable::~SILGlobalVariable() {
getModule().GlobalVariableTable.erase(Name);
}
static bool analyzeStaticInitializer(SILFunction *F, SILInstruction *&Val,
SILGlobalVariable *&GVar) {
Val = nullptr;
GVar = nullptr;
// We only handle a single SILBasicBlock for now.
if (F->size() != 1)
return false;
SILBasicBlock *BB = &F->front();
GlobalAddrInst *SGA = nullptr;
bool HasStore = false;
for (auto &I : *BB) {
// Make sure we have a single GlobalAddrInst and a single StoreInst.
// And the StoreInst writes to the GlobalAddrInst.
if (auto *sga = dyn_cast<GlobalAddrInst>(&I)) {
if (SGA)
return false;
SGA = sga;
GVar = SGA->getReferencedGlobal();
} else if (auto *SI = dyn_cast<StoreInst>(&I)) {
if (HasStore || SI->getDest().getDef() != SGA)
return false;
HasStore = true;
Val = dyn_cast<SILInstruction>(SI->getSrc().getDef());
// We only handle StructInst being stored to a global variable for now.
if (!isa<StructInst>(Val))
return false;
} else if (auto *ti = dyn_cast<TupleInst>(&I)) {
if (ti->getNumOperands())
return false;
} else {
if (I.getKind() != ValueKind::ReturnInst &&
I.getKind() != ValueKind::StructInst &&
I.getKind() != ValueKind::IntegerLiteralInst &&
I.getKind() != ValueKind::FloatLiteralInst &&
I.getKind() != ValueKind::StringLiteralInst)
return false;
}
}
return true;
}
bool SILGlobalVariable::canBeStaticInitializer(SILFunction *F) {
SILInstruction *dummySI;
SILGlobalVariable *dummyGV;
return analyzeStaticInitializer(F, dummySI, dummyGV);
}
/// Check if a given SILFunction can be a static initializer. If yes, return
/// the SILGlobalVariable that it writes to.
SILGlobalVariable *SILGlobalVariable::getVariableOfStaticInitializer(
SILFunction *F) {
SILInstruction *dummySI;
SILGlobalVariable *GV;
if(analyzeStaticInitializer(F, dummySI, GV))
return GV;
return nullptr;
}
/// Return the value that is written into the global variable.
SILInstruction *SILGlobalVariable::getValueOfStaticInitializer() {
if (!InitializerF)
return nullptr;
SILInstruction *SI;
SILGlobalVariable *dummyGV;
if(analyzeStaticInitializer(InitializerF, SI, dummyGV))
return SI;
return nullptr;
}
<commit_msg>[globalopt] fptrunc(float_literal) can be considered to be a simple static initializer.<commit_after>//===--- SILGlobalVariable.cpp - Defines SILGlobalVariable structure ------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
#include "swift/SIL/SILGlobalVariable.h"
#include "swift/SIL/SILModule.h"
using namespace swift;
SILGlobalVariable *SILGlobalVariable::create(SILModule &M, SILLinkage linkage,
bool IsFragile,
StringRef name,
SILType loweredType,
Optional<SILLocation> loc,
VarDecl *Decl) {
// Get a StringMapEntry for the variable. As a sop to error cases,
// allow the name to have an empty string.
llvm::StringMapEntry<SILGlobalVariable*> *entry = nullptr;
if (!name.empty()) {
entry = &*M.GlobalVariableTable.insert(std::make_pair(name, nullptr)).first;
assert(!entry->getValue() && "global variable already exists");
name = entry->getKey();
}
auto var = new (M) SILGlobalVariable(M, linkage, IsFragile, name,
loweredType, loc, Decl);
if (entry) entry->setValue(var);
return var;
}
SILGlobalVariable::SILGlobalVariable(SILModule &Module, SILLinkage Linkage,
bool IsFragile,
StringRef Name, SILType LoweredType,
Optional<SILLocation> Loc, VarDecl *Decl)
: Module(Module),
Name(Name),
LoweredType(LoweredType),
Location(Loc),
Linkage(unsigned(Linkage)),
Fragile(IsFragile),
VDecl(Decl) {
IsDeclaration = isAvailableExternally(Linkage);
setLet(Decl ? Decl->isLet() : false);
InitializerF = nullptr;
Module.silGlobals.push_back(this);
}
void SILGlobalVariable::setInitializer(SILFunction *InitF) {
if (InitializerF)
InitializerF->decrementRefCount();
// Increment the ref count to make sure it will not be eliminated.
InitF->incrementRefCount();
InitializerF = InitF;
}
SILGlobalVariable::~SILGlobalVariable() {
getModule().GlobalVariableTable.erase(Name);
}
static bool analyzeStaticInitializer(SILFunction *F, SILInstruction *&Val,
SILGlobalVariable *&GVar) {
Val = nullptr;
GVar = nullptr;
// We only handle a single SILBasicBlock for now.
if (F->size() != 1)
return false;
SILBasicBlock *BB = &F->front();
GlobalAddrInst *SGA = nullptr;
bool HasStore = false;
for (auto &I : *BB) {
// Make sure we have a single GlobalAddrInst and a single StoreInst.
// And the StoreInst writes to the GlobalAddrInst.
if (auto *sga = dyn_cast<GlobalAddrInst>(&I)) {
if (SGA)
return false;
SGA = sga;
GVar = SGA->getReferencedGlobal();
} else if (auto *SI = dyn_cast<StoreInst>(&I)) {
if (HasStore || SI->getDest().getDef() != SGA)
return false;
HasStore = true;
Val = dyn_cast<SILInstruction>(SI->getSrc().getDef());
// We only handle StructInst being stored to a global variable for now.
if (!isa<StructInst>(Val))
return false;
} else if (auto *ti = dyn_cast<TupleInst>(&I)) {
if (ti->getNumOperands())
return false;
} else {
if (auto *bi = dyn_cast<BuiltinInst>(&I)) {
switch (bi->getBuiltinInfo().ID) {
case BuiltinValueKind::FPTrunc:
if (isa<LiteralInst>(bi->getArguments()[0]))
continue;
break;
default:
return false;
}
}
if (I.getKind() != ValueKind::ReturnInst &&
I.getKind() != ValueKind::StructInst &&
I.getKind() != ValueKind::IntegerLiteralInst &&
I.getKind() != ValueKind::FloatLiteralInst &&
I.getKind() != ValueKind::StringLiteralInst)
return false;
}
}
return true;
}
bool SILGlobalVariable::canBeStaticInitializer(SILFunction *F) {
SILInstruction *dummySI;
SILGlobalVariable *dummyGV;
return analyzeStaticInitializer(F, dummySI, dummyGV);
}
/// Check if a given SILFunction can be a static initializer. If yes, return
/// the SILGlobalVariable that it writes to.
SILGlobalVariable *SILGlobalVariable::getVariableOfStaticInitializer(
SILFunction *F) {
SILInstruction *dummySI;
SILGlobalVariable *GV;
if(analyzeStaticInitializer(F, dummySI, GV))
return GV;
return nullptr;
}
/// Return the value that is written into the global variable.
SILInstruction *SILGlobalVariable::getValueOfStaticInitializer() {
if (!InitializerF)
return nullptr;
SILInstruction *SI;
SILGlobalVariable *dummyGV;
if(analyzeStaticInitializer(InitializerF, SI, dummyGV))
return SI;
return nullptr;
}
<|endoftext|> |
<commit_before>//===-- X86JITInfo.cpp - Implement the JIT interfaces for the X86 target --===//
//
// The LLVM Compiler Infrastructure
//
// This file was developed by the LLVM research group and is distributed under
// the University of Illinois Open Source License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file implements the JIT interfaces for the X86 target.
//
//===----------------------------------------------------------------------===//
#define DEBUG_TYPE "jit"
#include "X86JITInfo.h"
#include "X86Relocations.h"
#include "llvm/CodeGen/MachineCodeEmitter.h"
#include "llvm/Config/alloca.h"
#include <cstdlib>
#include <iostream>
using namespace llvm;
#ifdef _MSC_VER
extern "C" void *_AddressOfReturnAddress(void);
#pragma intrinsic(_AddressOfReturnAddress)
#endif
void X86JITInfo::replaceMachineCodeForFunction(void *Old, void *New) {
unsigned char *OldByte = (unsigned char *)Old;
*OldByte++ = 0xE9; // Emit JMP opcode.
unsigned *OldWord = (unsigned *)OldByte;
unsigned NewAddr = (intptr_t)New;
unsigned OldAddr = (intptr_t)OldWord;
*OldWord = NewAddr - OldAddr - 4; // Emit PC-relative addr of New code.
}
/// JITCompilerFunction - This contains the address of the JIT function used to
/// compile a function lazily.
static TargetJITInfo::JITCompilerFn JITCompilerFunction;
// Provide a wrapper for X86CompilationCallback2 that saves non-traditional
// callee saved registers, for the fastcc calling convention.
extern "C" {
#if defined(__i386__) || defined(i386) || defined(_M_IX86)
#ifndef _MSC_VER
void X86CompilationCallback(void);
asm(
".text\n"
".align 8\n"
#if defined(__CYGWIN__) || defined(__APPLE__) || defined(__MINGW32__)
".globl _X86CompilationCallback\n"
"_X86CompilationCallback:\n"
#else
".globl X86CompilationCallback\n"
"X86CompilationCallback:\n"
#endif
"pushl %ebp\n"
"movl %esp, %ebp\n" // Standard prologue
"pushl %eax\n"
"pushl %edx\n" // save EAX/EDX
#if defined(__CYGWIN__) || defined(__MINGW32__)
"call _X86CompilationCallback2\n"
#elif defined(__APPLE__)
"movl 4(%ebp), %eax\n" // load the address of return address
"movl $24, %edx\n" // if the opcode of the instruction at the
"cmpb $-51, (%eax)\n" // return address is our 0xCD marker, then
"movl $12, %eax\n" // subtract 24 from %esp to realign it to 16
"cmovne %eax, %edx\n" // bytes after the push of edx, the amount to.
"subl %edx, %esp\n" // the push of edx to keep it aligned.
"pushl %edx\n" // subtract. Otherwise, subtract 12 bytes after
"call _X86CompilationCallback2\n"
"popl %edx\n"
"addl %edx, %esp\n"
#else
"call X86CompilationCallback2\n"
#endif
"popl %edx\n"
"popl %eax\n"
"popl %ebp\n"
"ret\n");
#else
void X86CompilationCallback2(void);
_declspec(naked) void X86CompilationCallback(void) {
__asm {
push eax
push edx
call X86CompilationCallback2
pop edx
pop eax
ret
}
}
#endif // _MSC_VER
#else // Not an i386 host
void X86CompilationCallback() {
std::cerr << "Cannot call X86CompilationCallback() on a non-x86 arch!\n";
abort();
}
#endif
}
/// X86CompilationCallback - This is the target-specific function invoked by the
/// function stub when we did not know the real target of a call. This function
/// must locate the start of the stub or call site and pass it into the JIT
/// compiler function.
extern "C" void X86CompilationCallback2() {
#ifdef _MSC_VER
assert(sizeof(size_t) == 4); // FIXME: handle Win64
unsigned *RetAddrLoc = (unsigned *)_AddressOfReturnAddress();
RetAddrLoc += 3; // skip over ret addr, edx, eax
unsigned RetAddr = *RetAddrLoc;
#else
unsigned *StackPtr = (unsigned*)__builtin_frame_address(1);
unsigned RetAddr = (unsigned)(intptr_t)__builtin_return_address(1);
unsigned *RetAddrLoc = &StackPtr[1];
// NOTE: __builtin_frame_address doesn't work if frame pointer elimination has
// been performed. Having a variable sized alloca disables frame pointer
// elimination currently, even if it's dead. This is a gross hack.
alloca(10+(RetAddr >> 31));
#endif
assert(*RetAddrLoc == RetAddr &&
"Could not find return address on the stack!");
// It's a stub if there is an interrupt marker after the call.
bool isStub = ((unsigned char*)(intptr_t)RetAddr)[0] == 0xCD;
// The call instruction should have pushed the return value onto the stack...
RetAddr -= 4; // Backtrack to the reference itself...
#if 0
DEBUG(std::cerr << "In callback! Addr=" << (void*)RetAddr
<< " ESP=" << (void*)StackPtr
<< ": Resolving call to function: "
<< TheVM->getFunctionReferencedName((void*)RetAddr) << "\n");
#endif
// Sanity check to make sure this really is a call instruction.
assert(((unsigned char*)(intptr_t)RetAddr)[-1] == 0xE8 &&"Not a call instr!");
unsigned NewVal = (intptr_t)JITCompilerFunction((void*)(intptr_t)RetAddr);
// Rewrite the call target... so that we don't end up here every time we
// execute the call.
*(unsigned*)(intptr_t)RetAddr = NewVal-RetAddr-4;
if (isStub) {
// If this is a stub, rewrite the call into an unconditional branch
// instruction so that two return addresses are not pushed onto the stack
// when the requested function finally gets called. This also makes the
// 0xCD byte (interrupt) dead, so the marker doesn't effect anything.
((unsigned char*)(intptr_t)RetAddr)[-1] = 0xE9;
}
// Change the return address to reexecute the call instruction...
*RetAddrLoc -= 5;
}
TargetJITInfo::LazyResolverFn
X86JITInfo::getLazyResolverFunction(JITCompilerFn F) {
JITCompilerFunction = F;
return X86CompilationCallback;
}
void *X86JITInfo::emitFunctionStub(void *Fn, MachineCodeEmitter &MCE) {
if (Fn != (void*)X86CompilationCallback) {
MCE.startFunctionStub(5);
MCE.emitByte(0xE9);
MCE.emitWordLE((intptr_t)Fn-MCE.getCurrentPCValue()-4);
return MCE.finishFunctionStub(0);
}
MCE.startFunctionStub(6);
MCE.emitByte(0xE8); // Call with 32 bit pc-rel destination...
MCE.emitWordLE((intptr_t)Fn-MCE.getCurrentPCValue()-4);
MCE.emitByte(0xCD); // Interrupt - Just a marker identifying the stub!
return MCE.finishFunctionStub(0);
}
/// relocate - Before the JIT can run a block of code that has been emitted,
/// it must rewrite the code to contain the actual addresses of any
/// referenced global symbols.
void X86JITInfo::relocate(void *Function, MachineRelocation *MR,
unsigned NumRelocs, unsigned char* GOTBase) {
for (unsigned i = 0; i != NumRelocs; ++i, ++MR) {
void *RelocPos = (char*)Function + MR->getMachineCodeOffset();
intptr_t ResultPtr = (intptr_t)MR->getResultPointer();
switch ((X86::RelocationType)MR->getRelocationType()) {
case X86::reloc_pcrel_word:
// PC relative relocation, add the relocated value to the value already in
// memory, after we adjust it for where the PC is.
ResultPtr = ResultPtr-(intptr_t)RelocPos-4;
*((intptr_t*)RelocPos) += ResultPtr;
break;
case X86::reloc_absolute_word:
// Absolute relocation, just add the relocated value to the value already
// in memory.
*((intptr_t*)RelocPos) += ResultPtr;
break;
}
}
}
<commit_msg>Silence -pedantic warning.<commit_after>//===-- X86JITInfo.cpp - Implement the JIT interfaces for the X86 target --===//
//
// The LLVM Compiler Infrastructure
//
// This file was developed by the LLVM research group and is distributed under
// the University of Illinois Open Source License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file implements the JIT interfaces for the X86 target.
//
//===----------------------------------------------------------------------===//
#define DEBUG_TYPE "jit"
#include "X86JITInfo.h"
#include "X86Relocations.h"
#include "llvm/CodeGen/MachineCodeEmitter.h"
#include "llvm/Config/alloca.h"
#include <cstdlib>
#include <iostream>
using namespace llvm;
#ifdef _MSC_VER
extern "C" void *_AddressOfReturnAddress(void);
#pragma intrinsic(_AddressOfReturnAddress)
#endif
void X86JITInfo::replaceMachineCodeForFunction(void *Old, void *New) {
unsigned char *OldByte = (unsigned char *)Old;
*OldByte++ = 0xE9; // Emit JMP opcode.
unsigned *OldWord = (unsigned *)OldByte;
unsigned NewAddr = (intptr_t)New;
unsigned OldAddr = (intptr_t)OldWord;
*OldWord = NewAddr - OldAddr - 4; // Emit PC-relative addr of New code.
}
/// JITCompilerFunction - This contains the address of the JIT function used to
/// compile a function lazily.
static TargetJITInfo::JITCompilerFn JITCompilerFunction;
// Provide a wrapper for X86CompilationCallback2 that saves non-traditional
// callee saved registers, for the fastcc calling convention.
extern "C" {
#if defined(__i386__) || defined(i386) || defined(_M_IX86)
#ifndef _MSC_VER
void X86CompilationCallback(void);
asm(
".text\n"
".align 8\n"
#if defined(__CYGWIN__) || defined(__APPLE__) || defined(__MINGW32__)
".globl _X86CompilationCallback\n"
"_X86CompilationCallback:\n"
#else
".globl X86CompilationCallback\n"
"X86CompilationCallback:\n"
#endif
"pushl %ebp\n"
"movl %esp, %ebp\n" // Standard prologue
"pushl %eax\n"
"pushl %edx\n" // save EAX/EDX
#if defined(__CYGWIN__) || defined(__MINGW32__)
"call _X86CompilationCallback2\n"
#elif defined(__APPLE__)
"movl 4(%ebp), %eax\n" // load the address of return address
"movl $24, %edx\n" // if the opcode of the instruction at the
"cmpb $-51, (%eax)\n" // return address is our 0xCD marker, then
"movl $12, %eax\n" // subtract 24 from %esp to realign it to 16
"cmovne %eax, %edx\n" // bytes after the push of edx, the amount to.
"subl %edx, %esp\n" // the push of edx to keep it aligned.
"pushl %edx\n" // subtract. Otherwise, subtract 12 bytes after
"call _X86CompilationCallback2\n"
"popl %edx\n"
"addl %edx, %esp\n"
#else
"call X86CompilationCallback2\n"
#endif
"popl %edx\n"
"popl %eax\n"
"popl %ebp\n"
"ret\n");
#else
void X86CompilationCallback2(void);
_declspec(naked) void X86CompilationCallback(void) {
__asm {
push eax
push edx
call X86CompilationCallback2
pop edx
pop eax
ret
}
}
#endif // _MSC_VER
#else // Not an i386 host
void X86CompilationCallback() {
std::cerr << "Cannot call X86CompilationCallback() on a non-x86 arch!\n";
abort();
}
#endif
}
/// X86CompilationCallback - This is the target-specific function invoked by the
/// function stub when we did not know the real target of a call. This function
/// must locate the start of the stub or call site and pass it into the JIT
/// compiler function.
extern "C" void X86CompilationCallback2() {
#ifdef _MSC_VER
assert(sizeof(size_t) == 4); // FIXME: handle Win64
unsigned *RetAddrLoc = (unsigned *)_AddressOfReturnAddress();
RetAddrLoc += 3; // skip over ret addr, edx, eax
unsigned RetAddr = *RetAddrLoc;
#else
unsigned *StackPtr = (unsigned*)__builtin_frame_address(1);
unsigned RetAddr = (unsigned)(intptr_t)__builtin_return_address(1);
unsigned *RetAddrLoc = &StackPtr[1];
// NOTE: __builtin_frame_address doesn't work if frame pointer elimination has
// been performed. Having a variable sized alloca disables frame pointer
// elimination currently, even if it's dead. This is a gross hack.
alloca(10+(RetAddr >> 31));
#endif
assert(*RetAddrLoc == RetAddr &&
"Could not find return address on the stack!");
// It's a stub if there is an interrupt marker after the call.
bool isStub = ((unsigned char*)(intptr_t)RetAddr)[0] == 0xCD;
// The call instruction should have pushed the return value onto the stack...
RetAddr -= 4; // Backtrack to the reference itself...
#if 0
DEBUG(std::cerr << "In callback! Addr=" << (void*)RetAddr
<< " ESP=" << (void*)StackPtr
<< ": Resolving call to function: "
<< TheVM->getFunctionReferencedName((void*)RetAddr) << "\n");
#endif
// Sanity check to make sure this really is a call instruction.
assert(((unsigned char*)(intptr_t)RetAddr)[-1] == 0xE8 &&"Not a call instr!");
unsigned NewVal = (intptr_t)JITCompilerFunction((void*)(intptr_t)RetAddr);
// Rewrite the call target... so that we don't end up here every time we
// execute the call.
*(unsigned*)(intptr_t)RetAddr = NewVal-RetAddr-4;
if (isStub) {
// If this is a stub, rewrite the call into an unconditional branch
// instruction so that two return addresses are not pushed onto the stack
// when the requested function finally gets called. This also makes the
// 0xCD byte (interrupt) dead, so the marker doesn't effect anything.
((unsigned char*)(intptr_t)RetAddr)[-1] = 0xE9;
}
// Change the return address to reexecute the call instruction...
*RetAddrLoc -= 5;
}
TargetJITInfo::LazyResolverFn
X86JITInfo::getLazyResolverFunction(JITCompilerFn F) {
JITCompilerFunction = F;
return X86CompilationCallback;
}
void *X86JITInfo::emitFunctionStub(void *Fn, MachineCodeEmitter &MCE) {
// Note, we cast to intptr_t here to silence a -pedantic warning that
// complains about casting a function pointer to a normal pointer.
if (Fn != (void*)(intptr_t)X86CompilationCallback) {
MCE.startFunctionStub(5);
MCE.emitByte(0xE9);
MCE.emitWordLE((intptr_t)Fn-MCE.getCurrentPCValue()-4);
return MCE.finishFunctionStub(0);
}
MCE.startFunctionStub(6);
MCE.emitByte(0xE8); // Call with 32 bit pc-rel destination...
MCE.emitWordLE((intptr_t)Fn-MCE.getCurrentPCValue()-4);
MCE.emitByte(0xCD); // Interrupt - Just a marker identifying the stub!
return MCE.finishFunctionStub(0);
}
/// relocate - Before the JIT can run a block of code that has been emitted,
/// it must rewrite the code to contain the actual addresses of any
/// referenced global symbols.
void X86JITInfo::relocate(void *Function, MachineRelocation *MR,
unsigned NumRelocs, unsigned char* GOTBase) {
for (unsigned i = 0; i != NumRelocs; ++i, ++MR) {
void *RelocPos = (char*)Function + MR->getMachineCodeOffset();
intptr_t ResultPtr = (intptr_t)MR->getResultPointer();
switch ((X86::RelocationType)MR->getRelocationType()) {
case X86::reloc_pcrel_word:
// PC relative relocation, add the relocated value to the value already in
// memory, after we adjust it for where the PC is.
ResultPtr = ResultPtr-(intptr_t)RelocPos-4;
*((intptr_t*)RelocPos) += ResultPtr;
break;
case X86::reloc_absolute_word:
// Absolute relocation, just add the relocated value to the value already
// in memory.
*((intptr_t*)RelocPos) += ResultPtr;
break;
}
}
}
<|endoftext|> |
<commit_before>#include <cmath>
#include <cassert>
#include <sstream>
#include "libinterpreter/builtins.h"
const Value builtins::dispatch(BuiltinAtom::Id atom_id, ExecutionContext& ctxt,
const std::vector<Value>& arguments) {
switch (atom_id) {
case BuiltinAtom::Id::POW:
return std::move(pow(arguments[0], arguments[1]));
case BuiltinAtom::Id::HEX:
return std::move(hex(arguments[0]));
case BuiltinAtom::Id::NTH:
return std::move(nth(arguments[0], arguments[1]));
case BuiltinAtom::Id::APP:
return std::move(app(ctxt, arguments[0], arguments[1]));
case BuiltinAtom::Id::CONS:
return std::move(cons(ctxt, arguments[0], arguments[1]));
case BuiltinAtom::Id::TAIL:
return std::move(tail(ctxt, arguments[0]));
case BuiltinAtom::Id::LEN:
return std::move(len(arguments[0]));
case BuiltinAtom::Id::PEEK:
return std::move(peek(arguments[0]));
case BuiltinAtom::Id::BOOLEAN2INT:
return std::move(boolean2int(arguments[0]));
case BuiltinAtom::Id::INT2BOOLEAN:
return std::move(int2boolean(arguments[0]));
case BuiltinAtom::Id::ENUM2INT:
return std::move(enum2int(arguments[0]));
case BuiltinAtom::Id::ASINT:
return std::move(asint(arguments[0]));
case BuiltinAtom::Id::ASFLOAT:
return std::move(asfloat(arguments[0]));
case BuiltinAtom::Id::ASRATIONAL:
return std::move(asrational(arguments[0]));
case BuiltinAtom::Id::SYMBOLIC:
return std::move(symbolic(arguments[0]));
default: return std::move(shared::dispatch(atom_id, arguments, ctxt));
}
}
const Value builtins::pow(const Value& base, const Value& power) {
switch (base.type) {
case TypeType::INT:
return std::move(Value((INT_T)std::pow(base.value.ival, power.value.ival)));
case TypeType::FLOAT:
return std::move(Value((FLOAT_T)std::pow(base.value.fval, power.value.fval)));
default: assert(0);
}
}
const Value builtins::hex(const Value& arg) {
// TODO LEAK!
if (arg.is_undef()) {
return std::move(Value(new std::string("undef")));
}
std::stringstream ss;
if (arg.value.ival < 0) {
ss << "-" << std::hex << (-1) * arg.value.ival;
} else {
ss << std::hex << arg.value.ival;
}
return std::move(Value(new std::string(ss.str())));
}
const Value builtins::nth(const Value& list_arg, const Value& index ) {
if (list_arg.is_undef() || index.is_undef()) {
return Value();
}
List *list = list_arg.value.list;
List::const_iterator iter = list->begin();
INT_T i = 1;
while (iter != list->end() && i < index.value.ival) {
i++;
iter++;
}
if (i == index.value.ival && iter != list->end()) {
return std::move(Value(*iter));
} else {
return std::move(Value());
}
}
const Value builtins::app(ExecutionContext& ctxt, const Value& list, const Value& val) {
// TODO LEAK
if (list.is_undef()) {
return std::move(Value());
}
List *current = list.value.list;
while (1 == 1) {
if (current->list_type == List::ListType::HEAD) {
current = reinterpret_cast<HeadList*>(current)->right;
}
if (current->list_type == List::ListType::SKIP) {
current = reinterpret_cast<SkipList*>(current)->bottom;
}
if (current->list_type == List::ListType::BOTTOM) {
BottomList *bottom = reinterpret_cast<BottomList*>(current);
if (bottom->tail) {
current = bottom->tail;
} else {
break;
}
}
if (current->list_type == List::ListType::TAIL) {
TailList *tail = reinterpret_cast<TailList*>(current);
if (tail->right) {
current = tail->right;
} else {
break;
}
}
}
TailList *tail = new TailList(nullptr, val);
ctxt.temp_lists.push_back(tail);
if (current->list_type == List::ListType::TAIL) {
reinterpret_cast<TailList*>(current)->right = tail;
} else if (current->list_type == List::ListType::BOTTOM) {
reinterpret_cast<BottomList*>(current)->tail = tail;
} else {
assert(0);
}
return std::move(Value(list.type, list.value.list));
}
const Value builtins::cons(ExecutionContext& ctxt, const Value& val, const Value& list) {
// TODO LEAK
if (list.is_undef()) {
return std::move(Value());
}
HeadList *consed_list = new HeadList(list.value.list, val);
ctxt.temp_lists.push_back(consed_list);
return Value(list.type, consed_list);
}
const Value builtins::tail(ExecutionContext& ctxt, const Value& arg_list) {
if (arg_list.is_undef()) {
return std::move(Value());
}
List *list = arg_list.value.list;
if (list->is_head()) {
return std::move(Value(arg_list.type, reinterpret_cast<HeadList*>(list)->right));
} else if (list->is_bottom()) {
BottomList *btm = reinterpret_cast<BottomList*>(list);
SkipList *skip = new SkipList(1, btm);
ctxt.temp_lists.push_back(skip);
return std::move(Value(arg_list.type, skip));
} else {
SkipList *old_skip = reinterpret_cast<SkipList*>(list);
SkipList *skip = new SkipList(old_skip->skip+1, old_skip->bottom);
ctxt.temp_lists.push_back(skip);
return std::move(Value(arg_list.type, skip));
}
}
const Value builtins::len(const Value& list_arg) {
// TODO len is really slow right now, it itertes over complete list
if (list_arg.is_undef()) {
return std::move(Value());
}
List *list = list_arg.value.list;
List::const_iterator iter = list->begin();
size_t count = 0;
while (iter != list->end()) {
count++;
iter++;
}
return std::move(Value((INT_T) count));
}
const Value builtins::peek(const Value& arg_list) {
if (arg_list.is_undef()) {
return std::move(Value());
}
List *list = arg_list.value.list;
if (list->begin() != list->end()) {
return std::move(Value(*(list->begin())));
} else {
return std::move(Value());
}
}
const Value builtins::boolean2int(const Value& arg) {
if (arg.is_undef()) {
return std::move(arg);
}
return std::move(Value((INT_T)arg.value.bval));
}
const Value builtins::int2boolean(const Value& arg) {
if (arg.is_undef()) {
return std::move(arg);
}
return std::move(Value((bool)arg.value.ival));
}
const Value builtins::enum2int(const Value& arg) {
if (arg.is_undef()) {
return std::move(arg);
}
return std::move(Value((INT_T)arg.value.enum_val->id));
}
const Value builtins::asint(const Value& arg) {
if (arg.is_undef()) {
return std::move(arg);
}
switch (arg.type) {
case TypeType::INT:
return std::move(Value(arg.value.ival));
case TypeType::FLOAT:
return std::move(Value((INT_T)arg.value.fval));
case TypeType::RATIONAL:
return std::move(Value((INT_T)(arg.value.rat->numerator / arg.value.rat->denominator)));
default: assert(0);
}
}
const Value builtins::asfloat(const Value& arg) {
if (arg.is_undef()) {
return std::move(arg);
}
switch (arg.type) {
case TypeType::INT:
return std::move(Value((FLOAT_T) arg.value.ival));
case TypeType::FLOAT:
return std::move(Value(arg.value.fval));
case TypeType::RATIONAL:
return std::move(Value(((FLOAT_T)arg.value.rat->numerator) / arg.value.rat->denominator));
default: assert(0);
}
}
void get_numerator_denominator(double x, int64_t *num, int64_t *denom) {
// thanks to
// http://stackoverflow.com/a/96035/781502
uint64_t m[2][2];
double startx = x;
int64_t maxden = 10000000000;
int64_t ai;
/* initialize matrix */
m[0][0] = m[1][1] = 1;
m[0][1] = m[1][0] = 0;
/* loop finding terms until denom gets too big */
while (m[1][0] * ( ai = (int64_t)x ) + m[1][1] <= maxden) {
long t;
t = m[0][0] * ai + m[0][1];
m[0][1] = m[0][0];
m[0][0] = t;
t = m[1][0] * ai + m[1][1];
m[1][1] = m[1][0];
m[1][0] = t;
if(x==(double)ai) break; // AF: division by zero
x = 1/(x - (double) ai);
if(x>(double)0x7FFFFFFF) break; // AF: representation failure
}
/* now remaining x is between 0 and 1/ai */
/* approx as either 0 or 1/m where m is max that will fit in maxden */
/* first try zero */
double error1 = startx - ((double) m[0][0] / (double) m[1][0]);
*num = m[0][0];
*denom = m[1][0];
/* now try other possibility */
ai = (maxden - m[1][1]) / m[1][0];
m[0][0] = m[0][0] * ai + m[0][1];
m[1][0] = m[1][0] * ai + m[1][1];
double error2 = startx - ((double) m[0][0] / (double) m[1][0]);
if (abs(error1) > abs(error2)) {
*num = m[0][0];
*denom = m[1][0];
}
}
const Value builtins::asrational(const Value& arg) {
if (arg.is_undef()) {
return std::move(arg);
}
rational_t *result = (rational_t*) pp_mem_alloc(
&(ExecutionContext::value_stack), sizeof(rational_t)
);
switch (arg.type) {
case TypeType::INT:
result->numerator = arg.value.ival;
result->denominator = 1;
return std::move(Value(result));
case TypeType::FLOAT:
get_numerator_denominator(arg.value.fval, &result->numerator, &result->denominator);
return std::move(Value(result));
case TypeType::RATIONAL:
return std::move(Value(arg.value.rat));
default: assert(0);
}
}
const Value builtins::symbolic(const Value& arg) {
if (arg.is_symbolic() && !arg.value.sym->list) {
return std::move(Value(true));
} else {
return std::move(Value(false));
}
}
namespace builtins {
namespace shared {
#include "shared_glue.h"
IGNORE_VARIADIC_WARNINGS
// the CASM runtime heavily depens on macros, whatever you think of it ...
// here we need to provide all definitions ...
#define TRUE 1
#define FALSE 0
#define ARG(TYPE, NAME) TYPE* NAME
#define SARG(VAR) #VAR " {0x%lx,%u}"
#define PARG(TYPE, VAR) (uint64_t)VAR->value, VAR->defined
#define CASM_RT(FORMAT, ARGS...) /* printf-able */
#define CASM_INFO(FORMAT, ARGS...) /* printf-able */
// create concrete variants of the shareds
#define CASM_CALL_SHARED(NAME, VALUE, ARGS...) NAME(VALUE, ##ARGS)
#define DEFINE_CASM_SHARED(NAME, VALUE, ARGS...) void NAME(VALUE, ##ARGS)
#include "libcasmrt/pp_casm_shared.h"
namespace symbolic {
// create symbolic variants of shareds
namespace BV {
// mock BV namespace as expected by the pp_casm_shared builtins
struct helper_t {
bool next() { return true; }
};
static helper_t symbolic_nopointer;
helper_t *symbolic_ = &symbolic_nopointer;
}
#undef CASM_CALL_SHARED
#undef DEFINE_CASM_SHARED
#define SYMBOLIC
#define CASM_CALL_SHARED(NAME, VALUE, ARGS...) symbolic_##NAME(VALUE, ##ARGS)
#define DEFINE_CASM_SHARED(NAME, VALUE, ARGS...) void symbolic_##NAME(VALUE, ##ARGS)
#include "libcasmrt/pp_casm_shared.h"
}
REENABLE_VARIADIC_WARNINGS
const Value dispatch(BuiltinAtom::Id builtin_id,
const std::vector<Value>& arguments, ExecutionContext& ctxt) {
const char *sym_name;
Int ret;
Int arg0;
Int arg1;
Int arg2;
Int arg3;
Int arg4;
switch (builtin_id) {
SHARED_DISPATCH
default: assert(0);
}
if (ret.defined == TRUE) {
return std::move(Value((INT_T)ret.value));
} else if (ctxt.symbolic && ret.sym) {
Value v(new symbol_t(::symbolic::next_symbol_id()));
::symbolic::dump_builtin(ctxt.trace, sym_name, arguments, v);
return std::move(v);
} else {
return std::move(Value());
}
}
}
}
<commit_msg>Disable unused-warnings for shared-builtins<commit_after>#include <cmath>
#include <cassert>
#include <sstream>
#include "libinterpreter/builtins.h"
const Value builtins::dispatch(BuiltinAtom::Id atom_id, ExecutionContext& ctxt,
const std::vector<Value>& arguments) {
switch (atom_id) {
case BuiltinAtom::Id::POW:
return std::move(pow(arguments[0], arguments[1]));
case BuiltinAtom::Id::HEX:
return std::move(hex(arguments[0]));
case BuiltinAtom::Id::NTH:
return std::move(nth(arguments[0], arguments[1]));
case BuiltinAtom::Id::APP:
return std::move(app(ctxt, arguments[0], arguments[1]));
case BuiltinAtom::Id::CONS:
return std::move(cons(ctxt, arguments[0], arguments[1]));
case BuiltinAtom::Id::TAIL:
return std::move(tail(ctxt, arguments[0]));
case BuiltinAtom::Id::LEN:
return std::move(len(arguments[0]));
case BuiltinAtom::Id::PEEK:
return std::move(peek(arguments[0]));
case BuiltinAtom::Id::BOOLEAN2INT:
return std::move(boolean2int(arguments[0]));
case BuiltinAtom::Id::INT2BOOLEAN:
return std::move(int2boolean(arguments[0]));
case BuiltinAtom::Id::ENUM2INT:
return std::move(enum2int(arguments[0]));
case BuiltinAtom::Id::ASINT:
return std::move(asint(arguments[0]));
case BuiltinAtom::Id::ASFLOAT:
return std::move(asfloat(arguments[0]));
case BuiltinAtom::Id::ASRATIONAL:
return std::move(asrational(arguments[0]));
case BuiltinAtom::Id::SYMBOLIC:
return std::move(symbolic(arguments[0]));
default: return std::move(shared::dispatch(atom_id, arguments, ctxt));
}
}
const Value builtins::pow(const Value& base, const Value& power) {
switch (base.type) {
case TypeType::INT:
return std::move(Value((INT_T)std::pow(base.value.ival, power.value.ival)));
case TypeType::FLOAT:
return std::move(Value((FLOAT_T)std::pow(base.value.fval, power.value.fval)));
default: assert(0);
}
}
const Value builtins::hex(const Value& arg) {
// TODO LEAK!
if (arg.is_undef()) {
return std::move(Value(new std::string("undef")));
}
std::stringstream ss;
if (arg.value.ival < 0) {
ss << "-" << std::hex << (-1) * arg.value.ival;
} else {
ss << std::hex << arg.value.ival;
}
return std::move(Value(new std::string(ss.str())));
}
const Value builtins::nth(const Value& list_arg, const Value& index ) {
if (list_arg.is_undef() || index.is_undef()) {
return Value();
}
List *list = list_arg.value.list;
List::const_iterator iter = list->begin();
INT_T i = 1;
while (iter != list->end() && i < index.value.ival) {
i++;
iter++;
}
if (i == index.value.ival && iter != list->end()) {
return std::move(Value(*iter));
} else {
return std::move(Value());
}
}
const Value builtins::app(ExecutionContext& ctxt, const Value& list, const Value& val) {
// TODO LEAK
if (list.is_undef()) {
return std::move(Value());
}
List *current = list.value.list;
while (1 == 1) {
if (current->list_type == List::ListType::HEAD) {
current = reinterpret_cast<HeadList*>(current)->right;
}
if (current->list_type == List::ListType::SKIP) {
current = reinterpret_cast<SkipList*>(current)->bottom;
}
if (current->list_type == List::ListType::BOTTOM) {
BottomList *bottom = reinterpret_cast<BottomList*>(current);
if (bottom->tail) {
current = bottom->tail;
} else {
break;
}
}
if (current->list_type == List::ListType::TAIL) {
TailList *tail = reinterpret_cast<TailList*>(current);
if (tail->right) {
current = tail->right;
} else {
break;
}
}
}
TailList *tail = new TailList(nullptr, val);
ctxt.temp_lists.push_back(tail);
if (current->list_type == List::ListType::TAIL) {
reinterpret_cast<TailList*>(current)->right = tail;
} else if (current->list_type == List::ListType::BOTTOM) {
reinterpret_cast<BottomList*>(current)->tail = tail;
} else {
assert(0);
}
return std::move(Value(list.type, list.value.list));
}
const Value builtins::cons(ExecutionContext& ctxt, const Value& val, const Value& list) {
// TODO LEAK
if (list.is_undef()) {
return std::move(Value());
}
HeadList *consed_list = new HeadList(list.value.list, val);
ctxt.temp_lists.push_back(consed_list);
return Value(list.type, consed_list);
}
const Value builtins::tail(ExecutionContext& ctxt, const Value& arg_list) {
if (arg_list.is_undef()) {
return std::move(Value());
}
List *list = arg_list.value.list;
if (list->is_head()) {
return std::move(Value(arg_list.type, reinterpret_cast<HeadList*>(list)->right));
} else if (list->is_bottom()) {
BottomList *btm = reinterpret_cast<BottomList*>(list);
SkipList *skip = new SkipList(1, btm);
ctxt.temp_lists.push_back(skip);
return std::move(Value(arg_list.type, skip));
} else {
SkipList *old_skip = reinterpret_cast<SkipList*>(list);
SkipList *skip = new SkipList(old_skip->skip+1, old_skip->bottom);
ctxt.temp_lists.push_back(skip);
return std::move(Value(arg_list.type, skip));
}
}
const Value builtins::len(const Value& list_arg) {
// TODO len is really slow right now, it itertes over complete list
if (list_arg.is_undef()) {
return std::move(Value());
}
List *list = list_arg.value.list;
List::const_iterator iter = list->begin();
size_t count = 0;
while (iter != list->end()) {
count++;
iter++;
}
return std::move(Value((INT_T) count));
}
const Value builtins::peek(const Value& arg_list) {
if (arg_list.is_undef()) {
return std::move(Value());
}
List *list = arg_list.value.list;
if (list->begin() != list->end()) {
return std::move(Value(*(list->begin())));
} else {
return std::move(Value());
}
}
const Value builtins::boolean2int(const Value& arg) {
if (arg.is_undef()) {
return std::move(arg);
}
return std::move(Value((INT_T)arg.value.bval));
}
const Value builtins::int2boolean(const Value& arg) {
if (arg.is_undef()) {
return std::move(arg);
}
return std::move(Value((bool)arg.value.ival));
}
const Value builtins::enum2int(const Value& arg) {
if (arg.is_undef()) {
return std::move(arg);
}
return std::move(Value((INT_T)arg.value.enum_val->id));
}
const Value builtins::asint(const Value& arg) {
if (arg.is_undef()) {
return std::move(arg);
}
switch (arg.type) {
case TypeType::INT:
return std::move(Value(arg.value.ival));
case TypeType::FLOAT:
return std::move(Value((INT_T)arg.value.fval));
case TypeType::RATIONAL:
return std::move(Value((INT_T)(arg.value.rat->numerator / arg.value.rat->denominator)));
default: assert(0);
}
}
const Value builtins::asfloat(const Value& arg) {
if (arg.is_undef()) {
return std::move(arg);
}
switch (arg.type) {
case TypeType::INT:
return std::move(Value((FLOAT_T) arg.value.ival));
case TypeType::FLOAT:
return std::move(Value(arg.value.fval));
case TypeType::RATIONAL:
return std::move(Value(((FLOAT_T)arg.value.rat->numerator) / arg.value.rat->denominator));
default: assert(0);
}
}
void get_numerator_denominator(double x, int64_t *num, int64_t *denom) {
// thanks to
// http://stackoverflow.com/a/96035/781502
uint64_t m[2][2];
double startx = x;
int64_t maxden = 10000000000;
int64_t ai;
/* initialize matrix */
m[0][0] = m[1][1] = 1;
m[0][1] = m[1][0] = 0;
/* loop finding terms until denom gets too big */
while (m[1][0] * ( ai = (int64_t)x ) + m[1][1] <= maxden) {
long t;
t = m[0][0] * ai + m[0][1];
m[0][1] = m[0][0];
m[0][0] = t;
t = m[1][0] * ai + m[1][1];
m[1][1] = m[1][0];
m[1][0] = t;
if(x==(double)ai) break; // AF: division by zero
x = 1/(x - (double) ai);
if(x>(double)0x7FFFFFFF) break; // AF: representation failure
}
/* now remaining x is between 0 and 1/ai */
/* approx as either 0 or 1/m where m is max that will fit in maxden */
/* first try zero */
double error1 = startx - ((double) m[0][0] / (double) m[1][0]);
*num = m[0][0];
*denom = m[1][0];
/* now try other possibility */
ai = (maxden - m[1][1]) / m[1][0];
m[0][0] = m[0][0] * ai + m[0][1];
m[1][0] = m[1][0] * ai + m[1][1];
double error2 = startx - ((double) m[0][0] / (double) m[1][0]);
if (abs(error1) > abs(error2)) {
*num = m[0][0];
*denom = m[1][0];
}
}
const Value builtins::asrational(const Value& arg) {
if (arg.is_undef()) {
return std::move(arg);
}
rational_t *result = (rational_t*) pp_mem_alloc(
&(ExecutionContext::value_stack), sizeof(rational_t)
);
switch (arg.type) {
case TypeType::INT:
result->numerator = arg.value.ival;
result->denominator = 1;
return std::move(Value(result));
case TypeType::FLOAT:
get_numerator_denominator(arg.value.fval, &result->numerator, &result->denominator);
return std::move(Value(result));
case TypeType::RATIONAL:
return std::move(Value(arg.value.rat));
default: assert(0);
}
}
const Value builtins::symbolic(const Value& arg) {
if (arg.is_symbolic() && !arg.value.sym->list) {
return std::move(Value(true));
} else {
return std::move(Value(false));
}
}
namespace builtins {
namespace shared {
#include "shared_glue.h"
IGNORE_VARIADIC_WARNINGS
#pragma GCC diagnostic ignored "-Wmissing-field-initializers"
#pragma GCC diagnostic ignored "-Wunused-parameter"
// the CASM runtime heavily depens on macros, whatever you think of it ...
// here we need to provide all definitions ...
#define TRUE 1
#define FALSE 0
#define ARG(TYPE, NAME) TYPE* NAME
#define SARG(VAR) #VAR " {0x%lx,%u}"
#define PARG(TYPE, VAR) (uint64_t)VAR->value, VAR->defined
#define CASM_RT(FORMAT, ARGS...) /* printf-able */
#define CASM_INFO(FORMAT, ARGS...) /* printf-able */
// create concrete variants of the shareds
#define CASM_CALL_SHARED(NAME, VALUE, ARGS...) NAME(VALUE, ##ARGS)
#define DEFINE_CASM_SHARED(NAME, VALUE, ARGS...) void NAME(VALUE, ##ARGS)
#include "libcasmrt/pp_casm_shared.h"
namespace symbolic {
// create symbolic variants of shareds
namespace BV {
// mock BV namespace as expected by the pp_casm_shared builtins
struct helper_t {
bool next() { return true; }
};
static helper_t symbolic_nopointer;
helper_t *symbolic_ = &symbolic_nopointer;
}
#undef CASM_CALL_SHARED
#undef DEFINE_CASM_SHARED
#define SYMBOLIC
#define CASM_CALL_SHARED(NAME, VALUE, ARGS...) symbolic_##NAME(VALUE, ##ARGS)
#define DEFINE_CASM_SHARED(NAME, VALUE, ARGS...) void symbolic_##NAME(VALUE, ##ARGS)
#include "libcasmrt/pp_casm_shared.h"
}
#pragma GCC diagnostic warning "-Wmissing-field-initializers"
#pragma GCC diagnostic warning "-Wunused-parameter"
REENABLE_VARIADIC_WARNINGS
const Value dispatch(BuiltinAtom::Id builtin_id,
const std::vector<Value>& arguments, ExecutionContext& ctxt) {
const char *sym_name;
Int ret;
Int arg0;
Int arg1;
Int arg2;
Int arg3;
Int arg4;
switch (builtin_id) {
SHARED_DISPATCH
default: assert(0);
}
if (ret.defined == TRUE) {
return std::move(Value((INT_T)ret.value));
} else if (ctxt.symbolic && ret.sym) {
Value v(new symbol_t(::symbolic::next_symbol_id()));
::symbolic::dump_builtin(ctxt.trace, sym_name, arguments, v);
return std::move(v);
} else {
return std::move(Value());
}
}
}
}
<|endoftext|> |
<commit_before>//===-- asan_suppressions.cc ----------------------------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file is a part of AddressSanitizer, an address sanity checker.
//
// Issue suppression and suppression-related functions.
//===----------------------------------------------------------------------===//
#include "asan_suppressions.h"
#include "asan_stack.h"
#include "sanitizer_common/sanitizer_placement_new.h"
#include "sanitizer_common/sanitizer_suppressions.h"
#include "sanitizer_common/sanitizer_symbolizer.h"
namespace __asan {
ALIGNED(64) static char suppression_placeholder[sizeof(SuppressionContext)];
static SuppressionContext *suppression_ctx = nullptr;
static const char kInterceptorName[] = "interceptor_name";
static const char kInterceptorViaFunction[] = "interceptor_via_fun";
static const char kInterceptorViaLibrary[] = "interceptor_via_lib";
static const char kODRViolation[] = "odr_violation";
static const char *kSuppressionTypes[] = {
kInterceptorName, kInterceptorViaFunction, kInterceptorViaLibrary,
kODRViolation};
extern "C" {
#if SANITIZER_SUPPORTS_WEAK_HOOKS
SANITIZER_INTERFACE_ATTRIBUTE SANITIZER_WEAK_ATTRIBUTE
const char *__asan_default_suppressions();
#else
// No week hooks, provide empty implementation.
const char *__asan_default_suppressions() { return ""; }
#endif // SANITIZER_SUPPORTS_WEAK_HOOKS
} // extern "C"
void InitializeSuppressions() {
CHECK_EQ(nullptr, suppression_ctx);
suppression_ctx = new (suppression_placeholder) // NOLINT
SuppressionContext(kSuppressionTypes, ARRAY_SIZE(kSuppressionTypes));
suppression_ctx->ParseFromFile(flags()->suppressions);
if (&__asan_default_suppressions)
suppression_ctx->Parse(__asan_default_suppressions());
}
bool IsInterceptorSuppressed(const char *interceptor_name) {
CHECK(suppression_ctx);
Suppression *s;
// Match "interceptor_name" suppressions.
return suppression_ctx->Match(interceptor_name, kInterceptorName, &s);
}
bool HaveStackTraceBasedSuppressions() {
CHECK(suppression_ctx);
return suppression_ctx->HasSuppressionType(kInterceptorViaFunction) ||
suppression_ctx->HasSuppressionType(kInterceptorViaLibrary);
}
bool IsODRViolationSuppressed(const char *global_var_name) {
CHECK(suppression_ctx);
Suppression *s;
// Match "odr_violation" suppressions.
return suppression_ctx->Match(global_var_name, kODRViolation, &s);
}
bool IsStackTraceSuppressed(const StackTrace *stack) {
if (!HaveStackTraceBasedSuppressions())
return false;
CHECK(suppression_ctx);
Symbolizer *symbolizer = Symbolizer::GetOrInit();
Suppression *s;
for (uptr i = 0; i < stack->size && stack->trace[i]; i++) {
uptr addr = stack->trace[i];
if (suppression_ctx->HasSuppressionType(kInterceptorViaLibrary)) {
const char *module_name;
uptr module_offset;
// Match "interceptor_via_lib" suppressions.
if (symbolizer->GetModuleNameAndOffsetForPC(addr, &module_name,
&module_offset) &&
suppression_ctx->Match(module_name, kInterceptorViaLibrary, &s)) {
return true;
}
}
if (suppression_ctx->HasSuppressionType(kInterceptorViaFunction)) {
SymbolizedStack *frames = symbolizer->SymbolizePC(addr);
for (SymbolizedStack *cur = frames; cur; cur = cur->next) {
const char *function_name = cur->info.function;
if (!function_name) {
continue;
}
// Match "interceptor_via_fun" suppressions.
if (suppression_ctx->Match(function_name, kInterceptorViaFunction,
&s)) {
frames->ClearAll();
return true;
}
}
frames->ClearAll();
}
}
return false;
}
} // namespace __asan
<commit_msg>[asan] attempting to fix the windows build <commit_after>//===-- asan_suppressions.cc ----------------------------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file is a part of AddressSanitizer, an address sanity checker.
//
// Issue suppression and suppression-related functions.
//===----------------------------------------------------------------------===//
#include "asan_suppressions.h"
#include "asan_stack.h"
#include "sanitizer_common/sanitizer_placement_new.h"
#include "sanitizer_common/sanitizer_suppressions.h"
#include "sanitizer_common/sanitizer_symbolizer.h"
namespace __asan {
ALIGNED(64) static char suppression_placeholder[sizeof(SuppressionContext)];
static SuppressionContext *suppression_ctx = nullptr;
static const char kInterceptorName[] = "interceptor_name";
static const char kInterceptorViaFunction[] = "interceptor_via_fun";
static const char kInterceptorViaLibrary[] = "interceptor_via_lib";
static const char kODRViolation[] = "odr_violation";
static const char *kSuppressionTypes[] = {
kInterceptorName, kInterceptorViaFunction, kInterceptorViaLibrary,
kODRViolation};
#if SANITIZER_SUPPORTS_WEAK_HOOKS
extern "C" {
SANITIZER_INTERFACE_ATTRIBUTE SANITIZER_WEAK_ATTRIBUTE
const char *__asan_default_suppressions();
} // extern "C"
#endif // SANITIZER_SUPPORTS_WEAK_HOOKS
void InitializeSuppressions() {
CHECK_EQ(nullptr, suppression_ctx);
suppression_ctx = new (suppression_placeholder) // NOLINT
SuppressionContext(kSuppressionTypes, ARRAY_SIZE(kSuppressionTypes));
suppression_ctx->ParseFromFile(flags()->suppressions);
#if SANITIZER_SUPPORTS_WEAK_HOOKS
if (&__asan_default_suppressions)
suppression_ctx->Parse(__asan_default_suppressions());
#endif // SANITIZER_SUPPORTS_WEAK_HOOKS
}
bool IsInterceptorSuppressed(const char *interceptor_name) {
CHECK(suppression_ctx);
Suppression *s;
// Match "interceptor_name" suppressions.
return suppression_ctx->Match(interceptor_name, kInterceptorName, &s);
}
bool HaveStackTraceBasedSuppressions() {
CHECK(suppression_ctx);
return suppression_ctx->HasSuppressionType(kInterceptorViaFunction) ||
suppression_ctx->HasSuppressionType(kInterceptorViaLibrary);
}
bool IsODRViolationSuppressed(const char *global_var_name) {
CHECK(suppression_ctx);
Suppression *s;
// Match "odr_violation" suppressions.
return suppression_ctx->Match(global_var_name, kODRViolation, &s);
}
bool IsStackTraceSuppressed(const StackTrace *stack) {
if (!HaveStackTraceBasedSuppressions())
return false;
CHECK(suppression_ctx);
Symbolizer *symbolizer = Symbolizer::GetOrInit();
Suppression *s;
for (uptr i = 0; i < stack->size && stack->trace[i]; i++) {
uptr addr = stack->trace[i];
if (suppression_ctx->HasSuppressionType(kInterceptorViaLibrary)) {
const char *module_name;
uptr module_offset;
// Match "interceptor_via_lib" suppressions.
if (symbolizer->GetModuleNameAndOffsetForPC(addr, &module_name,
&module_offset) &&
suppression_ctx->Match(module_name, kInterceptorViaLibrary, &s)) {
return true;
}
}
if (suppression_ctx->HasSuppressionType(kInterceptorViaFunction)) {
SymbolizedStack *frames = symbolizer->SymbolizePC(addr);
for (SymbolizedStack *cur = frames; cur; cur = cur->next) {
const char *function_name = cur->info.function;
if (!function_name) {
continue;
}
// Match "interceptor_via_fun" suppressions.
if (suppression_ctx->Match(function_name, kInterceptorViaFunction,
&s)) {
frames->ClearAll();
return true;
}
}
frames->ClearAll();
}
}
return false;
}
} // namespace __asan
<|endoftext|> |
<commit_before>// Copyright (c) 2007, 2008 libmv authors.
//
// 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 <cassert>
#include <vector>
#include "libmv/numeric/numeric.h"
#include "libmv/correspondence/klt.h"
#include "libmv/image/image.h"
#include "libmv/image/image_io.h"
#include "libmv/image/convolve.h"
#include "libmv/image/sample.h"
using std::vector;
namespace libmv {
static void FindLocalMaxima(const FloatImage &trackness,
float min_trackness,
KLTContext::FeatureList *features) {
for (int i = 1; i < trackness.Height()-1; ++i) {
for (int j = 1; j < trackness.Width()-1; ++j) {
if ( trackness(i,j) >= min_trackness
&& trackness(i,j) >= trackness(i-1, j-1)
&& trackness(i,j) >= trackness(i-1, j )
&& trackness(i,j) >= trackness(i-1, j+1)
&& trackness(i,j) >= trackness(i , j-1)
&& trackness(i,j) >= trackness(i , j+1)
&& trackness(i,j) >= trackness(i+1, j-1)
&& trackness(i,j) >= trackness(i+1, j )
&& trackness(i,j) >= trackness(i+1, j+1)) {
KLTPointFeature *p = new KLTPointFeature;
p->position(1) = i;
p->position(0) = j;
p->trackness = trackness(i,j);
features->push_back(p);
}
}
}
}
// Compute the gradient matrix noted by Z in Good Features to Track.
//
// Z = [gxx gxy; gxy gyy]
//
// This function computes the matrix for every pixel.
static void ComputeGradientMatrix(const Array3Df &image_and_gradients,
int window_size,
Array3Df *gradient_matrix) {
Array3Df gradients;
gradients.ResizeLike(image_and_gradients);
for (int j = 0; j < image_and_gradients.Height(); ++j) {
for (int i = 0; i < image_and_gradients.Width(); ++i) {
float gx = image_and_gradients(j, i, 1);
float gy = image_and_gradients(j, i, 2);
gradients(j, i, 0) = gx * gx;
gradients(j, i, 1) = gx * gy;
gradients(j, i, 2) = gy * gy;
}
}
// Sum the gradient matrix over tracking window for each pixel.
BoxFilter(gradients, window_size, gradient_matrix);
}
// Given the three distinct elements of the symmetric 2x2 matrix
//
// [gxx gxy]
// [gxy gyy],
//
// return the minimum eigenvalue of the matrix.
// Borrowed from Stan Birchfield's KLT implementation.
static float MinEigenValue(float gxx, float gxy, float gyy) {
return (gxx + gyy - sqrt((gxx - gyy) * (gxx - gyy) + 4 * gxy * gxy)) / 2.0f;
}
// Compute trackness of every pixel given the gradient matrix.
// This is done as described in the Good Features to Track paper.
static void ComputeTrackness(const Array3Df gradient_matrix,
Array3Df *trackness_pointer,
double *trackness_mean) {
Array3Df &trackness = *trackness_pointer;
trackness.Resize(gradient_matrix.Height(), gradient_matrix.Width());
*trackness_mean = 0;
for (int i = 0; i < trackness.Height(); ++i) {
for (int j = 0; j < trackness.Width(); ++j) {
double t = MinEigenValue(gradient_matrix(i, j, 0),
gradient_matrix(i, j, 1),
gradient_matrix(i, j, 2));
trackness(i, j) = t;
*trackness_mean += t;
}
}
*trackness_mean /= trackness.Size();
}
static double dist2(const Vec2f &x, const Vec2f &y) {
double a = x(0) - y(0);
double b = x(1) - y(1);
return a * a + b * b;
}
// TODO(keir): Use Stan's neat trick of using a 'punch-out' array to detect
// too-closes features. This is O(n^2)!
static void RemoveTooCloseFeatures(KLTContext::FeatureList *features,
double mindist2) {
KLTContext::FeatureList::iterator i = features->begin();
while (i != features->end()) {
bool i_deleted = false;
KLTContext::FeatureList::iterator j = i;
++j;
while (j != features->end() && !i_deleted) {
if (dist2((*i)->position, (*j)->position) < mindist2) {
KLTContext::FeatureList::iterator to_delete;
if ((*i)->trackness < (*j)->trackness) {
to_delete = i;
++i;
i_deleted = true;
} else {
to_delete = j;
++j;
}
delete *to_delete;
features->erase(to_delete);
} else {
++j;
}
}
if (!i_deleted) {
++i;
}
}
}
void KLTContext::DetectGoodFeatures(const Array3Df &image_and_gradients,
FeatureList *features) {
Array3Df gradient_matrix;
ComputeGradientMatrix(image_and_gradients, WindowSize(), &gradient_matrix);
Array3Df trackness;
double trackness_mean;
ComputeTrackness(gradient_matrix, &trackness, &trackness_mean);
min_trackness_ = trackness_mean;
FindLocalMaxima(trackness, min_trackness_, features);
RemoveTooCloseFeatures(features, min_feature_dist_ * min_feature_dist_);
}
// TODO(keir): Restore or delete these functions...
void KLTContext::TrackFeatures(ImagePyramid *pyramid1,
const FeatureList &features1,
ImagePyramid *pyramid2,
FeatureList *features2_pointer) {
FeatureList &features2 = *features2_pointer;
features2.clear();
for (FeatureList::const_iterator i = features1.begin();
i != features1.end(); ++i) {
KLTPointFeature *tracked_feature = new KLTPointFeature;
TrackFeature(pyramid1, **i, pyramid2, tracked_feature);
features2.push_back(tracked_feature);
}
}
void KLTContext::TrackFeature(ImagePyramid *pyramid1,
const KLTPointFeature &feature1,
ImagePyramid *pyramid2,
KLTPointFeature *feature2_pointer) {
const int highest_level = pyramid1->NumLevels() - 1;
Vec2 position1, position2;
position2(0) = feature1.position(0) / pow(2., highest_level + 1);
position2(1) = feature1.position(1) / pow(2., highest_level + 1);
for (int i = highest_level; i >= 0; --i) {
position1(0) = feature1.position(0) / pow(2., i);
position1(1) = feature1.position(1) / pow(2., i);
position2(0) *= 2;
position2(1) *= 2;
TrackFeatureOneLevel(pyramid1->Level(i),
position1,
pyramid2->Level(i),
&position2);
}
feature2_pointer->position = position2;
}
// Compute the gradient matrix noted by Z and the error vector e.
// See Good Features to Track.
static void ComputeTrackingEquation(const Array3Df &image_and_gradient1,
const Array3Df &image_and_gradient2,
const Vec2 &position1,
const Vec2 &position2,
int half_width,
float *gxx,
float *gxy,
float *gyy,
float *ex,
float *ey) {
*gxx = 0;
*gxy = 0;
*gyy = 0;
*ex = 0;
*ey = 0;
for (int i = -half_width; i <= half_width; ++i) {
for (int j = -half_width; j <= half_width; ++j) {
float x1 = position1(0) + j;
float y1 = position1(1) + i;
float x2 = position2(0) + j;
float y2 = position2(1) + i;
// TODO(pau): should do boundary checking outside this loop, and call here
// a sampler that does not boundary checking.
float I = SampleLinear(image_and_gradient1, y1, x1, 0);
float J = SampleLinear(image_and_gradient2, y2, x2, 0);
float gx = SampleLinear(image_and_gradient2, y2, x2, 1);
float gy = SampleLinear(image_and_gradient2, y2, x2, 2);
*gxx += gx * gx;
*gxy += gx * gy;
*gyy += gy * gy;
*ex += (I - J) * gx;
*ey += (I - J) * gy;
}
}
}
// Solve the tracking equation
//
// [gxx gxy] [dx] = [ex]
// [gxy gyy] [dy] = [ey]
//
// for dx and dy. Borrowed from Stan Birchfield's KLT implementation.
static bool SolveTrackingEquation(float gxx, float gxy, float gyy,
float ex, float ey,
float min_determinant,
float *dx, float *dy) {
float det = gxx * gyy - gxy * gxy;
// printf("det=%f, min_det=%f, gxx=%f, gxy=%f, gyy=%f\n", det, min_determinant,
// gxx, gxy, gyy);
if (det < min_determinant) {
*dx = 0;
*dy = 0;
return false;
}
*dx = (gyy * ex - gxy * ey) / det;
*dy = (gxx * ey - gxy * ex) / det;
return true;
}
void KLTContext::TrackFeatureOneLevel(const Array3Df &image_and_gradient1,
const Vec2 &position1,
const Array3Df &image_and_gradient2,
Vec2 *position2_pointer) {
Vec2 &position2 = *position2_pointer;
for (int i = 0; i < max_iterations_; ++i) {
// Compute gradient matrix and error vector.
float gxx, gxy, gyy, ex, ey;
ComputeTrackingEquation(image_and_gradient1, image_and_gradient2,
position1, position2,
HalfWindowSize(),
&gxx, &gxy, &gyy, &ex, &ey);
// Solve the linear system for deltad.
float dx, dy;
if (!SolveTrackingEquation(gxx, gxy, gyy, ex, ey, min_determinant_,
&dx, &dy)) {
// TODO(keir): drop feature.
// printf("dropped!\n");
}
// Update feature2 position.
position2(0) += dx;
position2(1) += dy;
// TODO(keir): Handle other tracking failure conditions and pass the
// reasons out to the caller. For example, for pyramid tracking a failure
// at a coarse level suggests trying again at a finer level.
if (Square(dx) + Square(dy) < min_update_distance2_) {
// printf("distance too small: %f, %f\n", dx, dy);
break;
}
// printf("dx=%f, dy=%f\n", dx, dy);
}
}
void KLTContext::DrawFeatureList(const FeatureList &features,
const Vec3 &color,
FloatImage *image) const {
for (FeatureList::const_iterator i = features.begin();
i != features.end(); ++i) {
DrawFeature(**i, color, image);
}
}
void KLTContext::DrawFeature(const KLTPointFeature &feature,
const Vec3 &color,
FloatImage *image) const {
assert(image->Depth() == 3);
const int cross_width = 5;
int x = lround(feature.position(0));
int y = lround(feature.position(1));
if (!image->Contains(y,x)) {
return;
}
// Draw vertical line.
for (int i = max(0, y - cross_width);
i < min(image->Height(), y + cross_width + 1); ++i) {
for (int k = 0; k < 3; ++k) {
(*image)(i, x, k) = color(k);
}
}
// Draw horizontal line.
for (int j = max(0, x - cross_width);
j < min(image->Width(), x + cross_width + 1); ++j) {
for (int k = 0; k < 3; ++k) {
(*image)(y, j, k) = color(k);
}
}
}
} // namespace libmv
<commit_msg>Add debug printing to KLT.<commit_after>// Copyright (c) 2007, 2008 libmv authors.
//
// 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 <cassert>
#include <vector>
#include "libmv/numeric/numeric.h"
#include "libmv/correspondence/klt.h"
#include "libmv/image/image.h"
#include "libmv/image/image_io.h"
#include "libmv/image/convolve.h"
#include "libmv/image/sample.h"
using std::vector;
namespace libmv {
static void FindLocalMaxima(const FloatImage &trackness,
float min_trackness,
KLTContext::FeatureList *features) {
for (int i = 1; i < trackness.Height()-1; ++i) {
for (int j = 1; j < trackness.Width()-1; ++j) {
if ( trackness(i,j) >= min_trackness
&& trackness(i,j) >= trackness(i-1, j-1)
&& trackness(i,j) >= trackness(i-1, j )
&& trackness(i,j) >= trackness(i-1, j+1)
&& trackness(i,j) >= trackness(i , j-1)
&& trackness(i,j) >= trackness(i , j+1)
&& trackness(i,j) >= trackness(i+1, j-1)
&& trackness(i,j) >= trackness(i+1, j )
&& trackness(i,j) >= trackness(i+1, j+1)) {
KLTPointFeature *p = new KLTPointFeature;
p->position(1) = i;
p->position(0) = j;
p->trackness = trackness(i,j);
features->push_back(p);
}
}
}
}
// Compute the gradient matrix noted by Z in Good Features to Track.
//
// Z = [gxx gxy; gxy gyy]
//
// This function computes the matrix for every pixel.
static void ComputeGradientMatrix(const Array3Df &image_and_gradients,
int window_size,
Array3Df *gradient_matrix) {
Array3Df gradients;
gradients.ResizeLike(image_and_gradients);
for (int j = 0; j < image_and_gradients.Height(); ++j) {
for (int i = 0; i < image_and_gradients.Width(); ++i) {
float gx = image_and_gradients(j, i, 1);
float gy = image_and_gradients(j, i, 2);
gradients(j, i, 0) = gx * gx;
gradients(j, i, 1) = gx * gy;
gradients(j, i, 2) = gy * gy;
}
}
// Sum the gradient matrix over tracking window for each pixel.
BoxFilter(gradients, window_size, gradient_matrix);
}
// Given the three distinct elements of the symmetric 2x2 matrix
//
// [gxx gxy]
// [gxy gyy],
//
// return the minimum eigenvalue of the matrix.
// Borrowed from Stan Birchfield's KLT implementation.
static float MinEigenValue(float gxx, float gxy, float gyy) {
return (gxx + gyy - sqrt((gxx - gyy) * (gxx - gyy) + 4 * gxy * gxy)) / 2.0f;
}
// Compute trackness of every pixel given the gradient matrix.
// This is done as described in the Good Features to Track paper.
static void ComputeTrackness(const Array3Df gradient_matrix,
Array3Df *trackness_pointer,
double *trackness_mean) {
Array3Df &trackness = *trackness_pointer;
trackness.Resize(gradient_matrix.Height(), gradient_matrix.Width());
*trackness_mean = 0;
for (int i = 0; i < trackness.Height(); ++i) {
for (int j = 0; j < trackness.Width(); ++j) {
double t = MinEigenValue(gradient_matrix(i, j, 0),
gradient_matrix(i, j, 1),
gradient_matrix(i, j, 2));
trackness(i, j) = t;
*trackness_mean += t;
}
}
*trackness_mean /= trackness.Size();
}
static double dist2(const Vec2f &x, const Vec2f &y) {
double a = x(0) - y(0);
double b = x(1) - y(1);
return a * a + b * b;
}
// TODO(keir): Use Stan's neat trick of using a 'punch-out' array to detect
// too-closes features. This is O(n^2)!
static void RemoveTooCloseFeatures(KLTContext::FeatureList *features,
double mindist2) {
KLTContext::FeatureList::iterator i = features->begin();
while (i != features->end()) {
bool i_deleted = false;
KLTContext::FeatureList::iterator j = i;
++j;
while (j != features->end() && !i_deleted) {
if (dist2((*i)->position, (*j)->position) < mindist2) {
KLTContext::FeatureList::iterator to_delete;
if ((*i)->trackness < (*j)->trackness) {
to_delete = i;
++i;
i_deleted = true;
} else {
to_delete = j;
++j;
}
delete *to_delete;
features->erase(to_delete);
} else {
++j;
}
}
if (!i_deleted) {
++i;
}
}
}
void KLTContext::DetectGoodFeatures(const Array3Df &image_and_gradients,
FeatureList *features) {
Array3Df gradient_matrix;
ComputeGradientMatrix(image_and_gradients, WindowSize(), &gradient_matrix);
Array3Df trackness;
double trackness_mean;
ComputeTrackness(gradient_matrix, &trackness, &trackness_mean);
min_trackness_ = trackness_mean;
FindLocalMaxima(trackness, min_trackness_, features);
RemoveTooCloseFeatures(features, min_feature_dist_ * min_feature_dist_);
}
// TODO(keir): Restore or delete these functions...
void KLTContext::TrackFeatures(ImagePyramid *pyramid1,
const FeatureList &features1,
ImagePyramid *pyramid2,
FeatureList *features2_pointer) {
FeatureList &features2 = *features2_pointer;
features2.clear();
for (FeatureList::const_iterator i = features1.begin();
i != features1.end(); ++i) {
KLTPointFeature *tracked_feature = new KLTPointFeature;
TrackFeature(pyramid1, **i, pyramid2, tracked_feature);
features2.push_back(tracked_feature);
}
}
void KLTContext::TrackFeature(ImagePyramid *pyramid1,
const KLTPointFeature &feature1,
ImagePyramid *pyramid2,
KLTPointFeature *feature2_pointer) {
const int highest_level = pyramid1->NumLevels() - 1;
Vec2 position1, position2;
position2(0) = feature1.position(0) / pow(2., highest_level + 1);
position2(1) = feature1.position(1) / pow(2., highest_level + 1);
for (int i = highest_level; i >= 0; --i) {
position1(0) = feature1.position(0) / pow(2., i);
position1(1) = feature1.position(1) / pow(2., i);
position2(0) *= 2;
position2(1) *= 2;
TrackFeatureOneLevel(pyramid1->Level(i),
position1,
pyramid2->Level(i),
&position2);
}
feature2_pointer->position = position2;
}
// Compute the gradient matrix noted by Z and the error vector e.
// See Good Features to Track.
static void ComputeTrackingEquation(const Array3Df &image_and_gradient1,
const Array3Df &image_and_gradient2,
const Vec2 &position1,
const Vec2 &position2,
int half_width,
float *gxx,
float *gxy,
float *gyy,
float *ex,
float *ey) {
*gxx = 0;
*gxy = 0;
*gyy = 0;
*ex = 0;
*ey = 0;
for (int i = -half_width; i <= half_width; ++i) {
for (int j = -half_width; j <= half_width; ++j) {
float x1 = position1(0) + j;
float y1 = position1(1) + i;
float x2 = position2(0) + j;
float y2 = position2(1) + i;
// TODO(pau): should do boundary checking outside this loop, and call here
// a sampler that does not boundary checking.
float I = SampleLinear(image_and_gradient1, y1, x1, 0);
float J = SampleLinear(image_and_gradient2, y2, x2, 0);
float gx = SampleLinear(image_and_gradient2, y2, x2, 1);
float gy = SampleLinear(image_and_gradient2, y2, x2, 2);
*gxx += gx * gx;
*gxy += gx * gy;
*gyy += gy * gy;
*ex += (I - J) * gx;
*ey += (I - J) * gy;
}
}
}
// Solve the tracking equation
//
// [gxx gxy] [dx] = [ex]
// [gxy gyy] [dy] = [ey]
//
// for dx and dy. Borrowed from Stan Birchfield's KLT implementation.
static bool SolveTrackingEquation(float gxx, float gxy, float gyy,
float ex, float ey,
float min_determinant,
float *dx, float *dy) {
float det = gxx * gyy - gxy * gxy;
// printf("det=%f, min_det=%f, gxx=%f, gxy=%f, gyy=%f\n", det, min_determinant,
// gxx, gxy, gyy);
if (det < min_determinant) {
*dx = 0;
*dy = 0;
return false;
}
*dx = (gyy * ex - gxy * ey) / det;
*dy = (gxx * ey - gxy * ex) / det;
return true;
}
void KLTContext::TrackFeatureOneLevel(const Array3Df &image_and_gradient1,
const Vec2 &position1,
const Array3Df &image_and_gradient2,
Vec2 *position2_pointer) {
Vec2 &position2 = *position2_pointer;
int i;
float dx=0, dy=0;
max_iterations_ = 30;
printf("disps = array([\n");
for (i = 0; i < max_iterations_; ++i) {
// Compute gradient matrix and error vector.
float gxx, gxy, gyy, ex, ey;
ComputeTrackingEquation(image_and_gradient1, image_and_gradient2,
position1, position2,
HalfWindowSize(),
&gxx, &gxy, &gyy, &ex, &ey);
// Solve the linear system for deltad.
if (!SolveTrackingEquation(gxx, gxy, gyy, ex, ey, min_determinant_,
&dx, &dy)) {
// TODO(keir): drop feature.
printf("dropped!\n");
}
// shrink the update
dx *= 0.5;
dy *= 0.5;
// Update feature2 position.
position2(0) += dx;
position2(1) += dy;
printf(" [%10f, %10f, %10f, %10f],\n", dx, dy, position2(0), position2(1));
// TODO(keir): Handle other tracking failure conditions and pass the
// reasons out to the caller. For example, for pyramid tracking a failure
// at a coarse level suggests trying again at a finer level.
if (Square(dx) + Square(dy) < min_update_distance2_) {
printf("# distance too small: %f, %f\n", dx, dy);
break;
}
// printf("dx=%f, dy=%f\n", dx, dy);
}
printf("])\n");
if (i == max_iterations_) {
printf("hit max iters. dx=%f, dy=%f\n", dx, dy);
}
}
void KLTContext::DrawFeatureList(const FeatureList &features,
const Vec3 &color,
FloatImage *image) const {
for (FeatureList::const_iterator i = features.begin();
i != features.end(); ++i) {
DrawFeature(**i, color, image);
}
}
void KLTContext::DrawFeature(const KLTPointFeature &feature,
const Vec3 &color,
FloatImage *image) const {
assert(image->Depth() == 3);
const int cross_width = 5;
int x = lround(feature.position(0));
int y = lround(feature.position(1));
if (!image->Contains(y,x)) {
return;
}
// Draw vertical line.
for (int i = max(0, y - cross_width);
i < min(image->Height(), y + cross_width + 1); ++i) {
for (int k = 0; k < 3; ++k) {
(*image)(i, x, k) = color(k);
}
}
// Draw horizontal line.
for (int j = max(0, x - cross_width);
j < min(image->Width(), x + cross_width + 1); ++j) {
for (int k = 0; k < 3; ++k) {
(*image)(y, j, k) = color(k);
}
}
}
} // namespace libmv
<|endoftext|> |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.