text stringlengths 54 60.6k |
|---|
<commit_before>//
// LemonScriptState.cpp
// FiniteStateMachine
//
// Created by Donald Pinckney on 12/24/15.
// Copyright © 2015 Donald Pinckney. All rights reserved.
//
#include <stdlib.h>
#include "LemonScriptState.h"
void LemonScriptState::declareVariable(int line, const std::string &name, DataType type, void *pointerToValue) {
if(variableAddresses.find(name) != variableAddresses.end()) {
throw "Line " + std::to_string(line) + ":\nDuplicate variable definition: " + name;
}
void *address;
switch (type) {
case INT:
address = malloc(sizeof(int));
memcpy(address, pointerToValue, sizeof(int));
break;
case FLOAT:
address = malloc(sizeof(float));
memcpy(address, pointerToValue, sizeof(float));
break;
case BOOLEAN:
address = malloc(sizeof(bool));
memcpy(address, pointerToValue, sizeof(bool));
break;
default:
break;
}
variableAddresses[name] = address;
variableTypes[name] = type;
}
void LemonScriptState::declareAvailableCppCommand(const AvailableCppCommandDeclaration *decl) {
std::string name = decl->functionName;
std::vector<const AvailableCppCommandDeclaration *> &commands = availableCppCommands[name];
for (auto it = commands.begin(); it != commands.end(); ++it) {
if((*it)->parameters == decl->parameters) {
throw "Duplicate command definition with params: " + name;
}
}
commands.push_back(decl);
}
void * LemonScriptState::addressOfVariable(const std::string &variableName) const {
auto it = variableAddresses.find(variableName);
if(it != variableAddresses.end()) {
return it->second;
} else {
return NULL;
}
}
DataType LemonScriptState::typeOfVariable(const std::string &variableName) const {
auto it = variableTypes.find(variableName);
if(it != variableTypes.end()) {
return it->second;
} else {
return INT;
}
}
const AvailableCppCommandDeclaration * LemonScriptState::lookupCommandDeclaration(const std::string &name, const std::vector<DataType> ¶meterTypes) const {
auto mapIt = availableCppCommands.find(name);
if(mapIt == availableCppCommands.end()) {
return NULL;
}
const std::vector<const AvailableCppCommandDeclaration *> &commands = mapIt->second;
for (auto it = commands.begin(); it != commands.end(); ++it) {
const AvailableCppCommandDeclaration *decl = *it;
if(decl->parameters == parameterTypes) {
return decl;
}
}
return NULL;
}<commit_msg>Add string include<commit_after>//
// LemonScriptState.cpp
// FiniteStateMachine
//
// Created by Donald Pinckney on 12/24/15.
// Copyright © 2015 Donald Pinckney. All rights reserved.
//
#include <stdlib.h>
#include <string.h>
#include "LemonScriptState.h"
void LemonScriptState::declareVariable(int line, const std::string &name, DataType type, void *pointerToValue) {
if(variableAddresses.find(name) != variableAddresses.end()) {
throw "Line " + std::to_string(line) + ":\nDuplicate variable definition: " + name;
}
void *address;
switch (type) {
case INT:
address = malloc(sizeof(int));
memcpy(address, pointerToValue, sizeof(int));
break;
case FLOAT:
address = malloc(sizeof(float));
memcpy(address, pointerToValue, sizeof(float));
break;
case BOOLEAN:
address = malloc(sizeof(bool));
memcpy(address, pointerToValue, sizeof(bool));
break;
default:
break;
}
variableAddresses[name] = address;
variableTypes[name] = type;
}
void LemonScriptState::declareAvailableCppCommand(const AvailableCppCommandDeclaration *decl) {
std::string name = decl->functionName;
std::vector<const AvailableCppCommandDeclaration *> &commands = availableCppCommands[name];
for (auto it = commands.begin(); it != commands.end(); ++it) {
if((*it)->parameters == decl->parameters) {
throw "Duplicate command definition with params: " + name;
}
}
commands.push_back(decl);
}
void * LemonScriptState::addressOfVariable(const std::string &variableName) const {
auto it = variableAddresses.find(variableName);
if(it != variableAddresses.end()) {
return it->second;
} else {
return NULL;
}
}
DataType LemonScriptState::typeOfVariable(const std::string &variableName) const {
auto it = variableTypes.find(variableName);
if(it != variableTypes.end()) {
return it->second;
} else {
return INT;
}
}
const AvailableCppCommandDeclaration * LemonScriptState::lookupCommandDeclaration(const std::string &name, const std::vector<DataType> ¶meterTypes) const {
auto mapIt = availableCppCommands.find(name);
if(mapIt == availableCppCommands.end()) {
return NULL;
}
const std::vector<const AvailableCppCommandDeclaration *> &commands = mapIt->second;
for (auto it = commands.begin(); it != commands.end(); ++it) {
const AvailableCppCommandDeclaration *decl = *it;
if(decl->parameters == parameterTypes) {
return decl;
}
}
return NULL;
}<|endoftext|> |
<commit_before>/*
* fMBT, free Model Based Testing tool
* Copyright (c) 2011, Intel Corporation.
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU Lesser General Public License,
* version 2.1, as published by the Free Software Foundation.
*
* This program is distributed in the hope 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 program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin St - Fifth Floor, Boston, MA 02110-1301 USA.
*
*/
#include <glib.h>
#include <string>
#include <sys/types.h>
#include <sys/wait.h>
class remote {
public:
remote():pid(0),id(0) {}
virtual ~remote() {
if (id)
g_source_remove(id);
}
protected:
void monitor() {
id=g_child_watch_add(pid, watch_func,this);
fprintf(stderr,"monitor() id==%i,pid %i\n",id,pid);
}
static void watch_func(GPid pid,gint status,gpointer user_data) {
remote* r;
r=(remote*)user_data;
if (WIFEXITED(status)) {
// child terminated normally
fprintf(stderr,"%s Terminated normally (%i)\n",r->prefix.c_str(),WEXITSTATUS(status)); // The exit status.
return;
}
if (WIFSIGNALED(status)) {
// Terminated by a signal
fprintf(stderr,"%s Terminated by a signal (%i)\n",r->prefix.c_str(),WTERMSIG(status)); // The signal
return;
}
if (WCOREDUMP(status)) {
// dumped...
fprintf(stderr,"%s dumped the core\n",r->prefix.c_str());
return;
}
// Currently we don't care about the rest
}
GPid pid;
guint id;
std::string prefix;
};
<commit_msg>Remove debug prints<commit_after>/*
* fMBT, free Model Based Testing tool
* Copyright (c) 2011, Intel Corporation.
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU Lesser General Public License,
* version 2.1, as published by the Free Software Foundation.
*
* This program is distributed in the hope 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 program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin St - Fifth Floor, Boston, MA 02110-1301 USA.
*
*/
#include <glib.h>
#include <string>
#include <sys/types.h>
#include <sys/wait.h>
class remote {
public:
remote():pid(0),id(0) {}
virtual ~remote() {
if (id)
g_source_remove(id);
}
protected:
void monitor() {
id=g_child_watch_add(pid, watch_func,this);
}
static void watch_func(GPid pid,gint status,gpointer user_data) {
remote* r;
r=(remote*)user_data;
if (WIFEXITED(status)) {
// child terminated normally
fprintf(stderr,"%s Terminated normally (%i)\n",r->prefix.c_str(),WEXITSTATUS(status)); // The exit status.
return;
}
if (WIFSIGNALED(status)) {
// Terminated by a signal
fprintf(stderr,"%s Terminated by a signal (%i)\n",r->prefix.c_str(),WTERMSIG(status)); // The signal
return;
}
if (WCOREDUMP(status)) {
// dumped...
fprintf(stderr,"%s dumped the core\n",r->prefix.c_str());
return;
}
// Currently we don't care about the rest
}
GPid pid;
guint id;
std::string prefix;
};
<|endoftext|> |
<commit_before>// Copyright (c) 2014-2015 The Dash developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "main.h"
#include "activemasternode.h"
#include "masternode-sync.h"
#include "masternode-payments.h"
#include "masternode-budget.h"
#include "masternode.h"
#include "masternodeman.h"
#include "util.h"
#include "addrman.h"
class CMasternodeSync;
CMasternodeSync masternodeSync;
CMasternodeSync::CMasternodeSync()
{
Reset();
}
bool CMasternodeSync::IsSynced()
{
return RequestedMasternodeAssets == MASTERNODE_SYNC_FINISHED;
}
bool CMasternodeSync::IsBlockchainSynced()
{
static bool fBlockchainSynced = false;
static int64_t lastProcess = GetTime();
// if the last call to this function was more than 60 minutes ago (client was in sleep mode) reset the sync process
if(GetTime() - lastProcess > 60*60) {
Reset();
fBlockchainSynced = false;
}
lastProcess = GetTime();
if(fBlockchainSynced) return true;
if (fImporting || fReindex) return false;
TRY_LOCK(cs_main, lockMain);
if(!lockMain) return false;
CBlockIndex* pindex = chainActive.Tip();
if(pindex == NULL) return false;
if(pindex->nTime + 60*60 < GetTime())
return false;
fBlockchainSynced = true;
return true;
}
void CMasternodeSync::Reset()
{
lastMasternodeList = 0;
lastMasternodeWinner = 0;
lastBudgetItem = 0;
mapSeenSyncMNB.clear();
mapSeenSyncMNW.clear();
mapSeenSyncBudget.clear();
lastFailure = 0;
nCountFailures = 0;
sumMasternodeList = 0;
sumMasternodeWinner = 0;
sumBudgetItemProp = 0;
sumBudgetItemFin = 0;
countMasternodeList = 0;
countMasternodeWinner = 0;
countBudgetItemProp = 0;
countBudgetItemFin = 0;
RequestedMasternodeAssets = MASTERNODE_SYNC_INITIAL;
RequestedMasternodeAttempt = 0;
}
void CMasternodeSync::AddedMasternodeList(uint256 hash)
{
if(mnodeman.mapSeenMasternodeBroadcast.count(hash)) {
if(mapSeenSyncMNB[hash] < MASTERNODE_SYNC_THRESHOLD) {
lastMasternodeList = GetTime();
mapSeenSyncMNB[hash]++;
}
} else {
lastMasternodeList = GetTime();
mapSeenSyncMNB.insert(make_pair(hash, 1));
}
}
void CMasternodeSync::AddedMasternodeWinner(uint256 hash)
{
if(masternodePayments.mapMasternodePayeeVotes.count(hash)) {
if(mapSeenSyncMNW[hash] < MASTERNODE_SYNC_THRESHOLD) {
lastMasternodeWinner = GetTime();
mapSeenSyncMNW[hash]++;
}
} else {
lastMasternodeWinner = GetTime();
mapSeenSyncMNW.insert(make_pair(hash, 1));
}
}
void CMasternodeSync::AddedBudgetItem(uint256 hash)
{
if(budget.mapSeenMasternodeBudgetProposals.count(hash) || budget.mapSeenMasternodeBudgetVotes.count(hash) ||
budget.mapSeenFinalizedBudgets.count(hash) || budget.mapSeenFinalizedBudgetVotes.count(hash)) {
if(mapSeenSyncBudget[hash] < MASTERNODE_SYNC_THRESHOLD) {
lastBudgetItem = GetTime();
mapSeenSyncBudget[hash]++;
}
} else {
lastBudgetItem = GetTime();
mapSeenSyncBudget.insert(make_pair(hash, 1));
}
}
bool CMasternodeSync::IsBudgetPropEmpty()
{
return sumBudgetItemProp==0 && countBudgetItemProp>0;
}
bool CMasternodeSync::IsBudgetFinEmpty()
{
return sumBudgetItemFin==0 && countBudgetItemFin>0;
}
void CMasternodeSync::GetNextAsset()
{
switch(RequestedMasternodeAssets)
{
case(MASTERNODE_SYNC_INITIAL):
case(MASTERNODE_SYNC_FAILED): // should never be used here actually, use Reset() instead
ClearFulfilledRequest();
RequestedMasternodeAssets = MASTERNODE_SYNC_SPORKS;
break;
case(MASTERNODE_SYNC_SPORKS):
RequestedMasternodeAssets = MASTERNODE_SYNC_LIST;
break;
case(MASTERNODE_SYNC_LIST):
RequestedMasternodeAssets = MASTERNODE_SYNC_MNW;
break;
case(MASTERNODE_SYNC_MNW):
RequestedMasternodeAssets = MASTERNODE_SYNC_BUDGET;
break;
case(MASTERNODE_SYNC_BUDGET):
LogPrintf("CMasternodeSync::GetNextAsset - Sync has finished\n");
RequestedMasternodeAssets = MASTERNODE_SYNC_FINISHED;
break;
}
RequestedMasternodeAttempt = 0;
}
void CMasternodeSync::ProcessMessage(CNode* pfrom, std::string& strCommand, CDataStream& vRecv)
{
if (strCommand == "ssc") { //Sync status count
int nItemID;
int nCount;
vRecv >> nItemID >> nCount;
if(RequestedMasternodeAssets >= MASTERNODE_SYNC_FINISHED) return;
//this means we will receive no further communication
switch(nItemID)
{
case(MASTERNODE_SYNC_LIST):
if(nItemID != RequestedMasternodeAssets) return;
sumMasternodeList += nCount;
countMasternodeList++;
break;
case(MASTERNODE_SYNC_MNW):
if(nItemID != RequestedMasternodeAssets) return;
sumMasternodeWinner += nCount;
countMasternodeWinner++;
break;
case(MASTERNODE_SYNC_BUDGET_PROP):
if(RequestedMasternodeAssets != MASTERNODE_SYNC_BUDGET) return;
sumBudgetItemProp += nCount;
countBudgetItemProp++;
break;
case(MASTERNODE_SYNC_BUDGET_FIN):
if(RequestedMasternodeAssets != MASTERNODE_SYNC_BUDGET) return;
sumBudgetItemFin += nCount;
countBudgetItemFin++;
break;
}
LogPrintf("CMasternodeSync:ProcessMessage - ssc - got inventory count %d %d\n", nItemID, nCount);
}
}
void CMasternodeSync::ClearFulfilledRequest()
{
TRY_LOCK(cs_vNodes, lockRecv);
if(!lockRecv) return;
BOOST_FOREACH(CNode* pnode, vNodes)
{
pnode->ClearFulfilledRequest("getspork");
pnode->ClearFulfilledRequest("mnsync");
pnode->ClearFulfilledRequest("mnwsync");
pnode->ClearFulfilledRequest("busync");
}
}
void CMasternodeSync::Process()
{
static int tick = 0;
if(tick++ % MASTERNODE_SYNC_TIMEOUT != 0) return;
if(IsSynced()) {
/*
Resync if we lose all masternodes from sleep/wake or failure to sync originally
*/
if(mnodeman.CountEnabled() == 0) {
Reset();
} else
return;
}
//try syncing again in an hour
if(RequestedMasternodeAssets == MASTERNODE_SYNC_FAILED && lastFailure + (60*60) < GetTime()) {
Reset();
} else if (RequestedMasternodeAssets == MASTERNODE_SYNC_FAILED) {
return;
}
if(fDebug) LogPrintf("CMasternodeSync::Process() - tick %d RequestedMasternodeAssets %d\n", tick, RequestedMasternodeAssets);
if(RequestedMasternodeAssets == MASTERNODE_SYNC_INITIAL) GetNextAsset();
// sporks synced but blockchain is not, wait until we're almost at a recent block to continue
if(Params().NetworkID() != CBaseChainParams::REGTEST &&
!IsBlockchainSynced() && RequestedMasternodeAssets > MASTERNODE_SYNC_SPORKS) return;
TRY_LOCK(cs_vNodes, lockRecv);
if(!lockRecv) return;
BOOST_FOREACH(CNode* pnode, vNodes)
{
if(Params().NetworkID() == CBaseChainParams::REGTEST){
if(RequestedMasternodeAttempt <= 2) {
pnode->PushMessage("getsporks"); //get current network sporks
} else if(RequestedMasternodeAttempt < 4) {
mnodeman.DsegUpdate(pnode);
} else if(RequestedMasternodeAttempt < 6) {
int nMnCount = mnodeman.CountEnabled()*2;
pnode->PushMessage("mnget", nMnCount); //sync payees
uint256 n = 0;
pnode->PushMessage("mnvs", n); //sync masternode votes
} else {
RequestedMasternodeAssets = MASTERNODE_SYNC_FINISHED;
}
RequestedMasternodeAttempt++;
return;
}
//set to synced
if(RequestedMasternodeAssets == MASTERNODE_SYNC_SPORKS){
if(pnode->HasFulfilledRequest("getspork")) continue;
pnode->FulfilledRequest("getspork");
pnode->PushMessage("getsporks"); //get current network sporks
if(RequestedMasternodeAttempt >= 2) GetNextAsset();
RequestedMasternodeAttempt++;
return;
}
if (pnode->nVersion >= masternodePayments.GetMinMasternodePaymentsProto()) {
if(RequestedMasternodeAssets == MASTERNODE_SYNC_LIST) {
if(fDebug) LogPrintf("CMasternodeSync::Process() - lastMasternodeList %lld (GetTime() - MASTERNODE_SYNC_TIMEOUT) %lld\n", lastMasternodeList, GetTime() - MASTERNODE_SYNC_TIMEOUT);
if(lastMasternodeList > 0 && lastMasternodeList < GetTime() - MASTERNODE_SYNC_TIMEOUT && RequestedMasternodeAttempt >= MASTERNODE_SYNC_THRESHOLD){ //hasn't received a new item in the last five seconds, so we'll move to the
GetNextAsset();
return;
}
if(pnode->HasFulfilledRequest("mnsync")) continue;
pnode->FulfilledRequest("mnsync");
mnodeman.DsegUpdate(pnode);
RequestedMasternodeAttempt++;
return;
}
if(RequestedMasternodeAssets == MASTERNODE_SYNC_MNW) {
if(lastMasternodeWinner > 0 && lastMasternodeWinner < GetTime() - MASTERNODE_SYNC_TIMEOUT && RequestedMasternodeAttempt >= MASTERNODE_SYNC_THRESHOLD){ //hasn't received a new item in the last five seconds, so we'll move to the
GetNextAsset();
return;
}
if(pnode->HasFulfilledRequest("mnwsync")) continue;
pnode->FulfilledRequest("mnwsync");
CBlockIndex* pindexPrev = chainActive.Tip();
if(pindexPrev == NULL) return;
int nMnCount = mnodeman.CountEnabled()*2;
pnode->PushMessage("mnget", nMnCount); //sync payees
RequestedMasternodeAttempt++;
return;
}
}
if (pnode->nVersion >= MIN_BUDGET_PEER_PROTO_VERSION) {
if(RequestedMasternodeAssets == MASTERNODE_SYNC_BUDGET){
//we'll start rejecting votes if we accidentally get set as synced too soon
if(lastBudgetItem > 0 && lastBudgetItem < GetTime() - MASTERNODE_SYNC_TIMEOUT && RequestedMasternodeAttempt >= MASTERNODE_SYNC_THRESHOLD){ //hasn't received a new item in the last five seconds, so we'll move to the
//LogPrintf("CMasternodeSync::Process - HasNextFinalizedBudget %d nCountFailures %d IsBudgetPropEmpty %d\n", budget.HasNextFinalizedBudget(), nCountFailures, IsBudgetPropEmpty());
//if(budget.HasNextFinalizedBudget() || nCountFailures >= 2 || IsBudgetPropEmpty()) {
GetNextAsset();
//try to activate our masternode if possible
activeMasternode.ManageStatus();
// } else { //we've failed to sync, this state will reject the next budget block
// LogPrintf("CMasternodeSync::Process - ERROR - Sync has failed, will retry later\n");
// RequestedMasternodeAssets = MASTERNODE_SYNC_FAILED;
// RequestedMasternodeAttempt = 0;
// lastFailure = GetTime();
// nCountFailures++;
// }
return;
}
if(pnode->HasFulfilledRequest("busync")) continue;
pnode->FulfilledRequest("busync");
uint256 n = 0;
pnode->PushMessage("mnvs", n); //sync masternode votes
RequestedMasternodeAttempt++;
return;
}
}
}
}
<commit_msg>add budget timeout<commit_after>// Copyright (c) 2014-2015 The Dash developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "main.h"
#include "activemasternode.h"
#include "masternode-sync.h"
#include "masternode-payments.h"
#include "masternode-budget.h"
#include "masternode.h"
#include "masternodeman.h"
#include "util.h"
#include "addrman.h"
class CMasternodeSync;
CMasternodeSync masternodeSync;
CMasternodeSync::CMasternodeSync()
{
Reset();
}
bool CMasternodeSync::IsSynced()
{
return RequestedMasternodeAssets == MASTERNODE_SYNC_FINISHED;
}
bool CMasternodeSync::IsBlockchainSynced()
{
static bool fBlockchainSynced = false;
static int64_t lastProcess = GetTime();
// if the last call to this function was more than 60 minutes ago (client was in sleep mode) reset the sync process
if(GetTime() - lastProcess > 60*60) {
Reset();
fBlockchainSynced = false;
}
lastProcess = GetTime();
if(fBlockchainSynced) return true;
if (fImporting || fReindex) return false;
TRY_LOCK(cs_main, lockMain);
if(!lockMain) return false;
CBlockIndex* pindex = chainActive.Tip();
if(pindex == NULL) return false;
if(pindex->nTime + 60*60 < GetTime())
return false;
fBlockchainSynced = true;
return true;
}
void CMasternodeSync::Reset()
{
lastMasternodeList = 0;
lastMasternodeWinner = 0;
lastBudgetItem = 0;
mapSeenSyncMNB.clear();
mapSeenSyncMNW.clear();
mapSeenSyncBudget.clear();
lastFailure = 0;
nCountFailures = 0;
sumMasternodeList = 0;
sumMasternodeWinner = 0;
sumBudgetItemProp = 0;
sumBudgetItemFin = 0;
countMasternodeList = 0;
countMasternodeWinner = 0;
countBudgetItemProp = 0;
countBudgetItemFin = 0;
RequestedMasternodeAssets = MASTERNODE_SYNC_INITIAL;
RequestedMasternodeAttempt = 0;
}
void CMasternodeSync::AddedMasternodeList(uint256 hash)
{
if(mnodeman.mapSeenMasternodeBroadcast.count(hash)) {
if(mapSeenSyncMNB[hash] < MASTERNODE_SYNC_THRESHOLD) {
lastMasternodeList = GetTime();
mapSeenSyncMNB[hash]++;
}
} else {
lastMasternodeList = GetTime();
mapSeenSyncMNB.insert(make_pair(hash, 1));
}
}
void CMasternodeSync::AddedMasternodeWinner(uint256 hash)
{
if(masternodePayments.mapMasternodePayeeVotes.count(hash)) {
if(mapSeenSyncMNW[hash] < MASTERNODE_SYNC_THRESHOLD) {
lastMasternodeWinner = GetTime();
mapSeenSyncMNW[hash]++;
}
} else {
lastMasternodeWinner = GetTime();
mapSeenSyncMNW.insert(make_pair(hash, 1));
}
}
void CMasternodeSync::AddedBudgetItem(uint256 hash)
{
if(budget.mapSeenMasternodeBudgetProposals.count(hash) || budget.mapSeenMasternodeBudgetVotes.count(hash) ||
budget.mapSeenFinalizedBudgets.count(hash) || budget.mapSeenFinalizedBudgetVotes.count(hash)) {
if(mapSeenSyncBudget[hash] < MASTERNODE_SYNC_THRESHOLD) {
lastBudgetItem = GetTime();
mapSeenSyncBudget[hash]++;
}
} else {
lastBudgetItem = GetTime();
mapSeenSyncBudget.insert(make_pair(hash, 1));
}
}
bool CMasternodeSync::IsBudgetPropEmpty()
{
return sumBudgetItemProp==0 && countBudgetItemProp>0;
}
bool CMasternodeSync::IsBudgetFinEmpty()
{
return sumBudgetItemFin==0 && countBudgetItemFin>0;
}
void CMasternodeSync::GetNextAsset()
{
switch(RequestedMasternodeAssets)
{
case(MASTERNODE_SYNC_INITIAL):
case(MASTERNODE_SYNC_FAILED): // should never be used here actually, use Reset() instead
ClearFulfilledRequest();
RequestedMasternodeAssets = MASTERNODE_SYNC_SPORKS;
break;
case(MASTERNODE_SYNC_SPORKS):
RequestedMasternodeAssets = MASTERNODE_SYNC_LIST;
break;
case(MASTERNODE_SYNC_LIST):
RequestedMasternodeAssets = MASTERNODE_SYNC_MNW;
break;
case(MASTERNODE_SYNC_MNW):
RequestedMasternodeAssets = MASTERNODE_SYNC_BUDGET;
break;
case(MASTERNODE_SYNC_BUDGET):
LogPrintf("CMasternodeSync::GetNextAsset - Sync has finished\n");
RequestedMasternodeAssets = MASTERNODE_SYNC_FINISHED;
break;
}
RequestedMasternodeAttempt = 0;
}
void CMasternodeSync::ProcessMessage(CNode* pfrom, std::string& strCommand, CDataStream& vRecv)
{
if (strCommand == "ssc") { //Sync status count
int nItemID;
int nCount;
vRecv >> nItemID >> nCount;
if(RequestedMasternodeAssets >= MASTERNODE_SYNC_FINISHED) return;
//this means we will receive no further communication
switch(nItemID)
{
case(MASTERNODE_SYNC_LIST):
if(nItemID != RequestedMasternodeAssets) return;
sumMasternodeList += nCount;
countMasternodeList++;
break;
case(MASTERNODE_SYNC_MNW):
if(nItemID != RequestedMasternodeAssets) return;
sumMasternodeWinner += nCount;
countMasternodeWinner++;
break;
case(MASTERNODE_SYNC_BUDGET_PROP):
if(RequestedMasternodeAssets != MASTERNODE_SYNC_BUDGET) return;
sumBudgetItemProp += nCount;
countBudgetItemProp++;
break;
case(MASTERNODE_SYNC_BUDGET_FIN):
if(RequestedMasternodeAssets != MASTERNODE_SYNC_BUDGET) return;
sumBudgetItemFin += nCount;
countBudgetItemFin++;
break;
}
LogPrintf("CMasternodeSync:ProcessMessage - ssc - got inventory count %d %d\n", nItemID, nCount);
}
}
void CMasternodeSync::ClearFulfilledRequest()
{
TRY_LOCK(cs_vNodes, lockRecv);
if(!lockRecv) return;
BOOST_FOREACH(CNode* pnode, vNodes)
{
pnode->ClearFulfilledRequest("getspork");
pnode->ClearFulfilledRequest("mnsync");
pnode->ClearFulfilledRequest("mnwsync");
pnode->ClearFulfilledRequest("busync");
}
}
void CMasternodeSync::Process()
{
static int tick = 0;
if(tick++ % MASTERNODE_SYNC_TIMEOUT != 0) return;
if(IsSynced()) {
/*
Resync if we lose all masternodes from sleep/wake or failure to sync originally
*/
if(mnodeman.CountEnabled() == 0) {
Reset();
} else
return;
}
//try syncing again in an hour
if(RequestedMasternodeAssets == MASTERNODE_SYNC_FAILED && lastFailure + (60*60) < GetTime()) {
Reset();
} else if (RequestedMasternodeAssets == MASTERNODE_SYNC_FAILED) {
return;
}
if(fDebug) LogPrintf("CMasternodeSync::Process() - tick %d RequestedMasternodeAssets %d\n", tick, RequestedMasternodeAssets);
if(RequestedMasternodeAssets == MASTERNODE_SYNC_INITIAL) GetNextAsset();
// sporks synced but blockchain is not, wait until we're almost at a recent block to continue
if(Params().NetworkID() != CBaseChainParams::REGTEST &&
!IsBlockchainSynced() && RequestedMasternodeAssets > MASTERNODE_SYNC_SPORKS) return;
TRY_LOCK(cs_vNodes, lockRecv);
if(!lockRecv) return;
BOOST_FOREACH(CNode* pnode, vNodes)
{
if(Params().NetworkID() == CBaseChainParams::REGTEST){
if(RequestedMasternodeAttempt <= 2) {
pnode->PushMessage("getsporks"); //get current network sporks
} else if(RequestedMasternodeAttempt < 4) {
mnodeman.DsegUpdate(pnode);
} else if(RequestedMasternodeAttempt < 6) {
int nMnCount = mnodeman.CountEnabled()*2;
pnode->PushMessage("mnget", nMnCount); //sync payees
uint256 n = 0;
pnode->PushMessage("mnvs", n); //sync masternode votes
} else {
RequestedMasternodeAssets = MASTERNODE_SYNC_FINISHED;
}
RequestedMasternodeAttempt++;
return;
}
//set to synced
if(RequestedMasternodeAssets == MASTERNODE_SYNC_SPORKS){
if(pnode->HasFulfilledRequest("getspork")) continue;
pnode->FulfilledRequest("getspork");
pnode->PushMessage("getsporks"); //get current network sporks
if(RequestedMasternodeAttempt >= 2) GetNextAsset();
RequestedMasternodeAttempt++;
return;
}
if (pnode->nVersion >= masternodePayments.GetMinMasternodePaymentsProto()) {
if(RequestedMasternodeAssets == MASTERNODE_SYNC_LIST) {
if(fDebug) LogPrintf("CMasternodeSync::Process() - lastMasternodeList %lld (GetTime() - MASTERNODE_SYNC_TIMEOUT) %lld\n", lastMasternodeList, GetTime() - MASTERNODE_SYNC_TIMEOUT);
if(lastMasternodeList > 0 && lastMasternodeList < GetTime() - MASTERNODE_SYNC_TIMEOUT && RequestedMasternodeAttempt >= MASTERNODE_SYNC_THRESHOLD){ //hasn't received a new item in the last five seconds, so we'll move to the
GetNextAsset();
return;
}
if(pnode->HasFulfilledRequest("mnsync")) continue;
pnode->FulfilledRequest("mnsync");
mnodeman.DsegUpdate(pnode);
RequestedMasternodeAttempt++;
return;
}
if(RequestedMasternodeAssets == MASTERNODE_SYNC_MNW) {
if(lastMasternodeWinner > 0 && lastMasternodeWinner < GetTime() - MASTERNODE_SYNC_TIMEOUT && RequestedMasternodeAttempt >= MASTERNODE_SYNC_THRESHOLD){ //hasn't received a new item in the last five seconds, so we'll move to the
GetNextAsset();
return;
}
if(pnode->HasFulfilledRequest("mnwsync")) continue;
pnode->FulfilledRequest("mnwsync");
CBlockIndex* pindexPrev = chainActive.Tip();
if(pindexPrev == NULL) return;
int nMnCount = mnodeman.CountEnabled()*2;
pnode->PushMessage("mnget", nMnCount); //sync payees
RequestedMasternodeAttempt++;
return;
}
}
if (pnode->nVersion >= MIN_BUDGET_PEER_PROTO_VERSION) {
if(RequestedMasternodeAssets == MASTERNODE_SYNC_BUDGET){
//we'll start rejecting votes if we accidentally get set as synced too soon
if(lastBudgetItem > 0 && lastBudgetItem < GetTime() - MASTERNODE_SYNC_TIMEOUT && RequestedMasternodeAttempt >= MASTERNODE_SYNC_THRESHOLD){ //hasn't received a new item in the last five seconds, so we'll move to the
//LogPrintf("CMasternodeSync::Process - HasNextFinalizedBudget %d nCountFailures %d IsBudgetPropEmpty %d\n", budget.HasNextFinalizedBudget(), nCountFailures, IsBudgetPropEmpty());
//if(budget.HasNextFinalizedBudget() || nCountFailures >= 2 || IsBudgetPropEmpty()) {
GetNextAsset();
//try to activate our masternode if possible
activeMasternode.ManageStatus();
// } else { //we've failed to sync, this state will reject the next budget block
// LogPrintf("CMasternodeSync::Process - ERROR - Sync has failed, will retry later\n");
// RequestedMasternodeAssets = MASTERNODE_SYNC_FAILED;
// RequestedMasternodeAttempt = 0;
// lastFailure = GetTime();
// nCountFailures++;
// }
return;
}
// timeout
if(lastBudgetItem == 0 && RequestedMasternodeAttempt >= MASTERNODE_SYNC_THRESHOLD*3) {
GetNextAsset();
activeMasternode.ManageStatus();
return;
}
if(pnode->HasFulfilledRequest("busync")) continue;
pnode->FulfilledRequest("busync");
uint256 n = 0;
pnode->PushMessage("mnvs", n); //sync masternode votes
RequestedMasternodeAttempt++;
return;
}
}
}
}
<|endoftext|> |
<commit_before>#pragma once
#ifndef OPENGM_LEARNING_BUNDLE_OPTIMIZER_HXX
#define OPENGM_LEARNING_BUNDLE_OPTIMIZER_HXX
#include "solver/QuadraticSolverFactory.h"
namespace opengm {
namespace learning {
enum OptimizerResult {
// the minimal optimization gap was reached
ReachedMinGap,
// the requested number of steps was exceeded
ReachedSteps,
// something went wrong
Error
};
template <typename ValueType>
class BundleOptimizer {
public:
struct Parameter {
Parameter() :
min_gap(1e-5),
steps(0) {}
// stopping criteria of the bundle method optimization
ValueType min_gap;
// the maximal number of steps to perform, 0 = no limit
unsigned int steps;
};
BundleOptimizer();
~BundleOptimizer();
/**
* Start the bundle method optimization on the given dataset. It is assumed
* that the models in the dataset were already augmented by the loss.
*/
template <typename DatasetType>
OptimizerResult optimize(const DatasetType& dataset, typename DatasetType::ModelParameters& w);
private:
void setupQp();
void findMinLowerBound(std::vector<ValueType>& w, ValueType& value);
ValueType dot(const std::vector<ValueType>& a, const std::vector<ValueType>& b);
solver::QuadraticSolverBackend* _solver;
};
template <typename T>
BundleOptimizer<T>::BundleOptimizer() :
_solver(0) {}
template <typename T>
BundleOptimizer<T>::~BundleOptimizer() {
if (_solver)
delete _solver;
}
template <typename T>
template <typename DatasetType>
OptimizerResult
BundleOptimizer<T>::optimize(const DatasetType& dataset, typename DatasetType::ModelParameters& w) {
setupQp();
/*
1. w_0 = 0, t = 0
2. t++
3. compute a_t = ∂L(w_t-1)/∂w
4. compute b_t = L(w_t-1) - <w_t-1,a_t>
5. ℒ_t(w) = max_i <w,a_i> + b_i
6. w_t = argmin λ½|w|² + ℒ_t(w)
7. ε_t = min_i [ λ½|w_i|² + L(w_i) ] - [ λ½|w_t|² + ℒ_t(w_t) ]
^^^^^^^^^^^^^^^^^^^^^^^^^^^ ^^^^^^^^^^^^^^^^^^^^^^^
smallest L(w) ever seen current min of lower bound
8. if ε_t > ε, goto 2
9. return w_t
*/
//std::vector<T> w(_dims, 0.0);
//T minValue = std::numeric_limits<T>::infinity();
//unsigned int t = 0;
//while (true) {
//t++;
//LOG_USER(bundlelog) << std::endl << "----------------- iteration " << t << std::endl;
//std::vector<T> w_tm1 = w;
//LOG_DEBUG(bundlelog) << "current w is " << w_tm1 << std::endl;
//// value of L at current w
//T L_w_tm1 = 0.0;
//// gradient of L at current w
//std::vector<T> a_t(_dims, 0.0);
//// get current value and gradient
//_valueGradientCallback(w_tm1, L_w_tm1, a_t);
//LOG_DEBUG(bundlelog) << " L(w) is: " << L_w_tm1 << std::endl;
//LOG_ALL(bundlelog) << " ∂L(w)/∂ is: " << a_t << std::endl;
//// update smallest observed value of regularized L
//minValue = std::min(minValue, L_w_tm1 + _lambda*0.5*dot(w_tm1, w_tm1));
//LOG_DEBUG(bundlelog) << " min_i L(w_i) + ½λ|w_i|² is: " << minValue << std::endl;
//// compute hyperplane offset
//T b_t = L_w_tm1 - dot(w_tm1, a_t);
//LOG_ALL(bundlelog) << "adding hyperplane " << a_t << "*w + " << b_t << std::endl;
//// update lower bound
//_bundleCollector->addHyperplane(a_t, b_t);
//// minimal value of lower bound
//T minLower;
//// update w and get minimal value
//findMinLowerBound(w, minLower);
//LOG_DEBUG(bundlelog) << " min_w ℒ(w) + ½λ|w|² is: " << minLower << std::endl;
//LOG_DEBUG(bundlelog) << " w* of ℒ(w) + ½λ|w|² is: " << w << std::endl;
//// compute gap
//T eps_t = minValue - minLower;
//LOG_USER(bundlelog) << " ε is: " << eps_t << std::endl;
//// converged?
//if (eps_t <= _eps) {
//if (eps_t >= 0) {
//LOG_USER(bundlelog) << "converged!" << std::endl;
//} else {
//LOG_ERROR(bundlelog) << "ε < 0 -- something went wrong" << std::endl;
//}
//break;
//}
//}
return ReachedMinGap;
}
template <typename T>
void
BundleOptimizer<T>::setupQp() {
/*
w* = argmin λ½|w|² + ξ, s.t. <w,a_i> + b_i ≤ ξ ∀i
*/
//// one variable for each component of w and for ξ
//_qpObjective->resize(_dims + 1);
//// regularizer
//for (unsigned int i = 0; i < _dims; i++)
//_qpObjective->setQuadraticCoefficient(i, i, 0.5*_lambda);
//// ξ
//_qpObjective->setCoefficient(_dims, 1.0);
//// we minimize
//_qpObjective->setSense(Minimize);
//// connect pipeline
//_qpSolver->setInput("objective", _qpObjective);
//_qpSolver->setInput("linear constraints", _bundleCollector->getOutput());
//_qpSolver->setInput("parameters", _qpParameters);
//_qpSolution = _qpSolver->getOutput("solution");
}
template <typename T>
void
BundleOptimizer<T>::findMinLowerBound(std::vector<T>& w, T& value) {
// read the solution (pipeline magic!)
//for (unsigned int i = 0; i < _dims; i++)
//w[i] = (*_qpSolution)[i];
//value = _qpSolution->getValue();
}
template <typename T>
T
BundleOptimizer<T>::dot(const std::vector<T>& a, const std::vector<T>& b) {
OPENGM_ASSERT(a.size() == b.size());
T d = 0.0;
typename std::vector<T>::const_iterator i, j;
for (i = a.begin(), j = b.begin(); i != a.end(); i++, j++)
d += (*i)*(*j);
return d;
}
} // learning
} // opengm
#endif // OPENGM_LEARNING_BUNDLE_OPTIMIZER_HXX
<commit_msg>bundle-optimizer: added setup of QP<commit_after>#pragma once
#ifndef OPENGM_LEARNING_BUNDLE_OPTIMIZER_HXX
#define OPENGM_LEARNING_BUNDLE_OPTIMIZER_HXX
#include "solver/QuadraticSolverFactory.h"
namespace opengm {
namespace learning {
enum OptimizerResult {
// the minimal optimization gap was reached
ReachedMinGap,
// the requested number of steps was exceeded
ReachedSteps,
// something went wrong
Error
};
template <typename ValueType>
class BundleOptimizer {
public:
struct Parameter {
Parameter() :
lambda(1.0),
min_gap(1e-5),
steps(0) {}
// regularizer weight
double lambda;
// stopping criteria of the bundle method optimization
ValueType min_gap;
// the maximal number of steps to perform, 0 = no limit
unsigned int steps;
};
BundleOptimizer(const Parameter& parameter = Parameter());
~BundleOptimizer();
/**
* Start the bundle method optimization on the given dataset. It is assumed
* that the models in the dataset were already augmented by the loss.
*/
template <typename DatasetType>
OptimizerResult optimize(const DatasetType& dataset, typename DatasetType::ModelParameters& w);
private:
template <typename ModelParameters>
void setupQp(const ModelParameters& w);
void findMinLowerBound(std::vector<ValueType>& w, ValueType& value);
ValueType dot(const std::vector<ValueType>& a, const std::vector<ValueType>& b);
Parameter _parameter;
solver::QuadraticSolverBackend* _solver;
};
template <typename T>
BundleOptimizer<T>::BundleOptimizer(const Parameter& parameter) :
_parameter(parameter),
_solver(0) {}
template <typename T>
BundleOptimizer<T>::~BundleOptimizer() {
if (_solver)
delete _solver;
}
template <typename T>
template <typename DatasetType>
OptimizerResult
BundleOptimizer<T>::optimize(const DatasetType& dataset, typename DatasetType::ModelParameters& w) {
setupQp(w);
/*
1. w_0 = 0, t = 0
2. t++
3. compute a_t = ∂L(w_t-1)/∂w
4. compute b_t = L(w_t-1) - <w_t-1,a_t>
5. ℒ_t(w) = max_i <w,a_i> + b_i
6. w_t = argmin λ½|w|² + ℒ_t(w)
7. ε_t = min_i [ λ½|w_i|² + L(w_i) ] - [ λ½|w_t|² + ℒ_t(w_t) ]
^^^^^^^^^^^^^^^^^^^^^^^^^^^ ^^^^^^^^^^^^^^^^^^^^^^^
smallest L(w) ever seen current min of lower bound
8. if ε_t > ε, goto 2
9. return w_t
*/
//std::vector<T> w(_dims, 0.0);
//T minValue = std::numeric_limits<T>::infinity();
//unsigned int t = 0;
//while (true) {
//t++;
//LOG_USER(bundlelog) << std::endl << "----------------- iteration " << t << std::endl;
//std::vector<T> w_tm1 = w;
//LOG_DEBUG(bundlelog) << "current w is " << w_tm1 << std::endl;
//// value of L at current w
//T L_w_tm1 = 0.0;
//// gradient of L at current w
//std::vector<T> a_t(_dims, 0.0);
//// get current value and gradient
//_valueGradientCallback(w_tm1, L_w_tm1, a_t);
//LOG_DEBUG(bundlelog) << " L(w) is: " << L_w_tm1 << std::endl;
//LOG_ALL(bundlelog) << " ∂L(w)/∂ is: " << a_t << std::endl;
//// update smallest observed value of regularized L
//minValue = std::min(minValue, L_w_tm1 + _lambda*0.5*dot(w_tm1, w_tm1));
//LOG_DEBUG(bundlelog) << " min_i L(w_i) + ½λ|w_i|² is: " << minValue << std::endl;
//// compute hyperplane offset
//T b_t = L_w_tm1 - dot(w_tm1, a_t);
//LOG_ALL(bundlelog) << "adding hyperplane " << a_t << "*w + " << b_t << std::endl;
//// update lower bound
//_bundleCollector->addHyperplane(a_t, b_t);
//// minimal value of lower bound
//T minLower;
//// update w and get minimal value
//findMinLowerBound(w, minLower);
//LOG_DEBUG(bundlelog) << " min_w ℒ(w) + ½λ|w|² is: " << minLower << std::endl;
//LOG_DEBUG(bundlelog) << " w* of ℒ(w) + ½λ|w|² is: " << w << std::endl;
//// compute gap
//T eps_t = minValue - minLower;
//LOG_USER(bundlelog) << " ε is: " << eps_t << std::endl;
//// converged?
//if (eps_t <= _eps) {
//if (eps_t >= 0) {
//LOG_USER(bundlelog) << "converged!" << std::endl;
//} else {
//LOG_ERROR(bundlelog) << "ε < 0 -- something went wrong" << std::endl;
//}
//break;
//}
//}
return ReachedMinGap;
}
template <typename T>
template <typename ModelParameters>
void
BundleOptimizer<T>::setupQp(const ModelParameters& w) {
/*
w* = argmin λ½|w|² + ξ, s.t. <w,a_i> + b_i ≤ ξ ∀i
*/
if (!_solver)
_solver = solver::QuadraticSolverFactory::Create();
// one variable for each component of w and for ξ
solver::QuadraticObjective obj(w.numberOfParameters() + 1);
// regularizer
for (unsigned int i = 0; i < w.numberOfParameters(); i++)
obj.setQuadraticCoefficient(i, i, 0.5*_parameter.lambda);
// ξ
obj.setCoefficient(w.numberOfParameters(), 1.0);
// we minimize
obj.setSense(solver::Minimize);
// we are done with the objective -- this does not change anymore
_solver->setObjective(obj);
}
template <typename T>
void
BundleOptimizer<T>::findMinLowerBound(std::vector<T>& w, T& value) {
// read the solution (pipeline magic!)
//for (unsigned int i = 0; i < _dims; i++)
//w[i] = (*_qpSolution)[i];
//value = _qpSolution->getValue();
}
template <typename T>
T
BundleOptimizer<T>::dot(const std::vector<T>& a, const std::vector<T>& b) {
OPENGM_ASSERT(a.size() == b.size());
T d = 0.0;
typename std::vector<T>::const_iterator i, j;
for (i = a.begin(), j = b.begin(); i != a.end(); i++, j++)
d += (*i)*(*j);
return d;
}
} // learning
} // opengm
#endif // OPENGM_LEARNING_BUNDLE_OPTIMIZER_HXX
<|endoftext|> |
<commit_before>#include "pkcs11test.h"
using namespace std; // So sue me
// Explicitly test Initialize/Finalize.
TEST(Init, Simple) {
EXPECT_CKR_OK(g_fns->C_Initialize(NULL_PTR));
EXPECT_CKR_OK(g_fns->C_Finalize(NULL_PTR));
}
TEST(Init, UnexpectedFinalize) {
EXPECT_EQ(CKR_CRYPTOKI_NOT_INITIALIZED, g_fns->C_Finalize(NULL_PTR));
}
TEST(Init, InitArgsBadReserved) {
CK_C_INITIALIZE_ARGS init_args = {0};
init_args.pReserved = (void*)1;
EXPECT_EQ(CKR_ARGUMENTS_BAD, g_fns->C_Initialize(&init_args));
}
TEST(Init, InitArgsNoNewThreads) {
CK_C_INITIALIZE_ARGS init_args = {0};
init_args.flags = CKF_LIBRARY_CANT_CREATE_OS_THREADS;
CK_RV rv = g_fns->C_Initialize(&init_args);
if (rv == CKR_OK) {
cout << "Library can cope without creating OS threads" << endl;
EXPECT_CKR_OK(g_fns->C_Finalize(NULL_PTR));
} else {
cout << "Library needs to be able to create OS threads" << endl;
EXPECT_EQ(CKR_NEED_TO_CREATE_THREADS, rv);
}
}
TEST(Init, InitArgsNoLock) {
CK_C_INITIALIZE_ARGS init_args = {0};
EXPECT_CKR_OK(g_fns->C_Initialize(&init_args));
EXPECT_CKR_OK(g_fns->C_Finalize(NULL_PTR));
}
TEST(Init, InitArgsInternalLocks) {
CK_C_INITIALIZE_ARGS init_args = {0};
init_args.flags = CKF_OS_LOCKING_OK;
// Expect the library to use OS threading primitives
EXPECT_CKR_OK(g_fns->C_Initialize(&init_args));
EXPECT_CKR_OK(g_fns->C_Finalize(NULL_PTR));
}
// TODO(drysdale): add the other two cases (function pointers supplied, flag set+not-set)
// From here on, wrap Initialize/Finalize in a fixture.
class InitTest : public ::testing::Test {
protected:
virtual void SetUp() {
EXPECT_CKR_OK(g_fns->C_Initialize(NULL_PTR));
}
virtual void TearDown() {
EXPECT_CKR_OK(g_fns->C_Finalize(NULL_PTR));
}
};
TEST_F(InitTest, NestedFail) {
EXPECT_EQ(CKR_CRYPTOKI_ALREADY_INITIALIZED, g_fns->C_Initialize(NULL_PTR));
}
TEST_F(InitTest, GetInfo) {
CK_INFO info = {0};
EXPECT_CKR_OK(g_fns->C_GetInfo(&info));
cout << info_description(&info) << endl;
}
TEST_F(InitTest, FailedTermination) {
EXPECT_EQ(CKR_ARGUMENTS_BAD, g_fns->C_Finalize((void *)1));
}
<commit_msg>Add comment on single-threading<commit_after>#include "pkcs11test.h"
using namespace std; // So sue me
// Explicitly test Initialize/Finalize.
TEST(Init, Simple) {
EXPECT_CKR_OK(g_fns->C_Initialize(NULL_PTR));
EXPECT_CKR_OK(g_fns->C_Finalize(NULL_PTR));
}
TEST(Init, UnexpectedFinalize) {
EXPECT_EQ(CKR_CRYPTOKI_NOT_INITIALIZED, g_fns->C_Finalize(NULL_PTR));
}
TEST(Init, InitArgsBadReserved) {
CK_C_INITIALIZE_ARGS init_args = {0};
init_args.pReserved = (void*)1;
EXPECT_EQ(CKR_ARGUMENTS_BAD, g_fns->C_Initialize(&init_args));
}
TEST(Init, InitArgsNoNewThreads) {
CK_C_INITIALIZE_ARGS init_args = {0};
init_args.flags = CKF_LIBRARY_CANT_CREATE_OS_THREADS;
CK_RV rv = g_fns->C_Initialize(&init_args);
if (rv == CKR_OK) {
cout << "Library can cope without creating OS threads" << endl;
EXPECT_CKR_OK(g_fns->C_Finalize(NULL_PTR));
} else {
cout << "Library needs to be able to create OS threads" << endl;
EXPECT_EQ(CKR_NEED_TO_CREATE_THREADS, rv);
}
}
TEST(Init, InitArgsNoLock) {
CK_C_INITIALIZE_ARGS init_args = {0};
EXPECT_CKR_OK(g_fns->C_Initialize(&init_args));
EXPECT_CKR_OK(g_fns->C_Finalize(NULL_PTR));
}
TEST(Init, InitArgsInternalLocks) {
CK_C_INITIALIZE_ARGS init_args = {0};
init_args.flags = CKF_OS_LOCKING_OK;
// Expect the library to use OS threading primitives
EXPECT_CKR_OK(g_fns->C_Initialize(&init_args));
EXPECT_CKR_OK(g_fns->C_Finalize(NULL_PTR));
}
// TODO(drysdale): add the other two cases (function pointers supplied, flag set+not-set)
// From here on, wrap Initialize/Finalize in a fixture.
class InitTest : public ::testing::Test {
protected:
virtual void SetUp() {
// Null argument => only planning to use PKCS#11 from single thread.
EXPECT_CKR_OK(g_fns->C_Initialize(NULL_PTR));
}
virtual void TearDown() {
EXPECT_CKR_OK(g_fns->C_Finalize(NULL_PTR));
}
};
TEST_F(InitTest, NestedFail) {
EXPECT_EQ(CKR_CRYPTOKI_ALREADY_INITIALIZED, g_fns->C_Initialize(NULL_PTR));
}
TEST_F(InitTest, GetInfo) {
CK_INFO info = {0};
EXPECT_CKR_OK(g_fns->C_GetInfo(&info));
cout << info_description(&info) << endl;
}
TEST_F(InitTest, FailedTermination) {
EXPECT_EQ(CKR_ARGUMENTS_BAD, g_fns->C_Finalize((void *)1));
}
<|endoftext|> |
<commit_before>/*
* MoldUDP64 protocol support
*
* The implementation is based on the following specifications provided
* by NASDAQ:
*
* MoldUDP64 Protocol Specification
* V 1.00
* 07/07/2009
*/
#pragma once
#include "helix/nasdaq/moldudp64_messages.h"
#include "helix/compat/endian.h"
#include "helix/helix.hh"
#include "helix/net.hh"
namespace helix {
namespace nasdaq {
template<typename Handler>
class moldudp64_session : public session {
Handler _handler;
send_callback _send_cb;
uint64_t _seq_num;
public:
explicit moldudp64_session(void *data);
virtual bool is_rth_timestamp(uint64_t timestamp) override;
virtual void subscribe(const std::string& symbol, size_t max_orders) override;
virtual void register_callback(event_callback callback) override;
virtual void set_send_callback(send_callback callback) override;
virtual size_t process_packet(const net::packet_view& packet) override;
};
template<typename Handler>
moldudp64_session<Handler>::moldudp64_session(void* data)
: session{data}
, _seq_num{1}
{
}
template<typename Handler>
bool moldudp64_session<Handler>::is_rth_timestamp(uint64_t timestamp)
{
return _handler.is_rth_timestamp(timestamp);
}
template<typename Handler>
void moldudp64_session<Handler>::subscribe(const std::string& symbol, size_t max_orders)
{
_handler.subscribe(symbol, max_orders);
}
template<typename Handler>
void moldudp64_session<Handler>::register_callback(event_callback callback)
{
_handler.register_callback(callback);
}
template<typename Handler>
void moldudp64_session<Handler>::set_send_callback(send_callback send_cb)
{
_send_cb = send_cb;
}
template<typename Handler>
size_t moldudp64_session<Handler>::process_packet(const net::packet_view& packet)
{
auto* p = packet.buf();
assert(packet.len() >= sizeof(moldudp64_header));
auto* header = packet.cast<moldudp64_header>();
auto sequence_number = be64toh(header->SequenceNumber);
if (sequence_number != _seq_num) {
throw std::runtime_error(std::string("invalid sequence number: ") + std::to_string(sequence_number) + ", expected: " + std::to_string(_seq_num));
}
p += sizeof(moldudp64_header);
for (int i = 0; i < be16toh(header->MessageCount); i++) {
auto* msg_block = reinterpret_cast<const moldudp64_message_block*>(p);
p += sizeof(moldudp64_message_block);
auto message_length = be16toh(msg_block->MessageLength);
_handler.process_packet(net::packet_view{p, message_length});
p += message_length;
_seq_num++;
}
return p - packet.buf();
}
}
}
<commit_msg>nasdaq/moldudp64: Sequence number gap handling<commit_after>/*
* MoldUDP64 protocol support
*
* The implementation is based on the following specifications provided
* by NASDAQ:
*
* MoldUDP64 Protocol Specification
* V 1.00
* 07/07/2009
*/
#pragma once
#include "helix/nasdaq/moldudp64_messages.h"
#include "helix/compat/endian.h"
#include "helix/helix.hh"
#include "helix/net.hh"
#include <experimental/optional>
namespace helix {
namespace nasdaq {
enum moldudp64_state {
synchronized,
gap_fill,
};
template<typename Handler>
class moldudp64_session : public session {
Handler _handler;
send_callback _send_cb;
uint64_t _expected_seq_no = 1;
moldudp64_state _state = moldudp64_state::synchronized;
std::experimental::optional<uint64_t> _sync_to_seq_no;
public:
explicit moldudp64_session(void *data);
virtual bool is_rth_timestamp(uint64_t timestamp) override;
virtual void subscribe(const std::string& symbol, size_t max_orders) override;
virtual void register_callback(event_callback callback) override;
virtual void set_send_callback(send_callback callback) override;
virtual size_t process_packet(const net::packet_view& packet) override;
private:
void retransmit_request(uint64_t seq_no, uint64_t expected_seq_no);
};
template<typename Handler>
moldudp64_session<Handler>::moldudp64_session(void* data)
: session{data}
{
}
template<typename Handler>
bool moldudp64_session<Handler>::is_rth_timestamp(uint64_t timestamp)
{
return _handler.is_rth_timestamp(timestamp);
}
template<typename Handler>
void moldudp64_session<Handler>::subscribe(const std::string& symbol, size_t max_orders)
{
_handler.subscribe(symbol, max_orders);
}
template<typename Handler>
void moldudp64_session<Handler>::register_callback(event_callback callback)
{
_handler.register_callback(callback);
}
template<typename Handler>
void moldudp64_session<Handler>::set_send_callback(send_callback send_cb)
{
_send_cb = send_cb;
}
template<typename Handler>
size_t moldudp64_session<Handler>::process_packet(const net::packet_view& packet)
{
auto* p = packet.buf();
assert(packet.len() >= sizeof(moldudp64_header));
auto* header = packet.cast<moldudp64_header>();
auto recv_seq_no = be64toh(header->SequenceNumber);
if (recv_seq_no < _expected_seq_no) {
return packet.len();
}
if (_expected_seq_no < recv_seq_no) {
_sync_to_seq_no = recv_seq_no;
if (_state == moldudp64_state::synchronized) {
_state = moldudp64_state::gap_fill;
retransmit_request(recv_seq_no, _expected_seq_no);
}
return packet.len();
}
p += sizeof(moldudp64_header);
for (int i = 0; i < be16toh(header->MessageCount); i++) {
auto* msg_block = reinterpret_cast<const moldudp64_message_block*>(p);
p += sizeof(moldudp64_message_block);
auto message_length = be16toh(msg_block->MessageLength);
_handler.process_packet(net::packet_view{p, message_length});
p += message_length;
_expected_seq_no++;
}
if (_state == moldudp64_state::gap_fill) {
if (_expected_seq_no >= _sync_to_seq_no.value()) {
_state = moldudp64_state::synchronized;
_sync_to_seq_no = std::experimental::nullopt;
} else {
retransmit_request(recv_seq_no, _expected_seq_no);
}
}
return p - packet.buf();
}
template<typename Handler>
void moldudp64_session<Handler>::retransmit_request(uint64_t seq_no, uint64_t expected_seq_no)
{
if (!bool(_send_cb)) {
throw std::runtime_error(std::string("invalid sequence number: ") + std::to_string(seq_no) + ", expected: " + std::to_string(expected_seq_no));
}
uint64_t message_count = 0xfffe;
moldudp64_request_packet request_packet;
request_packet.SequenceNumber = htobe64(expected_seq_no);
request_packet.MessageCount = htobe16(message_count);
char *base = reinterpret_cast<char*>(&request_packet);
size_t len = sizeof(request_packet);
_send_cb(base, len);
}
}
}
<|endoftext|> |
<commit_before>// Copyright (c) 2019 Dr. Colin Hirsch and Daniel Frey
// Please see LICENSE for license or visit https://github.com/taocpp/PEGTL/
#ifndef TAO_PEGTL_CONTRIB_CHANGE_CONTROL_HPP
#define TAO_PEGTL_CONTRIB_CHANGE_CONTROL_HPP
#include "../apply_mode.hpp"
#include "../config.hpp"
#include "../rewind_mode.hpp"
namespace tao
{
namespace TAO_PEGTL_NAMESPACE
{
template< template< typename... > class NewControl >
struct change_control
{
template< typename Rule,
apply_mode A,
rewind_mode M,
template< typename... >
class Action,
template< typename... >
class Control,
typename Input,
typename... States >
[[nodiscard]] static bool match( Input& in, States&&... st )
{
return TAO_PEGTL_NAMESPACE::match< Rule, A, M, Action, NewControl >( in, st... );
}
};
} // namespace TAO_PEGTL_NAMESPACE
} // namespace tao
#endif
<commit_msg>Add missing include<commit_after>// Copyright (c) 2019 Dr. Colin Hirsch and Daniel Frey
// Please see LICENSE for license or visit https://github.com/taocpp/PEGTL/
#ifndef TAO_PEGTL_CONTRIB_CHANGE_CONTROL_HPP
#define TAO_PEGTL_CONTRIB_CHANGE_CONTROL_HPP
#include "../apply_mode.hpp"
#include "../config.hpp"
#include "../match.hpp"
#include "../rewind_mode.hpp"
namespace tao
{
namespace TAO_PEGTL_NAMESPACE
{
template< template< typename... > class NewControl >
struct change_control
{
template< typename Rule,
apply_mode A,
rewind_mode M,
template< typename... >
class Action,
template< typename... >
class Control,
typename Input,
typename... States >
[[nodiscard]] static bool match( Input& in, States&&... st )
{
return TAO_PEGTL_NAMESPACE::match< Rule, A, M, Action, NewControl >( in, st... );
}
};
} // namespace TAO_PEGTL_NAMESPACE
} // namespace tao
#endif
<|endoftext|> |
<commit_before>// Copyright 2012 Cloudera 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 "common/logging.h"
#include <boost/thread/mutex.hpp>
#include <boost/uuid/uuid.hpp>
#include <boost/uuid/uuid_io.hpp>
#include <boost/uuid/uuid_generators.hpp>
#include <sstream>
#include <stdio.h>
#include <iostream>
#include <fstream>
#include "common/logging.h"
DEFINE_string(log_filename, "",
"Prefix of log filename - "
"full path is <log_dir>/<log_filename>.[INFO|WARN|ERROR|FATAL]");
bool logging_initialized = false;
using namespace boost;
using namespace std;
using namespace boost::uuids;
mutex logging_mutex;
void impala::InitGoogleLoggingSafe(const char* arg) {
mutex::scoped_lock logging_lock(logging_mutex);
if (logging_initialized) return;
if (!FLAGS_log_filename.empty()) {
for (int severity = google::INFO; severity <= google::FATAL; ++severity) {
google::SetLogSymlink(severity, FLAGS_log_filename.c_str());
}
}
// This forces our logging to use /tmp rather than looking for a
// temporary directory if none is specified. This is done so that we
// can reliably construct the log file name without duplicating the
// complex logic that glog uses to guess at a temporary dir.
if (FLAGS_log_dir.empty()) {
FLAGS_log_dir = "/tmp";
}
if (!FLAGS_logtostderr) {
// Verify that a log file can be created in log_dir by creating a tmp file.
stringstream ss;
random_generator uuid_generator;
ss << FLAGS_log_dir << "/" << "impala_test_log." << uuid_generator();
const string file_name = ss.str();
ofstream test_file(file_name.c_str());
if (!test_file.is_open()) {
stringstream error_msg;
error_msg << "Could not open file in log_dir " << FLAGS_log_dir;
perror(error_msg.str().c_str());
// Unlock the mutex before exiting the program to avoid mutex d'tor assert.
logging_mutex.unlock();
exit(1);
}
remove(file_name.c_str());
}
google::InitGoogleLogging(arg);
// Needs to be done after InitGoogleLogging
if (FLAGS_log_filename.empty()) {
FLAGS_log_filename = google::ProgramInvocationShortName();
}
logging_initialized = true;
}
void impala::GetFullLogFilename(google::LogSeverity severity, string* filename) {
stringstream ss;
ss << FLAGS_log_dir << "/" << FLAGS_log_filename << "."
<< google::GetLogSeverityName(severity);
*filename = ss.str();
}
void impala::ShutdownLogging() {
// This method may only correctly be called once (which this lock does not
// enforce), but this lock protects against concurrent calls with
// InitGoogleLoggingSafe
mutex::scoped_lock logging_lock(logging_mutex);
google::ShutdownGoogleLogging();
}
void impala::LogCommandLineFlags() {
LOG(INFO) << "Flags (see also /varz are on debug webserver):" << endl
<< google::CommandlineFlagsIntoString();
}
<commit_msg>IMPALA-1349: Redirect stdout/stderr to INFO/ERROR log.<commit_after>// Copyright 2012 Cloudera 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 "common/logging.h"
#include <boost/thread/mutex.hpp>
#include <boost/uuid/uuid.hpp>
#include <boost/uuid/uuid_io.hpp>
#include <boost/uuid/uuid_generators.hpp>
#include <sstream>
#include <stdio.h>
#include <iostream>
#include <fstream>
#include "common/logging.h"
#include "util/error-util.h"
#include "util/test-info.h"
DEFINE_string(log_filename, "",
"Prefix of log filename - "
"full path is <log_dir>/<log_filename>.[INFO|WARN|ERROR|FATAL]");
DEFINE_bool(redirect_stdout_stderr, true,
"If true, redirects stdout/stderr to INFO/ERROR log.");
bool logging_initialized = false;
using namespace boost;
using namespace std;
using namespace boost::uuids;
mutex logging_mutex;
void impala::InitGoogleLoggingSafe(const char* arg) {
mutex::scoped_lock logging_lock(logging_mutex);
if (logging_initialized) return;
if (!FLAGS_log_filename.empty()) {
for (int severity = google::INFO; severity <= google::FATAL; ++severity) {
google::SetLogSymlink(severity, FLAGS_log_filename.c_str());
}
}
// This forces our logging to use /tmp rather than looking for a
// temporary directory if none is specified. This is done so that we
// can reliably construct the log file name without duplicating the
// complex logic that glog uses to guess at a temporary dir.
if (FLAGS_log_dir.empty()) {
FLAGS_log_dir = "/tmp";
}
if (FLAGS_redirect_stdout_stderr && !TestInfo::is_fe_test()) {
// We will be redirecting stdout/stderr to INFO/LOG so override any glog settings
// that log to stdout/stderr...
FLAGS_logtostderr = false;
FLAGS_alsologtostderr = false;
// Don't log to stderr on any threshold.
FLAGS_stderrthreshold = google::FATAL + 1;
}
if (!FLAGS_logtostderr) {
// Verify that a log file can be created in log_dir by creating a tmp file.
stringstream ss;
random_generator uuid_generator;
ss << FLAGS_log_dir << "/" << "impala_test_log." << uuid_generator();
const string file_name = ss.str();
ofstream test_file(file_name.c_str());
if (!test_file.is_open()) {
stringstream error_msg;
error_msg << "Could not open file in log_dir " << FLAGS_log_dir;
perror(error_msg.str().c_str());
// Unlock the mutex before exiting the program to avoid mutex d'tor assert.
logging_mutex.unlock();
exit(1);
}
remove(file_name.c_str());
}
google::InitGoogleLogging(arg);
// Needs to be done after InitGoogleLogging
if (FLAGS_log_filename.empty()) {
FLAGS_log_filename = google::ProgramInvocationShortName();
}
if (FLAGS_redirect_stdout_stderr && !TestInfo::is_fe_test()) {
// Needs to be done after InitGoogleLogging, to get the INFO/ERROR file paths.
// Redirect stdout to INFO log and stderr to ERROR log
string info_log_path, error_log_path;
GetFullLogFilename(google::INFO, &info_log_path);
GetFullLogFilename(google::ERROR, &error_log_path);
// The log files are created on first use, log something to each before redirecting.
LOG(INFO) << "stdout will be logged to this file.";
LOG(ERROR) << "stderr will be logged to this file.";
// Print to stderr/stdout before redirecting so people looking for these logs in
// the standard place know where to look.
cout << "Redirecting stdout to " << info_log_path << endl;
cerr << "Redirecting stderr to " << error_log_path << endl;
// TODO: how to handle these errors? Maybe abort the process?
if (freopen(info_log_path.c_str(), "a", stdout) == NULL) {
cout << "Could not redirect stdout: " << GetStrErrMsg();
}
if (freopen(error_log_path.c_str(), "a", stderr) == NULL) {
cerr << "Could not redirect stderr: " << GetStrErrMsg();
}
}
logging_initialized = true;
}
void impala::GetFullLogFilename(google::LogSeverity severity, string* filename) {
stringstream ss;
ss << FLAGS_log_dir << "/" << FLAGS_log_filename << "."
<< google::GetLogSeverityName(severity);
*filename = ss.str();
}
void impala::ShutdownLogging() {
// This method may only correctly be called once (which this lock does not
// enforce), but this lock protects against concurrent calls with
// InitGoogleLoggingSafe
mutex::scoped_lock logging_lock(logging_mutex);
google::ShutdownGoogleLogging();
}
void impala::LogCommandLineFlags() {
LOG(INFO) << "Flags (see also /varz are on debug webserver):" << endl
<< google::CommandlineFlagsIntoString();
}
<|endoftext|> |
<commit_before>// fmfRecord.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <FlyCapture2.h>
#include <omp.h>
using namespace FlyCapture2;
FILE **fout;
FlyCapture2::Camera** ppCameras;
FlyCapture2::Error error;
char fname[10][100];
void PrintCameraInfo( FlyCapture2::CameraInfo* pCamInfo )
{
printf("%u %s %s\n", pCamInfo->serialNumber, pCamInfo->modelName, pCamInfo->sensorResolution);
}
void PrintError( FlyCapture2::Error error )
{
error.PrintErrorTrace();
}
int RunSingleCamera(int i, int numImages)
{
int frameNumber;
double stamp;
FlyCapture2::Image rawImage;
// Create a converted image
FlyCapture2::Image convertedImage;
FlyCapture2::TimeStamp timestamp;
//int frameNumber=0;
// press [ESC] to exit from continuous streaming mode
for (frameNumber=0; frameNumber != numImages; frameNumber++)
{
// Start capturing images
error = ppCameras[i]->RetrieveBuffer( &rawImage );
//get image timestamp
timestamp = rawImage.GetTimeStamp();
stamp = (double) timestamp.seconds;
// Convert the raw image
error = rawImage.Convert( FlyCapture2::PIXEL_FORMAT_MONO8, &convertedImage );
if (error != FlyCapture2::PGRERROR_OK)
{
PrintError( error );
}
fwrite(&stamp, sizeof(double), 1, fout[i]);
fwrite(convertedImage.GetData(), convertedImage.GetDataSize(), 1, fout[i]);
if (GetAsyncKeyState(VK_ESCAPE))
break;
}
return frameNumber; //return frame number in the event that [ESC] was pressed to stop camera streaming before set nframes was reached
}
int _tmain(int argc, _TCHAR* argv[])
{
const Mode k_fmt7Mode = MODE_0;
const PixelFormat k_fmt7PixFmt = PIXEL_FORMAT_RAW8;
Format7Info fmt7Info;
bool supported;
FlyCapture2::PGRGuid guid;
FlyCapture2::BusManager busMgr;
unsigned int numCameras;
unsigned __int32 fmfVersion;
unsigned __int64 bytesPerChunk, nframes, nframesRun;
unsigned __int32 sizeHeight, sizeWidth;
error = busMgr.GetNumOfCameras(&numCameras);
if (error != FlyCapture2::PGRERROR_OK)
{
PrintError( error );
return -1;
}
printf( "Number of cameras detected: %u\n\n", numCameras );
if ( numCameras < 1 )
{
printf( "Insufficient number of cameras\n" );
getchar();
return -1;
}
if (argc == 2)
nframes = _ttoi(argv[1]);
else
nframes = -1;
// initialize camera and video writer instances
ppCameras = new FlyCapture2::Camera*[numCameras];
fout = new FILE*[numCameras];
SYSTEMTIME st;
GetLocalTime(&st);
for ( unsigned int i = 0; i < numCameras; i++)
{
ppCameras[i] = new FlyCapture2::Camera();
error = busMgr.GetCameraFromIndex( i, &guid );
if (error != FlyCapture2::PGRERROR_OK)
{
PrintError( error );
return -1;
}
// Connect to a camera
error = ppCameras[i]->Connect( &guid );
if (error != FlyCapture2::PGRERROR_OK)
{
PrintError( error );
return -1;
}
// Get the camera information
FlyCapture2::CameraInfo camInfo;
error = ppCameras[i]->GetCameraInfo( &camInfo );
if (error != FlyCapture2::PGRERROR_OK)
{
PrintError( error );
return -1;
}
PrintCameraInfo(&camInfo);
// Set all cameras to a specific mode and frame rate so they
// can be synchronized
/*error = ppCameras[i]->SetVideoModeAndFrameRate(
FlyCapture2::VIDEOMODE_640x480Y8,
FlyCapture2::FRAMERATE_60 );
*/
// Query for available Format 7 modes
fmt7Info.mode = k_fmt7Mode;
error = ppCameras[i]->GetFormat7Info( &fmt7Info, &supported );
if (error != PGRERROR_OK)
{
PrintError( error );
return -1;
}
if ( (k_fmt7PixFmt & fmt7Info.pixelFormatBitField) == 0 )
{
// Pixel format not supported!
printf("Pixel format is not supported\n");
return -1;
}
Format7ImageSettings fmt7ImageSettings;
fmt7ImageSettings.mode = k_fmt7Mode;
fmt7ImageSettings.offsetX = 0;
fmt7ImageSettings.offsetY = 0;
fmt7ImageSettings.width = fmt7Info.maxWidth;
fmt7ImageSettings.height = fmt7Info.maxHeight;
fmt7ImageSettings.pixelFormat = k_fmt7PixFmt;
bool valid;
Format7PacketInfo fmt7PacketInfo;
// Validate the settings to make sure that they are valid
error = ppCameras[i]->ValidateFormat7Settings(&fmt7ImageSettings, &valid, &fmt7PacketInfo );
if (error != PGRERROR_OK)
{
PrintError( error );
return -1;
}
if ( !valid )
{
// Settings are not valid
printf("Format7 settings are not valid\n");
return -1;
}
// Set the settings to the camera
error = ppCameras[i]->SetFormat7Configuration(&fmt7ImageSettings, fmt7PacketInfo.recommendedBytesPerPacket );
if (error != PGRERROR_OK)
{
PrintError( error );
return -1;
}
//settings for version 1.0 fmf header
fmfVersion = 1;
sizeHeight = fmt7ImageSettings.height;
sizeWidth = fmt7ImageSettings.width;
bytesPerChunk = sizeHeight*sizeWidth + sizeof(double);
sprintf_s(fname[i], "D:\\Cam%d-%d%02d%02dT%02d%02d%02d.fmf", i, st.wYear, st.wMonth, st.wDay, st.wHour, st.wMinute, st.wSecond);
remove(fname[i]);
fout[i] = fopen(fname[i], "wb");
if(fout[i]==NULL)
{
printf("\nError opening FMF writer. Recording terminated.");
return -1;
}
//write FMF header data
fwrite(&fmfVersion, sizeof(unsigned __int32), 1, fout[i]);
fwrite(&sizeHeight, sizeof(unsigned __int32), 1, fout[i]);
fwrite(&sizeWidth, sizeof(unsigned __int32), 1, fout[i]);
fwrite(&bytesPerChunk, sizeof(unsigned __int64), 1, fout[i]);
fwrite(&nframes, sizeof(unsigned __int64), 1, fout[i]);
}
//Starting the capture in sync mode
error = FlyCapture2::Camera::StartSyncCapture( numCameras, (const FlyCapture2::Camera**)ppCameras );
if (error != FlyCapture2::PGRERROR_OK)
{
PrintError( error );
return -1;
}
//OpenMP parallel execution of camera streaming and recording to uncompressed fmf format videos
#pragma omp parallel for num_threads(numCameras)
for (int i = 0; i < numCameras; i++ )
{
nframesRun = RunSingleCamera(i, nframes);
}
for ( unsigned int i = 0; i < numCameras; i++ )
{
//check if number of frames streamed from the camera were the same as what was initially set
if (nframesRun != nframes)
{
//seek to location in file where nframes is stored and replace
fseek (fout[i], 20 , SEEK_SET );
fwrite(&nframesRun, sizeof(unsigned __int64), 1, fout[i]);
}
// close fmf flies
fclose(fout[i]);
// Stop capturing images
ppCameras[i]->StopCapture();
if (error != FlyCapture2::PGRERROR_OK)
{
PrintError( error );
return -1;
}
// Disconnect the camera
ppCameras[i]->Disconnect();
if (error != FlyCapture2::PGRERROR_OK)
{
PrintError( error );
return -1;
}
// Delete camera instances
delete ppCameras[i];
}
// Free up memory
delete [] ppCameras;
printf("Done");
getchar();
return 0;
}
<commit_msg>Changed camera start functionality<commit_after>// fmfRecord.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <FlyCapture2.h>
#include <omp.h>
using namespace FlyCapture2;
FILE **fout;
FlyCapture2::Camera** ppCameras;
FlyCapture2::Error error;
char fname[10][100];
void PrintCameraInfo( FlyCapture2::CameraInfo* pCamInfo )
{
printf("%u %s %s\n", pCamInfo->serialNumber, pCamInfo->modelName, pCamInfo->sensorResolution);
}
void PrintError( FlyCapture2::Error error )
{
error.PrintErrorTrace();
}
int RunSingleCamera(int i, int numImages)
{
int frameNumber;
double stamp;
FlyCapture2::Image rawImage;
// Create a converted image
FlyCapture2::Image convertedImage;
FlyCapture2::TimeStamp timestamp;
// press [ESC] to exit from continuous streaming mode
for (frameNumber=0; frameNumber != numImages; frameNumber++)
{
// Start capturing images
error = ppCameras[i]->RetrieveBuffer( &rawImage );
//get image timestamp
timestamp = rawImage.GetTimeStamp();
stamp = (double) timestamp.seconds;
// Convert the raw image
error = rawImage.Convert( FlyCapture2::PIXEL_FORMAT_MONO8, &convertedImage );
if (error != FlyCapture2::PGRERROR_OK)
{
PrintError( error );
}
fwrite(&stamp, sizeof(double), 1, fout[i]);
fwrite(convertedImage.GetData(), convertedImage.GetDataSize(), 1, fout[i]);
if (GetAsyncKeyState(VK_ESCAPE))
break;
}
return frameNumber; //return frame number in the event that [ESC] was pressed to stop camera streaming before set nframes was reached
}
int _tmain(int argc, _TCHAR* argv[])
{
const Mode k_fmt7Mode = MODE_0;
const PixelFormat k_fmt7PixFmt = PIXEL_FORMAT_RAW8;
Format7Info fmt7Info;
bool supported;
FlyCapture2::PGRGuid guid;
FlyCapture2::BusManager busMgr;
unsigned int numCameras;
unsigned __int32 fmfVersion;
unsigned __int64 bytesPerChunk, nframes, nframesRun;
unsigned __int32 sizeHeight, sizeWidth;
error = busMgr.GetNumOfCameras(&numCameras);
if (error != FlyCapture2::PGRERROR_OK)
{
PrintError( error );
return -1;
}
printf( "Number of cameras detected: %u\n\n", numCameras );
if ( numCameras < 1 )
{
printf( "Insufficient number of cameras\n" );
getchar();
return -1;
}
if (argc == 2)
nframes = _ttoi(argv[1]);
else
nframes = -1;
// initialize camera and video writer instances
ppCameras = new FlyCapture2::Camera*[numCameras];
fout = new FILE*[numCameras];
SYSTEMTIME st;
GetLocalTime(&st);
for ( unsigned int i = 0; i < numCameras; i++)
{
ppCameras[i] = new FlyCapture2::Camera();
error = busMgr.GetCameraFromIndex( i, &guid );
if (error != FlyCapture2::PGRERROR_OK)
{
PrintError( error );
return -1;
}
// Connect to a camera
error = ppCameras[i]->Connect( &guid );
if (error != FlyCapture2::PGRERROR_OK)
{
PrintError( error );
return -1;
}
// Get the camera information
FlyCapture2::CameraInfo camInfo;
error = ppCameras[i]->GetCameraInfo( &camInfo );
if (error != FlyCapture2::PGRERROR_OK)
{
PrintError( error );
return -1;
}
PrintCameraInfo(&camInfo);
// Query for available Format 7 modes
fmt7Info.mode = k_fmt7Mode;
error = ppCameras[i]->GetFormat7Info( &fmt7Info, &supported );
if (error != PGRERROR_OK)
{
PrintError( error );
return -1;
}
if ( (k_fmt7PixFmt & fmt7Info.pixelFormatBitField) == 0 )
{
// Pixel format not supported!
printf("Pixel format is not supported\n");
return -1;
}
Format7ImageSettings fmt7ImageSettings;
fmt7ImageSettings.mode = k_fmt7Mode;
fmt7ImageSettings.offsetX = 0;
fmt7ImageSettings.offsetY = 0;
fmt7ImageSettings.width = fmt7Info.maxWidth;
fmt7ImageSettings.height = fmt7Info.maxHeight;
fmt7ImageSettings.pixelFormat = k_fmt7PixFmt;
bool valid;
Format7PacketInfo fmt7PacketInfo;
// Validate the settings to make sure that they are valid
error = ppCameras[i]->ValidateFormat7Settings(&fmt7ImageSettings, &valid, &fmt7PacketInfo );
if (error != PGRERROR_OK)
{
PrintError( error );
return -1;
}
if ( !valid )
{
// Settings are not valid
printf("Format7 settings are not valid\n");
return -1;
}
// Set the settings to the camera
error = ppCameras[i]->SetFormat7Configuration(&fmt7ImageSettings, fmt7PacketInfo.recommendedBytesPerPacket );
if (error != PGRERROR_OK)
{
PrintError( error );
return -1;
}
//settings for version 1.0 fmf header
fmfVersion = 1;
sizeHeight = fmt7ImageSettings.height;
sizeWidth = fmt7ImageSettings.width;
bytesPerChunk = sizeHeight*sizeWidth + sizeof(double);
sprintf_s(fname[i], "D:\\Cam%d-%d%02d%02dT%02d%02d%02d.fmf", i, st.wYear, st.wMonth, st.wDay, st.wHour, st.wMinute, st.wSecond);
remove(fname[i]);
fout[i] = fopen(fname[i], "wb");
if(fout[i]==NULL)
{
printf("\nError opening FMF writer. Recording terminated.");
return -1;
}
//write FMF header data
fwrite(&fmfVersion, sizeof(unsigned __int32), 1, fout[i]);
fwrite(&sizeHeight, sizeof(unsigned __int32), 1, fout[i]);
fwrite(&sizeWidth, sizeof(unsigned __int32), 1, fout[i]);
fwrite(&bytesPerChunk, sizeof(unsigned __int64), 1, fout[i]);
fwrite(&nframes, sizeof(unsigned __int64), 1, fout[i]);
}
//Starting individual cameras
for ( unsigned int i = 0; i < numCameras; i++)
{
error = ppCameras[i]->StartCapture();
if (error != FlyCapture2::PGRERROR_OK)
{
PrintError( error );
getchar();
return -1;
}
}
printf("\nGrabbing ...\n");
//OpenMP parallel execution of camera streaming and recording to uncompressed fmf format videos
#pragma omp parallel for num_threads(numCameras)
for (int i = 0; i < numCameras; i++ )
{
nframesRun = RunSingleCamera(i, nframes);
}
for ( unsigned int i = 0; i < numCameras; i++ )
{
//check if number of frames streamed from the camera were the same as what was initially set
if (nframesRun != nframes)
{
//seek to location in file where nframes is stored and replace
fseek (fout[i], 20 , SEEK_SET );
fwrite(&nframesRun, sizeof(unsigned __int64), 1, fout[i]);
}
// close fmf flies
fclose(fout[i]);
// Stop capturing images
ppCameras[i]->StopCapture();
if (error != FlyCapture2::PGRERROR_OK)
{
PrintError( error );
return -1;
}
// Disconnect the camera
ppCameras[i]->Disconnect();
if (error != FlyCapture2::PGRERROR_OK)
{
PrintError( error );
return -1;
}
// Delete camera instances
delete ppCameras[i];
}
// Free up memory
delete [] ppCameras;
printf("Done");
getchar();
return 0;
}
<|endoftext|> |
<commit_before>/*
* Copyright 2014 Matthew Harvey
*
* 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 GUARD_summary_report_writer_hpp_7957524563166092
#define GUARD_summary_report_writer_hpp_7957524563166092
#include "activity_stats.hpp"
#include "report_writer.hpp"
#include "stint.hpp"
#include "time_point.hpp"
#include <map>
#include <ostream>
#include <vector>
namespace swx
{
class SummaryReportWriter: public ReportWriter
{
// nested types
public:
struct Flags
{
using type = int;
static type constexpr none = 0;
static type constexpr exclude_subactivities = (1 << 0);
static type constexpr produce_csv = (1 << 1);
static type constexpr use_regex = (1 << 2);
static type constexpr include_beginning = (1 << 3);
static type constexpr include_ending = (1 << 4);
static type constexpr show_stints = (1 << 5);
static type constexpr verbose = (1 << 6);
static type constexpr succinct = (1 << 7);
}; // struct Flags
// special member functions
public:
SummaryReportWriter
( std::vector<Stint> const& p_stints,
Options const& p_options,
Flags::type p_flags
);
SummaryReportWriter(SummaryReportWriter const& rhs) = delete;
SummaryReportWriter(SummaryReportWriter&& rhs) = delete;
SummaryReportWriter& operator=(SummaryReportWriter const& rhs) = delete;
SummaryReportWriter& operator=(SummaryReportWriter&& rhs) = delete;
virtual ~SummaryReportWriter();
// inherited virtual member functions
private:
virtual void do_preprocess_stints
( std::ostream& p_os,
std::vector<Stint> const& p_stints
) override;
virtual void do_process_stint
( std::ostream& p_os,
Stint const& p_stint
) override;
virtual void do_postprocess_stints
( std::ostream& p_os,
std::vector<Stint> const& p_stints
) override;
// other virtual member functions
private:
virtual void do_write_summary
( std::ostream& p_os,
std::map<std::string, ActivityStats> const& p_activity_stats_map
) = 0;
protected:
bool has_flag(Flags::type p_flag) const;
// member variables
private:
Flags::type const m_flags;
std::map<std::string, ActivityStats> m_activity_stats_map;
}; // class SummaryReportWriter
} // namespace swx
#endif // GUARD_summary_report_writer_hpp_7957524563166092
<commit_msg>Minor comment edit<commit_after>/*
* Copyright 2014 Matthew Harvey
*
* 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 GUARD_summary_report_writer_hpp_7957524563166092
#define GUARD_summary_report_writer_hpp_7957524563166092
#include "activity_stats.hpp"
#include "report_writer.hpp"
#include "stint.hpp"
#include "time_point.hpp"
#include <map>
#include <ostream>
#include <vector>
namespace swx
{
class SummaryReportWriter: public ReportWriter
{
// nested types
public:
struct Flags
{
using type = int;
static type constexpr none = 0;
static type constexpr exclude_subactivities = (1 << 0);
static type constexpr produce_csv = (1 << 1);
static type constexpr use_regex = (1 << 2);
static type constexpr include_beginning = (1 << 3);
static type constexpr include_ending = (1 << 4);
static type constexpr show_stints = (1 << 5);
static type constexpr verbose = (1 << 6);
static type constexpr succinct = (1 << 7);
}; // struct Flags
// special member functions
public:
SummaryReportWriter
( std::vector<Stint> const& p_stints,
Options const& p_options,
Flags::type p_flags
);
SummaryReportWriter(SummaryReportWriter const& rhs) = delete;
SummaryReportWriter(SummaryReportWriter&& rhs) = delete;
SummaryReportWriter& operator=(SummaryReportWriter const& rhs) = delete;
SummaryReportWriter& operator=(SummaryReportWriter&& rhs) = delete;
virtual ~SummaryReportWriter();
// inherited virtual member functions
private:
virtual void do_preprocess_stints
( std::ostream& p_os,
std::vector<Stint> const& p_stints
) override;
virtual void do_process_stint
( std::ostream& p_os,
Stint const& p_stint
) override;
virtual void do_postprocess_stints
( std::ostream& p_os,
std::vector<Stint> const& p_stints
) override;
// other virtual member functions
private:
virtual void do_write_summary
( std::ostream& p_os,
std::map<std::string, ActivityStats> const& p_activity_stats_map
) = 0;
// ordinary member functions
protected:
bool has_flag(Flags::type p_flag) const;
// member variables
private:
Flags::type const m_flags;
std::map<std::string, ActivityStats> m_activity_stats_map;
}; // class SummaryReportWriter
} // namespace swx
#endif // GUARD_summary_report_writer_hpp_7957524563166092
<|endoftext|> |
<commit_before>/*!
\file hashlog.cpp
\brief Hash logs reader definition
\author Ivan Shynkarenka
\date 13.12.2021
\copyright MIT License
*/
#include "logging/record.h"
#include "logging/layouts/text_layout.h"
#include "logging/version.h"
#include "errors/fatal.h"
#include "filesystem/file.h"
#include "system/stream.h"
#include <cstdio>
#include <cstring>
#include <iostream>
#include <memory>
#include <vector>
#include <OptionParser.h>
using namespace CppCommon;
using namespace CppLogging;
std::unique_ptr<Reader> FindHashlog(const Path& current)
{
// Try to find .hashlog in the current path
Path hashlog = current.IsRegularFile() ? current : (current / ".hashlog");
if (hashlog.IsExists())
{
File* file = new File(hashlog);
file->Open(true, false);
return std::unique_ptr<Reader>(file);
}
// Try to find .hashlog in the parent path
Path parent = current.parent();
if (parent)
return FindHashlog(parent);
// Cannot find .hashlog file
return nullptr;
}
std::unordered_map<uint32_t, std::string> ReadHashlog(const std::unique_ptr<Reader>& hashlog)
{
std::unordered_map<uint32_t, std::string> hashmap;
// Check if .hashlog is avaliable
if (!hashlog)
return hashmap;
// Read the hash map size
uint32_t size;
if (hashlog->Read(&size, sizeof(uint32_t)) != sizeof(uint32_t))
return hashmap;
hashmap.reserve(size);
// Read the hash map content
while (size-- > 0)
{
uint32_t hash;
if (hashlog->Read(&hash, sizeof(uint32_t)) != sizeof(uint32_t))
return hashmap;
uint32_t length;
if (hashlog->Read(&length, sizeof(uint32_t)) != sizeof(uint32_t))
return hashmap;
std::vector<uint8_t> buffer(length);
if (hashlog->Read(buffer.data(), length) != length)
return hashmap;
std::string message(buffer.begin(), buffer.end());
hashmap[hash] = message;
}
return hashmap;
}
bool InputRecord(Reader& input, Record& record, const std::unordered_map<uint32_t, std::string>& hashmap)
{
// Clear the logging record
record.Clear();
// Read the logging record size
uint32_t size;
if (input.Read(&size, sizeof(uint32_t)) != sizeof(uint32_t))
return false;
record.raw.resize(size);
// Read the logging record raw data
if (input.Read(record.raw.data(), size) != size)
{
std::cerr << "Failed to read from the input source!" << std::endl;
return false;
}
// Get the buffer start position
const uint8_t* buffer = record.raw.data();
// Deserialize logging record
std::memcpy(&record.timestamp, buffer, sizeof(uint64_t));
buffer += sizeof(uint64_t);
std::memcpy(&record.thread, buffer, sizeof(uint64_t));
buffer += sizeof(uint64_t);
std::memcpy(&record.level, buffer, sizeof(Level));
buffer += sizeof(Level);
uint8_t logger_size;
std::memcpy(&logger_size, buffer, sizeof(uint8_t));
buffer += sizeof(uint8_t);
record.logger.insert(record.logger.begin(), buffer, buffer + logger_size);
buffer += logger_size;
uint32_t message_hash;
std::memcpy(&message_hash, buffer, sizeof(uint32_t));
buffer += sizeof(uint32_t);
const auto& message = hashmap.find(message_hash);
record.message.assign((message != hashmap.end()) ? message->second : format("0x{:X}", message_hash));
uint32_t buffer_size;
std::memcpy(&buffer_size, buffer, sizeof(uint32_t));
buffer += sizeof(uint32_t);
record.buffer.insert(record.buffer.begin(), buffer, buffer + buffer_size);
buffer += buffer_size;
// Skip the last zero byte
++buffer;
return true;
}
bool OutputRecord(Writer& output, Record& record)
{
TextLayout layout;
layout.LayoutRecord(record);
size_t size = record.raw.size() - 1;
if (output.Write(record.raw.data(), size) != size)
{
std::cerr << "Failed to write into the output source!" << std::endl;
return false;
}
return true;
}
int main(int argc, char** argv)
{
auto parser = optparse::OptionParser().version(version);
parser.add_option("-x", "--hashlog").dest("hashlog").help("Hashlog file name");
parser.add_option("-i", "--input").dest("input").help("Input file name");
parser.add_option("-o", "--output").dest("output").help("Output file name");
optparse::Values options = parser.parse_args(argc, argv);
// Print help
if (options.get("help"))
{
parser.print_help();
return 0;
}
try
{
// Open the hashlog file
std::unique_ptr<Reader> hashlog = FindHashlog(Path::current());
if (options.is_set("hashlog"))
hashlog = FindHashlog(Path(options.get("hashlog")));
// Read .hashlog file and fill the logging messages hash map
std::unordered_map<uint32_t, std::string> hashmap = ReadHashlog(hashlog);
// Open the input file or stdin
std::unique_ptr<Reader> input(new StdInput());
if (options.is_set("input"))
{
File* file = new File(Path(options.get("input")));
file->Open(true, false);
input.reset(file);
}
// Open the output file or stdout
std::unique_ptr<Writer> output(new StdOutput());
if (options.is_set("output"))
{
File* file = new File(Path(options.get("output")));
file->Open(false, true);
output.reset(file);
}
// Process all logging record
Record record;
while (InputRecord(*input, record, hashmap))
if (!OutputRecord(*output, record))
break;
return 0;
}
catch (const std::exception& ex)
{
std::cerr << ex.what() << std::endl;
return -1;
}
}
<commit_msg>Bugfixing<commit_after>/*!
\file hashlog.cpp
\brief Hash logs reader definition
\author Ivan Shynkarenka
\date 13.12.2021
\copyright MIT License
*/
#include "logging/record.h"
#include "logging/layouts/text_layout.h"
#include "logging/version.h"
#include "errors/fatal.h"
#include "filesystem/file.h"
#include "system/stream.h"
#include <cstdio>
#include <cstring>
#include <iostream>
#include <memory>
#include <unordered_map>
#include <vector>
#include <OptionParser.h>
using namespace CppCommon;
using namespace CppLogging;
std::unique_ptr<Reader> FindHashlog(const Path& current)
{
// Try to find .hashlog in the current path
Path hashlog = current.IsRegularFile() ? current : (current / ".hashlog");
if (hashlog.IsExists())
{
File* file = new File(hashlog);
file->Open(true, false);
return std::unique_ptr<Reader>(file);
}
// Try to find .hashlog in the parent path
Path parent = current.parent();
if (parent)
return FindHashlog(parent);
// Cannot find .hashlog file
return nullptr;
}
std::unordered_map<uint32_t, std::string> ReadHashlog(const std::unique_ptr<Reader>& hashlog)
{
std::unordered_map<uint32_t, std::string> hashmap;
// Check if .hashlog is avaliable
if (!hashlog)
return hashmap;
// Read the hash map size
uint32_t size;
if (hashlog->Read(&size, sizeof(uint32_t)) != sizeof(uint32_t))
return hashmap;
hashmap.reserve(size);
// Read the hash map content
while (size-- > 0)
{
uint32_t hash;
if (hashlog->Read(&hash, sizeof(uint32_t)) != sizeof(uint32_t))
return hashmap;
uint32_t length;
if (hashlog->Read(&length, sizeof(uint32_t)) != sizeof(uint32_t))
return hashmap;
std::vector<uint8_t> buffer(length);
if (hashlog->Read(buffer.data(), length) != length)
return hashmap;
std::string message(buffer.begin(), buffer.end());
hashmap[hash] = message;
}
return hashmap;
}
bool InputRecord(Reader& input, Record& record, const std::unordered_map<uint32_t, std::string>& hashmap)
{
// Clear the logging record
record.Clear();
// Read the logging record size
uint32_t size;
if (input.Read(&size, sizeof(uint32_t)) != sizeof(uint32_t))
return false;
record.raw.resize(size);
// Read the logging record raw data
if (input.Read(record.raw.data(), size) != size)
{
std::cerr << "Failed to read from the input source!" << std::endl;
return false;
}
// Get the buffer start position
const uint8_t* buffer = record.raw.data();
// Deserialize logging record
std::memcpy(&record.timestamp, buffer, sizeof(uint64_t));
buffer += sizeof(uint64_t);
std::memcpy(&record.thread, buffer, sizeof(uint64_t));
buffer += sizeof(uint64_t);
std::memcpy(&record.level, buffer, sizeof(Level));
buffer += sizeof(Level);
uint8_t logger_size;
std::memcpy(&logger_size, buffer, sizeof(uint8_t));
buffer += sizeof(uint8_t);
record.logger.insert(record.logger.begin(), buffer, buffer + logger_size);
buffer += logger_size;
uint32_t message_hash;
std::memcpy(&message_hash, buffer, sizeof(uint32_t));
buffer += sizeof(uint32_t);
const auto& message = hashmap.find(message_hash);
record.message.assign((message != hashmap.end()) ? message->second : format("0x{:X}", message_hash));
uint32_t buffer_size;
std::memcpy(&buffer_size, buffer, sizeof(uint32_t));
buffer += sizeof(uint32_t);
record.buffer.insert(record.buffer.begin(), buffer, buffer + buffer_size);
buffer += buffer_size;
// Skip the last zero byte
++buffer;
return true;
}
bool OutputRecord(Writer& output, Record& record)
{
TextLayout layout;
layout.LayoutRecord(record);
size_t size = record.raw.size() - 1;
if (output.Write(record.raw.data(), size) != size)
{
std::cerr << "Failed to write into the output source!" << std::endl;
return false;
}
return true;
}
int main(int argc, char** argv)
{
auto parser = optparse::OptionParser().version(version);
parser.add_option("-x", "--hashlog").dest("hashlog").help("Hashlog file name");
parser.add_option("-i", "--input").dest("input").help("Input file name");
parser.add_option("-o", "--output").dest("output").help("Output file name");
optparse::Values options = parser.parse_args(argc, argv);
// Print help
if (options.get("help"))
{
parser.print_help();
return 0;
}
try
{
// Open the hashlog file
std::unique_ptr<Reader> hashlog = FindHashlog(Path::current());
if (options.is_set("hashlog"))
hashlog = FindHashlog(Path(options.get("hashlog")));
// Read .hashlog file and fill the logging messages hash map
std::unordered_map<uint32_t, std::string> hashmap = ReadHashlog(hashlog);
// Open the input file or stdin
std::unique_ptr<Reader> input(new StdInput());
if (options.is_set("input"))
{
File* file = new File(Path(options.get("input")));
file->Open(true, false);
input.reset(file);
}
// Open the output file or stdout
std::unique_ptr<Writer> output(new StdOutput());
if (options.is_set("output"))
{
File* file = new File(Path(options.get("output")));
file->Open(false, true);
output.reset(file);
}
// Process all logging record
Record record;
while (InputRecord(*input, record, hashmap))
if (!OutputRecord(*output, record))
break;
return 0;
}
catch (const std::exception& ex)
{
std::cerr << ex.what() << std::endl;
return -1;
}
}
<|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/reset.h"
#include <algorithm>
#include <vector>
#include "libcellml/variable.h"
namespace libcellml {
/**
* @brief The Reset::ResetImpl struct.
*
* The private implementation for the Reset class.
*/
struct Reset::ResetImpl
{
int mOrder = 0; /**< The relative order of the reset.*/
bool mOrderSet = false; /**< Whether the relative order of the reset has been set.*/
VariablePtr mVariable; /**< The associated variable for the reset.*/
VariablePtr mTestVariable; /**< The associated test_variable for the reset.*/
std::string mTestValue; /**< The MathML string for the test_value.*/
std::string mTestValueId; /**< The id of the test_value block */
std::string mResetValue; /**< The MathML string for the reset_value.*/
std::string mResetValueId; /**< The id of the reset_value block */
};
Reset::Reset()
: mPimpl(new ResetImpl())
{
}
Reset::Reset(int order)
: mPimpl(new ResetImpl())
{
setOrder(order);
}
ResetPtr Reset::create() noexcept
{
return std::shared_ptr<Reset> {new Reset {}};
}
ResetPtr Reset::create(int order) noexcept
{
return std::shared_ptr<Reset> {new Reset {order}};
}
Reset::~Reset()
{
delete mPimpl;
}
void Reset::setOrder(int order)
{
mPimpl->mOrder = order;
mPimpl->mOrderSet = true;
}
int Reset::order() const
{
return mPimpl->mOrder;
}
void Reset::unsetOrder()
{
mPimpl->mOrderSet = false;
}
bool Reset::isOrderSet()
{
return mPimpl->mOrderSet;
}
void Reset::setVariable(const VariablePtr &variable)
{
mPimpl->mVariable = variable;
}
VariablePtr Reset::variable() const
{
return mPimpl->mVariable;
}
void Reset::setTestVariable(const VariablePtr &variable)
{
mPimpl->mTestVariable = variable;
}
VariablePtr Reset::testVariable() const
{
return mPimpl->mTestVariable;
}
void Reset::appendTestValue(const std::string &math)
{
mPimpl->mTestValue.append(math);
}
std::string Reset::testValue() const
{
return mPimpl->mTestValue;
}
void Reset::setTestValueId(const std::string &id)
{
mPimpl->mTestValueId = id;
}
void Reset::removeTestValueId()
{
mPimpl->mTestValueId = "";
}
std::string Reset::testValueId() const
{
return mPimpl->mTestValueId;
}
void Reset::setTestValue(const std::string &math)
{
mPimpl->mTestValue = math;
}
void Reset::removeTestValue()
{
mPimpl->mTestValue = "";
}
void Reset::appendResetValue(const std::string &math)
{
mPimpl->mResetValue.append(math);
}
std::string Reset::resetValue() const
{
return mPimpl->mResetValue;
}
void Reset::setResetValue(const std::string &math)
{
mPimpl->mResetValue = math;
}
void Reset::removeResetValue()
{
mPimpl->mResetValue = "";
}
void Reset::setResetValueId(const std::string &id)
{
mPimpl->mResetValueId = id;
}
void Reset::removeResetValueId()
{
mPimpl->mResetValueId = "";
}
std::string Reset::resetValueId() const
{
return mPimpl->mResetValueId;
}
ResetPtr Reset::clone() const
{
auto r = create();
r->setId(id());
r->setOrder(order());
r->setResetValue(resetValue());
r->setResetValueId(resetValueId());
r->setTestValue(testValue());
r->setTestValueId(testValueId());
if (mPimpl->mVariable != nullptr) {
r->setVariable(mPimpl->mVariable->clone());
}
if (mPimpl->mTestVariable != nullptr) {
r->setTestVariable(mPimpl->mTestVariable->clone());
}
return r;
}
bool Reset::doEqual(const EntityPtr &other) const
{
if (Entity::doEqual(other)) {
auto reset = std::dynamic_pointer_cast<Reset>(other);
if (reset != nullptr &&
mPimpl->mOrder == reset->order() &&
mPimpl->mResetValue == reset->resetValue() &&
mPimpl->mResetValueId == reset->resetValueId() &&
mPimpl->mTestValue == reset->testValue() &&
mPimpl->mTestValueId == reset->testValueId()) {
if (mPimpl->mTestVariable != nullptr &&
!mPimpl->mTestVariable->equal(reset->testVariable())) {
return false;
} else if (mPimpl->mTestVariable == nullptr &&
reset->testVariable() != nullptr) {
return false;
}
if (mPimpl->mVariable != nullptr &&
!mPimpl->mVariable->equal(reset->variable())) {
return false;
} else if (mPimpl->mVariable == nullptr &&
reset->variable() != nullptr) {
return false;
}
return true;
}
}
return false;
}
} // namespace libcellml
<commit_msg>Address clang-tidy error.<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/reset.h"
#include <algorithm>
#include <vector>
#include "libcellml/variable.h"
namespace libcellml {
/**
* @brief The Reset::ResetImpl struct.
*
* The private implementation for the Reset class.
*/
struct Reset::ResetImpl
{
int mOrder = 0; /**< The relative order of the reset.*/
bool mOrderSet = false; /**< Whether the relative order of the reset has been set.*/
VariablePtr mVariable; /**< The associated variable for the reset.*/
VariablePtr mTestVariable; /**< The associated test_variable for the reset.*/
std::string mTestValue; /**< The MathML string for the test_value.*/
std::string mTestValueId; /**< The id of the test_value block */
std::string mResetValue; /**< The MathML string for the reset_value.*/
std::string mResetValueId; /**< The id of the reset_value block */
};
Reset::Reset()
: mPimpl(new ResetImpl())
{
}
Reset::Reset(int order)
: mPimpl(new ResetImpl())
{
setOrder(order);
}
ResetPtr Reset::create() noexcept
{
return std::shared_ptr<Reset> {new Reset {}};
}
ResetPtr Reset::create(int order) noexcept
{
return std::shared_ptr<Reset> {new Reset {order}};
}
Reset::~Reset()
{
delete mPimpl;
}
void Reset::setOrder(int order)
{
mPimpl->mOrder = order;
mPimpl->mOrderSet = true;
}
int Reset::order() const
{
return mPimpl->mOrder;
}
void Reset::unsetOrder()
{
mPimpl->mOrderSet = false;
}
bool Reset::isOrderSet()
{
return mPimpl->mOrderSet;
}
void Reset::setVariable(const VariablePtr &variable)
{
mPimpl->mVariable = variable;
}
VariablePtr Reset::variable() const
{
return mPimpl->mVariable;
}
void Reset::setTestVariable(const VariablePtr &variable)
{
mPimpl->mTestVariable = variable;
}
VariablePtr Reset::testVariable() const
{
return mPimpl->mTestVariable;
}
void Reset::appendTestValue(const std::string &math)
{
mPimpl->mTestValue.append(math);
}
std::string Reset::testValue() const
{
return mPimpl->mTestValue;
}
void Reset::setTestValueId(const std::string &id)
{
mPimpl->mTestValueId = id;
}
void Reset::removeTestValueId()
{
mPimpl->mTestValueId = "";
}
std::string Reset::testValueId() const
{
return mPimpl->mTestValueId;
}
void Reset::setTestValue(const std::string &math)
{
mPimpl->mTestValue = math;
}
void Reset::removeTestValue()
{
mPimpl->mTestValue = "";
}
void Reset::appendResetValue(const std::string &math)
{
mPimpl->mResetValue.append(math);
}
std::string Reset::resetValue() const
{
return mPimpl->mResetValue;
}
void Reset::setResetValue(const std::string &math)
{
mPimpl->mResetValue = math;
}
void Reset::removeResetValue()
{
mPimpl->mResetValue = "";
}
void Reset::setResetValueId(const std::string &id)
{
mPimpl->mResetValueId = id;
}
void Reset::removeResetValueId()
{
mPimpl->mResetValueId = "";
}
std::string Reset::resetValueId() const
{
return mPimpl->mResetValueId;
}
ResetPtr Reset::clone() const
{
auto r = create();
r->setId(id());
r->setOrder(order());
r->setResetValue(resetValue());
r->setResetValueId(resetValueId());
r->setTestValue(testValue());
r->setTestValueId(testValueId());
if (mPimpl->mVariable != nullptr) {
r->setVariable(mPimpl->mVariable->clone());
}
if (mPimpl->mTestVariable != nullptr) {
r->setTestVariable(mPimpl->mTestVariable->clone());
}
return r;
}
bool Reset::doEqual(const EntityPtr &other) const
{
if (Entity::doEqual(other)) {
auto reset = std::dynamic_pointer_cast<Reset>(other);
if (reset != nullptr &&
mPimpl->mOrder == reset->order() &&
mPimpl->mResetValue == reset->resetValue() &&
mPimpl->mResetValueId == reset->resetValueId() &&
mPimpl->mTestValue == reset->testValue() &&
mPimpl->mTestValueId == reset->testValueId()) {
bool equal = true;
if (mPimpl->mTestVariable != nullptr &&
!mPimpl->mTestVariable->equal(reset->testVariable())) {
equal = false;
} else if (mPimpl->mTestVariable == nullptr &&
reset->testVariable() != nullptr) {
equal = false;
}
if (mPimpl->mVariable != nullptr &&
!mPimpl->mVariable->equal(reset->variable())) {
equal = false;
} else if (mPimpl->mVariable == nullptr &&
reset->variable() != nullptr) {
equal = false;
}
return true;
}
}
return false;
}
} // namespace libcellml
<|endoftext|> |
<commit_before>/**
* @file llurldispatcher.cpp
* @brief Central registry for all URL handlers
*
* $LicenseInfo:firstyear=2007&license=viewergpl$
*
* Copyright (c) 2007-2009, Linden Research, Inc.
*
* Second Life Viewer Source Code
* The source code in this file ("Source Code") is provided by Linden Lab
* to you under the terms of the GNU General Public License, version 2.0
* ("GPL"), unless you have obtained a separate licensing agreement
* ("Other License"), formally executed by you and Linden Lab. Terms of
* the GPL can be found in doc/GPL-license.txt in this distribution, or
* online at http://secondlifegrid.net/programs/open_source/licensing/gplv2
*
* There are special exceptions to the terms and conditions of the GPL as
* it is applied to this Source Code. View the full text of the exception
* in the file doc/FLOSS-exception.txt in this software distribution, or
* online at
* http://secondlifegrid.net/programs/open_source/licensing/flossexception
*
* By copying, modifying or distributing this software, you acknowledge
* that you have read and understood your obligations described above,
* and agree to abide by those obligations.
*
* ALL LINDEN LAB SOURCE CODE IS PROVIDED "AS IS." LINDEN LAB MAKES NO
* WARRANTIES, EXPRESS, IMPLIED OR OTHERWISE, REGARDING ITS ACCURACY,
* COMPLETENESS OR PERFORMANCE.
* $/LicenseInfo$
*/
#include "llviewerprecompiledheaders.h"
#include "llurldispatcher.h"
// viewer includes
#include "llagent.h" // teleportViaLocation()
#include "llcommandhandler.h"
#include "llfloaterhelpbrowser.h"
#include "llfloaterreg.h"
#include "llfloaterurldisplay.h"
#include "llfloaterworldmap.h"
#include "llpanellogin.h"
#include "llregionhandle.h"
#include "llsidetray.h"
#include "llslurl.h"
#include "llstartup.h" // gStartupState
#include "llurlsimstring.h"
#include "llweb.h"
#include "llworldmapmessage.h"
#include "llurldispatcherlistener.h"
// library includes
#include "llnotificationsutil.h"
#include "llsd.h"
static LLURLDispatcherListener sURLDispatcherListener;
class LLURLDispatcherImpl
{
public:
static bool dispatch(const std::string& url,
LLMediaCtrl* web,
bool trusted_browser);
// returns true if handled or explicitly blocked.
static bool dispatchRightClick(const std::string& url);
private:
static bool dispatchCore(const std::string& url,
bool right_mouse,
LLMediaCtrl* web,
bool trusted_browser);
// handles both left and right click
static bool dispatchHelp(const std::string& url, bool right_mouse);
// Handles sl://app.floater.html.help by showing Help floater.
// Returns true if handled.
static bool dispatchApp(const std::string& url,
bool right_mouse,
LLMediaCtrl* web,
bool trusted_browser);
// Handles secondlife:///app/agent/<agent_id>/about and similar
// by showing panel in Search floater.
// Returns true if handled or explicitly blocked.
static bool dispatchRegion(const std::string& url, bool right_mouse);
// handles secondlife://Ahern/123/45/67/
// Returns true if handled.
static void regionHandleCallback(U64 handle, const std::string& url,
const LLUUID& snapshot_id, bool teleport);
// Called by LLWorldMap when a location has been resolved to a
// region name
static void regionNameCallback(U64 handle, const std::string& url,
const LLUUID& snapshot_id, bool teleport);
// Called by LLWorldMap when a region name has been resolved to a
// location in-world, used by places-panel display.
friend class LLTeleportHandler;
};
// static
bool LLURLDispatcherImpl::dispatchCore(const std::string& url,
bool right_mouse,
LLMediaCtrl* web,
bool trusted_browser)
{
if (url.empty()) return false;
//if (dispatchHelp(url, right_mouse)) return true;
if (dispatchApp(url, right_mouse, web, trusted_browser)) return true;
if (dispatchRegion(url, right_mouse)) return true;
/*
// Inform the user we can't handle this
std::map<std::string, std::string> args;
args["SLURL"] = url;
r;
*/
return false;
}
// static
bool LLURLDispatcherImpl::dispatch(const std::string& url,
LLMediaCtrl* web,
bool trusted_browser)
{
llinfos << "url: " << url << llendl;
const bool right_click = false;
return dispatchCore(url, right_click, web, trusted_browser);
}
// static
bool LLURLDispatcherImpl::dispatchRightClick(const std::string& url)
{
llinfos << "url: " << url << llendl;
const bool right_click = true;
LLMediaCtrl* web = NULL;
const bool trusted_browser = false;
return dispatchCore(url, right_click, web, trusted_browser);
}
// static
bool LLURLDispatcherImpl::dispatchApp(const std::string& url,
bool right_mouse,
LLMediaCtrl* web,
bool trusted_browser)
{
// ensure the URL is in the secondlife:///app/ format
if (!LLSLURL::isSLURLCommand(url))
{
return false;
}
LLURI uri(url);
LLSD pathArray = uri.pathArray();
pathArray.erase(0); // erase "app"
std::string cmd = pathArray.get(0);
pathArray.erase(0); // erase "cmd"
bool handled = LLCommandDispatcher::dispatch(
cmd, pathArray, uri.queryMap(), web, trusted_browser);
// alert if we didn't handle this secondlife:///app/ SLURL
// (but still return true because it is a valid app SLURL)
if (! handled)
{
LLNotificationsUtil::add("UnsupportedCommandSLURL");
}
return true;
}
// static
bool LLURLDispatcherImpl::dispatchRegion(const std::string& url, bool right_mouse)
{
if (!LLSLURL::isSLURL(url))
{
return false;
}
// Before we're logged in, need to update the startup screen
// to tell the user where they are going.
if (LLStartUp::getStartupState() < STATE_LOGIN_CLEANUP)
{
// Parse it and stash in globals, it will be dispatched in
// STATE_CLEANUP.
LLURLSimString::setString(url);
// We're at the login screen, so make sure user can see
// the login location box to know where they are going.
LLPanelLogin::refreshLocation( true );
return true;
}
std::string sim_string = LLSLURL::stripProtocol(url);
std::string region_name;
S32 x = 128;
S32 y = 128;
S32 z = 0;
LLURLSimString::parse(sim_string, ®ion_name, &x, &y, &z);
// LLFloaterURLDisplay functionality moved to LLPanelPlaces in Side Tray.
//LLFloaterURLDisplay* url_displayp = LLFloaterReg::getTypedInstance<LLFloaterURLDisplay>("preview_url",LLSD());
//if(url_displayp) url_displayp->setName(region_name);
// Request a region handle by name
LLWorldMapMessage::getInstance()->sendNamedRegionRequest(region_name,
LLURLDispatcherImpl::regionNameCallback,
url,
false); // don't teleport
return true;
}
/*static*/
void LLURLDispatcherImpl::regionNameCallback(U64 region_handle, const std::string& url, const LLUUID& snapshot_id, bool teleport)
{
std::string sim_string = LLSLURL::stripProtocol(url);
std::string region_name;
S32 x = 128;
S32 y = 128;
S32 z = 0;
LLURLSimString::parse(sim_string, ®ion_name, &x, &y, &z);
// Invalid location? EXT-5380
if (!region_handle)
{
if(!region_name.empty() && !LLStringOps::isDigit(region_name.c_str()[0]))// it is no sense to search an empty region_name or when the region_name starts with digits
{
// may be an user types incorrect region name, let's help him to find a correct one
LLFloaterReg::showInstance("search", LLSD().with("category", "places").with("id", LLSD(region_name)));
}
//*TODO: add notification about invalid region_name
return;
}
LLVector3 local_pos;
local_pos.mV[VX] = (F32)x;
local_pos.mV[VY] = (F32)y;
local_pos.mV[VZ] = (F32)z;
// determine whether the point is in this region
if ((x >= 0) && (x < REGION_WIDTH_UNITS) &&
(y >= 0) && (y < REGION_WIDTH_UNITS))
{
// if so, we're done
regionHandleCallback(region_handle, url, snapshot_id, teleport);
}
else
{
// otherwise find the new region from the location
// add the position to get the new region
LLVector3d global_pos = from_region_handle(region_handle) + LLVector3d(local_pos);
U64 new_region_handle = to_region_handle(global_pos);
LLWorldMapMessage::getInstance()->sendHandleRegionRequest(new_region_handle,
LLURLDispatcherImpl::regionHandleCallback,
url, teleport);
}
}
/* static */
void LLURLDispatcherImpl::regionHandleCallback(U64 region_handle, const std::string& url, const LLUUID& snapshot_id, bool teleport)
{
std::string sim_string = LLSLURL::stripProtocol(url);
std::string region_name;
S32 x = 128;
S32 y = 128;
S32 z = 0;
LLURLSimString::parse(sim_string, ®ion_name, &x, &y, &z);
// remap x and y to local coordinates
S32 local_x = x % REGION_WIDTH_UNITS;
S32 local_y = y % REGION_WIDTH_UNITS;
if (local_x < 0)
local_x += REGION_WIDTH_UNITS;
if (local_y < 0)
local_y += REGION_WIDTH_UNITS;
LLVector3 local_pos;
local_pos.mV[VX] = (F32)local_x;
local_pos.mV[VY] = (F32)local_y;
local_pos.mV[VZ] = (F32)z;
LLVector3d global_pos = from_region_handle(region_handle);
global_pos += LLVector3d(local_pos);
if (teleport)
{
gAgent.teleportViaLocation(global_pos);
LLFloaterWorldMap* instance = LLFloaterWorldMap::getInstance();
if(instance)
{
instance->trackLocation(global_pos);
}
}
else
{
LLSD key;
key["type"] = "remote_place";
key["x"] = global_pos.mdV[VX];
key["y"] = global_pos.mdV[VY];
key["z"] = global_pos.mdV[VZ];
LLSideTray::getInstance()->showPanel("panel_places", key);
// LLFloaterURLDisplay functionality moved to LLPanelPlaces in Side Tray.
// // display informational floater, allow user to click teleport btn
// LLFloaterURLDisplay* url_displayp = LLFloaterReg::getTypedInstance<LLFloaterURLDisplay>("preview_url",LLSD());
// if(url_displayp)
// {
// url_displayp->displayParcelInfo(region_handle, local_pos);
// if(snapshot_id.notNull())
// {
// url_displayp->setSnapshotDisplay(snapshot_id);
// }
// std::string locationString = llformat("%s %d, %d, %d", region_name.c_str(), x, y, z);
// url_displayp->setLocationString(locationString);
// }
}
}
//---------------------------------------------------------------------------
// Teleportation links are handled here because they are tightly coupled
// to URL parsing and sim-fragment parsing
class LLTeleportHandler : public LLCommandHandler
{
public:
// Teleport requests *must* come from a trusted browser
// inside the app, otherwise a malicious web page could
// cause a constant teleport loop. JC
LLTeleportHandler() : LLCommandHandler("teleport", UNTRUSTED_BLOCK) { }
bool handle(const LLSD& tokens, const LLSD& query_map,
LLMediaCtrl* web)
{
// construct a "normal" SLURL, resolve the region to
// a global position, and teleport to it
if (tokens.size() < 1) return false;
// Region names may be %20 escaped.
std::string region_name = LLURLSimString::unescapeRegionName(tokens[0]);
// build secondlife://De%20Haro/123/45/67 for use in callback
std::string url = LLSLURL::PREFIX_SECONDLIFE;
for (int i = 0; i < tokens.size(); ++i)
{
url += tokens[i].asString() + "/";
}
LLWorldMapMessage::getInstance()->sendNamedRegionRequest(region_name,
LLURLDispatcherImpl::regionHandleCallback,
url,
true); // teleport
return true;
}
};
LLTeleportHandler gTeleportHandler;
//---------------------------------------------------------------------------
// static
bool LLURLDispatcher::dispatch(const std::string& url,
LLMediaCtrl* web,
bool trusted_browser)
{
return LLURLDispatcherImpl::dispatch(url, web, trusted_browser);
}
// static
bool LLURLDispatcher::dispatchRightClick(const std::string& url)
{
return LLURLDispatcherImpl::dispatchRightClick(url);
}
// static
bool LLURLDispatcher::dispatchFromTextEditor(const std::string& url)
{
// *NOTE: Text editors are considered sources of trusted URLs
// in order to make avatar profile links in chat history work.
// While a malicious resident could chat an app SLURL, the
// receiving resident will see it and must affirmatively
// click on it.
// *TODO: Make this trust model more refined. JC
const bool trusted_browser = true;
LLMediaCtrl* web = NULL;
return LLURLDispatcherImpl::dispatch(url, web, trusted_browser);
}
<commit_msg>Rolling back a previous fix EXT-5380. More convenient approach has been founded.<commit_after>/**
* @file llurldispatcher.cpp
* @brief Central registry for all URL handlers
*
* $LicenseInfo:firstyear=2007&license=viewergpl$
*
* Copyright (c) 2007-2009, Linden Research, Inc.
*
* Second Life Viewer Source Code
* The source code in this file ("Source Code") is provided by Linden Lab
* to you under the terms of the GNU General Public License, version 2.0
* ("GPL"), unless you have obtained a separate licensing agreement
* ("Other License"), formally executed by you and Linden Lab. Terms of
* the GPL can be found in doc/GPL-license.txt in this distribution, or
* online at http://secondlifegrid.net/programs/open_source/licensing/gplv2
*
* There are special exceptions to the terms and conditions of the GPL as
* it is applied to this Source Code. View the full text of the exception
* in the file doc/FLOSS-exception.txt in this software distribution, or
* online at
* http://secondlifegrid.net/programs/open_source/licensing/flossexception
*
* By copying, modifying or distributing this software, you acknowledge
* that you have read and understood your obligations described above,
* and agree to abide by those obligations.
*
* ALL LINDEN LAB SOURCE CODE IS PROVIDED "AS IS." LINDEN LAB MAKES NO
* WARRANTIES, EXPRESS, IMPLIED OR OTHERWISE, REGARDING ITS ACCURACY,
* COMPLETENESS OR PERFORMANCE.
* $/LicenseInfo$
*/
#include "llviewerprecompiledheaders.h"
#include "llurldispatcher.h"
// viewer includes
#include "llagent.h" // teleportViaLocation()
#include "llcommandhandler.h"
#include "llfloaterhelpbrowser.h"
#include "llfloaterreg.h"
#include "llfloaterurldisplay.h"
#include "llfloaterworldmap.h"
#include "llpanellogin.h"
#include "llregionhandle.h"
#include "llsidetray.h"
#include "llslurl.h"
#include "llstartup.h" // gStartupState
#include "llurlsimstring.h"
#include "llweb.h"
#include "llworldmapmessage.h"
#include "llurldispatcherlistener.h"
// library includes
#include "llnotificationsutil.h"
#include "llsd.h"
static LLURLDispatcherListener sURLDispatcherListener;
class LLURLDispatcherImpl
{
public:
static bool dispatch(const std::string& url,
LLMediaCtrl* web,
bool trusted_browser);
// returns true if handled or explicitly blocked.
static bool dispatchRightClick(const std::string& url);
private:
static bool dispatchCore(const std::string& url,
bool right_mouse,
LLMediaCtrl* web,
bool trusted_browser);
// handles both left and right click
static bool dispatchHelp(const std::string& url, bool right_mouse);
// Handles sl://app.floater.html.help by showing Help floater.
// Returns true if handled.
static bool dispatchApp(const std::string& url,
bool right_mouse,
LLMediaCtrl* web,
bool trusted_browser);
// Handles secondlife:///app/agent/<agent_id>/about and similar
// by showing panel in Search floater.
// Returns true if handled or explicitly blocked.
static bool dispatchRegion(const std::string& url, bool right_mouse);
// handles secondlife://Ahern/123/45/67/
// Returns true if handled.
static void regionHandleCallback(U64 handle, const std::string& url,
const LLUUID& snapshot_id, bool teleport);
// Called by LLWorldMap when a location has been resolved to a
// region name
static void regionNameCallback(U64 handle, const std::string& url,
const LLUUID& snapshot_id, bool teleport);
// Called by LLWorldMap when a region name has been resolved to a
// location in-world, used by places-panel display.
friend class LLTeleportHandler;
};
// static
bool LLURLDispatcherImpl::dispatchCore(const std::string& url,
bool right_mouse,
LLMediaCtrl* web,
bool trusted_browser)
{
if (url.empty()) return false;
//if (dispatchHelp(url, right_mouse)) return true;
if (dispatchApp(url, right_mouse, web, trusted_browser)) return true;
if (dispatchRegion(url, right_mouse)) return true;
/*
// Inform the user we can't handle this
std::map<std::string, std::string> args;
args["SLURL"] = url;
r;
*/
return false;
}
// static
bool LLURLDispatcherImpl::dispatch(const std::string& url,
LLMediaCtrl* web,
bool trusted_browser)
{
llinfos << "url: " << url << llendl;
const bool right_click = false;
return dispatchCore(url, right_click, web, trusted_browser);
}
// static
bool LLURLDispatcherImpl::dispatchRightClick(const std::string& url)
{
llinfos << "url: " << url << llendl;
const bool right_click = true;
LLMediaCtrl* web = NULL;
const bool trusted_browser = false;
return dispatchCore(url, right_click, web, trusted_browser);
}
// static
bool LLURLDispatcherImpl::dispatchApp(const std::string& url,
bool right_mouse,
LLMediaCtrl* web,
bool trusted_browser)
{
// ensure the URL is in the secondlife:///app/ format
if (!LLSLURL::isSLURLCommand(url))
{
return false;
}
LLURI uri(url);
LLSD pathArray = uri.pathArray();
pathArray.erase(0); // erase "app"
std::string cmd = pathArray.get(0);
pathArray.erase(0); // erase "cmd"
bool handled = LLCommandDispatcher::dispatch(
cmd, pathArray, uri.queryMap(), web, trusted_browser);
// alert if we didn't handle this secondlife:///app/ SLURL
// (but still return true because it is a valid app SLURL)
if (! handled)
{
LLNotificationsUtil::add("UnsupportedCommandSLURL");
}
return true;
}
// static
bool LLURLDispatcherImpl::dispatchRegion(const std::string& url, bool right_mouse)
{
if (!LLSLURL::isSLURL(url))
{
return false;
}
// Before we're logged in, need to update the startup screen
// to tell the user where they are going.
if (LLStartUp::getStartupState() < STATE_LOGIN_CLEANUP)
{
// Parse it and stash in globals, it will be dispatched in
// STATE_CLEANUP.
LLURLSimString::setString(url);
// We're at the login screen, so make sure user can see
// the login location box to know where they are going.
LLPanelLogin::refreshLocation( true );
return true;
}
std::string sim_string = LLSLURL::stripProtocol(url);
std::string region_name;
S32 x = 128;
S32 y = 128;
S32 z = 0;
LLURLSimString::parse(sim_string, ®ion_name, &x, &y, &z);
// LLFloaterURLDisplay functionality moved to LLPanelPlaces in Side Tray.
//LLFloaterURLDisplay* url_displayp = LLFloaterReg::getTypedInstance<LLFloaterURLDisplay>("preview_url",LLSD());
//if(url_displayp) url_displayp->setName(region_name);
// Request a region handle by name
LLWorldMapMessage::getInstance()->sendNamedRegionRequest(region_name,
LLURLDispatcherImpl::regionNameCallback,
url,
false); // don't teleport
return true;
}
/*static*/
void LLURLDispatcherImpl::regionNameCallback(U64 region_handle, const std::string& url, const LLUUID& snapshot_id, bool teleport)
{
std::string sim_string = LLSLURL::stripProtocol(url);
std::string region_name;
S32 x = 128;
S32 y = 128;
S32 z = 0;
LLURLSimString::parse(sim_string, ®ion_name, &x, &y, &z);
LLVector3 local_pos;
local_pos.mV[VX] = (F32)x;
local_pos.mV[VY] = (F32)y;
local_pos.mV[VZ] = (F32)z;
// determine whether the point is in this region
if ((x >= 0) && (x < REGION_WIDTH_UNITS) &&
(y >= 0) && (y < REGION_WIDTH_UNITS))
{
// if so, we're done
regionHandleCallback(region_handle, url, snapshot_id, teleport);
}
else
{
// otherwise find the new region from the location
// add the position to get the new region
LLVector3d global_pos = from_region_handle(region_handle) + LLVector3d(local_pos);
U64 new_region_handle = to_region_handle(global_pos);
LLWorldMapMessage::getInstance()->sendHandleRegionRequest(new_region_handle,
LLURLDispatcherImpl::regionHandleCallback,
url, teleport);
}
}
/* static */
void LLURLDispatcherImpl::regionHandleCallback(U64 region_handle, const std::string& url, const LLUUID& snapshot_id, bool teleport)
{
std::string sim_string = LLSLURL::stripProtocol(url);
std::string region_name;
S32 x = 128;
S32 y = 128;
S32 z = 0;
LLURLSimString::parse(sim_string, ®ion_name, &x, &y, &z);
// remap x and y to local coordinates
S32 local_x = x % REGION_WIDTH_UNITS;
S32 local_y = y % REGION_WIDTH_UNITS;
if (local_x < 0)
local_x += REGION_WIDTH_UNITS;
if (local_y < 0)
local_y += REGION_WIDTH_UNITS;
LLVector3 local_pos;
local_pos.mV[VX] = (F32)local_x;
local_pos.mV[VY] = (F32)local_y;
local_pos.mV[VZ] = (F32)z;
LLVector3d global_pos = from_region_handle(region_handle);
global_pos += LLVector3d(local_pos);
if (teleport)
{
gAgent.teleportViaLocation(global_pos);
LLFloaterWorldMap* instance = LLFloaterWorldMap::getInstance();
if(instance)
{
instance->trackLocation(global_pos);
}
}
else
{
LLSD key;
key["type"] = "remote_place";
key["x"] = global_pos.mdV[VX];
key["y"] = global_pos.mdV[VY];
key["z"] = global_pos.mdV[VZ];
LLSideTray::getInstance()->showPanel("panel_places", key);
// LLFloaterURLDisplay functionality moved to LLPanelPlaces in Side Tray.
// // display informational floater, allow user to click teleport btn
// LLFloaterURLDisplay* url_displayp = LLFloaterReg::getTypedInstance<LLFloaterURLDisplay>("preview_url",LLSD());
// if(url_displayp)
// {
// url_displayp->displayParcelInfo(region_handle, local_pos);
// if(snapshot_id.notNull())
// {
// url_displayp->setSnapshotDisplay(snapshot_id);
// }
// std::string locationString = llformat("%s %d, %d, %d", region_name.c_str(), x, y, z);
// url_displayp->setLocationString(locationString);
// }
}
}
//---------------------------------------------------------------------------
// Teleportation links are handled here because they are tightly coupled
// to URL parsing and sim-fragment parsing
class LLTeleportHandler : public LLCommandHandler
{
public:
// Teleport requests *must* come from a trusted browser
// inside the app, otherwise a malicious web page could
// cause a constant teleport loop. JC
LLTeleportHandler() : LLCommandHandler("teleport", UNTRUSTED_BLOCK) { }
bool handle(const LLSD& tokens, const LLSD& query_map,
LLMediaCtrl* web)
{
// construct a "normal" SLURL, resolve the region to
// a global position, and teleport to it
if (tokens.size() < 1) return false;
// Region names may be %20 escaped.
std::string region_name = LLURLSimString::unescapeRegionName(tokens[0]);
// build secondlife://De%20Haro/123/45/67 for use in callback
std::string url = LLSLURL::PREFIX_SECONDLIFE;
for (int i = 0; i < tokens.size(); ++i)
{
url += tokens[i].asString() + "/";
}
LLWorldMapMessage::getInstance()->sendNamedRegionRequest(region_name,
LLURLDispatcherImpl::regionHandleCallback,
url,
true); // teleport
return true;
}
};
LLTeleportHandler gTeleportHandler;
//---------------------------------------------------------------------------
// static
bool LLURLDispatcher::dispatch(const std::string& url,
LLMediaCtrl* web,
bool trusted_browser)
{
return LLURLDispatcherImpl::dispatch(url, web, trusted_browser);
}
// static
bool LLURLDispatcher::dispatchRightClick(const std::string& url)
{
return LLURLDispatcherImpl::dispatchRightClick(url);
}
// static
bool LLURLDispatcher::dispatchFromTextEditor(const std::string& url)
{
// *NOTE: Text editors are considered sources of trusted URLs
// in order to make avatar profile links in chat history work.
// While a malicious resident could chat an app SLURL, the
// receiving resident will see it and must affirmatively
// click on it.
// *TODO: Make this trust model more refined. JC
const bool trusted_browser = true;
LLMediaCtrl* web = NULL;
return LLURLDispatcherImpl::dispatch(url, web, trusted_browser);
}
<|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-CHROMIUM file.
#include "browser/browser_main_parts.h"
#include "browser/browser_context.h"
#include "browser/devtools_manager_delegate.h"
#include "browser/web_ui_controller_factory.h"
#include "base/command_line.h"
#include "base/strings/string_number_conversions.h"
#include "components/devtools_http_handler/devtools_http_handler.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/common/content_switches.h"
#include "net/proxy/proxy_resolver_v8.h"
#if defined(USE_AURA)
#include "ui/gfx/screen.h"
#include "ui/views/widget/desktop_aura/desktop_screen.h"
#endif
#if defined(TOOLKIT_VIEWS)
#include "browser/views/views_delegate.h"
#endif
#if defined(USE_X11)
#include "base/environment.h"
#include "base/path_service.h"
#include "base/nix/xdg_util.h"
#include "base/thread_task_runner_handle.h"
#include "browser/brightray_paths.h"
#include "chrome/browser/ui/libgtk2ui/gtk2_ui.h"
#include "ui/base/x/x11_util.h"
#include "ui/base/x/x11_util_internal.h"
#include "ui/views/linux_ui/linux_ui.h"
#include "ui/wm/core/wm_state.h"
#endif
#if defined(OS_WIN)
#include "ui/base/cursor/cursor_loader_win.h"
#include "ui/base/l10n/l10n_util.h"
#include "ui/base/l10n/l10n_util_win.h"
#include "ui/gfx/platform_font_win.h"
#endif
using content::BrowserThread;
namespace brightray {
namespace {
#if defined(OS_WIN)
// gfx::Font callbacks
void AdjustUIFont(LOGFONT* logfont) {
l10n_util::AdjustUIFont(logfont);
}
int GetMinimumFontSize() {
return 10;
}
#endif
#if defined(USE_X11)
// Indicates that we're currently responding to an IO error (by shutting down).
bool g_in_x11_io_error_handler = false;
// Number of seconds to wait for UI thread to get an IO error if we get it on
// the background thread.
const int kWaitForUIThreadSeconds = 10;
void OverrideLinuxAppDataPath() {
base::FilePath path;
if (PathService::Get(DIR_APP_DATA, &path))
return;
scoped_ptr<base::Environment> env(base::Environment::Create());
path = base::nix::GetXDGDirectory(env.get(),
base::nix::kXdgConfigHomeEnvVar,
base::nix::kDotConfigDir);
PathService::Override(DIR_APP_DATA, path);
}
int BrowserX11ErrorHandler(Display* d, XErrorEvent* error) {
if (!g_in_x11_io_error_handler) {
base::ThreadTaskRunnerHandle::Get()->PostTask(
FROM_HERE, base::Bind(&ui::LogErrorEventDescription, d, *error));
}
return 0;
}
// This function is used to help us diagnose crash dumps that happen
// during the shutdown process.
NOINLINE void WaitingForUIThreadToHandleIOError() {
// Ensure function isn't optimized away.
asm("");
sleep(kWaitForUIThreadSeconds);
}
int BrowserX11IOErrorHandler(Display* d) {
if (!BrowserThread::CurrentlyOn(BrowserThread::UI)) {
// Wait for the UI thread (which has a different connection to the X server)
// to get the error. We can't call shutdown from this thread without
// tripping an error. Doing it through a function so that we'll be able
// to see it in any crash dumps.
WaitingForUIThreadToHandleIOError();
return 0;
}
// If there's an IO error it likely means the X server has gone away.
// If this CHECK fails, then that means SessionEnding() below triggered some
// code that tried to talk to the X server, resulting in yet another error.
CHECK(!g_in_x11_io_error_handler);
g_in_x11_io_error_handler = true;
LOG(ERROR) << "X IO error received (X server probably went away)";
base::ThreadTaskRunnerHandle::Get()->PostTask(
FROM_HERE, base::MessageLoop::QuitWhenIdleClosure());
return 0;
}
int X11EmptyErrorHandler(Display* d, XErrorEvent* error) {
return 0;
}
int X11EmptyIOErrorHandler(Display* d) {
return 0;
}
#endif
} // namespace
BrowserMainParts::BrowserMainParts() {
}
BrowserMainParts::~BrowserMainParts() {
}
void BrowserMainParts::PreEarlyInitialization() {
#if defined(OS_MACOSX)
IncreaseFileDescriptorLimit();
#endif
#if defined(USE_X11)
views::LinuxUI::SetInstance(BuildGtk2UI());
OverrideLinuxAppDataPath();
// Installs the X11 error handlers for the browser process used during
// startup. They simply print error messages and exit because
// we can't shutdown properly while creating and initializing services.
ui::SetX11ErrorHandlers(nullptr, nullptr);
#endif
}
void BrowserMainParts::ToolkitInitialized() {
#if defined(USE_AURA) && defined(USE_X11)
views::LinuxUI::instance()->Initialize();
wm_state_.reset(new wm::WMState);
#endif
#if defined(TOOLKIT_VIEWS)
views_delegate_.reset(new ViewsDelegate);
#endif
#if defined(OS_WIN)
gfx::PlatformFontWin::adjust_font_callback = &AdjustUIFont;
gfx::PlatformFontWin::get_minimum_font_size_callback = &GetMinimumFontSize;
wchar_t module_name[MAX_PATH] = { 0 };
if (GetModuleFileName(NULL, module_name, MAX_PATH))
ui::CursorLoaderWin::SetCursorResourceModule(module_name);
#endif
}
void BrowserMainParts::PreMainMessageLoopStart() {
#if defined(OS_MACOSX)
InitializeMainNib();
#endif
}
void BrowserMainParts::PreMainMessageLoopRun() {
browser_context_ = BrowserContext::From("", false);
content::WebUIControllerFactory::RegisterFactory(
WebUIControllerFactory::GetInstance());
// --remote-debugging-port
auto command_line = base::CommandLine::ForCurrentProcess();
if (command_line->HasSwitch(switches::kRemoteDebuggingPort))
devtools_http_handler_.reset(DevToolsManagerDelegate::CreateHttpHandler());
}
void BrowserMainParts::PostMainMessageLoopStart() {
#if defined(USE_X11)
// Installs the X11 error handlers for the browser process after the
// main message loop has started. This will allow us to exit cleanly
// if X exits before us.
ui::SetX11ErrorHandlers(BrowserX11ErrorHandler, BrowserX11IOErrorHandler);
#endif
}
void BrowserMainParts::PostMainMessageLoopRun() {
browser_context_ = nullptr;
#if defined(USE_X11)
// Unset the X11 error handlers. The X11 error handlers log the errors using a
// |PostTask()| on the message-loop. But since the message-loop is in the
// process of terminating, this can cause errors.
ui::SetX11ErrorHandlers(X11EmptyErrorHandler, X11EmptyIOErrorHandler);
#endif
}
int BrowserMainParts::PreCreateThreads() {
#if defined(USE_AURA)
gfx::Screen::SetScreenInstance(gfx::SCREEN_TYPE_NATIVE,
views::CreateDesktopScreen());
#endif
return 0;
}
} // namespace brightray
<commit_msg>linux: Set device scaling factor<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-CHROMIUM file.
#include "browser/browser_main_parts.h"
#include "browser/browser_context.h"
#include "browser/devtools_manager_delegate.h"
#include "browser/web_ui_controller_factory.h"
#include "base/command_line.h"
#include "base/strings/string_number_conversions.h"
#include "components/devtools_http_handler/devtools_http_handler.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/common/content_switches.h"
#include "net/proxy/proxy_resolver_v8.h"
#if defined(USE_AURA)
#include "ui/gfx/screen.h"
#include "ui/views/widget/desktop_aura/desktop_screen.h"
#endif
#if defined(TOOLKIT_VIEWS)
#include "browser/views/views_delegate.h"
#endif
#if defined(USE_X11)
#include "base/environment.h"
#include "base/path_service.h"
#include "base/nix/xdg_util.h"
#include "base/thread_task_runner_handle.h"
#include "browser/brightray_paths.h"
#include "chrome/browser/ui/libgtk2ui/gtk2_ui.h"
#include "ui/base/x/x11_util.h"
#include "ui/base/x/x11_util_internal.h"
#include "ui/views/linux_ui/linux_ui.h"
#include "ui/wm/core/wm_state.h"
#endif
#if defined(OS_WIN)
#include "ui/base/cursor/cursor_loader_win.h"
#include "ui/base/l10n/l10n_util.h"
#include "ui/base/l10n/l10n_util_win.h"
#include "ui/gfx/platform_font_win.h"
#endif
using content::BrowserThread;
namespace brightray {
namespace {
#if defined(OS_WIN)
// gfx::Font callbacks
void AdjustUIFont(LOGFONT* logfont) {
l10n_util::AdjustUIFont(logfont);
}
int GetMinimumFontSize() {
return 10;
}
#endif
#if defined(USE_X11)
// Indicates that we're currently responding to an IO error (by shutting down).
bool g_in_x11_io_error_handler = false;
// Number of seconds to wait for UI thread to get an IO error if we get it on
// the background thread.
const int kWaitForUIThreadSeconds = 10;
void OverrideLinuxAppDataPath() {
base::FilePath path;
if (PathService::Get(DIR_APP_DATA, &path))
return;
scoped_ptr<base::Environment> env(base::Environment::Create());
path = base::nix::GetXDGDirectory(env.get(),
base::nix::kXdgConfigHomeEnvVar,
base::nix::kDotConfigDir);
PathService::Override(DIR_APP_DATA, path);
}
int BrowserX11ErrorHandler(Display* d, XErrorEvent* error) {
if (!g_in_x11_io_error_handler) {
base::ThreadTaskRunnerHandle::Get()->PostTask(
FROM_HERE, base::Bind(&ui::LogErrorEventDescription, d, *error));
}
return 0;
}
// This function is used to help us diagnose crash dumps that happen
// during the shutdown process.
NOINLINE void WaitingForUIThreadToHandleIOError() {
// Ensure function isn't optimized away.
asm("");
sleep(kWaitForUIThreadSeconds);
}
int BrowserX11IOErrorHandler(Display* d) {
if (!BrowserThread::CurrentlyOn(BrowserThread::UI)) {
// Wait for the UI thread (which has a different connection to the X server)
// to get the error. We can't call shutdown from this thread without
// tripping an error. Doing it through a function so that we'll be able
// to see it in any crash dumps.
WaitingForUIThreadToHandleIOError();
return 0;
}
// If there's an IO error it likely means the X server has gone away.
// If this CHECK fails, then that means SessionEnding() below triggered some
// code that tried to talk to the X server, resulting in yet another error.
CHECK(!g_in_x11_io_error_handler);
g_in_x11_io_error_handler = true;
LOG(ERROR) << "X IO error received (X server probably went away)";
base::ThreadTaskRunnerHandle::Get()->PostTask(
FROM_HERE, base::MessageLoop::QuitWhenIdleClosure());
return 0;
}
int X11EmptyErrorHandler(Display* d, XErrorEvent* error) {
return 0;
}
int X11EmptyIOErrorHandler(Display* d) {
return 0;
}
#endif
} // namespace
BrowserMainParts::BrowserMainParts() {
}
BrowserMainParts::~BrowserMainParts() {
}
void BrowserMainParts::PreEarlyInitialization() {
#if defined(OS_MACOSX)
IncreaseFileDescriptorLimit();
#endif
#if defined(USE_X11)
views::LinuxUI::SetInstance(BuildGtk2UI());
OverrideLinuxAppDataPath();
// Installs the X11 error handlers for the browser process used during
// startup. They simply print error messages and exit because
// we can't shutdown properly while creating and initializing services.
ui::SetX11ErrorHandlers(nullptr, nullptr);
#endif
}
void BrowserMainParts::ToolkitInitialized() {
#if defined(USE_AURA) && defined(USE_X11)
views::LinuxUI::instance()->Initialize();
wm_state_.reset(new wm::WMState);
#endif
#if defined(TOOLKIT_VIEWS)
views_delegate_.reset(new ViewsDelegate);
#endif
#if defined(OS_WIN)
gfx::PlatformFontWin::adjust_font_callback = &AdjustUIFont;
gfx::PlatformFontWin::get_minimum_font_size_callback = &GetMinimumFontSize;
wchar_t module_name[MAX_PATH] = { 0 };
if (GetModuleFileName(NULL, module_name, MAX_PATH))
ui::CursorLoaderWin::SetCursorResourceModule(module_name);
#endif
}
void BrowserMainParts::PreMainMessageLoopStart() {
#if defined(OS_MACOSX)
InitializeMainNib();
#endif
}
void BrowserMainParts::PreMainMessageLoopRun() {
browser_context_ = BrowserContext::From("", false);
content::WebUIControllerFactory::RegisterFactory(
WebUIControllerFactory::GetInstance());
// --remote-debugging-port
auto command_line = base::CommandLine::ForCurrentProcess();
if (command_line->HasSwitch(switches::kRemoteDebuggingPort))
devtools_http_handler_.reset(DevToolsManagerDelegate::CreateHttpHandler());
}
void BrowserMainParts::PostMainMessageLoopStart() {
#if defined(USE_X11)
// Installs the X11 error handlers for the browser process after the
// main message loop has started. This will allow us to exit cleanly
// if X exits before us.
ui::SetX11ErrorHandlers(BrowserX11ErrorHandler, BrowserX11IOErrorHandler);
#endif
}
void BrowserMainParts::PostMainMessageLoopRun() {
browser_context_ = nullptr;
#if defined(USE_X11)
// Unset the X11 error handlers. The X11 error handlers log the errors using a
// |PostTask()| on the message-loop. But since the message-loop is in the
// process of terminating, this can cause errors.
ui::SetX11ErrorHandlers(X11EmptyErrorHandler, X11EmptyIOErrorHandler);
#endif
}
int BrowserMainParts::PreCreateThreads() {
#if defined(USE_AURA)
gfx::Screen* screen = views::CreateDesktopScreen();
gfx::Screen::SetScreenInstance(gfx::SCREEN_TYPE_NATIVE, screen);
#if defined(USE_X11)
views::LinuxUI::instance()->UpdateDeviceScaleFactor(
screen->GetPrimaryDisplay().device_scale_factor());
#endif
#endif
return 0;
}
} // namespace brightray
<|endoftext|> |
<commit_before>/*
* File: collision.cpp
* Author: Nick (original version), ahnonay (SFML2 compatibility)
*
* Modified indentation, include path, included function to check alpha != 0 at vector position and
* included function to compare bounds
*/
#include "../../include/Collision.hpp"
#include <iostream>
#include <map>
namespace Collision {
class BitmaskManager {
public:
~BitmaskManager() {
std::map< const sf::Texture*, sf::Uint8* >::const_iterator end = Bitmasks.end();
for( std::map< const sf::Texture*, sf::Uint8* >::const_iterator iter = Bitmasks.begin();
iter != end;
iter++ )
delete[] iter->second;
}
sf::Uint8
GetPixel( const sf::Uint8* mask, const sf::Texture* tex, unsigned int x, unsigned int y ) {
if( x > tex->getSize().x || y > tex->getSize().y )
return 0;
return mask[ x + y * tex->getSize().x ];
}
sf::Uint8* GetMask( const sf::Texture* tex ) {
sf::Uint8* mask;
std::map< const sf::Texture*, sf::Uint8* >::iterator pair = Bitmasks.find( tex );
if( pair == Bitmasks.end() ) {
sf::Image img = tex->copyToImage();
mask = CreateMask( tex, img );
} else
mask = pair->second;
return mask;
}
sf::Uint8* CreateMask( const sf::Texture* tex, const sf::Image& img ) {
sf::Uint8* mask = new sf::Uint8[ tex->getSize().y * tex->getSize().x ];
for( unsigned int y = 0; y < tex->getSize().y; y++ ) {
for( unsigned int x = 0; x < tex->getSize().x; x++ )
mask[ x + y * tex->getSize().x ] = img.getPixel( x, y ).a;
}
Bitmasks.insert( std::pair< const sf::Texture*, sf::Uint8* >( tex, mask ) );
return mask;
}
private:
std::map< const sf::Texture*, sf::Uint8* > Bitmasks;
};
BitmaskManager Bitmasks;
bool SimpleTest( const sf::Sprite& Object1, const sf::Sprite& Object2 ) {
return Object1.getGlobalBounds().intersects( Object2.getGlobalBounds() );
}
bool
PixelPerfectTest( const sf::Sprite& Object1, const sf::Sprite& Object2, sf::Uint8 AlphaLimit ) {
sf::FloatRect Intersection;
if( Object1.getGlobalBounds().intersects( Object2.getGlobalBounds(), Intersection ) ) {
sf::IntRect O1SubRect = Object1.getTextureRect();
sf::IntRect O2SubRect = Object2.getTextureRect();
sf::Uint8* mask1 = Bitmasks.GetMask( Object1.getTexture() );
sf::Uint8* mask2 = Bitmasks.GetMask( Object2.getTexture() );
// Loop through our pixels
for( int i = Intersection.left; i < Intersection.left + Intersection.width; i++ ) {
for( int j = Intersection.top; j < Intersection.top + Intersection.height; j++ ) {
sf::Vector2f o1v = Object1.getInverseTransform().transformPoint( i, j );
sf::Vector2f o2v = Object2.getInverseTransform().transformPoint( i, j );
// Make sure pixels fall within the sprite's subrect
if( o1v.x > 0 && o1v.y > 0 && o2v.x > 0 && o2v.y > 0 &&
o1v.x < O1SubRect.width && o1v.y < O1SubRect.height &&
o2v.x < O2SubRect.width && o2v.y < O2SubRect.height ) {
if( Bitmasks.GetPixel( mask1,
Object1.getTexture(),
(int)( o1v.x ) + O1SubRect.left,
(int)( o1v.y ) + O1SubRect.top ) > AlphaLimit &&
Bitmasks.GetPixel( mask2,
Object2.getTexture(),
(int)( o2v.x ) + O2SubRect.left,
(int)( o2v.y ) + O2SubRect.top ) > AlphaLimit )
return true;
}
}
}
}
return false;
}
bool VectorPerfectTest( const sf::Sprite& Object1, const sf::Vector2< float >& Vector ) {
sf::Uint8 AlphaLimit = 0;
if( Object1.getGlobalBounds().contains( Vector ) ) {
sf::Uint8* mask1 = Bitmasks.GetMask( Object1.getTexture() );
if( Bitmasks.GetPixel(
mask1, Object1.getTexture(), (int)( Vector.x ), (int)( Vector.y ) ) >
AlphaLimit ) {
return true;
}
}
return false;
}
bool CreateTextureAndBitmask( sf::Texture& LoadInto, const std::string& Filename ) {
sf::Image img;
if( !img.loadFromFile( Filename ) )
return false;
if( !LoadInto.loadFromImage( img ) )
return false;
Bitmasks.CreateMask( &LoadInto, img );
return true;
}
sf::Vector2f GetSpriteCenter( const sf::Sprite& Object ) {
sf::FloatRect AABB = Object.getGlobalBounds();
return sf::Vector2f( AABB.left + AABB.width / 2.f, AABB.top + AABB.height / 2.f );
}
sf::Vector2f GetSpriteSize( const sf::Sprite& Object ) {
sf::IntRect OriginalSize = Object.getTextureRect();
sf::Vector2f Scale = Object.getScale();
return sf::Vector2f( OriginalSize.width * Scale.x, OriginalSize.height * Scale.y );
}
bool CircleTest( const sf::Sprite& Object1, const sf::Sprite& Object2 ) {
sf::Vector2f Obj1Size = GetSpriteSize( Object1 );
sf::Vector2f Obj2Size = GetSpriteSize( Object2 );
float Radius1 = ( Obj1Size.x + Obj1Size.y ) / 4;
float Radius2 = ( Obj2Size.x + Obj2Size.y ) / 4;
sf::Vector2f Distance = GetSpriteCenter( Object1 ) - GetSpriteCenter( Object2 );
return ( Distance.x * Distance.x + Distance.y * Distance.y <=
( Radius1 + Radius2 ) * ( Radius1 + Radius2 ) );
}
class OrientedBoundingBox // Used in the BoundingBoxTest
{
public:
OrientedBoundingBox( const sf::Sprite& Object ) // Calculate the four points of the OBB from
// a transformed (scaled, rotated...) sprite
{
sf::Transform trans = Object.getTransform();
sf::IntRect local = Object.getTextureRect();
Points[ 0 ] = trans.transformPoint( 0.f, 0.f );
Points[ 1 ] = trans.transformPoint( local.width, 0.f );
Points[ 2 ] = trans.transformPoint( local.width, local.height );
Points[ 3 ] = trans.transformPoint( 0.f, local.height );
}
sf::Vector2f Points[ 4 ];
void ProjectOntoAxis( const sf::Vector2f& Axis,
float& Min,
float& Max ) // Project all four points of the OBB onto the given axis
// and return the dotproducts of the two outermost points
{
Min = ( Points[ 0 ].x * Axis.x + Points[ 0 ].y * Axis.y );
Max = Min;
for( int j = 1; j < 4; j++ ) {
float Projection = ( Points[ j ].x * Axis.x + Points[ j ].y * Axis.y );
if( Projection < Min )
Min = Projection;
if( Projection > Max )
Max = Projection;
}
}
};
bool BoundingBoxTest( const sf::Sprite& Object1, const sf::Sprite& Object2 ) {
OrientedBoundingBox OBB1( Object1 );
OrientedBoundingBox OBB2( Object2 );
// Create the four distinct axes that are perpendicular to the edges of the two rectangles
sf::Vector2f Axes[ 4 ] = {sf::Vector2f( OBB1.Points[ 1 ].x - OBB1.Points[ 0 ].x,
OBB1.Points[ 1 ].y - OBB1.Points[ 0 ].y ),
sf::Vector2f( OBB1.Points[ 1 ].x - OBB1.Points[ 2 ].x,
OBB1.Points[ 1 ].y - OBB1.Points[ 2 ].y ),
sf::Vector2f( OBB2.Points[ 0 ].x - OBB2.Points[ 3 ].x,
OBB2.Points[ 0 ].y - OBB2.Points[ 3 ].y ),
sf::Vector2f( OBB2.Points[ 0 ].x - OBB2.Points[ 1 ].x,
OBB2.Points[ 0 ].y - OBB2.Points[ 1 ].y )};
for( int i = 0; i < 4; i++ ) // For each axis...
{
float MinOBB1, MaxOBB1, MinOBB2, MaxOBB2;
// ... project the points of both OBBs onto the axis ...
OBB1.ProjectOntoAxis( Axes[ i ], MinOBB1, MaxOBB1 );
OBB2.ProjectOntoAxis( Axes[ i ], MinOBB2, MaxOBB2 );
// ... and check whether the outermost projected points of both OBBs overlap.
// If this is not the case, the Separating Axis Theorem states that there can be no
// collision between the rectangles
if( !( ( MinOBB2 <= MaxOBB1 ) && ( MaxOBB2 >= MinOBB1 ) ) )
return false;
}
return true;
}
} // namespace Collision
<commit_msg>Construtor explícito e correção do iterator<commit_after>/*
* File: collision.cpp
* Author: Nick (original version), ahnonay (SFML2 compatibility)
*
* Modified indentation, include path, included function to check alpha != 0 at vector position and
* included function to compare bounds
*/
#include "../../include/Collision.hpp"
#include <iostream>
#include <map>
namespace Collision {
class BitmaskManager {
public:
~BitmaskManager() {
std::map< const sf::Texture*, sf::Uint8* >::const_iterator end = Bitmasks.end();
for( std::map< const sf::Texture*, sf::Uint8* >::const_iterator iter = Bitmasks.begin();
iter != end;
++iter )
delete[] iter->second;
}
sf::Uint8
GetPixel( const sf::Uint8* mask, const sf::Texture* tex, unsigned int x, unsigned int y ) {
if( x > tex->getSize().x || y > tex->getSize().y )
return 0;
return mask[ x + y * tex->getSize().x ];
}
sf::Uint8* GetMask( const sf::Texture* tex ) {
sf::Uint8* mask;
std::map< const sf::Texture*, sf::Uint8* >::iterator pair = Bitmasks.find( tex );
if( pair == Bitmasks.end() ) {
sf::Image img = tex->copyToImage();
mask = CreateMask( tex, img );
} else
mask = pair->second;
return mask;
}
sf::Uint8* CreateMask( const sf::Texture* tex, const sf::Image& img ) {
sf::Uint8* mask = new sf::Uint8[ tex->getSize().y * tex->getSize().x ];
for( unsigned int y = 0; y < tex->getSize().y; y++ ) {
for( unsigned int x = 0; x < tex->getSize().x; x++ )
mask[ x + y * tex->getSize().x ] = img.getPixel( x, y ).a;
}
Bitmasks.insert( std::pair< const sf::Texture*, sf::Uint8* >( tex, mask ) );
return mask;
}
private:
std::map< const sf::Texture*, sf::Uint8* > Bitmasks;
};
BitmaskManager Bitmasks;
bool SimpleTest( const sf::Sprite& Object1, const sf::Sprite& Object2 ) {
return Object1.getGlobalBounds().intersects( Object2.getGlobalBounds() );
}
bool
PixelPerfectTest( const sf::Sprite& Object1, const sf::Sprite& Object2, sf::Uint8 AlphaLimit ) {
sf::FloatRect Intersection;
if( Object1.getGlobalBounds().intersects( Object2.getGlobalBounds(), Intersection ) ) {
sf::IntRect O1SubRect = Object1.getTextureRect();
sf::IntRect O2SubRect = Object2.getTextureRect();
sf::Uint8* mask1 = Bitmasks.GetMask( Object1.getTexture() );
sf::Uint8* mask2 = Bitmasks.GetMask( Object2.getTexture() );
// Loop through our pixels
for( int i = Intersection.left; i < Intersection.left + Intersection.width; i++ ) {
for( int j = Intersection.top; j < Intersection.top + Intersection.height; j++ ) {
sf::Vector2f o1v = Object1.getInverseTransform().transformPoint( i, j );
sf::Vector2f o2v = Object2.getInverseTransform().transformPoint( i, j );
// Make sure pixels fall within the sprite's subrect
if( o1v.x > 0 && o1v.y > 0 && o2v.x > 0 && o2v.y > 0 &&
o1v.x < O1SubRect.width && o1v.y < O1SubRect.height &&
o2v.x < O2SubRect.width && o2v.y < O2SubRect.height ) {
if( Bitmasks.GetPixel( mask1,
Object1.getTexture(),
(int)( o1v.x ) + O1SubRect.left,
(int)( o1v.y ) + O1SubRect.top ) > AlphaLimit &&
Bitmasks.GetPixel( mask2,
Object2.getTexture(),
(int)( o2v.x ) + O2SubRect.left,
(int)( o2v.y ) + O2SubRect.top ) > AlphaLimit )
return true;
}
}
}
}
return false;
}
bool VectorPerfectTest( const sf::Sprite& Object1, const sf::Vector2< float >& Vector ) {
sf::Uint8 AlphaLimit = 0;
if( Object1.getGlobalBounds().contains( Vector ) ) {
sf::Uint8* mask1 = Bitmasks.GetMask( Object1.getTexture() );
if( Bitmasks.GetPixel(
mask1, Object1.getTexture(), (int)( Vector.x ), (int)( Vector.y ) ) >
AlphaLimit ) {
return true;
}
}
return false;
}
bool CreateTextureAndBitmask( sf::Texture& LoadInto, const std::string& Filename ) {
sf::Image img;
if( !img.loadFromFile( Filename ) )
return false;
if( !LoadInto.loadFromImage( img ) )
return false;
Bitmasks.CreateMask( &LoadInto, img );
return true;
}
sf::Vector2f GetSpriteCenter( const sf::Sprite& Object ) {
sf::FloatRect AABB = Object.getGlobalBounds();
return sf::Vector2f( AABB.left + AABB.width / 2.f, AABB.top + AABB.height / 2.f );
}
sf::Vector2f GetSpriteSize( const sf::Sprite& Object ) {
sf::IntRect OriginalSize = Object.getTextureRect();
sf::Vector2f Scale = Object.getScale();
return sf::Vector2f( OriginalSize.width * Scale.x, OriginalSize.height * Scale.y );
}
bool CircleTest( const sf::Sprite& Object1, const sf::Sprite& Object2 ) {
sf::Vector2f Obj1Size = GetSpriteSize( Object1 );
sf::Vector2f Obj2Size = GetSpriteSize( Object2 );
float Radius1 = ( Obj1Size.x + Obj1Size.y ) / 4;
float Radius2 = ( Obj2Size.x + Obj2Size.y ) / 4;
sf::Vector2f Distance = GetSpriteCenter( Object1 ) - GetSpriteCenter( Object2 );
return ( Distance.x * Distance.x + Distance.y * Distance.y <=
( Radius1 + Radius2 ) * ( Radius1 + Radius2 ) );
}
class OrientedBoundingBox // Used in the BoundingBoxTest
{
public:
explicit OrientedBoundingBox( const sf::Sprite& Object ) // Calculate the four points of the
// OBB from a transformed (scaled,
// rotated...) sprite
{
sf::Transform trans = Object.getTransform();
sf::IntRect local = Object.getTextureRect();
Points[ 0 ] = trans.transformPoint( 0.f, 0.f );
Points[ 1 ] = trans.transformPoint( local.width, 0.f );
Points[ 2 ] = trans.transformPoint( local.width, local.height );
Points[ 3 ] = trans.transformPoint( 0.f, local.height );
}
sf::Vector2f Points[ 4 ];
void ProjectOntoAxis( const sf::Vector2f& Axis,
float& Min,
float& Max ) // Project all four points of the OBB onto the given axis
// and return the dotproducts of the two outermost points
{
Min = ( Points[ 0 ].x * Axis.x + Points[ 0 ].y * Axis.y );
Max = Min;
for( int j = 1; j < 4; j++ ) {
float Projection = ( Points[ j ].x * Axis.x + Points[ j ].y * Axis.y );
if( Projection < Min )
Min = Projection;
if( Projection > Max )
Max = Projection;
}
}
};
bool BoundingBoxTest( const sf::Sprite& Object1, const sf::Sprite& Object2 ) {
OrientedBoundingBox OBB1( Object1 );
OrientedBoundingBox OBB2( Object2 );
// Create the four distinct axes that are perpendicular to the edges of the two rectangles
sf::Vector2f Axes[ 4 ] = {sf::Vector2f( OBB1.Points[ 1 ].x - OBB1.Points[ 0 ].x,
OBB1.Points[ 1 ].y - OBB1.Points[ 0 ].y ),
sf::Vector2f( OBB1.Points[ 1 ].x - OBB1.Points[ 2 ].x,
OBB1.Points[ 1 ].y - OBB1.Points[ 2 ].y ),
sf::Vector2f( OBB2.Points[ 0 ].x - OBB2.Points[ 3 ].x,
OBB2.Points[ 0 ].y - OBB2.Points[ 3 ].y ),
sf::Vector2f( OBB2.Points[ 0 ].x - OBB2.Points[ 1 ].x,
OBB2.Points[ 0 ].y - OBB2.Points[ 1 ].y )};
for( int i = 0; i < 4; i++ ) // For each axis...
{
float MinOBB1, MaxOBB1, MinOBB2, MaxOBB2;
// ... project the points of both OBBs onto the axis ...
OBB1.ProjectOntoAxis( Axes[ i ], MinOBB1, MaxOBB1 );
OBB2.ProjectOntoAxis( Axes[ i ], MinOBB2, MaxOBB2 );
// ... and check whether the outermost projected points of both OBBs overlap.
// If this is not the case, the Separating Axis Theorem states that there can be no
// collision between the rectangles
if( !( ( MinOBB2 <= MaxOBB1 ) && ( MaxOBB2 >= MinOBB1 ) ) )
return false;
}
return true;
}
} // namespace Collision
<|endoftext|> |
<commit_before>#include "Application.h"
Application::Application() : running(false)
{
set_frame_limit(30);
}
Application::~Application()
{
}
void Application::stop()
{
running = false;
return;
}
void Application::set_frame_limit(const unsigned int frame_rate)
{
frame_time = float(1000) / float(frame_rate);
return;
}
void Application::initialize()
{
SDL_Init(SDL_INIT_EVERYTHING);
return;
}
void Application::shutdown()
{
SDL_Quit();
return;
}
void Application::loop()
{
running = true;
while(running && !state_stack.empty())
{
// interact directly with SDL for frame timing to reduce
// overhead incurred by function calls
const unsigned int frame_start = SDL_GetTicks();
process_input();
update();
display();
const unsigned int frame_duration = SDL_GetTicks() - frame_start;
if(frame_duration > frame_time)
SDL_Delay(frame_time - frame_duration);
}
}
void Application::push(State* const s)
{
state_stack.back()->pause();
s->initialize();
state_stack.push_back(s);
return;
}
State* Application::pop()
{
state_stack.back()->shutdown();
State* const s = state_stack.back();
state_stack.pop_back();
state_stack.back()->resume();
return s;
}
<commit_msg>Fix delay calculation.<commit_after>#include "Application.h"
Application::Application() : running(false)
{
set_frame_limit(30);
}
Application::~Application()
{
}
void Application::stop()
{
running = false;
return;
}
void Application::set_frame_limit(const unsigned int frame_rate)
{
frame_time = float(1000) / float(frame_rate);
return;
}
void Application::initialize()
{
SDL_Init(SDL_INIT_EVERYTHING);
return;
}
void Application::shutdown()
{
SDL_Quit();
return;
}
void Application::loop()
{
running = true;
while(running && !state_stack.empty())
{
// interact directly with SDL for frame timing to reduce
// overhead incurred by function calls
const unsigned int frame_start = SDL_GetTicks();
process_input();
update();
display();
const unsigned int frame_duration = SDL_GetTicks() - frame_start;
if(frame_duration < frame_time)
SDL_Delay(frame_time - frame_duration);
}
}
void Application::push(State* const s)
{
state_stack.back()->pause();
s->initialize();
state_stack.push_back(s);
return;
}
State* Application::pop()
{
state_stack.back()->shutdown();
State* const s = state_stack.back();
state_stack.pop_back();
state_stack.back()->resume();
return s;
}
<|endoftext|> |
<commit_before>/*
* Copyright (c) 2017, James Jackson and Daniel Koch, BYU MAGICC Lab
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* * Neither the name of the copyright holder nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "estimator.h"
#include "rosflight.h"
namespace rosflight_firmware
{
Estimator::Estimator(ROSflight &_rf):
RF_(_rf)
{}
void Estimator::reset_state()
{
state_.attitude.w = 1.0f;
state_.attitude.x = 0.0f;
state_.attitude.y = 0.0f;
state_.attitude.z = 0.0f;
state_.angular_velocity.x = 0.0f;
state_.angular_velocity.y = 0.0f;
state_.angular_velocity.z = 0.0f;
state_.roll = 0.0f;
state_.pitch = 0.0f;
state_.yaw = 0.0f;
w1_.x = 0.0f;
w1_.y = 0.0f;
w1_.z = 0.0f;
w2_.x = 0.0f;
w2_.y = 0.0f;
w2_.z = 0.0f;
bias_.x = 0.0f;
bias_.y = 0.0f;
bias_.z = 0.0f;
accel_LPF_.x = 0;
accel_LPF_.y = 0;
accel_LPF_.z = -9.80665;
gyro_LPF_.x = 0;
gyro_LPF_.y = 0;
gyro_LPF_.z = 0;
state_.timestamp_us = RF_.board_.clock_micros();
// Clear the unhealthy estimator flag
RF_.state_manager_.clear_error(StateManager::ERROR_UNHEALTHY_ESTIMATOR);
}
void Estimator::reset_adaptive_bias()
{
bias_.x = 0;
bias_.y = 0;
bias_.z = 0;
}
void Estimator::init()
{
last_time_ = 0;
last_acc_update_us_ = 0;
reset_state();
}
void Estimator::run_LPF()
{
float alpha_acc = RF_.params_.get_param_float(PARAM_ACC_ALPHA);
const vector_t& raw_accel = RF_.sensors_.data().accel;
accel_LPF_.x = (1.0f-alpha_acc)*raw_accel.x + alpha_acc*accel_LPF_.x;
accel_LPF_.y = (1.0f-alpha_acc)*raw_accel.y + alpha_acc*accel_LPF_.y;
accel_LPF_.z = (1.0f-alpha_acc)*raw_accel.z + alpha_acc*accel_LPF_.z;
float alpha_gyro = RF_.params_.get_param_float(PARAM_GYRO_ALPHA);
const vector_t& raw_gyro = RF_.sensors_.data().gyro;
gyro_LPF_.x = (1.0f-alpha_gyro)*raw_gyro.x + alpha_gyro*gyro_LPF_.x;
gyro_LPF_.y = (1.0f-alpha_gyro)*raw_gyro.y + alpha_gyro*gyro_LPF_.y;
gyro_LPF_.z = (1.0f-alpha_gyro)*raw_gyro.z + alpha_gyro*gyro_LPF_.z;
}
void Estimator::run()
{
float kp, ki;
uint64_t now_us = RF_.sensors_.data().imu_time;
if (last_time_ == 0)
{
last_time_ = now_us;
last_acc_update_us_ = last_time_;
return;
}
else if (now_us < last_time_)
{
// this shouldn't happen
RF_.state_manager_.set_error(StateManager::ERROR_TIME_GOING_BACKWARDS);
last_time_ = now_us;
return;
}
else if (now_us == last_time_)
{
volatile int debug = 1;
return;
}
RF_.state_manager_.clear_error(StateManager::ERROR_TIME_GOING_BACKWARDS);
float dt = (now_us - last_time_) * 1e-6f;
last_time_ = now_us;
state_.timestamp_us = now_us;
// Crank up the gains for the first few seconds for quick convergence
if (now_us < (uint64_t)RF_.params_.get_param_int(PARAM_INIT_TIME)*1000)
{
kp = RF_.params_.get_param_float(PARAM_FILTER_KP)*10.0f;
ki = RF_.params_.get_param_float(PARAM_FILTER_KI)*10.0f;
}
else
{
kp = RF_.params_.get_param_float(PARAM_FILTER_KP);
ki = RF_.params_.get_param_float(PARAM_FILTER_KI);
}
// Run LPF to reject a lot of noise
run_LPF();
// add in accelerometer
float a_sqrd_norm = sqrd_norm(accel_LPF_);
vector_t w_acc;
if (RF_.params_.get_param_int(PARAM_FILTER_USE_ACC)
&& a_sqrd_norm < 1.15f*1.15f*9.80665f*9.80665f && a_sqrd_norm > 0.85f*0.85f*9.80665f*9.80665f)
{
// Get error estimated by accelerometer measurement
last_acc_update_us_ = now_us;
// turn measurement into a unit vector
vector_t a = vector_normalize(accel_LPF_);
// Get the quaternion from accelerometer (low-frequency measure q)
// (Not in either paper)
quaternion_t q_acc_inv = quat_from_two_unit_vectors(g_, a);
// Get the error quaternion between observer and low-freq q
// Below Eq. 45 Mahony Paper
quaternion_t q_tilde = quaternion_multiply(q_acc_inv, state_.attitude);
// Correction Term of Eq. 47a and 47b Mahony Paper
// w_acc = 2*s_tilde*v_tilde
w_acc.x = -2.0f*q_tilde.w*q_tilde.x;
w_acc.y = -2.0f*q_tilde.w*q_tilde.y;
w_acc.z = 0.0f; // Don't correct z, because it's unobservable from the accelerometer
// integrate biases from accelerometer feedback
// (eq 47b Mahony Paper, using correction term w_acc found above
bias_.x -= ki*w_acc.x*dt;
bias_.y -= ki*w_acc.y*dt;
bias_.z = 0.0; // Don't integrate z bias, because it's unobservable
}
else
{
w_acc.x = 0.0f;
w_acc.y = 0.0f;
w_acc.z = 0.0f;
}
// Handle Gyro Measurements
vector_t wbar;
if (RF_.params_.get_param_int(PARAM_FILTER_USE_QUAD_INT))
{
// Quadratic Interpolation (Eq. 14 Casey Paper)
// this step adds 12 us on the STM32F10x chips
wbar = vector_add(vector_add(scalar_multiply(-1.0f/12.0f,w2_), scalar_multiply(8.0f/12.0f,w1_)),
scalar_multiply(5.0f/12.0f,gyro_LPF_));
w2_ = w1_;
w1_ = gyro_LPF_;
}
else
{
wbar = gyro_LPF_;
}
// Build the composite omega vector for kinematic propagation
// This the stuff inside the p function in eq. 47a - Mahony Paper
vector_t wfinal = vector_add(vector_sub(wbar, bias_), scalar_multiply(kp, w_acc));
// Propagate Dynamics (only if we've moved)
float sqrd_norm_w = sqrd_norm(wfinal);
if (sqrd_norm_w > 0.0f)
{
float p = wfinal.x;
float q = wfinal.y;
float r = wfinal.z;
if (RF_.params_.get_param_int(PARAM_FILTER_USE_MAT_EXP))
{
// Matrix Exponential Approximation (From Attitude Representation and Kinematic
// Propagation for Low-Cost UAVs by Robert T. Casey)
// (Eq. 12 Casey Paper)
// This adds 90 us on STM32F10x chips
float norm_w = sqrt(sqrd_norm_w);
quaternion_t qhat_np1;
float t1 = cos((norm_w*dt)/2.0f);
float t2 = 1.0f/norm_w * sin((norm_w*dt)/2.0f);
qhat_np1.w = t1*state_.attitude.w + t2*(-p*state_.attitude.x - q*state_.attitude.y - r*state_.attitude.z);
qhat_np1.x = t1*state_.attitude.x + t2*( p*state_.attitude.w + r*state_.attitude.y - q*state_.attitude.z);
qhat_np1.y = t1*state_.attitude.y + t2*( q*state_.attitude.w - r*state_.attitude.x + p*state_.attitude.z);
qhat_np1.z = t1*state_.attitude.z + t2*( r*state_.attitude.w + q*state_.attitude.x - p*state_.attitude.y);
state_.attitude = quaternion_normalize(qhat_np1);
}
else
{
// Euler Integration
// (Eq. 47a Mahony Paper), but this is pretty straight-forward
quaternion_t qdot = {0.5f * (-p*state_.attitude.x - q*state_.attitude.y - r*state_.attitude.z),
0.5f * ( p*state_.attitude.w + r*state_.attitude.y - q*state_.attitude.z),
0.5f * ( q*state_.attitude.w - r*state_.attitude.x + p*state_.attitude.z),
0.5f * ( r*state_.attitude.w + q*state_.attitude.x - p*state_.attitude.y)
};
state_.attitude.w += qdot.w*dt;
state_.attitude.x += qdot.x*dt;
state_.attitude.y += qdot.y*dt;
state_.attitude.z += qdot.z*dt;
state_.attitude = quaternion_normalize(state_.attitude);
}
// Make sure the quaternion is canoncial (w is always positive)
if (state_.attitude.w < 0.0f)
{
state_.attitude.w *= -1.0f;
state_.attitude.x *= -1.0f;
state_.attitude.y *= -1.0f;
state_.attitude.z *= -1.0f;
}
}
// Extract Euler Angles for controller
euler_from_quat(state_.attitude, &state_.roll, &state_.pitch, &state_.yaw);
// Save off adjust gyro measurements with estimated biases for control
state_.angular_velocity = vector_sub(gyro_LPF_, bias_);
// If it has been more than 0.5 seconds since the acc update ran and we are supposed to be getting them
// then trigger an unhealthy estimator error
if (RF_.params_.get_param_int(PARAM_FILTER_USE_ACC) && now_us > 500000 + last_acc_update_us_)
{
RF_.state_manager_.set_error(StateManager::ERROR_UNHEALTHY_ESTIMATOR);
}
else
{
RF_.state_manager_.clear_error(StateManager::ERROR_UNHEALTHY_ESTIMATOR);
}
}
}
<commit_msg>keep ogre3d implementation of quat_from_two_vectors<commit_after>/*
* Copyright (c) 2017, James Jackson and Daniel Koch, BYU MAGICC Lab
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* * Neither the name of the copyright holder nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "estimator.h"
#include "rosflight.h"
namespace rosflight_firmware
{
Estimator::Estimator(ROSflight &_rf):
RF_(_rf)
{}
void Estimator::reset_state()
{
state_.attitude.w = 1.0f;
state_.attitude.x = 0.0f;
state_.attitude.y = 0.0f;
state_.attitude.z = 0.0f;
state_.angular_velocity.x = 0.0f;
state_.angular_velocity.y = 0.0f;
state_.angular_velocity.z = 0.0f;
state_.roll = 0.0f;
state_.pitch = 0.0f;
state_.yaw = 0.0f;
w1_.x = 0.0f;
w1_.y = 0.0f;
w1_.z = 0.0f;
w2_.x = 0.0f;
w2_.y = 0.0f;
w2_.z = 0.0f;
bias_.x = 0.0f;
bias_.y = 0.0f;
bias_.z = 0.0f;
accel_LPF_.x = 0;
accel_LPF_.y = 0;
accel_LPF_.z = -9.80665;
gyro_LPF_.x = 0;
gyro_LPF_.y = 0;
gyro_LPF_.z = 0;
state_.timestamp_us = RF_.board_.clock_micros();
// Clear the unhealthy estimator flag
RF_.state_manager_.clear_error(StateManager::ERROR_UNHEALTHY_ESTIMATOR);
}
void Estimator::reset_adaptive_bias()
{
bias_.x = 0;
bias_.y = 0;
bias_.z = 0;
}
void Estimator::init()
{
last_time_ = 0;
last_acc_update_us_ = 0;
reset_state();
}
void Estimator::run_LPF()
{
float alpha_acc = RF_.params_.get_param_float(PARAM_ACC_ALPHA);
const vector_t& raw_accel = RF_.sensors_.data().accel;
accel_LPF_.x = (1.0f-alpha_acc)*raw_accel.x + alpha_acc*accel_LPF_.x;
accel_LPF_.y = (1.0f-alpha_acc)*raw_accel.y + alpha_acc*accel_LPF_.y;
accel_LPF_.z = (1.0f-alpha_acc)*raw_accel.z + alpha_acc*accel_LPF_.z;
float alpha_gyro = RF_.params_.get_param_float(PARAM_GYRO_ALPHA);
const vector_t& raw_gyro = RF_.sensors_.data().gyro;
gyro_LPF_.x = (1.0f-alpha_gyro)*raw_gyro.x + alpha_gyro*gyro_LPF_.x;
gyro_LPF_.y = (1.0f-alpha_gyro)*raw_gyro.y + alpha_gyro*gyro_LPF_.y;
gyro_LPF_.z = (1.0f-alpha_gyro)*raw_gyro.z + alpha_gyro*gyro_LPF_.z;
}
void Estimator::run()
{
float kp, ki;
uint64_t now_us = RF_.sensors_.data().imu_time;
if (last_time_ == 0)
{
last_time_ = now_us;
last_acc_update_us_ = last_time_;
return;
}
else if (now_us < last_time_)
{
// this shouldn't happen
RF_.state_manager_.set_error(StateManager::ERROR_TIME_GOING_BACKWARDS);
last_time_ = now_us;
return;
}
else if (now_us == last_time_)
{
volatile int debug = 1;
return;
}
RF_.state_manager_.clear_error(StateManager::ERROR_TIME_GOING_BACKWARDS);
float dt = (now_us - last_time_) * 1e-6f;
last_time_ = now_us;
state_.timestamp_us = now_us;
// Crank up the gains for the first few seconds for quick convergence
if (now_us < (uint64_t)RF_.params_.get_param_int(PARAM_INIT_TIME)*1000)
{
kp = RF_.params_.get_param_float(PARAM_FILTER_KP)*10.0f;
ki = RF_.params_.get_param_float(PARAM_FILTER_KI)*10.0f;
}
else
{
kp = RF_.params_.get_param_float(PARAM_FILTER_KP);
ki = RF_.params_.get_param_float(PARAM_FILTER_KI);
}
// Run LPF to reject a lot of noise
run_LPF();
// add in accelerometer
float a_sqrd_norm = sqrd_norm(accel_LPF_);
vector_t w_acc;
if (RF_.params_.get_param_int(PARAM_FILTER_USE_ACC)
&& a_sqrd_norm < 1.1f*1.1f*9.80665f*9.80665f && a_sqrd_norm > 0.9f*0.9f*9.80665f*9.80665f)
{
// Get error estimated by accelerometer measurement
last_acc_update_us_ = now_us;
// turn measurement into a unit vector
vector_t a = vector_normalize(accel_LPF_);
// Get the quaternion from accelerometer (low-frequency measure q)
// (Not in either paper)
quaternion_t q_acc_inv = quat_from_two_unit_vectors(g_, a);
// Get the error quaternion between observer and low-freq q
// Below Eq. 45 Mahony Paper
quaternion_t q_tilde = quaternion_multiply(q_acc_inv, state_.attitude);
// Correction Term of Eq. 47a and 47b Mahony Paper
// w_acc = 2*s_tilde*v_tilde
w_acc.x = -2.0f*q_tilde.w*q_tilde.x;
w_acc.y = -2.0f*q_tilde.w*q_tilde.y;
w_acc.z = 0.0f; // Don't correct z, because it's unobservable from the accelerometer
// integrate biases from accelerometer feedback
// (eq 47b Mahony Paper, using correction term w_acc found above
bias_.x -= ki*w_acc.x*dt;
bias_.y -= ki*w_acc.y*dt;
bias_.z = 0.0; // Don't integrate z bias, because it's unobservable
}
else
{
w_acc.x = 0.0f;
w_acc.y = 0.0f;
w_acc.z = 0.0f;
}
// Handle Gyro Measurements
vector_t wbar;
if (RF_.params_.get_param_int(PARAM_FILTER_USE_QUAD_INT))
{
// Quadratic Interpolation (Eq. 14 Casey Paper)
// this step adds 12 us on the STM32F10x chips
wbar = vector_add(vector_add(scalar_multiply(-1.0f/12.0f,w2_), scalar_multiply(8.0f/12.0f,w1_)),
scalar_multiply(5.0f/12.0f,gyro_LPF_));
w2_ = w1_;
w1_ = gyro_LPF_;
}
else
{
wbar = gyro_LPF_;
}
// Build the composite omega vector for kinematic propagation
// This the stuff inside the p function in eq. 47a - Mahony Paper
vector_t wfinal = vector_add(vector_sub(wbar, bias_), scalar_multiply(kp, w_acc));
// Propagate Dynamics (only if we've moved)
float sqrd_norm_w = sqrd_norm(wfinal);
if (sqrd_norm_w > 0.0f)
{
float p = wfinal.x;
float q = wfinal.y;
float r = wfinal.z;
if (RF_.params_.get_param_int(PARAM_FILTER_USE_MAT_EXP))
{
// Matrix Exponential Approximation (From Attitude Representation and Kinematic
// Propagation for Low-Cost UAVs by Robert T. Casey)
// (Eq. 12 Casey Paper)
// This adds 90 us on STM32F10x chips
float norm_w = sqrt(sqrd_norm_w);
quaternion_t qhat_np1;
float t1 = cos((norm_w*dt)/2.0f);
float t2 = 1.0f/norm_w * sin((norm_w*dt)/2.0f);
qhat_np1.w = t1*state_.attitude.w + t2*(-p*state_.attitude.x - q*state_.attitude.y - r*state_.attitude.z);
qhat_np1.x = t1*state_.attitude.x + t2*( p*state_.attitude.w + r*state_.attitude.y - q*state_.attitude.z);
qhat_np1.y = t1*state_.attitude.y + t2*( q*state_.attitude.w - r*state_.attitude.x + p*state_.attitude.z);
qhat_np1.z = t1*state_.attitude.z + t2*( r*state_.attitude.w + q*state_.attitude.x - p*state_.attitude.y);
state_.attitude = quaternion_normalize(qhat_np1);
}
else
{
// Euler Integration
// (Eq. 47a Mahony Paper), but this is pretty straight-forward
quaternion_t qdot = {0.5f * (-p*state_.attitude.x - q*state_.attitude.y - r*state_.attitude.z),
0.5f * ( p*state_.attitude.w + r*state_.attitude.y - q*state_.attitude.z),
0.5f * ( q*state_.attitude.w - r*state_.attitude.x + p*state_.attitude.z),
0.5f * ( r*state_.attitude.w + q*state_.attitude.x - p*state_.attitude.y)
};
state_.attitude.w += qdot.w*dt;
state_.attitude.x += qdot.x*dt;
state_.attitude.y += qdot.y*dt;
state_.attitude.z += qdot.z*dt;
state_.attitude = quaternion_normalize(state_.attitude);
}
// Make sure the quaternion is canoncial (w is always positive)
if (state_.attitude.w < 0.0f)
{
state_.attitude.w *= -1.0f;
state_.attitude.x *= -1.0f;
state_.attitude.y *= -1.0f;
state_.attitude.z *= -1.0f;
}
}
// Extract Euler Angles for controller
euler_from_quat(state_.attitude, &state_.roll, &state_.pitch, &state_.yaw);
// Save off adjust gyro measurements with estimated biases for control
state_.angular_velocity = vector_sub(gyro_LPF_, bias_);
// If it has been more than 0.5 seconds since the acc update ran and we are supposed to be getting them
// then trigger an unhealthy estimator error
if (RF_.params_.get_param_int(PARAM_FILTER_USE_ACC) && now_us > 500000 + last_acc_update_us_)
{
RF_.state_manager_.set_error(StateManager::ERROR_UNHEALTHY_ESTIMATOR);
}
else
{
RF_.state_manager_.clear_error(StateManager::ERROR_UNHEALTHY_ESTIMATOR);
}
}
}
<|endoftext|> |
<commit_before>#include <iostream>
#include <unistd.h>
#include <sys/stat.h>
#include <stdio.h>
#include <vector>
#include <sstream>
#include <dirent.h>
#include <errno.h>
#include <sys/types.h>
using namespace std;
bool isDirectory(char* directoryName) {
struct stat directoryInCurrent;
if (-1 == (stat(directoryName, &directoryInCurrent))) {
perror("stat failed");
return false;
}
if (directoryInCurrent.st_mode & S_IFDIR) {
return true;
}
else {
return false;
}
}
bool ls(char* directoryName) {
char const *dirName = ".";
DIR *dirp;
if (!(dirp = opendir(dirName))) {
cerr << "Error(" << errno << ") opening " << dirName << endl;
return errno;
}
dirent *direntp;
while ((direntp = readdir(dirp))) {
if (direntp->d_name[0] != '.') {
//cout << direntp->d_name << endl; // use stat here to find attributes of a file
printf(direntp->d_name, 8);
cout << " ";
}
}
cout << endl;
closedir(dirp);
}
bool lsWithFlags(char* directoryName, vector<string> flags) {
bool isA = false;
bool isL = false;
bool isR = false;
for (unsigned i = 0; i < flags.size(); ++i) {
if (flags.at(i) == "a")
isA = true;
else if (flags.at(i) == "l")
isL = true;
else if (flags.at(i) == "R")
isR = true;
}
char const *dirName = directoryName;
DIR *dirp;
if (!(dirp = opendir(dirName))) {
cerr << "Error(" << errno << ") opening " << dirName << endl;
return errno;
}
dirent *direntp;
while ((direntp = readdir(dirp))) {
if (direntp->d_name[0] != '.') {
//cout << direntp->d_name << endl; // use stat here to find attributes of a file
printf(direntp->d_name, 8);
cout << " ";
}
}
cout << endl;
closedir(dirp);
}
int main(int argc, char* argv[]) {
if (argc == 1) {
if (!ls(".")) {
exit(1);
}
}
else {
vector<string> directories;
vector<string> flags;
for (int i = 1; i < argc; ++i) {
if (argv[i][0] == '-') {
flags.push_back(argv[i]);
}
/*else {
if (isDirectory(
}*/
}
}
}
<commit_msg>changed function lsWithFlags from bool to void<commit_after>#include <iostream>
#include <unistd.h>
#include <sys/stat.h>
#include <stdio.h>
#include <vector>
#include <sstream>
#include <dirent.h>
#include <errno.h>
#include <sys/types.h>
using namespace std;
bool isDirectory(char* directoryName) {
struct stat directoryInCurrent;
if (-1 == (stat(directoryName, &directoryInCurrent))) {
perror("stat failed");
return false;
}
if (directoryInCurrent.st_mode & S_IFDIR) {
return true;
}
else {
return false;
}
}
void ls(char* directoryName) {
char const *dirName = ".";
DIR *dirp;
if (!(dirp = opendir(dirName))) {
cerr << "Error(" << errno << ") opening " << dirName << endl;
return errno;
}
dirent *direntp;
while ((direntp = readdir(dirp))) {
if (direntp->d_name[0] != '.') {
//cout << direntp->d_name << endl; // use stat here to find attributes of a file
printf(direntp->d_name, 8);
cout << " ";
}
}
cout << endl;
closedir(dirp);
}
bool lsWithFlags(char* directoryName, vector<string> flags) {
bool isA = false;
bool isL = false;
bool isR = false;
for (unsigned i = 0; i < flags.size(); ++i) {
if (flags.at(i) == "a")
isA = true;
else if (flags.at(i) == "l")
isL = true;
else if (flags.at(i) == "R")
isR = true;
}
char const *dirName = directoryName;
DIR *dirp;
if (!(dirp = opendir(dirName))) {
cerr << "Error(" << errno << ") opening " << dirName << endl;
return errno;
}
dirent *direntp;
while ((direntp = readdir(dirp))) {
if (direntp->d_name[0] != '.') {
//cout << direntp->d_name << endl; // use stat here to find attributes of a file
printf(direntp->d_name, 8);
cout << " ";
}
}
cout << endl;
closedir(dirp);
}
int main(int argc, char* argv[]) {
if (argc == 1) {
if (!ls(".")) {
exit(1);
}
}
else {
vector<string> directories;
vector<string> flags;
for (int i = 1; i < argc; ++i) {
if (argv[i][0] == '-') {
flags.push_back(argv[i]);
}
/*else {
if (isDirectory(
}*/
}
}
}
<|endoftext|> |
<commit_before>#include <iostream>
#include <dirent.h>
#include <vector>
#include <sys/stat.h>
#include <iomanip>
using namespace std;
struct stat s;
void printStr(char *c) {
for (int i = 0; c[i] != '\0'; ++i) {
cout << c[i];
}
}
void printV(vector<string> &v) {
for (unsigned i = 0; i < v.size(); ++i) {
cout << v.at(i) << " ";
}
}
void printPermissions(int protec) {
if (S_ISDIR(protec) != 0) cout << "d";
else cout << "-";
cout << ((protec & S_IRUSR)?"r":"-");
cout << ((protec & S_IWUSR)?"w":"-");
cout << ((protec & S_IXUSR)?"x":"-");
cout << ((protec & S_IRGRP)?"r":"-");
cout << ((protec & S_IWGRP)?"w":"-");
cout << ((protec & S_IXGRP)?"x":"-");
cout << ((protec & S_IROTH)?"r":"-");
cout << ((protec & S_IWOTH)?"w":"-");
cout << ((protec & S_IXOTH)?"x":"-");
}
void printInformation(struct stat s) {
cout << " " << setw(10) << s.st_nlink;
cout << " " << setw(10) << s.st_uid;
cout << " " << setw(10) << s.st_gid;
cout << " " << setw(10) << s.st_size;
cout << " " << setw(10) << s.st_mtime;
cout << " ";
}
int main(int argc, char **argv)
{
char dir[] = ".";
vector <string> names;
if (argc == 1) {
argv[0] = dir;
}
else {
for(int i = 0; i < argc - 1; ++i) {
argv[i] = argv[i + 1];
}
argc--;
}
bool flag_a = false;
bool flag_l = false;
bool flag_R = false;
bool is_flag = false;
bool is_dir = false;
int dir_count = 0;
for (int i = 0; i < argc; ++i) {
is_flag = false;
if (argv[i][0] == '-') {
is_flag = true;
}
else {
is_dir = true;
argv[dir_count] = argv[i];
++dir_count;
}
for (int j = 1; argv[i][j] != '\0'; ++j) {
if (is_flag == true && is_dir == false) {
if(argv[i][j] == 'a') flag_a = true;
if(argv[i][j] == 'l') flag_l = true;
if(argv[i][j] == 'R') flag_R = true;
}
}
}
if (dir_count == 0) {
argv[0] = dir;
++dir_count;
}
for (int k = 0; k < dir_count; ++k) {
DIR *dirp1 = opendir(argv[k]);
if (dirp1 == NULL) {
if (!flag_l) {
printStr(argv[k]);
}
else {
stat(argv[k], &s);
int protec = s.st_mode;
printPermissions(protec);
printInformation(s);
printStr(argv[k]);
cout << endl;
}
}
else {
if (dir_count > 1){
cout << endl;
printStr(argv[k]);
cout << ":" << endl;
}
dirent *direntp;
while ((direntp = readdir(dirp1))) {
if (direntp == NULL) perror("readdir");
else {
if (!flag_a) {
if (direntp->d_name[0]!='.') {
string curr_str(direntp->d_name);
names.push_back(curr_str);
}
}
else {
string curr_str(direntp->d_name);
names.push_back(curr_str);
}
}
}
if (!flag_l) {
printV(names);
}
else {
for (unsigned l = 0; l < names.size(); ++l) {
stat(names.at(l).c_str(), &s);
int protec = s.st_mode;
printPermissions(protec);
printInformation(s);
cout << names.at(l) << endl;
}
}
if (closedir(dirp1) == -1) perror("closedir");
cout << endl;
}
names.clear();
}
return 0;
}
<commit_msg>Update ls.cpp<commit_after>#include <iostream>
#include <stdio.h>
#include <dirent.h>
#include <vector>
#include <sys/stat.h>
#include <iomanip>
using namespace std;
struct stat s;
void printStr(char *c) {
for (int i = 0; c[i] != '\0'; ++i) {
cout << c[i];
}
}
void printV(vector<string> &v) {
for (unsigned i = 0; i < v.size(); ++i) {
cout << v.at(i) << " ";
}
}
void printPermissions(int protec) {
if (S_ISDIR(protec) != 0) cout << "d";
else cout << "-";
cout << ((protec & S_IRUSR)?"r":"-");
cout << ((protec & S_IWUSR)?"w":"-");
cout << ((protec & S_IXUSR)?"x":"-");
cout << ((protec & S_IRGRP)?"r":"-");
cout << ((protec & S_IWGRP)?"w":"-");
cout << ((protec & S_IXGRP)?"x":"-");
cout << ((protec & S_IROTH)?"r":"-");
cout << ((protec & S_IWOTH)?"w":"-");
cout << ((protec & S_IXOTH)?"x":"-");
}
void printInformation(struct stat s) {
cout << " " << setw(10) << s.st_nlink;
cout << " " << setw(10) << s.st_uid;
cout << " " << setw(10) << s.st_gid;
cout << " " << setw(10) << s.st_size;
cout << " " << setw(10) << s.st_mtime;
cout << " ";
}
int main(int argc, char **argv)
{
char dir[] = ".";
vector <string> names;
if (argc == 1) {
argv[0] = dir;
}
else {
for(int i = 0; i < argc - 1; ++i) {
argv[i] = argv[i + 1];
}
argc--;
}
bool flag_a = false;
bool flag_l = false;
bool flag_R = false;
bool is_flag = false;
bool is_dir = false;
int dir_count = 0;
for (int i = 0; i < argc; ++i) {
is_flag = false;
if (argv[i][0] == '-') {
is_flag = true;
}
else {
is_dir = true;
argv[dir_count] = argv[i];
++dir_count;
}
for (int j = 1; argv[i][j] != '\0'; ++j) {
if (is_flag == true && is_dir == false) {
if(argv[i][j] == 'a') flag_a = true;
if(argv[i][j] == 'l') flag_l = true;
if(argv[i][j] == 'R') flag_R = true;
}
}
}
if (dir_count == 0) {
argv[0] = dir;
++dir_count;
}
for (int k = 0; k < dir_count; ++k) {
DIR *dirp1 = opendir(argv[k]);
if (dirp1 == NULL) {
if (!flag_l) {
printStr(argv[k]);
}
else {
stat(argv[k], &s);
int protec = s.st_mode;
printPermissions(protec);
printInformation(s);
printStr(argv[k]);
cout << endl;
}
}
else {
if (dir_count > 1){
cout << endl;
printStr(argv[k]);
cout << ":" << endl;
}
dirent *direntp;
while ((direntp = readdir(dirp1))) {
if (direntp == NULL) perror("readdir");
else {
if (!flag_a) {
if (direntp->d_name[0]!='.') {
string curr_str(direntp->d_name);
names.push_back(curr_str);
}
}
else {
string curr_str(direntp->d_name);
names.push_back(curr_str);
}
}
}
if (!flag_l) {
printV(names);
}
else {
for (unsigned l = 0; l < names.size(); ++l) {
stat(names.at(l).c_str(), &s);
int protec = s.st_mode;
printPermissions(protec);
printInformation(s);
cout << names.at(l) << endl;
}
}
if (closedir(dirp1) == -1) perror("closedir");
cout << endl;
}
names.clear();
}
return 0;
}
<|endoftext|> |
<commit_before>// Copyright (c) 2020 The Bitcoin developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <eventloop.h>
#include <scheduler.h>
EventLoop::~EventLoop() {
stopEventLoop();
}
bool EventLoop::startEventLoop(CScheduler &scheduler,
std::function<void()> runEventLoop,
std::chrono::milliseconds delta) {
LOCK(cs_running);
if (running) {
// Do not start the event loop twice.
return false;
}
running = true;
// Start the event loop.
scheduler.scheduleEvery(
[this, runEventLoop]() -> bool {
runEventLoop();
if (!stopRequest) {
return true;
}
LOCK(cs_running);
running = false;
cond_running.notify_all();
// A stop request was made.
return false;
},
delta);
return true;
}
bool EventLoop::stopEventLoop() {
WAIT_LOCK(cs_running, lock);
if (!running) {
return false;
}
// Request avalanche to stop.
stopRequest = true;
// Wait for avalanche to stop.
cond_running.wait(lock, [this]() EXCLUSIVE_LOCKS_REQUIRED(cs_running) {
return !running;
});
stopRequest = false;
return true;
}
<commit_msg>Fixup event loop comments<commit_after>// Copyright (c) 2020 The Bitcoin developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <eventloop.h>
#include <scheduler.h>
EventLoop::~EventLoop() {
stopEventLoop();
}
bool EventLoop::startEventLoop(CScheduler &scheduler,
std::function<void()> runEventLoop,
std::chrono::milliseconds delta) {
LOCK(cs_running);
if (running) {
// Do not start the event loop twice.
return false;
}
running = true;
// Start the event loop.
scheduler.scheduleEvery(
[this, runEventLoop]() -> bool {
runEventLoop();
if (!stopRequest) {
return true;
}
LOCK(cs_running);
running = false;
cond_running.notify_all();
// A stop request was made.
return false;
},
delta);
return true;
}
bool EventLoop::stopEventLoop() {
WAIT_LOCK(cs_running, lock);
if (!running) {
return false;
}
// Request event loop to stop.
stopRequest = true;
// Wait for event loop to stop.
cond_running.wait(lock, [this]() EXCLUSIVE_LOCKS_REQUIRED(cs_running) {
return !running;
});
stopRequest = false;
return true;
}
<|endoftext|> |
<commit_before>#include <vector>
#include <stdexcept>
#include <iostream>
#include "codes/bch.h"
#include "codes/rs.h"
template <typename T>
std::ostream &operator<<(std::ostream &os, const std::vector<T> &v) {
for (const auto &i : v)
os << i;
return os;
}
template <>
std::ostream &operator<<(std::ostream &os, const std::vector<uint8_t> &v) {
for (const auto &i : v)
os << static_cast<unsigned>(i);
return os;
}
/* Concepts:
* C1 operator!= C2
* operator<< C1
* operator<< C2
*/
template <typename C1, typename C2>
void expect_equal(const C1 &a, const C2 &b) {
if (a != b) {
std::cout << "Decoded word: " << b << std::endl;
std::cout << "Expected word: " << a << std::endl;
throw std::runtime_error("Decoding Error.");
}
}
void task_6_1() {
std::cout << std::endl << "Task 6.1" << std::endl << std::endl;
using code_type = cyclic::primitive_bch<4, dmin<7>>;
code_type code;
const std::vector<unsigned char> a(
{ 1, 1, 1, 0, 0, 0, 1, 0, 0, 1, 1, 0, 1, 0, 1 });
std::vector<unsigned> b1({ 1, 1, 1, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 1, 1 });
std::vector<unsigned> b2({ 1, 1, 1, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 1 });
std::cout << "Decoding b1" << std::endl;
expect_equal(a, code.correct(b1));
std::cout << "Decoding b2" << std::endl;
expect_equal(a, code.correct(b2));
}
void task_6_2() {
std::cout << std::endl << "Task 6.2" << std::endl << std::endl;
using code_type = cyclic::primitive_bch<4, dmin<5>>;
code_type code;
const std::vector<unsigned> a({ 1, 1, 1, 1, 0, 1, 1, 1, 0, 1, 0, 0, 0, 1, 1 });
const std::vector<unsigned> b({ 1, 0, 0, 1, 0, 1, 1, 1, 1, 0, 1, 1, 0, 0, 0 });
try {
auto b_ = code.correct(b);
std::cout << "Decoded b into: " << b << std::endl;
}
catch (const decoding_failure &e) {
std::cout << "Decoding failure:" << std::endl;
std::cout << e.what() << std::endl;
return;
}
throw std::runtime_error("Expected decoding failure");
}
void task_6_3() {
std::cout << std::endl << "Task 6.3" << std::endl << std::endl;
using code_type = cyclic::primitive_bch<4, dmin<6>>;
const std::vector<unsigned> a({ 1, 1, 1, 1, 0, 1, 1, 1, 0, 1, 0, 0, 0, 1, 1 });
code_type code;
const std::vector<unsigned> b1({ 1, 1, 1, 1, 0, 1, 1, 1, 0, 1, 0, 0, 0, 0, 1 });
const std::vector<unsigned> b2({ 1, 1, 1, 1, 0, 1, 1, 1, 0, 1, 0, 0, 1, 0, 1 });
const std::vector<unsigned> b3({ 0, 0, 0, 1, 0, 1, 1, 1, 0, 1, 0, 0, 0, 1, 1 });
expect_equal(a, code.correct<unsigned>(b1));
expect_equal(a, code.correct<unsigned>(b2));
try {
code.correct(b3);
}
catch (const std::exception &e) {
std::cout << "Decoding failure:" << std::endl;
std::cout << e.what() << std::endl;
}
}
void task_6_4() {
std::cout << std::endl << "Task 6.4" << std::endl << std::endl;
using code_type = cyclic::rs<3, errors<1>>;
using Element = typename code_type::Element;
std::vector<Element> b1({ Element(0), Element(0), Element(0),
Element(0), Element(0), Element(0),
Element::from_power(4) });
std::vector<Element> b2({ Element::from_power(2), Element::from_power(2),
Element(1), Element(0),
Element(0), Element(0),
Element::from_power(4) });
code_type code;
auto b_ = code.correct(b1);
std::cout << "Corrected vector: " << b_ << std::endl;
try {
b_ = code.correct(b2);
std::cout << "Expected decoding failure." << std::endl;
}
catch (const decoding_failure &e) {
std::cout << "Decoding failure:" << std::endl;
std::cout << e.what() << std::endl;
}
}
void task_6_5() {
std::cout << std::endl << "Task 6.5" << std::endl << std::endl;
using RS_Code = cyclic::rs<4, errors<3>>;
using Element = typename RS_Code::Element;
std::vector<Element> b({ Element(1), Element(1), Element(1), Element(1),
Element(0), Element(0), Element(0), Element(0),
Element(0), Element(0), Element(0), Element(0),
Element(0), Element(0), Element(0) });
RS_Code code;
std::cout << b << std::endl;
try {
auto b_ = code.correct<Element>(b);
std::cout << "Expected decoding failure." << std::endl;
}
catch (const decoding_failure &e) {
std::cout << "Decoding failure:" << std::endl;
std::cout << e.what() << std::endl;
}
}
void task_6_6() {
std::cout << std::endl << "Task 6.6" << std::endl << std::endl;
using RS_Code = cyclic::rs<3, errors<2>>;
using Element = RS_Code::Element;
std::vector<Element> b({ Element::from_power(6), Element::from_power(2),
Element::from_power(2), Element::from_power(5),
Element(0), Element(0),
Element::from_power(5) });
std::cout << b << std::endl;
RS_Code code;
auto b_ = code.correct<Element>(b);
std::cout << "Corrected vector: " << b_ << std::endl;
}
void task_6_7() {
std::cout << std::endl << "Task 6.7" << std::endl << std::endl;
using RS_Code = cyclic::rs<3, errors<2>, cyclic::berlekamp_massey_tag>;
using Element = RS_Code::Element;
const std::vector<unsigned> powers = { 6, 2, 2, 5, 4, 6, 5 };
const std::vector<unsigned> erasures = { 5, 4, 3, 2 };
std::vector<Element> a;
std::transform(
std::begin(powers), std::end(powers), std::back_inserter(a),
[](const unsigned &power) { return Element::from_power(power); });
std::vector<Element> b(a);
for (const auto &erasure : erasures)
b.at(erasure) = Element(0);
std::cout << "a: " << a << std::endl;
std::cout << "b: " << b << std::endl;
RS_Code code;
expect_equal(a, code.correct<Element>(b, erasures));
}
void task_6_8() {
std::cout << std::endl << "Task 6.8" << std::endl << std::endl;
using RS_Code = cyclic::rs<3, errors<2>, cyclic::berlekamp_massey_tag>;
using Element = RS_Code::Element;
const std::vector<unsigned> powers = { 2, 0, 4, 0, 5, 0, 2 };
const std::vector<unsigned> erasures = { 1, 3 };
std::vector<Element> b;
std::transform(
std::begin(powers), std::end(powers), std::back_inserter(b),
[](const unsigned &power) { return Element::from_power(power); });
std::cout << "b: " << b << std::endl;
RS_Code code;
auto b_ = code.correct<Element>(b, erasures);
std::cout << "Corrected vector: " << b_ << std::endl;
}
void task_6_9() {
std::cout << std::endl << "Task 6.9" << std::endl << std::endl;
using RS_Code_pgz = cyclic::rs<3, errors<2>>;
using RS_Code_bm = cyclic::rs<3, errors<2>, cyclic::berlekamp_massey_tag>;
using Element = RS_Code_pgz::Element;
std::vector<Element> b({ Element::from_power(3), Element::from_power(4),
Element::from_power(0), Element::from_power(3),
Element::from_power(4), Element::from_power(3),
Element::from_power(3) });
std::cout << "b: " << b << std::endl;
RS_Code_pgz pgz;
RS_Code_bm bm;
auto b_bm = bm.correct<Element>(b);
auto b_pzg = pgz.correct<Element>(b);
std::cout << "Corrected vector (PZG): " << b_pzg << std::endl;
std::cout << "Corrected vector (BMA/EUKLID): " << b_bm << std::endl;
}
void task_6_10() {
std::cout << std::endl << "Task 6.10" << std::endl << std::endl;
using code_type_peterson =
cyclic::primitive_bch<4, errors<2>, cyclic::peterson_gorenstein_zierler_tag>;
using code_type_berlekamp =
cyclic::primitive_bch<4, errors<2>, cyclic::berlekamp_massey_tag>;
using code_type_euklid =
cyclic::primitive_bch<4, errors<2>, cyclic::euklid_tag>;
const std::vector<uint8_t> a({ 1, 0, 1, 0, 0, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1 });
code_type_peterson peterson;
code_type_berlekamp berlekamp_massey;
code_type_euklid euklid;
std::cout << "PGZ: " << peterson.correct(a) << std::endl;
std::cout << "BM: " << berlekamp_massey.correct(a) << std::endl;
std::cout << "EUKLID: " << euklid.correct(a) << std::endl;
}
int main() {
task_6_1();
task_6_2();
task_6_3();
task_6_4();
task_6_5();
task_6_6();
task_6_7();
task_6_8();
task_6_9();
task_6_10();
}
<commit_msg>Add static storage specifier to functions<commit_after>#include <vector>
#include <stdexcept>
#include <iostream>
#include "codes/bch.h"
#include "codes/rs.h"
template <typename T>
std::ostream &operator<<(std::ostream &os, const std::vector<T> &v) {
for (const auto &i : v)
os << i;
return os;
}
template <>
std::ostream &operator<<(std::ostream &os, const std::vector<uint8_t> &v) {
for (const auto &i : v)
os << static_cast<unsigned>(i);
return os;
}
/* Concepts:
* C1 operator!= C2
* operator<< C1
* operator<< C2
*/
template <typename C1, typename C2>
void expect_equal(const C1 &a, const C2 &b) {
if (a != b) {
std::cout << "Decoded word: " << b << std::endl;
std::cout << "Expected word: " << a << std::endl;
throw std::runtime_error("Decoding Error.");
}
}
static void task_6_1() {
std::cout << std::endl << "Task 6.1" << std::endl << std::endl;
using code_type = cyclic::primitive_bch<4, dmin<7>>;
code_type code;
const std::vector<unsigned char> a(
{ 1, 1, 1, 0, 0, 0, 1, 0, 0, 1, 1, 0, 1, 0, 1 });
std::vector<unsigned> b1({ 1, 1, 1, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 1, 1 });
std::vector<unsigned> b2({ 1, 1, 1, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 1 });
std::cout << "Decoding b1" << std::endl;
expect_equal(a, code.correct(b1));
std::cout << "Decoding b2" << std::endl;
expect_equal(a, code.correct(b2));
}
static void task_6_2() {
std::cout << std::endl << "Task 6.2" << std::endl << std::endl;
using code_type = cyclic::primitive_bch<4, dmin<5>>;
code_type code;
const std::vector<unsigned> a({ 1, 1, 1, 1, 0, 1, 1, 1, 0, 1, 0, 0, 0, 1, 1 });
const std::vector<unsigned> b({ 1, 0, 0, 1, 0, 1, 1, 1, 1, 0, 1, 1, 0, 0, 0 });
try {
auto b_ = code.correct(b);
std::cout << "Decoded b into: " << b << std::endl;
}
catch (const decoding_failure &e) {
std::cout << "Decoding failure:" << std::endl;
std::cout << e.what() << std::endl;
return;
}
throw std::runtime_error("Expected decoding failure");
}
static void task_6_3() {
std::cout << std::endl << "Task 6.3" << std::endl << std::endl;
using code_type = cyclic::primitive_bch<4, dmin<6>>;
const std::vector<unsigned> a({ 1, 1, 1, 1, 0, 1, 1, 1, 0, 1, 0, 0, 0, 1, 1 });
code_type code;
const std::vector<unsigned> b1({ 1, 1, 1, 1, 0, 1, 1, 1, 0, 1, 0, 0, 0, 0, 1 });
const std::vector<unsigned> b2({ 1, 1, 1, 1, 0, 1, 1, 1, 0, 1, 0, 0, 1, 0, 1 });
const std::vector<unsigned> b3({ 0, 0, 0, 1, 0, 1, 1, 1, 0, 1, 0, 0, 0, 1, 1 });
expect_equal(a, code.correct<unsigned>(b1));
expect_equal(a, code.correct<unsigned>(b2));
try {
code.correct(b3);
}
catch (const std::exception &e) {
std::cout << "Decoding failure:" << std::endl;
std::cout << e.what() << std::endl;
}
}
static void task_6_4() {
std::cout << std::endl << "Task 6.4" << std::endl << std::endl;
using code_type = cyclic::rs<3, errors<1>>;
using Element = typename code_type::Element;
std::vector<Element> b1({ Element(0), Element(0), Element(0),
Element(0), Element(0), Element(0),
Element::from_power(4) });
std::vector<Element> b2({ Element::from_power(2), Element::from_power(2),
Element(1), Element(0),
Element(0), Element(0),
Element::from_power(4) });
code_type code;
auto b_ = code.correct(b1);
std::cout << "Corrected vector: " << b_ << std::endl;
try {
b_ = code.correct(b2);
std::cout << "Expected decoding failure." << std::endl;
}
catch (const decoding_failure &e) {
std::cout << "Decoding failure:" << std::endl;
std::cout << e.what() << std::endl;
}
}
static void task_6_5() {
std::cout << std::endl << "Task 6.5" << std::endl << std::endl;
using RS_Code = cyclic::rs<4, errors<3>>;
using Element = typename RS_Code::Element;
std::vector<Element> b({ Element(1), Element(1), Element(1), Element(1),
Element(0), Element(0), Element(0), Element(0),
Element(0), Element(0), Element(0), Element(0),
Element(0), Element(0), Element(0) });
RS_Code code;
std::cout << b << std::endl;
try {
auto b_ = code.correct<Element>(b);
std::cout << "Expected decoding failure." << std::endl;
}
catch (const decoding_failure &e) {
std::cout << "Decoding failure:" << std::endl;
std::cout << e.what() << std::endl;
}
}
static void task_6_6() {
std::cout << std::endl << "Task 6.6" << std::endl << std::endl;
using RS_Code = cyclic::rs<3, errors<2>>;
using Element = RS_Code::Element;
std::vector<Element> b({ Element::from_power(6), Element::from_power(2),
Element::from_power(2), Element::from_power(5),
Element(0), Element(0),
Element::from_power(5) });
std::cout << b << std::endl;
RS_Code code;
auto b_ = code.correct<Element>(b);
std::cout << "Corrected vector: " << b_ << std::endl;
}
static void task_6_7() {
std::cout << std::endl << "Task 6.7" << std::endl << std::endl;
using RS_Code = cyclic::rs<3, errors<2>, cyclic::berlekamp_massey_tag>;
using Element = RS_Code::Element;
const std::vector<unsigned> powers = { 6, 2, 2, 5, 4, 6, 5 };
const std::vector<unsigned> erasures = { 5, 4, 3, 2 };
std::vector<Element> a;
std::transform(
std::begin(powers), std::end(powers), std::back_inserter(a),
[](const unsigned &power) { return Element::from_power(power); });
std::vector<Element> b(a);
for (const auto &erasure : erasures)
b.at(erasure) = Element(0);
std::cout << "a: " << a << std::endl;
std::cout << "b: " << b << std::endl;
RS_Code code;
expect_equal(a, code.correct<Element>(b, erasures));
}
static void task_6_8() {
std::cout << std::endl << "Task 6.8" << std::endl << std::endl;
using RS_Code = cyclic::rs<3, errors<2>, cyclic::berlekamp_massey_tag>;
using Element = RS_Code::Element;
const std::vector<unsigned> powers = { 2, 0, 4, 0, 5, 0, 2 };
const std::vector<unsigned> erasures = { 1, 3 };
std::vector<Element> b;
std::transform(
std::begin(powers), std::end(powers), std::back_inserter(b),
[](const unsigned &power) { return Element::from_power(power); });
std::cout << "b: " << b << std::endl;
RS_Code code;
auto b_ = code.correct<Element>(b, erasures);
std::cout << "Corrected vector: " << b_ << std::endl;
}
static void task_6_9() {
std::cout << std::endl << "Task 6.9" << std::endl << std::endl;
using RS_Code_pgz = cyclic::rs<3, errors<2>>;
using RS_Code_bm = cyclic::rs<3, errors<2>, cyclic::berlekamp_massey_tag>;
using Element = RS_Code_pgz::Element;
std::vector<Element> b({ Element::from_power(3), Element::from_power(4),
Element::from_power(0), Element::from_power(3),
Element::from_power(4), Element::from_power(3),
Element::from_power(3) });
std::cout << "b: " << b << std::endl;
RS_Code_pgz pgz;
RS_Code_bm bm;
auto b_bm = bm.correct<Element>(b);
auto b_pzg = pgz.correct<Element>(b);
std::cout << "Corrected vector (PZG): " << b_pzg << std::endl;
std::cout << "Corrected vector (BMA/EUKLID): " << b_bm << std::endl;
}
static void task_6_10() {
std::cout << std::endl << "Task 6.10" << std::endl << std::endl;
using code_type_peterson =
cyclic::primitive_bch<4, errors<2>, cyclic::peterson_gorenstein_zierler_tag>;
using code_type_berlekamp =
cyclic::primitive_bch<4, errors<2>, cyclic::berlekamp_massey_tag>;
using code_type_euklid =
cyclic::primitive_bch<4, errors<2>, cyclic::euklid_tag>;
const std::vector<uint8_t> a({ 1, 0, 1, 0, 0, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1 });
code_type_peterson peterson;
code_type_berlekamp berlekamp_massey;
code_type_euklid euklid;
std::cout << "PGZ: " << peterson.correct(a) << std::endl;
std::cout << "BM: " << berlekamp_massey.correct(a) << std::endl;
std::cout << "EUKLID: " << euklid.correct(a) << std::endl;
}
int main() {
task_6_1();
task_6_2();
task_6_3();
task_6_4();
task_6_5();
task_6_6();
task_6_7();
task_6_8();
task_6_9();
task_6_10();
}
<|endoftext|> |
<commit_before>//===- CallPrinter.cpp - DOT printer for call graph -----------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file defines '-dot-callgraph', which emit a callgraph.<fnname>.dot
// containing the call graph of a module.
//
// There is also a pass available to directly call dotty ('-view-callgraph').
//
//===----------------------------------------------------------------------===//
#include "llvm/Analysis/CallGraph.h"
#include "llvm/Analysis/CallPrinter.h"
#include "llvm/Analysis/DOTGraphTraitsPass.h"
using namespace llvm;
namespace llvm {
template<>
struct DOTGraphTraits<CallGraph*> : public DefaultDOTGraphTraits {
DOTGraphTraits (bool isSimple=false) : DefaultDOTGraphTraits(isSimple) {}
static std::string getGraphName(CallGraph *Graph) {
return "Call graph";
}
std::string getNodeLabel(CallGraphNode *Node, CallGraph *Graph) {
if (Function *Func = Node->getFunction())
return Func->getName();
return "external node";
}
};
} // end llvm namespace
namespace {
struct CallGraphViewer
: public DOTGraphTraitsModuleViewer<CallGraph, true> {
static char ID;
CallGraphViewer()
: DOTGraphTraitsModuleViewer<CallGraph, true>("callgraph", ID) {
initializeCallGraphViewerPass(*PassRegistry::getPassRegistry());
}
};
struct CallGraphPrinter
: public DOTGraphTraitsModulePrinter<CallGraph, true> {
static char ID;
CallGraphPrinter()
: DOTGraphTraitsModulePrinter<CallGraph, true>("callgraph", ID) {
initializeCallGraphPrinterPass(*PassRegistry::getPassRegistry());
}
};
} // end anonymous namespace
char CallGraphViewer::ID = 0;
INITIALIZE_PASS(CallGraphViewer, "view-callgraph",
"View call graph",
false, false)
char CallGraphPrinter::ID = 0;
INITIALIZE_PASS(CallGraphPrinter, "dot-callgraph",
"Print call graph to 'dot' file",
false, false)
// Create methods available outside of this file, to use them
// "include/llvm/LinkAllPasses.h". Otherwise the pass would be deleted by
// the link time optimization.
ModulePass *llvm::createCallGraphViewerPass() {
return new CallGraphViewer();
}
ModulePass *llvm::createCallGraphPrinterPass() {
return new CallGraphPrinter();
}
<commit_msg>[PM] Reformat some code with clang-format as I'm going to be editting as part of generalizing the call graph infrastructure for the new pass manager.<commit_after>//===- CallPrinter.cpp - DOT printer for call graph -----------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file defines '-dot-callgraph', which emit a callgraph.<fnname>.dot
// containing the call graph of a module.
//
// There is also a pass available to directly call dotty ('-view-callgraph').
//
//===----------------------------------------------------------------------===//
#include "llvm/Analysis/CallGraph.h"
#include "llvm/Analysis/CallPrinter.h"
#include "llvm/Analysis/DOTGraphTraitsPass.h"
using namespace llvm;
namespace llvm {
template <> struct DOTGraphTraits<CallGraph *> : public DefaultDOTGraphTraits {
DOTGraphTraits(bool isSimple = false) : DefaultDOTGraphTraits(isSimple) {}
static std::string getGraphName(CallGraph *Graph) { return "Call graph"; }
std::string getNodeLabel(CallGraphNode *Node, CallGraph *Graph) {
if (Function *Func = Node->getFunction())
return Func->getName();
return "external node";
}
};
} // end llvm namespace
namespace {
struct CallGraphViewer : public DOTGraphTraitsModuleViewer<CallGraph, true> {
static char ID;
CallGraphViewer()
: DOTGraphTraitsModuleViewer<CallGraph, true>("callgraph", ID) {
initializeCallGraphViewerPass(*PassRegistry::getPassRegistry());
}
};
struct CallGraphPrinter : public DOTGraphTraitsModulePrinter<CallGraph, true> {
static char ID;
CallGraphPrinter()
: DOTGraphTraitsModulePrinter<CallGraph, true>("callgraph", ID) {
initializeCallGraphPrinterPass(*PassRegistry::getPassRegistry());
}
};
} // end anonymous namespace
char CallGraphViewer::ID = 0;
INITIALIZE_PASS(CallGraphViewer, "view-callgraph", "View call graph", false,
false)
char CallGraphPrinter::ID = 0;
INITIALIZE_PASS(CallGraphPrinter, "dot-callgraph",
"Print call graph to 'dot' file", false, false)
// Create methods available outside of this file, to use them
// "include/llvm/LinkAllPasses.h". Otherwise the pass would be deleted by
// the link time optimization.
ModulePass *llvm::createCallGraphViewerPass() { return new CallGraphViewer(); }
ModulePass *llvm::createCallGraphPrinterPass() {
return new CallGraphPrinter();
}
<|endoftext|> |
<commit_before><commit_msg>sd: remotecontrol: fix setsockopt call for WNT:<commit_after><|endoftext|> |
<commit_before>/**
* Extension.cpp
*
* @author Emiel Bruijntjes <emiel.bruijntjes@copernica.com>
* @copyright 2013 Copernica BV
*/
#include "includes.h"
/**
* Set up namespace
*/
namespace Php {
/**
* If this extension is compiled for a PHP version with multi
* threading support, we need an additional header file
*/
#ifdef ZTS
#include "TSRM.h"
#endif
/**
* Pointer to the one and only extension object
* @var Extension
*/
static Extension *extension = nullptr;
/**
* We're almost there, we now need to declare an instance of the
* structure defined above (if building for a single thread) or some
* sort of impossible to understand magic pointer-to-a-pointer (for
* multi-threading builds). We make this a static variable because
* this already is bad enough.
*/
ZEND_DECLARE_MODULE_GLOBALS(phpcpp)
/**
* Function that must be defined to initialize the "globals"
* We do not have to initialize anything, but PHP needs to call this
* method (crazy)
* @param globals
*/
static void init_globals(zend_phpcpp_globals *globals) {}
/**
* Function that is called when the extension initializes
* @param type Module type
* @param number Module number
* @return int 0 on success
*/
static int extension_startup(INIT_FUNC_ARGS)
{
// initialize and allocate the "global" variables
ZEND_INIT_MODULE_GLOBALS(phpcpp, init_globals, NULL);
// initialize the extension
return BOOL2SUCCESS(extension->initialize());
}
/**
* Function that is called when the extension is about to be stopped
* @param type Module type
* @param number Module number
* @return int
*/
static int extension_shutdown(SHUTDOWN_FUNC_ARGS)
{
// finalize the extension
return BOOL2SUCCESS(extension->finalize());
}
/**
* Function that is called when a request starts
* @param type Module type
* @param number Module number
* @return int 0 on success
*/
static int request_startup(INIT_FUNC_ARGS)
{
// start the request
return extension->startRequest();
}
/**
* Function that is called when a request is ended
* @param type Module type
* @param number Module number
* @return int 0 on success
*/
static int request_shutdown(INIT_FUNC_ARGS)
{
// end the request
return BOOL2SUCCESS(extension->endRequest());
}
/**
* Constructor
* @param name Name of the extension
* @param version Version number
* @param start Request start callback
* @param stop Request stop callback
*/
Extension::Extension(const char *name, const char *version, request_callback start, request_callback stop) : _start(start), _stop(stop)
{
// store extension variable
extension = this;
// allocate memory (we allocate this on the heap so that the size of the
// entry does not have to be defined in the .h file. We pay a performance
// price for this, but we pay this price becuase the design goal of the
// PHP-C++ library is to have an interface that is as simple as possible
_entry = new zend_module_entry;
// assign all members (apart from the globals)
_entry->size = sizeof(zend_module_entry); // size of the data
_entry->zend_api = ZEND_MODULE_API_NO; // api number
_entry->zend_debug = ZEND_DEBUG; // debug mode enabled?
_entry->zts = USING_ZTS; // is thread safety enabled?
_entry->ini_entry = NULL; // the php.ini record
_entry->deps = NULL; // dependencies on other modules
_entry->name = name; // extension name
_entry->functions = NULL; // functions supported by this module (none for now)
_entry->module_startup_func = extension_startup; // startup function for the whole extension
_entry->module_shutdown_func = extension_shutdown; // shutdown function for the whole extension
_entry->request_startup_func = request_startup; // startup function per request
_entry->request_shutdown_func = request_shutdown; // shutdown function per request
_entry->info_func = NULL; // information for retrieving info
_entry->version = version; // version string
_entry->globals_size = 0; // size of the global variables
_entry->globals_ptr = NULL; // pointer to the globals
_entry->globals_ctor = NULL; // constructor for global variables
_entry->globals_dtor = NULL; // destructor for global variables
_entry->post_deactivate_func = NULL; // unknown function
_entry->module_started = 0; // module is not yet started
_entry->type = 0; // temporary or persistent module, will be filled by Zend engine
_entry->handle = NULL; // dlopen() handle, will be filled by Zend engine
_entry->module_number = 0; // module number will be filled in by Zend engine
_entry->build_id = ZEND_MODULE_BUILD_ID; // check if extension and zend engine are compatible
// things that only need to be initialized
#ifdef ZTS
_entry->globals_id_ptr = NULL;
#else
_entry->globals_ptr = NULL;
#endif
}
/**
* Destructor
*/
Extension::~Extension()
{
// deallocate functions
if (_entry->functions) delete[] _entry->functions;
// deallocate entry
delete _entry;
}
/**
* Add a function to the library
* @param function Function object
* @return Function
*/
Function *Extension::add(Function *function)
{
// add the function to the map
_functions.insert(std::unique_ptr<Function>(function));
// the result is a pair with an iterator
return function;
}
/**
* Add a native function directly to the extension
* @param name Name of the function
* @param function The function to add
* @return Function The added function
*/
Function *Extension::add(const char *name, native_callback_0 function, const std::initializer_list<Argument> &arguments) { return add(new NativeFunction(name, function, arguments)); }
Function *Extension::add(const char *name, native_callback_1 function, const std::initializer_list<Argument> &arguments) { return add(new NativeFunction(name, function, arguments)); }
Function *Extension::add(const char *name, native_callback_2 function, const std::initializer_list<Argument> &arguments) { return add(new NativeFunction(name, function, arguments)); }
Function *Extension::add(const char *name, native_callback_3 function, const std::initializer_list<Argument> &arguments) { return add(new NativeFunction(name, function, arguments)); }
/**
* Retrieve the module entry
* @return zend_module_entry
*/
zend_module_entry *Extension::module()
{
// check if functions we're already defined
if (_entry->functions || _functions.size() == 0) return _entry;
// allocate memory for the functions
zend_function_entry *functions = new zend_function_entry[_functions.size() + 1];
// keep iterator counter
int i = 0;
// loop through the functions
for (auto it = begin(_functions); it != _functions.end(); it++)
{
// retrieve entry
zend_function_entry *entry = &functions[i++];
// let the function fill the entry
(*it)->fill(entry);
}
// last entry should be set to all zeros
zend_function_entry *last = &functions[i];
// all should be set to zero
memset(last, 0, sizeof(zend_function_entry));
// store functions in entry object
_entry->functions = functions;
// return the entry
return _entry;
}
/**
* Initialize the extension
* @return bool
*/
bool Extension::initialize()
{
// loop through the classes
for (auto iter = _classes.begin(); iter != _classes.end(); iter++)
{
// initialize the class
(*iter)->initialize();
}
// done
return true;
}
/**
* End of namespace
*/
}
<commit_msg>Fix problem that loading multiple C++ extensions causes PHP to crash with segmentation fault<commit_after>/**
* Extension.cpp
*
* @author Emiel Bruijntjes <emiel.bruijntjes@copernica.com>
* @copyright 2013 Copernica BV
*/
#include "includes.h"
/**
* Set up namespace
*/
namespace Php {
/**
* If this extension is compiled for a PHP version with multi
* threading support, we need an additional header file
*/
#ifdef ZTS
#include "TSRM.h"
#endif
/**
* We're almost there, we now need to declare an instance of the
* structure defined above (if building for a single thread) or some
* sort of impossible to understand magic pointer-to-a-pointer (for
* multi-threading builds). We make this a static variable because
* this already is bad enough.
*/
ZEND_DECLARE_MODULE_GLOBALS(phpcpp)
/**
* Function that must be defined to initialize the "globals"
* We do not have to initialize anything, but PHP needs to call this
* method (crazy)
* @param globals
*/
static void init_globals(zend_phpcpp_globals *globals) {}
/**
* The *startup() and *shutdown() callback functions are passed a module_number
* variable. However, there does not seem to be a decent API call in Zend to
* get back the original module_entry linked to this number. So we have to
* look up entries in a hash table to find the right module entry. To make things
* even worse, the records in this hash table are copies of the original
* zend_module_entry structure, so we can also not hide the C++ extension
* object pointer in the entry that we created ourselves.
*
* We have an ugly solution, we keep track of a map of all C++ extension names
* and their associated extension object, and a map of all module number and
* the linked extension object.
*
* @var map
*/
static std::map<std::string,Extension*> name2extension;
static std::map<int,Extension*> number2extension;
/**
* Handler function that is used in combination with zend_hash_apply()
*
* This function is called when we need to find an extension object based on
* an extension number. We loop through the list of all registered modules, and
* for each module we check if we know the extension based on the name
*
* @param _zend_module_entry
*/
static int match_module(_zend_module_entry *entry)
{
// check if there is an extension with this name
auto iter = name2extension.find(entry->name);
if (iter == name2extension.end()) return ZEND_HASH_APPLY_KEEP;
// we have the extension, store in combination with the number
number2extension[entry->module_number] = iter->second;
// done
return ZEND_HASH_APPLY_KEEP;
}
/**
* Find an extension based on the module number
* @param number
* @return Extension*
*/
static Extension *extension(int number)
{
// do we already have an extension with this number?
auto iter = number2extension.find(number);
if (iter != number2extension.end()) return iter->second;
// no, not yet, loop through all modules
zend_hash_apply(&module_registry, (apply_func_t)match_module);
// find again
iter = number2extension.find(number);
if (iter == number2extension.end()) return nullptr;
// found!
return iter->second;
}
/**
* Function that is called when the extension initializes
* @param type Module type
* @param number Module number
* @return int 0 on success
*/
static int extension_startup(INIT_FUNC_ARGS)
{
// initialize and allocate the "global" variables
ZEND_INIT_MODULE_GLOBALS(phpcpp, init_globals, NULL);
// initialize the extension
return BOOL2SUCCESS(extension(module_number)->initialize());
}
/**
* Function that is called when the extension is about to be stopped
* @param type Module type
* @param number Module number
* @return int
*/
static int extension_shutdown(SHUTDOWN_FUNC_ARGS)
{
// finalize the extension
return BOOL2SUCCESS(extension(module_number)->finalize());
}
/**
* Function that is called when a request starts
* @param type Module type
* @param number Module number
* @return int 0 on success
*/
static int request_startup(INIT_FUNC_ARGS)
{
// start the request
return extension(module_number)->startRequest();
}
/**
* Function that is called when a request is ended
* @param type Module type
* @param number Module number
* @return int 0 on success
*/
static int request_shutdown(INIT_FUNC_ARGS)
{
// end the request
return BOOL2SUCCESS(extension(module_number)->endRequest());
}
/**
* Constructor
* @param name Name of the extension
* @param version Version number
* @param start Request start callback
* @param stop Request stop callback
*/
Extension::Extension(const char *name, const char *version, request_callback start, request_callback stop) : _start(start), _stop(stop)
{
// keep extension pointer based on the name
name2extension[name] = this;
// allocate memory (we allocate this on the heap so that the size of the
// entry does not have to be defined in the .h file. We pay a performance
// price for this, but we pay this price becuase the design goal of the
// PHP-C++ library is to have an interface that is as simple as possible
_entry = new _zend_module_entry;
// assign all members (apart from the globals)
_entry->size = sizeof(zend_module_entry); // size of the data
_entry->zend_api = ZEND_MODULE_API_NO; // api number
_entry->zend_debug = ZEND_DEBUG; // debug mode enabled?
_entry->zts = USING_ZTS; // is thread safety enabled?
_entry->ini_entry = NULL; // the php.ini record
_entry->deps = NULL; // dependencies on other modules
_entry->name = name; // extension name
_entry->functions = NULL; // functions supported by this module (none for now)
_entry->module_startup_func = extension_startup; // startup function for the whole extension
_entry->module_shutdown_func = extension_shutdown; // shutdown function for the whole extension
_entry->request_startup_func = request_startup; // startup function per request
_entry->request_shutdown_func = request_shutdown; // shutdown function per request
_entry->info_func = NULL; // information for retrieving info
_entry->version = version; // version string
_entry->globals_size = 0; // size of the global variables
_entry->globals_ptr = NULL; // pointer to the globals
_entry->globals_ctor = NULL; // constructor for global variables
_entry->globals_dtor = NULL; // destructor for global variables
_entry->post_deactivate_func = NULL; // unknown function
_entry->module_started = 0; // module is not yet started
_entry->type = 0; // temporary or persistent module, will be filled by Zend engine
_entry->handle = NULL; // dlopen() handle, will be filled by Zend engine
_entry->module_number = 0; // module number will be filled in by Zend engine
_entry->build_id = ZEND_MODULE_BUILD_ID; // check if extension and zend engine are compatible
// things that only need to be initialized
#ifdef ZTS
_entry->globals_id_ptr = NULL;
#else
_entry->globals_ptr = NULL;
#endif
}
/**
* Destructor
*/
Extension::~Extension()
{
// deallocate functions
if (_entry->functions) delete[] _entry->functions;
// deallocate entry
delete _entry;
}
/**
* Add a function to the library
* @param function Function object
* @return Function
*/
Function *Extension::add(Function *function)
{
// add the function to the map
_functions.insert(std::unique_ptr<Function>(function));
// the result is a pair with an iterator
return function;
}
/**
* Add a native function directly to the extension
* @param name Name of the function
* @param function The function to add
* @return Function The added function
*/
Function *Extension::add(const char *name, native_callback_0 function, const std::initializer_list<Argument> &arguments) { return add(new NativeFunction(name, function, arguments)); }
Function *Extension::add(const char *name, native_callback_1 function, const std::initializer_list<Argument> &arguments) { return add(new NativeFunction(name, function, arguments)); }
Function *Extension::add(const char *name, native_callback_2 function, const std::initializer_list<Argument> &arguments) { return add(new NativeFunction(name, function, arguments)); }
Function *Extension::add(const char *name, native_callback_3 function, const std::initializer_list<Argument> &arguments) { return add(new NativeFunction(name, function, arguments)); }
/**
* Retrieve the module entry
* @return zend_module_entry
*/
zend_module_entry *Extension::module()
{
// check if functions we're already defined
if (_entry->functions || _functions.size() == 0) return _entry;
// allocate memory for the functions
zend_function_entry *functions = new zend_function_entry[_functions.size() + 1];
// keep iterator counter
int i = 0;
// loop through the functions
for (auto it = begin(_functions); it != _functions.end(); it++)
{
// retrieve entry
zend_function_entry *entry = &functions[i++];
// let the function fill the entry
(*it)->fill(entry);
}
// last entry should be set to all zeros
zend_function_entry *last = &functions[i];
// all should be set to zero
memset(last, 0, sizeof(zend_function_entry));
// store functions in entry object
_entry->functions = functions;
// return the entry
return _entry;
}
/**
* Initialize the extension
* @return bool
*/
bool Extension::initialize()
{
// loop through the classes
for (auto iter = _classes.begin(); iter != _classes.end(); iter++)
{
// initialize the class
(*iter)->initialize();
}
// done
return true;
}
/**
* End of namespace
*/
}
<|endoftext|> |
<commit_before>#include <iostream>
#include <stdio.h>
#include <unistd.h>
#include "errno.h"
#include <string>
#include <vector>
#include <list>
#include <iterator>
#include "boost/tokenizer.hpp"
#include "boost/algorithm/string.hpp"
using namespace std;
int main (int argc, char const *argv[])
{
char host[128];
gethostname(host, sizeof(host));
char * login = getlogin();
string input;
/*char* arg[] = {"sh", "-c", "echo \"This is true\" || echo \"This is false\""};
int result = execvp(arg[0], arg);
cout << result << endl;
exit(0);*/
while(true)
{
//Terminal prompt display
cout << login << "@" << host << " $ ";
cout.flush();
//Grab user input for bash prompt
getline(cin,input);
boost::trim(input);
//Setting up a boost tokenizer.
typedef boost::tokenizer<boost::escaped_list_separator<char> > tokenizer;
// typedef boost::tokenizer<boost::char_separator<char> > tokenizer;
// boost::char_separator<char> sep(" ", ";#|&"); //' ' (space) and " as delimiters
string separator1("\\");
string separator2(" ;");
string separator3("\"\'");
boost::escaped_list_separator<char> sep(separator1,separator2,separator3);
tokenizer tok(input, sep);
//ls is a temp list for storing the tokenized value
list<string> ls;
//vector for storing a command and its arguments
vector<char*> args;
//vector for storing all of the commands that have been chained together
vector<vector<char*> > commands;
/*
Check for # and immediatly end parsing since anything after it is a comment.
Check for ; or || or && to know if a new command needs to be created.
Put all of these new commands in the commands vector.
*/
for(tokenizer::iterator it = tok.begin(); it != tok.end(); ++it) {
if( !it->empty() ) {
cout << *it << endl;
if(*it == "#")
break;
//If the current element is the start of a connector, this checks to see if the following index contains the other half of the connector
else if( (*it == "|" && *next(it, 1) == "|" ) || (*it == "&" && *next(it, 1) == "&") ) {
}
else if(*it == ";") {
args.push_back(0);
commands.push_back(args);
args.clear();
}
else {
ls.push_back(*it);
args.push_back(const_cast<char*>(ls.back().c_str()));
}
}
}
if(!args.empty()) {
args.push_back(0);
commands.push_back(args);
}
//Go through all of the commands
for(int x = 0; x < commands.size(); x++) {
//Get the current command
vector<char*> com = commands.at(x);
if(com.empty())
break;
//Using string compare here since they're char * entries
if(strncmp(com[0], "exit", 4) == 0) {
exit(0);
}
//Main process thread
pid_t i = fork();
if(i < 0) { //Error
perror("Failed to create child process");
break;
}
else if(i == 0) { //Child process
int result = execvp(com[0], &com[0]);
if(result < 0) {
char result[100];
const char *error = "-rshell: ";
strcpy(result, error);
strcat(result, com[0]);
perror(result);
exit(1);
}
else {
exit(0);
}
}
else { //Parent process
int *status = nullptr;
waitpid(i, status, 0); //Temp fix just to get child to run properly.
if(status < 0) {
perror("Error during child process");
exit(1);
}
}
}
}
}
<commit_msg>String processing done. Working on connectors.<commit_after>#include <iostream>
#include <stdio.h>
#include <unistd.h>
#include "errno.h"
#include <string>
#include <vector>
#include <list>
#include <iterator>
#include "boost/tokenizer.hpp"
#include "boost/algorithm/string.hpp"
using namespace std;
int main (int argc, char const *argv[])
{
char host[128];
gethostname(host, sizeof(host));
char * login = getlogin();
string input;
vector<string> connectors;
bool pass = true;
/*char* arg[] = {"sh", "-c", "echo \"This is true\" || echo \"This is false\""};
int result = execvp(arg[0], arg);
cout << result << endl;
exit(0);*/
while(true)
{
//Terminal prompt display
cout << login << "@" << host << " $ ";
cout.flush();
//Grab user input for bash prompt
getline(cin,input);
boost::trim(input);
//Setting up a boost tokenizer.
typedef boost::tokenizer<boost::escaped_list_separator<char> > tokenizer;
// typedef boost::tokenizer<boost::char_separator<char> > tokenizer;
// boost::char_separator<char> sep(" ", ";#|&"); //' ' (space) and " as delimiters
string separator1("\\");
string separator2(" ");
string separator3("\"\'");
boost::escaped_list_separator<char> sep(separator1,separator2,separator3);
tokenizer tok(input, sep);
//ls is a temp list for storing the tokenized value
list<string> ls;
//vector for storing a command and its arguments
vector<char*> args;
//vector for storing all of the commands that have been chained together
vector<vector<char*> > commands;
/*
Check for # and immediatly end parsing since anything after it is a comment.
Check for ; or || or && to know if a new command needs to be created.
Put all of these new commands in the commands vector.
*/
for(tokenizer::iterator it = tok.begin(); it != tok.end(); ++it) {
if( !it->empty() ) {
if(*it == "#")
break;
//If the current element is the start of a connector, this checks to see if the following index contains the other half of the connector
else if (*it == "||" ) {
connectors.push_back("OR");
args.push_back(0);
commands.push_back(args);
args.clear();
}
else if (*it == "&&") {
connectors.push_back("AND");
args.push_back(0);
commands.push_back(args);
args.clear();
}
else if(strncmp(&it->back(), ";", 1) == 0) {
string temp = it->substr(0, it->size()-1);
if(temp.size() > 1) {
ls.push_back(temp);
args.push_back(const_cast<char*>(ls.back().c_str()));
}
args.push_back(0);
commands.push_back(args);
args.clear();
}
else {
connectors.push_back(" ");
ls.push_back(*it);
args.push_back(const_cast<char*>(ls.back().c_str()));
}
}
}
if(!args.empty()) {
connectors.push_back(" ");
args.push_back(0);
commands.push_back(args);
}
//Go through all of the commands
for(int x = 0; x < commands.size(); x++) {
//Get the current command
vector<char*> com = commands.at(x);
if(com.empty())
continue;
//Using string compare here since they're char * entries
if(strncmp(com[0], "exit", 4) == 0) {
exit(0);
}
//Main process thread
pid_t i = fork();
if(i < 0) { //Error
perror("Failed to create child process");
break;
}
else if(i == 0) { //Child process
/*
if(connectors.at(x+1) == "OR" && pass)
exit(0);
if(connectors.at(x+1) == "AND" && !pass)
exit(0);
*/
int result = execvp(com[0], &com[0]);
if(result < 0) {
char result[100];
const char *error = "-rshell: ";
strcpy(result, error);
strcat(result, com[0]);
perror(result);
exit(1);
}
else {
exit(0);
}
}
else { //Parent process
int *status = nullptr;
waitpid(i, status, 0); //Temp fix just to get child to run properly.
if(status < 0) {
perror("Error during child process");
pass = false;
exit(1);
}
else {
pass = true;
}
}
}
}
}
<|endoftext|> |
<commit_before>#ifndef SIEVE_GAUSS_SINGLE_THREADED_CPP
#define SIEVE_GAUSS_SINGLE_THREADED_CPP
#if !defined(SIEVE_GAUSS_SINGLE_THREADED) || GAUSS_SIEVE_IS_MULTI_THREADED == true
#error SieveST.cpp included with wrong macro settings
#endif
template<class ET>
bool Sieve<ET,false>::update_shortest_vector_found(LPType const & newvector)
{
if(newvector.norm2<= shortest_vector_found.norm2)
{
shortest_vector_found = newvector;
return true;
}
return false;
}
template<class ET>
typename Sieve<ET,false>::LPType Sieve<ET,false>::get_shortest_vector_found()
{
return shortest_vector_found;
}
template<class ET>
ET Sieve<ET,false>::get_best_length2()
{
return shortest_vector_found.norm2;
}
//to avoid errs from SieveMT
//template<class ET>
//void Sieve<ET,false>::run_2_sieve()
//{
// run_sieve (2);
//}
//we should re-use this function for k-sieve, but call different SieveInteration
template<class ET>
void Sieve<ET,false>::run()
{
//using SieveT = Sieve<ET,GAUSS_SIEVE_IS_MULTI_THREADED>;
//for ( LatticePoint<ET> & x : main_list) cout << x.norm2 << endl;
int i=0;
//int MaxIteration = 8000;
LatticePoint<ET> p;
//NumVect<ET> sample;
//check_if_done(); //sets up default conditions if not already set. We ignore the return value. -- Moved to run(), Gotti
//ET target_norm = term_cond.get_target_length();
while (!check_if_done() )
// while (i<2)
//while(main_list.cbegin()->norm2 > target_norm)
{
p=main_queue.true_pop();
if (sieve_k==2)
SieveIteration2(p);
else if (sieve_k==3)
SieveIteration3(p);
//cout << i << " list size" << current_list_size << " Queue: " << main_queue.size() << endl << flush;
++i;
//if (i % 500 == 0) {
// print_status();
//cout << "# of collisions: " << number_of_collisions << endl;
//cout << "norm2 of the so far shortest vector: " << get_best_length2() << endl;
//}
}
//Diagnostic and use of the information moved up to the caller.
/*
cout << "sv is " << endl;
main_list.cbegin().access_details()->printLatticePoint();
print_status();
*/
}
template<class ET>
void Sieve<ET,false>::SieveIteration2 (LatticePoint<ET> &p) //note : Queue might output Approx ?
{
if (p.norm2==0) return; //cerr << "Trying to reduce 0"; //TODO: Ensure sampler does not output 0 (currently, it happens).
ApproxLatticePoint<ET,false> pApprox (p);
//simplified the code, because main_list supports deleting AT pos and inserting BEFORE pos now. -- Gotti
int const n = get_ambient_dimension();
bool loop = true;
ET scalar; //reduction multiple output by check3red_new
typename MainListType::Iterator it_comparison_flip=main_list.cend(); //used to store the point where the list elements become larger than p.
while (loop) //while p keeps changing
{
loop = false;
for (auto it = main_list.cbegin(); it!=main_list.cend(); ++it)
{
if (p.norm2 < it.get_true_norm2())
{
it_comparison_flip = it;
break;
}
++number_of_scprods;
bool predict = LatticeApproximations::Compare_Sc_Prod(pApprox,*it,it->get_approx_norm2(),2* it->get_length_exponent()-1,n );
if(!predict) continue;
/* OLD IMPLEMENTATION: check2red both check and reduces p
if(GaussSieve::check2red(p, *(it.access_details()) ) ) //p was changed
{
if(p.norm2!=0) pApprox = static_cast< ApproxLatticePoint<ET,false> >(p);
cout << "p = ";
p.printLatticePoint();
loop = true;
break;
}
*/
++number_of_exact_scprods;
if ( GaussSieve::check2red_new(p, *(it.access_details()), scalar) )
{
p = GaussSieve::perform2red(p, *(it.access_details()), scalar);
//update the approximation of f
if (p.norm2!=0) pApprox = static_cast< ApproxLatticePoint<ET,false> >(p);
loop = true;
break;
}
else
{
++number_of_mispredictions;
}
}
}
//p no longer changes. it_comparison_flip is iterator to first (shortest) element in the list that is longer than p.
//If no such element exists, it_comparison_flip refers to after-the-end.
if (p.norm2 == 0)
{
//increase the number of collisions
number_of_collisions++;
return;
}
//insert p into main_list;
main_list.insert_before(it_comparison_flip,p);
++current_list_size;
if(update_shortest_vector_found(p))
{
if(verbosity>=2)
{
cout << "New shortest vector found. Norm2 = " << get_best_length2();
}
}
for(auto it = it_comparison_flip; it!=main_list.cend(); ) //go through rest of the list.
//We know that every element current_list_point=*it is at least as long as p, so we reduce x using p.
{
++number_of_scprods;
bool predict = LatticeApproximations::Compare_Sc_Prod(pApprox,*it,pApprox.get_approx_norm2(),2* pApprox.get_length_exponent()-1,n );
if(!predict){++it;continue;} //if prediction is bad, don't even bother to reduce.
LatticePoint<ET> current_list_point = it.get_exact_point();
++number_of_exact_scprods;
if (GaussSieve::check2red_new(current_list_point, p, scalar)) //We can reduce *it.
{
//create new list point
LatticePoint<ET> reduced = GaussSieve::perform2red(p, current_list_point, scalar);
//if (!predict) cerr << "Misprediction 2" << endl;
//cout << "v was found" << endl;
if (reduced.norm2 == 0) //Note : this cannot happen unless the list contains a non-trivial multiple of p (because the collision would have triggered before).
{
number_of_collisions++;
++it;
continue; //was a break. Changed to ++it;continue; -- Gotti
}
main_queue.push(reduced);
it = main_list.erase(it); //this also moves it forward
--current_list_size;
}
else
{
++number_of_mispredictions;
// prev = it1;
++it;
}
}
/* print for debugging */
//for (it1 = main_list.begin(); it1!=main_list.end(); ++it1) {
// (*it1).printLatticePoint();
//}
};
template<class ET>
void Sieve<ET,false>::SieveIteration3 (LatticePoint<ET> &p)
{
}
//template<class ET>
//void Sieve<ET,false>::run_3_sieve()
//{
//
// int i=0; //# of iterations
// LatticePoint<ET> p;
// while (! check_if_done()) {
//
// p=main_queue.true_pop();
//
//
// }
//
//}
//currently unused diagnostic code.
/*
template<class ET>
void PredictionDiagnosis (Sieve<ET,false> * gs, ApproxLatticePoint<ET,false> const & v1, LatticePoint<ET> const &d1, ApproxLatticePoint<ET,false> const &v2, LatticePoint<ET> const &d2, int dim);
template<class ET>
void PredictionDiagnosis (Sieve<ET,false> * gs, ApproxLatticePoint<ET,false> const & v1, LatticePoint<ET> const &d1, ApproxLatticePoint<ET,false> const &v2, LatticePoint<ET> const &d2, int dim)
{
static int count =0;
LatticePoint<ET> c1 = d1;
LatticePoint<ET> c2 = d2;
bool actual_red = GaussSieve::check2red(c1,c2);
//cout << (actual_red?"Red:yes" : "Red:no");
bool predict_red = LatticeApproximations::Compare_Sc_Prod(v1,v2,v2.get_approx_norm2(),2*v2.get_length_exponent() -2,dim);
//cout << (predict_red?"Predict:yes" : "Predict:no");
ET sc_prod, abs_scprod, scalar;
sc_product(sc_prod, d1, d2);
abs_scprod.mul_ui(sc_prod,2);
abs_scprod.abs(abs_scprod);
ET n1true = d1.get_norm2();
int32_t approxSP = abs(LatticeApproximations::compute_sc_prod(v1.get_approx(),v2.get_approx(),dim));
int approxExp1 = v1.get_length_exponent();
int approxExp2 = v2.get_length_exponent();
int approxExpScP = approxExp1 + approxExp2;
int32_t n1approx = v1.get_approx_norm2();
int n1exp = 2*v1.get_length_exponent();
ET approxSP_real;
ET n1_real;
LatticePoint<ET> approxv1_real(dim);
LatticePoint<ET> approxv2_real(dim);
approxSP_real = static_cast<long>(approxSP);
n1_real = static_cast<long>(n1approx);
for(int i=0;i<dim;++i) approxv1_real[i] = static_cast<long>( (v1.get_approx()) [i]);
for(int i=0;i<dim;++i) approxv2_real[i] = static_cast<long>( (v2.get_approx()) [i]);
//stupid:
for(int i=0;i < approxExp1 ; ++i) approxv1_real = approxv1_real + approxv1_real;
for(int i=0;i < approxExp2 ; ++i) approxv2_real = approxv2_real + approxv2_real;
for(int i=0;i < approxExpScP ; ++i) approxSP_real.mul_si(approxSP_real,2);
for(int i=0;i < n1exp; ++i) n1_real.mul_si(n1_real,2);
if(actual_red == true && predict_red ==false)
{
//misprediction.
cout << "Misprediction" << endl;
cout << "v1 =" << v1 << endl;
cout << "meaning of approx1 = " << approxv1_real << endl;
cout << "v2 =" << v2 << endl;
cout << "meaning of approx2 = " << approxv2_real << endl;
cout << "true absscalar product= " << abs_scprod << endl;
cout << "approx abssc product = " << approxSP << endl;
cout << "meaning " << approxSP_real << endl;
cout << "sqNorm1 = " << n1true << endl;
cout << "Approx Norm1 = " << n1approx << endl;
cout << "meaning " << n1_real << endl;
}
else if(count % 100 == 80)
{
cout <<"Prediction: ";
cout << (actual_red?"Red:yes" : "Red: no") << " , ";
cout << (predict_red?"Predict:yes" : "Predict: no") << endl;
cout << "v1 =" << v1 << endl;
cout << "meaning of approx1 = " << approxv1_real << endl;
cout << "v2 =" << v2 << endl;
cout << "meaning of approx2 = " << approxv2_real << endl;
cout << "true absscalar product= " << abs_scprod << endl;
cout << "approx abssc product = " << approxSP << endl;
cout << "meaning " << approxSP_real << endl;
cout << "sqNorm1 = " << n1true << endl;
cout << "Approx Norm1 = " << n1approx << endl;
cout << "meaning " << n1_real << endl;
}
++count;
//cout << endl;
}
*/
#endif
<commit_msg>3sieve begin<commit_after>#ifndef SIEVE_GAUSS_SINGLE_THREADED_CPP
#define SIEVE_GAUSS_SINGLE_THREADED_CPP
#if !defined(SIEVE_GAUSS_SINGLE_THREADED) || GAUSS_SIEVE_IS_MULTI_THREADED == true
#error SieveST.cpp included with wrong macro settings
#endif
template<class ET>
bool Sieve<ET,false>::update_shortest_vector_found(LPType const & newvector)
{
if(newvector.norm2<= shortest_vector_found.norm2)
{
shortest_vector_found = newvector;
return true;
}
return false;
}
template<class ET>
typename Sieve<ET,false>::LPType Sieve<ET,false>::get_shortest_vector_found()
{
return shortest_vector_found;
}
template<class ET>
ET Sieve<ET,false>::get_best_length2()
{
return shortest_vector_found.norm2;
}
//to avoid errs from SieveMT
//template<class ET>
//void Sieve<ET,false>::run_2_sieve()
//{
// run_sieve (2);
//}
//we should re-use this function for k-sieve, but call different SieveInteration
template<class ET>
void Sieve<ET,false>::run()
{
//using SieveT = Sieve<ET,GAUSS_SIEVE_IS_MULTI_THREADED>;
//for ( LatticePoint<ET> & x : main_list) cout << x.norm2 << endl;
int i=0;
//int MaxIteration = 8000;
LatticePoint<ET> p;
//NumVect<ET> sample;
//check_if_done(); //sets up default conditions if not already set. We ignore the return value. -- Moved to run(), Gotti
//ET target_norm = term_cond.get_target_length();
while (!check_if_done() )
// while (i<2)
//while(main_list.cbegin()->norm2 > target_norm)
{
p=main_queue.true_pop();
if (sieve_k==2)
SieveIteration2(p);
else if (sieve_k==3)
SieveIteration3(p);
//cout << i << " list size" << current_list_size << " Queue: " << main_queue.size() << endl << flush;
++i;
//if (i % 500 == 0) {
// print_status();
//cout << "# of collisions: " << number_of_collisions << endl;
//cout << "norm2 of the so far shortest vector: " << get_best_length2() << endl;
//}
}
//Diagnostic and use of the information moved up to the caller.
/*
cout << "sv is " << endl;
main_list.cbegin().access_details()->printLatticePoint();
print_status();
*/
}
template<class ET>
void Sieve<ET,false>::SieveIteration2 (LatticePoint<ET> &p) //note : Queue might output Approx ?
{
if (p.norm2==0) return; //cerr << "Trying to reduce 0"; //TODO: Ensure sampler does not output 0 (currently, it happens).
ApproxLatticePoint<ET,false> pApprox (p);
//simplified the code, because main_list supports deleting AT pos and inserting BEFORE pos now. -- Gotti
int const n = get_ambient_dimension();
bool loop = true;
ET scalar; //reduction multiple output by check2red_new
typename MainListType::Iterator it_comparison_flip=main_list.cend(); //used to store the point where the list elements become larger than p.
while (loop) //while p keeps changing
{
loop = false;
for (auto it = main_list.cbegin(); it!=main_list.cend(); ++it)
{
if (p.norm2 < it.get_true_norm2())
{
it_comparison_flip = it;
break;
}
++number_of_scprods;
bool predict = LatticeApproximations::Compare_Sc_Prod(pApprox,*it,it->get_approx_norm2(),2* it->get_length_exponent()-1,n );
if(!predict) continue;
/* OLD IMPLEMENTATION: check2red both check and reduces p
if(GaussSieve::check2red(p, *(it.access_details()) ) ) //p was changed
{
if(p.norm2!=0) pApprox = static_cast< ApproxLatticePoint<ET,false> >(p);
cout << "p = ";
p.printLatticePoint();
loop = true;
break;
}
*/
++number_of_exact_scprods;
if ( GaussSieve::check2red_new(p, *(it.access_details()), scalar) )
{
p = GaussSieve::perform2red(p, *(it.access_details()), scalar);
//update the approximation of f
if (p.norm2!=0) pApprox = static_cast< ApproxLatticePoint<ET,false> >(p);
loop = true;
break;
}
else
{
++number_of_mispredictions;
}
}
}
//p no longer changes. it_comparison_flip is iterator to first (shortest) element in the list that is longer than p.
//If no such element exists, it_comparison_flip refers to after-the-end.
if (p.norm2 == 0)
{
//increase the number of collisions
number_of_collisions++;
return;
}
//insert p into main_list;
main_list.insert_before(it_comparison_flip,p);
++current_list_size;
if(update_shortest_vector_found(p))
{
if(verbosity>=2)
{
cout << "New shortest vector found. Norm2 = " << get_best_length2();
}
}
for(auto it = it_comparison_flip; it!=main_list.cend(); ) //go through rest of the list.
//We know that every element current_list_point=*it is at least as long as p, so we reduce x using p.
{
++number_of_scprods;
bool predict = LatticeApproximations::Compare_Sc_Prod(pApprox,*it,pApprox.get_approx_norm2(),2* pApprox.get_length_exponent()-1,n );
if(!predict){++it;continue;} //if prediction is bad, don't even bother to reduce.
LatticePoint<ET> current_list_point = it.get_exact_point();
++number_of_exact_scprods;
if (GaussSieve::check2red_new(current_list_point, p, scalar)) //We can reduce *it.
{
//create new list point
LatticePoint<ET> reduced = GaussSieve::perform2red(p, current_list_point, scalar);
//if (!predict) cerr << "Misprediction 2" << endl;
//cout << "v was found" << endl;
if (reduced.norm2 == 0) //Note : this cannot happen unless the list contains a non-trivial multiple of p (because the collision would have triggered before).
{
number_of_collisions++;
++it;
continue; //was a break. Changed to ++it;continue; -- Gotti
}
main_queue.push(reduced);
it = main_list.erase(it); //this also moves it forward
--current_list_size;
}
else
{
++number_of_mispredictions;
// prev = it1;
++it;
}
}
/* print for debugging */
//for (it1 = main_list.begin(); it1!=main_list.end(); ++it1) {
// (*it1).printLatticePoint();
//}
}
template<class ET>
void Sieve<ET,false>::SieveIteration3 (LatticePoint<ET> &p)
{
if (p.norm2==0) return;
ApproxLatticePoint<ET,false> pApprox (p);
int const n = get_ambient_dimension();
ET scalar;
//typename MainListType::Iterator it_comparison_flip=main_list.cend();
for (auto it = main_list.cbegin(); it!=main_list.cend(); ++it)
{
if (p.norm2 < it.get_true_norm2())
break;
// check if 2-red is possible
++number_of_scprods;
bool predict = LatticeApproximations::Compare_Sc_Prod(pApprox,*it,it->get_approx_norm2(),2* it->get_length_exponent()-1,n );
if(!predict) continue;
++number_of_exact_scprods;
if ( GaussSieve::check2red_new(p, *(it.access_details()), scalar) )
{
p = GaussSieve::perform2red(p, *(it.access_details()), scalar);
//put p back into the queue and break
if (p.norm2!=0)
main_queue.push(p);
break;
}
else
++number_of_mispredictions;
}
};
//currently unused diagnostic code.
/*
template<class ET>
void PredictionDiagnosis (Sieve<ET,false> * gs, ApproxLatticePoint<ET,false> const & v1, LatticePoint<ET> const &d1, ApproxLatticePoint<ET,false> const &v2, LatticePoint<ET> const &d2, int dim);
template<class ET>
void PredictionDiagnosis (Sieve<ET,false> * gs, ApproxLatticePoint<ET,false> const & v1, LatticePoint<ET> const &d1, ApproxLatticePoint<ET,false> const &v2, LatticePoint<ET> const &d2, int dim)
{
static int count =0;
LatticePoint<ET> c1 = d1;
LatticePoint<ET> c2 = d2;
bool actual_red = GaussSieve::check2red(c1,c2);
//cout << (actual_red?"Red:yes" : "Red:no");
bool predict_red = LatticeApproximations::Compare_Sc_Prod(v1,v2,v2.get_approx_norm2(),2*v2.get_length_exponent() -2,dim);
//cout << (predict_red?"Predict:yes" : "Predict:no");
ET sc_prod, abs_scprod, scalar;
sc_product(sc_prod, d1, d2);
abs_scprod.mul_ui(sc_prod,2);
abs_scprod.abs(abs_scprod);
ET n1true = d1.get_norm2();
int32_t approxSP = abs(LatticeApproximations::compute_sc_prod(v1.get_approx(),v2.get_approx(),dim));
int approxExp1 = v1.get_length_exponent();
int approxExp2 = v2.get_length_exponent();
int approxExpScP = approxExp1 + approxExp2;
int32_t n1approx = v1.get_approx_norm2();
int n1exp = 2*v1.get_length_exponent();
ET approxSP_real;
ET n1_real;
LatticePoint<ET> approxv1_real(dim);
LatticePoint<ET> approxv2_real(dim);
approxSP_real = static_cast<long>(approxSP);
n1_real = static_cast<long>(n1approx);
for(int i=0;i<dim;++i) approxv1_real[i] = static_cast<long>( (v1.get_approx()) [i]);
for(int i=0;i<dim;++i) approxv2_real[i] = static_cast<long>( (v2.get_approx()) [i]);
//stupid:
for(int i=0;i < approxExp1 ; ++i) approxv1_real = approxv1_real + approxv1_real;
for(int i=0;i < approxExp2 ; ++i) approxv2_real = approxv2_real + approxv2_real;
for(int i=0;i < approxExpScP ; ++i) approxSP_real.mul_si(approxSP_real,2);
for(int i=0;i < n1exp; ++i) n1_real.mul_si(n1_real,2);
if(actual_red == true && predict_red ==false)
{
//misprediction.
cout << "Misprediction" << endl;
cout << "v1 =" << v1 << endl;
cout << "meaning of approx1 = " << approxv1_real << endl;
cout << "v2 =" << v2 << endl;
cout << "meaning of approx2 = " << approxv2_real << endl;
cout << "true absscalar product= " << abs_scprod << endl;
cout << "approx abssc product = " << approxSP << endl;
cout << "meaning " << approxSP_real << endl;
cout << "sqNorm1 = " << n1true << endl;
cout << "Approx Norm1 = " << n1approx << endl;
cout << "meaning " << n1_real << endl;
}
else if(count % 100 == 80)
{
cout <<"Prediction: ";
cout << (actual_red?"Red:yes" : "Red: no") << " , ";
cout << (predict_red?"Predict:yes" : "Predict: no") << endl;
cout << "v1 =" << v1 << endl;
cout << "meaning of approx1 = " << approxv1_real << endl;
cout << "v2 =" << v2 << endl;
cout << "meaning of approx2 = " << approxv2_real << endl;
cout << "true absscalar product= " << abs_scprod << endl;
cout << "approx abssc product = " << approxSP << endl;
cout << "meaning " << approxSP_real << endl;
cout << "sqNorm1 = " << n1true << endl;
cout << "Approx Norm1 = " << n1approx << endl;
cout << "meaning " << n1_real << endl;
}
++count;
//cout << endl;
}
*/
#endif
<|endoftext|> |
<commit_before>/*
* Copyright (C) 2015 Morwenn
*
* array_sort 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.
*
* array_sort 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 program. If not,
* see <http://www.gnu.org/licenses/>.
*/
#include <algorithm>
#include <array>
#include <chrono>
#include <ctime>
#include <iostream>
#include <iterator>
#include <numeric>
#include <random>
#include <utility>
#include <cpp-sort/sort.h>
template<
typename RandomAccessIterable,
typename Compare = std::less<>
>
auto std_sort(RandomAccessIterable& iterable, Compare&& compare={})
-> void
{
std::sort(std::begin(iterable), std::end(iterable), std::forward<Compare>(compare));
}
template<
typename T,
std::size_t N,
typename SortFunction1,
typename SortFunction2
>
auto time_compare(SortFunction1 sort1, SortFunction2 sort2, std::size_t times)
-> std::array<std::chrono::milliseconds, 2u>
{
// Random numbers generator
thread_local std::mt19937_64 engine(std::time(nullptr));
// Generate shuffled array, the same for both algorithms
std::array<T, N> array;
std::iota(std::begin(array), std::end(array), 0);
std::shuffle(std::begin(array), std::end(array), engine);
// Time first algorithm
auto start = std::chrono::high_resolution_clock::now();
for (std::size_t i = 0 ; i < times ; ++i)
{
auto unsorted = array;
sort1(unsorted, std::less<>{});
}
auto end = std::chrono::high_resolution_clock::now();
auto duration1 = std::chrono::duration_cast<std::chrono::milliseconds>(end - start);
// Time second algorithm
start = std::chrono::high_resolution_clock::now();
for (std::size_t i = 0 ; i < times ; ++i)
{
auto unsorted = array;
sort2(unsorted, std::less<>{});
}
end = std::chrono::high_resolution_clock::now();
auto duration2 = std::chrono::duration_cast<std::chrono::milliseconds>(end - start);
return { duration1, duration2 };
}
template<typename T, std::size_t... Ind>
auto time_them(std::size_t size, std::index_sequence<Ind...>)
-> std::array<
std::array<
std::chrono::milliseconds,
sizeof...(Ind)
>,
2u
>
{
// Benchmark the sorts std::sort
std::array<std::array<std::chrono::milliseconds, 2u>, sizeof...(Ind)> results = {
time_compare<T, Ind>(
&cppsort::sort<T, Ind, std::less<>>,
&std_sort<std::array<T, Ind>, std::less<>>,
size
)...
};
// Results for cppsort::sort
std::array<std::chrono::milliseconds, sizeof...(Ind)> first = {
std::get<Ind>(results)[0u]...
};
// Results for std::sort
std::array<std::chrono::milliseconds, sizeof...(Ind)> second = {
std::get<Ind>(results)[1u]...
};
return { first, second };
}
int main()
{
using indices = std::make_index_sequence<64u>;
auto sorts_times = time_them<int>(1000000u, indices{});
for (auto&& sort_times: sorts_times)
{
for (auto&& time: sort_times)
{
std::cout << time.count() << ' ';
}
std::cout << '\n';
}
}
<commit_msg>Always use a steady clock in the benchmarks.<commit_after>/*
* Copyright (C) 2015 Morwenn
*
* array_sort 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.
*
* array_sort 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 program. If not,
* see <http://www.gnu.org/licenses/>.
*/
#include <algorithm>
#include <array>
#include <chrono>
#include <ctime>
#include <iostream>
#include <iterator>
#include <numeric>
#include <random>
#include <type_traits>
#include <utility>
#include <cpp-sort/sort.h>
template<
typename RandomAccessIterable,
typename Compare = std::less<>
>
auto std_sort(RandomAccessIterable& iterable, Compare&& compare={})
-> void
{
std::sort(std::begin(iterable), std::end(iterable), std::forward<Compare>(compare));
}
template<
typename T,
std::size_t N,
typename SortFunction1,
typename SortFunction2
>
auto time_compare(SortFunction1 sort1, SortFunction2 sort2, std::size_t times)
-> std::array<std::chrono::milliseconds, 2u>
{
// Choose the best clock type (always steady)
using clock_type = std::conditional_t<
std::chrono::high_resolution_clock::is_steady,
std::chrono::high_resolution_clock,
std::chrono::steady_clock
>;
// Random numbers generator
thread_local std::mt19937_64 engine(std::time(nullptr));
// Generate shuffled array, the same for both algorithms
std::array<T, N> array;
std::iota(std::begin(array), std::end(array), 0);
std::shuffle(std::begin(array), std::end(array), engine);
// Time first algorithm
auto start = clock_type::now();
for (std::size_t i = 0 ; i < times ; ++i)
{
auto unsorted = array;
sort1(unsorted, std::less<>{});
}
auto end = clock_type::now();
auto duration1 = std::chrono::duration_cast<std::chrono::milliseconds>(end - start);
// Time second algorithm
start = clock_type::now();
for (std::size_t i = 0 ; i < times ; ++i)
{
auto unsorted = array;
sort2(unsorted, std::less<>{});
}
end = clock_type::now();
auto duration2 = std::chrono::duration_cast<std::chrono::milliseconds>(end - start);
return { duration1, duration2 };
}
template<typename T, std::size_t... Ind>
auto time_them(std::size_t size, std::index_sequence<Ind...>)
-> std::array<
std::array<
std::chrono::milliseconds,
sizeof...(Ind)
>,
2u
>
{
// Benchmark the sorts std::sort
std::array<std::array<std::chrono::milliseconds, 2u>, sizeof...(Ind)> results = {
time_compare<T, Ind>(
&cppsort::sort<T, Ind, std::less<>>,
&std_sort<std::array<T, Ind>, std::less<>>,
size
)...
};
// Results for cppsort::sort
std::array<std::chrono::milliseconds, sizeof...(Ind)> first = {
std::get<Ind>(results)[0u]...
};
// Results for std::sort
std::array<std::chrono::milliseconds, sizeof...(Ind)> second = {
std::get<Ind>(results)[1u]...
};
return { first, second };
}
int main()
{
using indices = std::make_index_sequence<64u>;
auto sorts_times = time_them<int>(1000000u, indices{});
for (auto&& sort_times: sorts_times)
{
for (auto&& time: sort_times)
{
std::cout << time.count() << ' ';
}
std::cout << '\n';
}
}
<|endoftext|> |
<commit_before>#include "window.h"
#include "control.h"
#include <FL/fl_ask.H>
#include <FL/Fl_Input.H>
#include <cassert>
#include <algorithm>
#include <vector>
void Vindow::FileNew(Fl_Widget*, void*)
{}
void Vindow::FileOpen(Fl_Widget*, void*)
{}
void Vindow::FileSave(Fl_Widget*, void*)
{}
void Vindow::FileSaveAs(Fl_Widget*, void*)
{}
void Vindow::FileReload(Fl_Widget*, void*)
{}
void Vindow::FileExit(Fl_Widget*, void*)
{
extern bool is_any_model_dirty();
if(is_any_model_dirty())
{
int which = fl_choice("There are unsaved documents.\nAre you sure you want to exit?\n(Hint: use Vindow/Close to close just one window)", "&No", nullptr, "&Yes");
if(which != 2) return;
}
exit(0);
}
void Vindow::EditUndo(Fl_Widget*, void*)
{}
void Vindow::EditCut(Fl_Widget*, void*)
{}
void Vindow::EditCopy(Fl_Widget*, void*)
{}
void Vindow::EditPaste(Fl_Widget*, void*)
{}
void Vindow::EditOverwrite(Fl_Widget*, void*)
{}
void Vindow::EditInsertRest(Fl_Widget*, void*)
{}
void Vindow::EditInsertBlank(Fl_Widget*, void*)
{}
void Vindow::EditClearColumns(Fl_Widget*, void*)
{}
void Vindow::EditDeleteColumns(Fl_Widget*, void*)
{}
void Vindow::EditAddWhat(Fl_Widget*, void*)
{}
void Vindow::EditAddWho(Fl_Widget*, void*)
{}
void Vindow::EditDeleteSection(Fl_Widget*, void*)
{}
void Vindow::WindowNew(Fl_Widget*, void* p)
{
extern void create_window(std::shared_ptr<Model>);
Vindow* me = (Vindow*)p;
create_window(me->model_);
}
void Vindow::WindowClose(Fl_Widget*, void* p)
{
extern void destroy_window(Vindow*);
Vindow* me = (Vindow*)p;
if(me->model_->dirty
&& me->model_->views.size() == 1)
{
int which = fl_choice("There are unsaved changes in the document.\nClosing this window will discard all changes.\nDo you want to close this document?", "&No", nullptr, "&Yes");
if(which != 2) return;
}
return destroy_window(me);
}
void Vindow::WindowCloseAll(Fl_Widget*, void* p)
{
extern void destroy_window(Vindow*);
Vindow* me = (Vindow*)p;
if(me->model_->dirty)
{
int which = fl_choice("There are unsaved changes in the document.\nDo you want to close this document, discarding changes?", "&No", nullptr, "&Yes");
if(which != 2) return;
}
std::vector<View*> toDestroy;
std::copy_if(me->model_->views.begin(), me->model_->views.end(), std::back_inserter(toDestroy), [me](View* view) -> bool {
auto* w = dynamic_cast<Vindow*>(view);
if(w == me) return false;
return w != nullptr;
});
for(auto* view : toDestroy)
{
auto* w = dynamic_cast<Vindow*>(view);
if(w) destroy_window(w);
}
return destroy_window(me);
}
void Vindow::HelpAbout(Fl_Widget*, void*)
{
fl_alert("JakBeat GUI\nCopyright (c) 2015-2017 Vlad Meșco\nAvailable under the 2-Clause BSD License");
}
void Vindow::WhatClicked(Fl_Widget* w, void* p)
{
Vindow* me = (Vindow*)p;
const char* label = w->label();
me->SetLayout(Layout::WHAT, label);
}
void Vindow::WhoClicked(Fl_Widget* w, void* p)
{
Vindow* me = (Vindow*)p;
const char* label = w->label();
me->SetLayout(Layout::WHO, label);
}
void Vindow::OutputClicked(Fl_Widget* w, void* p)
{
Vindow* me = (Vindow*)p;
me->SetLayout(Layout::OUTPUT);
}
void Vindow::WindowCallback(Fl_Widget* w, void* p)
{
WindowClose(w, p);
}
void Vindow::WhoNameChanged(Fl_Widget* w, void* p)
{
auto* inp = (Fl_Input*)w;
auto* me = (Vindow*)p;
const char* newName = inp->value();
const char* oldName = me->active_.c_str();
if(std::any_of(me->model_->whos.begin(), me->model_->whos.end(), [newName](WhoEntry const& e) -> bool {
return e.name == newName;
}))
{
fl_alert("Name needs to be unique");
inp->value(oldName);
//Fl::focus(inp); // doesn't work because e.g. the tab key is
// handled later...
return;
}
Control ctrl(me->model_, me);
ctrl.SetWhosName(oldName, newName);
}
<commit_msg>avoid corrupting the document<commit_after>#include "window.h"
#include "control.h"
#include <FL/fl_ask.H>
#include <FL/Fl_Input.H>
#include <cassert>
#include <algorithm>
#include <vector>
void Vindow::FileNew(Fl_Widget*, void*)
{}
void Vindow::FileOpen(Fl_Widget*, void*)
{}
void Vindow::FileSave(Fl_Widget*, void*)
{}
void Vindow::FileSaveAs(Fl_Widget*, void*)
{}
void Vindow::FileReload(Fl_Widget*, void*)
{}
void Vindow::FileExit(Fl_Widget*, void*)
{
extern bool is_any_model_dirty();
if(is_any_model_dirty())
{
int which = fl_choice("There are unsaved documents.\nAre you sure you want to exit?\n(Hint: use Vindow/Close to close just one window)", "&No", nullptr, "&Yes");
if(which != 2) return;
}
exit(0);
}
void Vindow::EditUndo(Fl_Widget*, void*)
{}
void Vindow::EditCut(Fl_Widget*, void*)
{}
void Vindow::EditCopy(Fl_Widget*, void*)
{}
void Vindow::EditPaste(Fl_Widget*, void*)
{}
void Vindow::EditOverwrite(Fl_Widget*, void*)
{}
void Vindow::EditInsertRest(Fl_Widget*, void*)
{}
void Vindow::EditInsertBlank(Fl_Widget*, void*)
{}
void Vindow::EditClearColumns(Fl_Widget*, void*)
{}
void Vindow::EditDeleteColumns(Fl_Widget*, void*)
{}
void Vindow::EditAddWhat(Fl_Widget*, void*)
{}
void Vindow::EditAddWho(Fl_Widget*, void*)
{}
void Vindow::EditDeleteSection(Fl_Widget*, void*)
{}
void Vindow::WindowNew(Fl_Widget*, void* p)
{
extern void create_window(std::shared_ptr<Model>);
Vindow* me = (Vindow*)p;
create_window(me->model_);
}
void Vindow::WindowClose(Fl_Widget*, void* p)
{
extern void destroy_window(Vindow*);
Vindow* me = (Vindow*)p;
if(me->model_->dirty
&& me->model_->views.size() == 1)
{
int which = fl_choice("There are unsaved changes in the document.\nClosing this window will discard all changes.\nDo you want to close this document?", "&No", nullptr, "&Yes");
if(which != 2) return;
}
return destroy_window(me);
}
void Vindow::WindowCloseAll(Fl_Widget*, void* p)
{
extern void destroy_window(Vindow*);
Vindow* me = (Vindow*)p;
if(me->model_->dirty)
{
int which = fl_choice("There are unsaved changes in the document.\nDo you want to close this document, discarding changes?", "&No", nullptr, "&Yes");
if(which != 2) return;
}
std::vector<View*> toDestroy;
std::copy_if(me->model_->views.begin(), me->model_->views.end(), std::back_inserter(toDestroy), [me](View* view) -> bool {
auto* w = dynamic_cast<Vindow*>(view);
if(w == me) return false;
return w != nullptr;
});
for(auto* view : toDestroy)
{
auto* w = dynamic_cast<Vindow*>(view);
if(w) destroy_window(w);
}
return destroy_window(me);
}
void Vindow::HelpAbout(Fl_Widget*, void*)
{
fl_alert("JakBeat GUI\nCopyright (c) 2015-2017 Vlad Meșco\nAvailable under the 2-Clause BSD License");
}
void Vindow::WhatClicked(Fl_Widget* w, void* p)
{
Vindow* me = (Vindow*)p;
const char* label = w->label();
me->SetLayout(Layout::WHAT, label);
}
void Vindow::WhoClicked(Fl_Widget* w, void* p)
{
Vindow* me = (Vindow*)p;
const char* label = w->label();
me->SetLayout(Layout::WHO, label);
}
void Vindow::OutputClicked(Fl_Widget* w, void* p)
{
Vindow* me = (Vindow*)p;
me->SetLayout(Layout::OUTPUT);
}
void Vindow::WindowCallback(Fl_Widget* w, void* p)
{
WindowClose(w, p);
}
void Vindow::WhoNameChanged(Fl_Widget* w, void* p)
{
auto* inp = (Fl_Input*)w;
auto* me = (Vindow*)p;
const char* newName = inp->value();
const char* oldName = me->active_.c_str();
assert(newName);
if(std::any_of(me->model_->whos.begin(), me->model_->whos.end(), [newName](WhoEntry const& e) -> bool {
return e.name == newName;
})
|| *newName == '\0')
{
fl_alert("Name needs to be unique and not null");
inp->value(oldName);
//Fl::focus(inp); // doesn't work because e.g. the tab key is
// handled later...
return;
}
Control ctrl(me->model_, me);
ctrl.SetWhosName(oldName, newName);
}
<|endoftext|> |
<commit_before>#include "../Functionalities.h"
#include <vector>
#include <string>
#include "../../Fuzzy.h"
#include "../../language/Grammar.h"
#include "../../util/Point3i.h"
#include "../../util/Sysout.h"
#include "../../world/World.h"
#include "../../world/Player.h"
#include "../../world/Room.h"
bool Move::execute(gmr::SentenceState* stnc, std::vector<std::string>* argumentWords, std::string alias)
{
if(argumentWords->size() == 0)
{
Sysout::println("Specify a direction.");
return false;
}
if(alias == "go")
{
return Fuzzy::runningGame->runCommandFromRawInput(argumentWords);
}
Player* player = Fuzzy::runningGame->player;
Point3i playerWorldLocation = player->getRoomLocation()->getWorldLocation();
World* world = player->getRoomLocation()->getWorld();
if(argumentWords->front() == "east")
{
Sysout::println("You moved east.");
player->setRoomLocation(world->getRoom(playerWorldLocation + Point3i(1, 0, 0)));
}
if(argumentWords->front() == "west")
{
Sysout::println("You moved west.");
player->setRoomLocation(world->getRoom(playerWorldLocation + Point3i(-1, 0, 0)));
}
if(argumentWords->front() == "south")
{
Sysout::println("You moved south.");
player->setRoomLocation(world->getRoom(playerWorldLocation + Point3i(0, 0, 1)));
}
if(argumentWords->front() == "north")
{
Sysout::println("You moved north.");
player->setRoomLocation(world->getRoom(playerWorldLocation + Point3i(0, 0, -1)));
}
Fuzzy::runningGame->runCommandFromSudoInput("look");
return true;
}
<commit_msg>Allows for actual "go north"<commit_after>#include "../Functionalities.h"
#include <vector>
#include <string>
#include "../../Fuzzy.h"
#include "../../language/Grammar.h"
#include "../../util/Point3i.h"
#include "../../util/Sysout.h"
#include "../../world/World.h"
#include "../../world/Player.h"
#include "../../world/Room.h"
bool Move::execute(gmr::SentenceState* stnc, std::vector<std::string>* argumentWords, std::string alias)
{
if(argumentWords->size() == 0)
{
Sysout::println("Specify a direction.");
return false;
}
if(alias == "go")
{
bool subCmdSuccess = Fuzzy::runningGame->runCommandFromRawInput(argumentWords);
if(subCmdSuccess)
{
return true;
}
}
Player* player = Fuzzy::runningGame->player;
Point3i playerWorldLocation = player->getRoomLocation()->getWorldLocation();
World* world = player->getRoomLocation()->getWorld();
if(argumentWords->front() == "east")
{
Sysout::println("You moved east.");
player->setRoomLocation(world->getRoom(playerWorldLocation + Point3i(1, 0, 0)));
}
if(argumentWords->front() == "west")
{
Sysout::println("You moved west.");
player->setRoomLocation(world->getRoom(playerWorldLocation + Point3i(-1, 0, 0)));
}
if(argumentWords->front() == "south")
{
Sysout::println("You moved south.");
player->setRoomLocation(world->getRoom(playerWorldLocation + Point3i(0, 0, 1)));
}
if(argumentWords->front() == "north")
{
Sysout::println("You moved north.");
player->setRoomLocation(world->getRoom(playerWorldLocation + Point3i(0, 0, -1)));
}
Fuzzy::runningGame->runCommandFromSudoInput("look");
return true;
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* $RCSfile: javaldx.cxx,v $
*
* $Revision: 1.6 $
*
* last change: $Author: rt $ $Date: 2004-10-28 16:24:18 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "sal/main.h"
#include "sal/types.h"
#include "osl/thread.h"
#include "rtl/ustring.hxx"
#include "rtl/byteseq.hxx"
#include "jvmfwk/framework.h"
using namespace rtl;
#define OUSTR(x) OUString(RTL_CONSTASCII_USTRINGPARAM( x ))
static sal_Bool hasOption(char* szOption, int argc, char** argv);
static rtl::OString getLD_LIBRARY_PATH(const rtl::ByteSequence & vendorData);
//static sal_Bool printPaths(const OUString& sPathFile);
#define HELP_TEXT \
"\njavaldx is necessary to make Java work on some UNIX platforms." \
"It prints a string to std out that consists of directories which " \
"have to be included into the LD_LIBRARY_PATH variable.The setting of " \
"the variable usually occurs in a shell script that runs javaldx.\n" \
"The directories are from the chosen java installation. \n" \
"Options are: \n"\
"--help or -h\n"
SAL_IMPLEMENT_MAIN_WITH_ARGS(argc, argv)
{
if( hasOption("--help",argc, argv) || hasOption("-h", argc, argv))
{
fprintf(stdout, HELP_TEXT);// default
return 0;
}
sal_Bool bEnabled = sal_False;
if (jfw_getEnabled( & bEnabled) != JFW_E_NONE)
{
fprintf(stderr,"javaldx failed! \n");
return -1;
}
if (bEnabled == sal_False)
{
//Do not do any preparation because that may only slow startup time.
return 0;
}
JavaInfo * pInfo = NULL;
javaFrameworkError errcode = JFW_E_NONE;
errcode = jfw_getSelectedJRE( & pInfo);
if (errcode == JFW_E_INVALID_SETTINGS)
{
fprintf(stderr,"javaldx failed. User must select a JRE from options dialog!");
return -1;
}
else if (errcode != JFW_E_NONE)
{
fprintf(stderr,"javaldx failed! \n");
return -1;
}
if (pInfo == NULL)
{
errcode = jfw_findAndSelectJRE( & pInfo);
if (errcode == JFW_E_NO_JAVA_FOUND)
{
fprintf(stderr,"javaldx: Could not find a Java Runtime Environment! \n");
return 0;
}
else if (errcode != JFW_E_NONE)
{
fprintf(stderr,"javaldx failed!\n");
return -1;
}
}
//Only do something if the sunjavaplugin created this JavaInfo
rtl::OUString sVendor1(RTL_CONSTASCII_USTRINGPARAM("Sun Microsystems Inc."));
rtl::OUString sVendor2(RTL_CONSTASCII_USTRINGPARAM("IBM Corporation"));
rtl::OUString sVendor3(RTL_CONSTASCII_USTRINGPARAM("Blackdown Java-Linux Team"));
rtl::OUString sVendor4(RTL_CONSTASCII_USTRINGPARAM("Apple Computer, Inc."));
if ( ! (sVendor1.equals(pInfo->sVendor) == sal_True
|| sVendor2.equals(pInfo->sVendor) == sal_True
|| sVendor3.equals(pInfo->sVendor) == sal_True
|| sVendor4.equals(pInfo->sVendor) == sal_True))
return 0;
rtl::OString sPaths = getLD_LIBRARY_PATH(pInfo->arVendorData);
fprintf(stdout, "%s\n", sPaths.getStr());
jfw_freeJavaInfo(pInfo);
return 0;
}
rtl::OString getLD_LIBRARY_PATH(const rtl::ByteSequence & vendorData)
{
const sal_Unicode* chars = (sal_Unicode*) vendorData.getConstArray();
sal_Int32 len = vendorData.getLength();
rtl::OUString sData(chars, len / 2);
//the runtime lib is on the first line
sal_Int32 index = 0;
rtl::OUString aToken = sData.getToken( 1, '\n', index);
rtl::OString paths =
rtl::OUStringToOString(aToken, osl_getThreadTextEncoding());
return paths;
}
static sal_Bool hasOption(char* szOption, int argc, char** argv)
{
sal_Bool retVal= sal_False;
for(sal_Int16 i= 1; i < argc; i++)
{
if( ! strcmp(argv[i], szOption))
{
retVal= sal_True;
break;
}
}
return retVal;
}
<commit_msg>INTEGRATION: CWS jl13 (1.5.10); FILE MERGED 2004/09/30 14:39:31 jl 1.5.10.1: #i29390#<commit_after>/*************************************************************************
*
* $RCSfile: javaldx.cxx,v $
*
* $Revision: 1.7 $
*
* last change: $Author: hr $ $Date: 2004-11-09 13:58:34 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "sal/main.h"
#include "sal/types.h"
#include "osl/thread.h"
#include "rtl/ustring.hxx"
#include "rtl/byteseq.hxx"
#include "jvmfwk/framework.h"
using namespace rtl;
#define OUSTR(x) OUString(RTL_CONSTASCII_USTRINGPARAM( x ))
static sal_Bool hasOption(char* szOption, int argc, char** argv);
static rtl::OString getLD_LIBRARY_PATH(const rtl::ByteSequence & vendorData);
//static sal_Bool printPaths(const OUString& sPathFile);
#define HELP_TEXT \
"\njavaldx is necessary to make Java work on some UNIX platforms." \
"It prints a string to std out that consists of directories which " \
"have to be included into the LD_LIBRARY_PATH variable.The setting of " \
"the variable usually occurs in a shell script that runs javaldx.\n" \
"The directories are from the chosen java installation. \n" \
"Options are: \n"\
"--help or -h\n"
SAL_IMPLEMENT_MAIN_WITH_ARGS(argc, argv)
{
if( hasOption("--help",argc, argv) || hasOption("-h", argc, argv))
{
fprintf(stdout, HELP_TEXT);// default
return 0;
}
javaFrameworkError errcode = JFW_E_NONE;
sal_Bool bEnabled = sal_False;
errcode = jfw_getEnabled( & bEnabled);
if (errcode == JFW_E_NONE && bEnabled == sal_False)
{
//Do not do any preparation because that may only slow startup time.
return 0;
}
else if (errcode != JFW_E_NONE && errcode != JFW_E_DIRECT_MODE)
{
fprintf(stderr,"javaldx failed! \n");
return -1;
}
JavaInfo * pInfo = NULL;
errcode = jfw_getSelectedJRE( & pInfo);
if (errcode == JFW_E_INVALID_SETTINGS)
{
fprintf(stderr,"javaldx failed. User must select a JRE from options dialog!");
return -1;
}
else if (errcode != JFW_E_NONE)
{
fprintf(stderr,"javaldx failed! \n");
return -1;
}
if (pInfo == NULL)
{
errcode = jfw_findAndSelectJRE( & pInfo);
if (errcode == JFW_E_NO_JAVA_FOUND)
{
fprintf(stderr,"javaldx: Could not find a Java Runtime Environment! \n");
return 0;
}
else if (errcode != JFW_E_NONE && errcode != JFW_E_DIRECT_MODE)
{
fprintf(stderr,"javaldx failed!\n");
return -1;
}
}
//Only do something if the sunjavaplugin created this JavaInfo
rtl::OUString sVendor1(RTL_CONSTASCII_USTRINGPARAM("Sun Microsystems Inc."));
rtl::OUString sVendor2(RTL_CONSTASCII_USTRINGPARAM("IBM Corporation"));
rtl::OUString sVendor3(RTL_CONSTASCII_USTRINGPARAM("Blackdown Java-Linux Team"));
rtl::OUString sVendor4(RTL_CONSTASCII_USTRINGPARAM("Apple Computer, Inc."));
if ( ! (sVendor1.equals(pInfo->sVendor) == sal_True
|| sVendor2.equals(pInfo->sVendor) == sal_True
|| sVendor3.equals(pInfo->sVendor) == sal_True
|| sVendor4.equals(pInfo->sVendor) == sal_True))
return 0;
rtl::OString sPaths = getLD_LIBRARY_PATH(pInfo->arVendorData);
fprintf(stdout, "%s\n", sPaths.getStr());
jfw_freeJavaInfo(pInfo);
return 0;
}
rtl::OString getLD_LIBRARY_PATH(const rtl::ByteSequence & vendorData)
{
const sal_Unicode* chars = (sal_Unicode*) vendorData.getConstArray();
sal_Int32 len = vendorData.getLength();
rtl::OUString sData(chars, len / 2);
//the runtime lib is on the first line
sal_Int32 index = 0;
rtl::OUString aToken = sData.getToken( 1, '\n', index);
rtl::OString paths =
rtl::OUStringToOString(aToken, osl_getThreadTextEncoding());
return paths;
}
static sal_Bool hasOption(char* szOption, int argc, char** argv)
{
sal_Bool retVal= sal_False;
for(sal_Int16 i= 1; i < argc; i++)
{
if( ! strcmp(argv[i], szOption))
{
retVal= sal_True;
break;
}
}
return retVal;
}
<|endoftext|> |
<commit_before>#include "gvki/opencl_header.h"
#include <cstdlib>
#include "gvki/UnderlyingCaller.h"
#include "gvki/Logger.h"
#include "gvki/Debug.h"
#include <cassert>
#include <cstring>
#ifdef MACRO_LIB
#define API_SUFFIX _hook
#else
#define API_SUFFIX
#endif
// This macro appends API_SUFFIX to its argument
#define __DEFN(name, suffix) name ## suffix
#define _DEFN(name, suffix) __DEFN(name, suffix)
#define DEFN(name) _DEFN(name, API_SUFFIX)
using namespace std;
using namespace gvki;
extern "C" {
cl_mem
DEFN(clCreateBuffer)
(cl_context context,
cl_mem_flags flags,
size_t size,
void * host_ptr,
cl_int * errcode_ret
)
{
DEBUG_MSG("Intercepted clCreateBuffer()");
cl_int success = CL_SUCCESS;
cl_mem buffer = UnderlyingCaller::Singleton().clCreateBufferU(context, flags, size, host_ptr, &success);
if (success == CL_SUCCESS)
{
Logger& l = Logger::Singleton();
BufferInfo bi;
bi.size = size;
bi.data = host_ptr;
bi.flags = flags;
l.buffers[buffer] = bi;
}
if (errcode_ret)
*errcode_ret = success;
return buffer;
}
cl_mem
DEFN(clCreateSubBuffer)
(cl_mem buffer,
cl_mem_flags flags,
cl_buffer_create_type buffer_create_type,
const void * buffer_create_info,
cl_int * errcode_ret)
{
DEBUG_MSG("Intercepted clCreateSubBuffer()");
ERROR_MSG("Not supported!!");
exit(1);
}
cl_mem
DEFN(clCreateImage2D)
(cl_context context,
cl_mem_flags flags,
const cl_image_format * image_format,
size_t image_width,
size_t image_height,
size_t image_row_pitch,
void * host_ptr,
cl_int * errcode_ret)
{
DEBUG_MSG("Intercepted clCreate2DImage()");
cl_int success = CL_SUCCESS;
cl_mem img = UnderlyingCaller::Singleton().clCreateImage2DU(context,
flags,
image_format,
image_width,
image_height,
image_row_pitch,
host_ptr,
&success);
if (success == CL_SUCCESS)
{
Logger& l = Logger::Singleton();
ImageInfo ii;
ii.flags = flags;
ii.type = CL_MEM_OBJECT_IMAGE2D;
l.images[img] = ii;
}
if (errcode_ret)
*errcode_ret = success;
return img;
}
cl_mem
DEFN(clCreateImage3D)
(cl_context context,
cl_mem_flags flags,
const cl_image_format * image_format,
size_t image_width,
size_t image_height,
size_t image_depth,
size_t image_row_pitch,
size_t image_slice_pitch,
void * host_ptr,
cl_int * errcode_ret)
{
DEBUG_MSG("Intercepted clCreate2DImage()");
cl_int success = CL_SUCCESS;
cl_mem img = UnderlyingCaller::Singleton().clCreateImage3DU(context,
flags,
image_format,
image_width,
image_height,
image_depth,
image_row_pitch,
image_slice_pitch,
host_ptr,
&success);
if (success == CL_SUCCESS)
{
Logger& l = Logger::Singleton();
ImageInfo ii;
ii.flags = flags;
ii.type = CL_MEM_OBJECT_IMAGE3D;
l.images[img] = ii;
}
if (errcode_ret)
*errcode_ret = success;
return img;
}
#ifdef CL_VERSION_1_2
cl_mem
DEFN(clCreateImage)
(cl_context context,
cl_mem_flags flags,
const cl_image_format* image_format,
const cl_image_desc* image_desc,
void* host_ptr,
cl_int* errcode_ret)
{
DEBUG_MSG("Intercepted clCreateImage()");
cl_int success = CL_SUCCESS;
cl_mem img = UnderlyingCaller::Singleton().clCreateImageU(context,
flags,
image_format,
image_desc,
host_ptr,
&success
);
if (success == CL_SUCCESS)
{
Logger& l = Logger::Singleton();
ImageInfo ii;
ii.flags = flags;
ii.type = image_desc->image_type;
l.images[img] = ii;
}
if (errcode_ret)
*errcode_ret = success;
return img;
}
#endif
cl_sampler
DEFN(clCreateSampler)
(cl_context context,
cl_bool normalized_coords,
cl_addressing_mode addressing_mode,
cl_filter_mode filter_mode,
cl_int * errcode_ret)
{
DEBUG_MSG("Intercepted clCreateSampler()");
cl_int success = CL_SUCCESS;
cl_sampler sampler = UnderlyingCaller::Singleton().clCreateSamplerU(context,
normalized_coords,
addressing_mode,
filter_mode,
&success
);
if (success == CL_SUCCESS)
{
Logger& l = Logger::Singleton();
SamplerInfo si;
si.normalized_coords = normalized_coords;
si.addressing_mode = addressing_mode;
si.filter_mode = filter_mode;
l.samplers[sampler] = si;
}
if (errcode_ret != NULL)
*errcode_ret = success;
return sampler;
}
/* 5.6 Program objects */
cl_program
DEFN(clCreateProgramWithSource)
(cl_context context,
cl_uint count,
const char ** strings,
const size_t * lengths,
cl_int * errcode_ret
)
{
DEBUG_MSG("Intercepted clCreateProgramWithSource()");
cl_int success = CL_SUCCESS;
cl_program program = UnderlyingCaller::Singleton().clCreateProgramWithSourceU(context, count, strings, lengths, &success);
if (success == CL_SUCCESS)
{
Logger& l = Logger::Singleton();
l.programs[program] = ProgramInfo();
// Make sure we work on the version in the container
// so we don't do lots of unnecessary copies
ProgramInfo& pi = l.programs[program];
if (lengths == NULL)
{
// All strings are null terminated
for (int pIndex=0; pIndex < count; ++pIndex)
{
pi.sources.push_back(std::string(strings[pIndex]));
}
}
else
{
// The user has specified the string length
for (int pIndex=0; pIndex < count; ++pIndex)
{
if (lengths[pIndex] == 0)
{
// This particular string is null terminated
pi.sources.push_back(std::string(strings[pIndex]));
}
else
{
size_t length = lengths[pIndex];
pi.sources.push_back(std::string(strings[pIndex], length));
}
}
}
}
if (errcode_ret)
*errcode_ret = success;
return program;
}
cl_int
DEFN(clBuildProgram)
(cl_program program,
cl_uint num_devices,
const cl_device_id * device_list,
const char * options,
void (*pfn_notify)(cl_program /* program */, void * /* user_data */),
void * user_data
)
{
DEBUG_MSG("Intercepted clCreateBuildProgram()");
cl_int success = UnderlyingCaller::Singleton().clBuildProgramU(program,
num_devices,
device_list,
options,
pfn_notify,
user_data);
if (success == CL_SUCCESS)
{
Logger& l = Logger::Singleton();
assert(l.programs.count(program) == 1 && "Program was not logged!");
// Make sure we work on the version in the container
// so we don't do lots of unnecessary copies
ProgramInfo& pi = l.programs[program];
if (options != NULL)
{
pi.compileFlags = std::string(options);
}
else
{
pi.compileFlags = std::string("");
}
}
return success;
}
/* 5.7 Kernel objects */
cl_kernel
DEFN(clCreateKernel)
(cl_program program,
const char * kernel_name,
cl_int * errcode_ret
)
{
DEBUG_MSG("Intercepted clCreateKernel()");
cl_int success = CL_SUCCESS;
cl_kernel kernel = UnderlyingCaller::Singleton().clCreateKernelU(program, kernel_name, errcode_ret);
if ( success == CL_SUCCESS)
{
Logger& l = Logger::Singleton();
l.kernels[kernel] = KernelInfo();
assert(l.programs.count(program) == 1 && "Program was not logged!");
// Make sure we work on the version in the container
// so we don't do lots of unnecessary copies
KernelInfo& ki = l.kernels[kernel];
ki.program = program;
ki.entryPointName = std::string(kernel_name);
}
if (errcode_ret)
*errcode_ret = success;
return kernel;
}
cl_int
DEFN(clCreateKernelsInProgram)
(cl_program program,
cl_uint num_kernels,
cl_kernel * kernels,
cl_uint * num_kernels_ret
)
{
DEBUG_MSG("Intercepted clCreatKernelsInProgram()");
cl_int success = CL_SUCCESS;
success = UnderlyingCaller::Singleton().clCreateKernelsInProgramU(program, num_kernels, kernels, num_kernels_ret);
if (success == CL_SUCCESS && kernels != NULL)
{
Logger& l = Logger::Singleton();
assert(num_kernels > 0 && "num_kernels had an invalid value");
assert(l.programs.count(program) == 1 && "Program was not logged!");
for(int i=0; i < num_kernels; ++i)
{
cl_kernel k = kernels[i];
l.kernels[k] = KernelInfo();
// Make sure we work on the version in the container
KernelInfo& ki = l.kernels[k];
ki.program = program;
// Get the entry point name
size_t stringSize = 0;
cl_int genSuccess = clGetKernelInfo(k,
CL_KERNEL_FUNCTION_NAME,
0,
NULL,
&stringSize
);
if (genSuccess != CL_SUCCESS)
{
ERROR_MSG("Failed to get size of kernel name");
exit(1);
}
assert(stringSize > 0);
char* kernelName = (char*) malloc(sizeof(char)*stringSize);
if (kernelName == NULL)
{
ERROR_MSG("Failed to malloc() memory for cstring of size " << stringSize);
exit(1);
}
genSuccess = clGetKernelInfo(k,
CL_KERNEL_FUNCTION_NAME,
stringSize,
kernelName,
NULL
);
if (genSuccess != CL_SUCCESS)
{
ERROR_MSG("Failed to get kernel name");
exit(1);
}
ki.entryPointName = std::string(kernelName);
DEBUG_MSG("Kernel \"" << ki.entryPointName << "\" created");
free(kernelName);
}
}
return success;
}
cl_int
DEFN(clSetKernelArg)
(cl_kernel kernel,
cl_uint arg_index,
size_t arg_size,
const void * arg_value)
{
DEBUG_MSG("Intercepted clSetKernelArg()");
cl_int success = UnderlyingCaller::Singleton().clSetKernelArgU(kernel,
arg_index,
arg_size,
arg_value);
if (success == CL_SUCCESS)
{
Logger& l = Logger::Singleton();
assert (l.kernels.count(kernel) == 1 && "Kernel was not logged");
KernelInfo& ki = l.kernels[kernel];
// Resize arguments vector if necessary
if (ki.arguments.size() <= arg_index)
ki.arguments.resize(arg_index +1);
ArgInfo& ai = ki.arguments[arg_index];
if (ai.argValue != NULL)
{
// We must have malloc()'ed from a previous call to this
// function so free the pointer
free((void*) ai.argValue);
}
// The user is allowed to do whatever
// they want with the memory pointed
// to by ``arg_value`` so we need to
// copy its contents.
//
// FIXME: We aren't always free'ing the memory
// allocated here because we aren't tracking
// cl_kernel or cl_context destruction
ai.argValue = malloc(arg_size);
memcpy((void*) ai.argValue, arg_value, arg_size);
ai.argSize = arg_size;
ki.arguments[arg_index] = ai;
}
return success;
}
/* 5.8 Executing kernels */
cl_int
DEFN(clEnqueueNDRangeKernel)
(cl_command_queue command_queue,
cl_kernel kernel,
cl_uint work_dim,
const size_t * global_work_offset,
const size_t * global_work_size,
const size_t * local_work_size,
cl_uint num_events_in_wait_list,
const cl_event * event_wait_list,
cl_event * event
)
{
DEBUG_MSG("Intercepted clEnqueueNDRangeKernel()");
cl_int success = UnderlyingCaller::Singleton().clEnqueueNDRangeKernelU(command_queue,
kernel,
work_dim,
global_work_offset,
global_work_size,
local_work_size,
num_events_in_wait_list,
event_wait_list,
event);
if (success == CL_SUCCESS)
{
// TODO: Log
Logger& l = Logger::Singleton();
assert(l.kernels.count(kernel) == 1 && "kernel was not logged");
KernelInfo& ki = l.kernels[kernel];
ki.dimensions = work_dim;
// Resize recorded NDRange vectors if necessary
if (ki.globalWorkOffset.size() != work_dim)
ki.globalWorkOffset.resize(work_dim);
if (ki.globalWorkSize.size() != work_dim)
ki.globalWorkSize.resize(work_dim);
if (ki.localWorkSize.size() != work_dim)
ki.localWorkSize.resize(work_dim);
for (int dim=0; dim < work_dim; ++dim)
{
if (global_work_offset != NULL)
{
ki.globalWorkOffset[dim] = global_work_offset[dim];
}
else
{
ki.globalWorkOffset[dim] = 0;
}
ki.globalWorkSize[dim] = global_work_size[dim];
if (local_work_size != NULL)
{
ki.localWorkSize[dim] = local_work_size[dim];
}
else
{
// It is implementation defined how to divide the NDRange
// in this case. We will make the same size as the global_work_size
// so that there is a single work group.
ki.localWorkSize[dim] = global_work_size[dim];
}
}
// Log stuff now.
// We need to do this now because the kernel information
// might be modified later.
l.dump(kernel);
}
return success;
}
}
<commit_msg>Improve KernelInfo.arguments initialisation. The size of the vector should never change so we should just initialise it when the cl_kernel object is created.<commit_after>#include "gvki/opencl_header.h"
#include <cstdlib>
#include "gvki/UnderlyingCaller.h"
#include "gvki/Logger.h"
#include "gvki/Debug.h"
#include <cassert>
#include <cstring>
#ifdef MACRO_LIB
#define API_SUFFIX _hook
#else
#define API_SUFFIX
#endif
// This macro appends API_SUFFIX to its argument
#define __DEFN(name, suffix) name ## suffix
#define _DEFN(name, suffix) __DEFN(name, suffix)
#define DEFN(name) _DEFN(name, API_SUFFIX)
using namespace std;
using namespace gvki;
extern "C" {
cl_mem
DEFN(clCreateBuffer)
(cl_context context,
cl_mem_flags flags,
size_t size,
void * host_ptr,
cl_int * errcode_ret
)
{
DEBUG_MSG("Intercepted clCreateBuffer()");
cl_int success = CL_SUCCESS;
cl_mem buffer = UnderlyingCaller::Singleton().clCreateBufferU(context, flags, size, host_ptr, &success);
if (success == CL_SUCCESS)
{
Logger& l = Logger::Singleton();
BufferInfo bi;
bi.size = size;
bi.data = host_ptr;
bi.flags = flags;
l.buffers[buffer] = bi;
}
if (errcode_ret)
*errcode_ret = success;
return buffer;
}
cl_mem
DEFN(clCreateSubBuffer)
(cl_mem buffer,
cl_mem_flags flags,
cl_buffer_create_type buffer_create_type,
const void * buffer_create_info,
cl_int * errcode_ret)
{
DEBUG_MSG("Intercepted clCreateSubBuffer()");
ERROR_MSG("Not supported!!");
exit(1);
}
cl_mem
DEFN(clCreateImage2D)
(cl_context context,
cl_mem_flags flags,
const cl_image_format * image_format,
size_t image_width,
size_t image_height,
size_t image_row_pitch,
void * host_ptr,
cl_int * errcode_ret)
{
DEBUG_MSG("Intercepted clCreate2DImage()");
cl_int success = CL_SUCCESS;
cl_mem img = UnderlyingCaller::Singleton().clCreateImage2DU(context,
flags,
image_format,
image_width,
image_height,
image_row_pitch,
host_ptr,
&success);
if (success == CL_SUCCESS)
{
Logger& l = Logger::Singleton();
ImageInfo ii;
ii.flags = flags;
ii.type = CL_MEM_OBJECT_IMAGE2D;
l.images[img] = ii;
}
if (errcode_ret)
*errcode_ret = success;
return img;
}
cl_mem
DEFN(clCreateImage3D)
(cl_context context,
cl_mem_flags flags,
const cl_image_format * image_format,
size_t image_width,
size_t image_height,
size_t image_depth,
size_t image_row_pitch,
size_t image_slice_pitch,
void * host_ptr,
cl_int * errcode_ret)
{
DEBUG_MSG("Intercepted clCreate2DImage()");
cl_int success = CL_SUCCESS;
cl_mem img = UnderlyingCaller::Singleton().clCreateImage3DU(context,
flags,
image_format,
image_width,
image_height,
image_depth,
image_row_pitch,
image_slice_pitch,
host_ptr,
&success);
if (success == CL_SUCCESS)
{
Logger& l = Logger::Singleton();
ImageInfo ii;
ii.flags = flags;
ii.type = CL_MEM_OBJECT_IMAGE3D;
l.images[img] = ii;
}
if (errcode_ret)
*errcode_ret = success;
return img;
}
#ifdef CL_VERSION_1_2
cl_mem
DEFN(clCreateImage)
(cl_context context,
cl_mem_flags flags,
const cl_image_format* image_format,
const cl_image_desc* image_desc,
void* host_ptr,
cl_int* errcode_ret)
{
DEBUG_MSG("Intercepted clCreateImage()");
cl_int success = CL_SUCCESS;
cl_mem img = UnderlyingCaller::Singleton().clCreateImageU(context,
flags,
image_format,
image_desc,
host_ptr,
&success
);
if (success == CL_SUCCESS)
{
Logger& l = Logger::Singleton();
ImageInfo ii;
ii.flags = flags;
ii.type = image_desc->image_type;
l.images[img] = ii;
}
if (errcode_ret)
*errcode_ret = success;
return img;
}
#endif
cl_sampler
DEFN(clCreateSampler)
(cl_context context,
cl_bool normalized_coords,
cl_addressing_mode addressing_mode,
cl_filter_mode filter_mode,
cl_int * errcode_ret)
{
DEBUG_MSG("Intercepted clCreateSampler()");
cl_int success = CL_SUCCESS;
cl_sampler sampler = UnderlyingCaller::Singleton().clCreateSamplerU(context,
normalized_coords,
addressing_mode,
filter_mode,
&success
);
if (success == CL_SUCCESS)
{
Logger& l = Logger::Singleton();
SamplerInfo si;
si.normalized_coords = normalized_coords;
si.addressing_mode = addressing_mode;
si.filter_mode = filter_mode;
l.samplers[sampler] = si;
}
if (errcode_ret != NULL)
*errcode_ret = success;
return sampler;
}
/* 5.6 Program objects */
cl_program
DEFN(clCreateProgramWithSource)
(cl_context context,
cl_uint count,
const char ** strings,
const size_t * lengths,
cl_int * errcode_ret
)
{
DEBUG_MSG("Intercepted clCreateProgramWithSource()");
cl_int success = CL_SUCCESS;
cl_program program = UnderlyingCaller::Singleton().clCreateProgramWithSourceU(context, count, strings, lengths, &success);
if (success == CL_SUCCESS)
{
Logger& l = Logger::Singleton();
l.programs[program] = ProgramInfo();
// Make sure we work on the version in the container
// so we don't do lots of unnecessary copies
ProgramInfo& pi = l.programs[program];
if (lengths == NULL)
{
// All strings are null terminated
for (int pIndex=0; pIndex < count; ++pIndex)
{
pi.sources.push_back(std::string(strings[pIndex]));
}
}
else
{
// The user has specified the string length
for (int pIndex=0; pIndex < count; ++pIndex)
{
if (lengths[pIndex] == 0)
{
// This particular string is null terminated
pi.sources.push_back(std::string(strings[pIndex]));
}
else
{
size_t length = lengths[pIndex];
pi.sources.push_back(std::string(strings[pIndex], length));
}
}
}
}
if (errcode_ret)
*errcode_ret = success;
return program;
}
cl_int
DEFN(clBuildProgram)
(cl_program program,
cl_uint num_devices,
const cl_device_id * device_list,
const char * options,
void (*pfn_notify)(cl_program /* program */, void * /* user_data */),
void * user_data
)
{
DEBUG_MSG("Intercepted clCreateBuildProgram()");
cl_int success = UnderlyingCaller::Singleton().clBuildProgramU(program,
num_devices,
device_list,
options,
pfn_notify,
user_data);
if (success == CL_SUCCESS)
{
Logger& l = Logger::Singleton();
assert(l.programs.count(program) == 1 && "Program was not logged!");
// Make sure we work on the version in the container
// so we don't do lots of unnecessary copies
ProgramInfo& pi = l.programs[program];
if (options != NULL)
{
pi.compileFlags = std::string(options);
}
else
{
pi.compileFlags = std::string("");
}
}
return success;
}
/* 5.7 Kernel objects */
void static gvkiSetupKernelArguments(cl_kernel kernel, KernelInfo& ki)
{
cl_uint numberOfArgs = 0;
cl_int success = clGetKernelInfo(kernel,
CL_KERNEL_NUM_ARGS,
sizeof(cl_uint),
&numberOfArgs,
NULL
);
if (success != CL_SUCCESS)
{
ERROR_MSG("Failed to determine number of arguments to kernel");
exit(1);
}
assert(ki.arguments.size() == 0 && "arguments should not have been initialised already");
assert(numberOfArgs > 0 && "numberOfArgs should be greater than zero");
// Set the size of the arguments vector. This never change
for (cl_uint index=0; index < numberOfArgs; ++index)
{
ki.arguments.push_back( ArgInfo() );
}
}
cl_kernel
DEFN(clCreateKernel)
(cl_program program,
const char * kernel_name,
cl_int * errcode_ret
)
{
DEBUG_MSG("Intercepted clCreateKernel()");
cl_int success = CL_SUCCESS;
cl_kernel kernel = UnderlyingCaller::Singleton().clCreateKernelU(program, kernel_name, errcode_ret);
if ( success == CL_SUCCESS)
{
Logger& l = Logger::Singleton();
l.kernels[kernel] = KernelInfo();
assert(l.programs.count(program) == 1 && "Program was not logged!");
// Make sure we work on the version in the container
// so we don't do lots of unnecessary copies
KernelInfo& ki = l.kernels[kernel];
ki.program = program;
ki.entryPointName = std::string(kernel_name);
gvkiSetupKernelArguments(kernel, ki);
DEBUG_MSG("Kernel \"" << ki.entryPointName << "\" created");
}
if (errcode_ret)
*errcode_ret = success;
return kernel;
}
cl_int
DEFN(clCreateKernelsInProgram)
(cl_program program,
cl_uint num_kernels,
cl_kernel * kernels,
cl_uint * num_kernels_ret
)
{
DEBUG_MSG("Intercepted clCreatKernelsInProgram()");
cl_int success = CL_SUCCESS;
success = UnderlyingCaller::Singleton().clCreateKernelsInProgramU(program, num_kernels, kernels, num_kernels_ret);
if (success == CL_SUCCESS && kernels != NULL)
{
Logger& l = Logger::Singleton();
assert(num_kernels > 0 && "num_kernels had an invalid value");
assert(l.programs.count(program) == 1 && "Program was not logged!");
for(int i=0; i < num_kernels; ++i)
{
cl_kernel k = kernels[i];
l.kernels[k] = KernelInfo();
// Make sure we work on the version in the container
KernelInfo& ki = l.kernels[k];
ki.program = program;
// Get the entry point name
size_t stringSize = 0;
cl_int genSuccess = clGetKernelInfo(k,
CL_KERNEL_FUNCTION_NAME,
0,
NULL,
&stringSize
);
if (genSuccess != CL_SUCCESS)
{
ERROR_MSG("Failed to get size of kernel name");
exit(1);
}
assert(stringSize > 0);
char* kernelName = (char*) malloc(sizeof(char)*stringSize);
if (kernelName == NULL)
{
ERROR_MSG("Failed to malloc() memory for cstring of size " << stringSize);
exit(1);
}
genSuccess = clGetKernelInfo(k,
CL_KERNEL_FUNCTION_NAME,
stringSize,
kernelName,
NULL
);
if (genSuccess != CL_SUCCESS)
{
ERROR_MSG("Failed to get kernel name");
exit(1);
}
ki.entryPointName = std::string(kernelName);
gvkiSetupKernelArguments(k, ki);
DEBUG_MSG("Kernel \"" << ki.entryPointName << "\" created");
free(kernelName);
}
}
return success;
}
cl_int
DEFN(clSetKernelArg)
(cl_kernel kernel,
cl_uint arg_index,
size_t arg_size,
const void * arg_value)
{
DEBUG_MSG("Intercepted clSetKernelArg()");
cl_int success = UnderlyingCaller::Singleton().clSetKernelArgU(kernel,
arg_index,
arg_size,
arg_value);
if (success == CL_SUCCESS)
{
Logger& l = Logger::Singleton();
assert (l.kernels.count(kernel) == 1 && "Kernel was not logged");
KernelInfo& ki = l.kernels[kernel];
assert(arg_index <= ( ki.arguments.size() -1) && "Invalid argument index for kernel");
ArgInfo& ai = ki.arguments[arg_index];
if (ai.argValue != NULL)
{
// We must have malloc()'ed from a previous call to this
// function so free the pointer
free((void*) ai.argValue);
}
// The user is allowed to do whatever
// they want with the memory pointed
// to by ``arg_value`` so we need to
// copy its contents.
//
// FIXME: We aren't always free'ing the memory
// allocated here because we aren't tracking
// cl_kernel or cl_context destruction
ai.argValue = malloc(arg_size);
memcpy((void*) ai.argValue, arg_value, arg_size);
ai.argSize = arg_size;
ki.arguments[arg_index] = ai;
}
return success;
}
/* 5.8 Executing kernels */
cl_int
DEFN(clEnqueueNDRangeKernel)
(cl_command_queue command_queue,
cl_kernel kernel,
cl_uint work_dim,
const size_t * global_work_offset,
const size_t * global_work_size,
const size_t * local_work_size,
cl_uint num_events_in_wait_list,
const cl_event * event_wait_list,
cl_event * event
)
{
DEBUG_MSG("Intercepted clEnqueueNDRangeKernel()");
cl_int success = UnderlyingCaller::Singleton().clEnqueueNDRangeKernelU(command_queue,
kernel,
work_dim,
global_work_offset,
global_work_size,
local_work_size,
num_events_in_wait_list,
event_wait_list,
event);
if (success == CL_SUCCESS)
{
// TODO: Log
Logger& l = Logger::Singleton();
assert(l.kernels.count(kernel) == 1 && "kernel was not logged");
KernelInfo& ki = l.kernels[kernel];
ki.dimensions = work_dim;
// Resize recorded NDRange vectors if necessary
if (ki.globalWorkOffset.size() != work_dim)
ki.globalWorkOffset.resize(work_dim);
if (ki.globalWorkSize.size() != work_dim)
ki.globalWorkSize.resize(work_dim);
if (ki.localWorkSize.size() != work_dim)
ki.localWorkSize.resize(work_dim);
for (int dim=0; dim < work_dim; ++dim)
{
if (global_work_offset != NULL)
{
ki.globalWorkOffset[dim] = global_work_offset[dim];
}
else
{
ki.globalWorkOffset[dim] = 0;
}
ki.globalWorkSize[dim] = global_work_size[dim];
if (local_work_size != NULL)
{
ki.localWorkSize[dim] = local_work_size[dim];
}
else
{
// It is implementation defined how to divide the NDRange
// in this case. We will make the same size as the global_work_size
// so that there is a single work group.
ki.localWorkSize[dim] = global_work_size[dim];
}
}
// Log stuff now.
// We need to do this now because the kernel information
// might be modified later.
l.dump(kernel);
}
return success;
}
}
<|endoftext|> |
<commit_before>// Copyright (c) 2010, Google Inc.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
// Unit tests for FileID
#include <elf.h>
#include <stdlib.h>
#include <string>
#include "common/linux/file_id.h"
#include "common/linux/safe_readlink.h"
#include "common/linux/synth_elf.h"
#include "common/test_assembler.h"
#include "common/tests/auto_tempdir.h"
#include "common/using_std_string.h"
#include "breakpad_googletest_includes.h"
using namespace google_breakpad;
using google_breakpad::SafeReadLink;
using google_breakpad::synth_elf::BuildIDNote;
using google_breakpad::synth_elf::ELF;
using google_breakpad::test_assembler::kLittleEndian;
using google_breakpad::test_assembler::Section;
namespace {
// Simply calling Section::Append(size, byte) produces a uninteresting pattern
// that tends to get hashed to 0000...0000. This populates the section with
// data to produce better hashes.
void PopulateSection(Section* section, int size, int prime_number) {
for (int i = 0; i < size; i++)
section->Append(1, (i % prime_number) % 256);
}
} // namespace
TEST(FileIDStripTest, StripSelf) {
// Calculate the File ID of this binary using
// FileID::ElfFileIdentifier, then make a copy of this binary,
// strip it, and ensure that the result is the same.
char exe_name[PATH_MAX];
ASSERT_TRUE(SafeReadLink("/proc/self/exe", exe_name));
// copy our binary to a temp file, and strip it
AutoTempDir temp_dir;
string templ = temp_dir.path() + "/file-id-unittest";
char cmdline[4096];
sprintf(cmdline, "cp \"%s\" \"%s\"", exe_name, templ.c_str());
ASSERT_EQ(0, system(cmdline)) << "Failed to execute: " << cmdline;
sprintf(cmdline, "chmod u+w \"%s\"", templ.c_str());
ASSERT_EQ(0, system(cmdline)) << "Failed to execute: " << cmdline;
sprintf(cmdline, "strip \"%s\"", templ.c_str());
ASSERT_EQ(0, system(cmdline)) << "Failed to execute: " << cmdline;
uint8_t identifier1[sizeof(MDGUID)];
uint8_t identifier2[sizeof(MDGUID)];
FileID fileid1(exe_name);
EXPECT_TRUE(fileid1.ElfFileIdentifier(identifier1));
FileID fileid2(templ.c_str());
EXPECT_TRUE(fileid2.ElfFileIdentifier(identifier2));
char identifier_string1[37];
char identifier_string2[37];
FileID::ConvertIdentifierToString(identifier1, identifier_string1,
37);
FileID::ConvertIdentifierToString(identifier2, identifier_string2,
37);
EXPECT_STREQ(identifier_string1, identifier_string2);
}
class FileIDTest : public testing::Test {
public:
void GetElfContents(ELF& elf) {
string contents;
ASSERT_TRUE(elf.GetContents(&contents));
ASSERT_LT(0U, contents.size());
elfdata_v.clear();
elfdata_v.insert(elfdata_v.begin(), contents.begin(), contents.end());
elfdata = &elfdata_v[0];
}
vector<uint8_t> elfdata_v;
uint8_t* elfdata;
};
TEST_F(FileIDTest, ElfClass) {
uint8_t identifier[sizeof(MDGUID)];
const char expected_identifier_string[] =
"80808080-8080-0000-0000-008080808080";
char identifier_string[sizeof(expected_identifier_string)];
const size_t kTextSectionSize = 128;
ELF elf32(EM_386, ELFCLASS32, kLittleEndian);
Section text32(kLittleEndian);
for (size_t i = 0; i < kTextSectionSize; ++i) {
text32.D8(i * 3);
}
elf32.AddSection(".text", text32, SHT_PROGBITS);
elf32.Finish();
GetElfContents(elf32);
EXPECT_TRUE(FileID::ElfFileIdentifierFromMappedFile(elfdata, identifier));
FileID::ConvertIdentifierToString(identifier, identifier_string,
sizeof(identifier_string));
EXPECT_STREQ(expected_identifier_string, identifier_string);
memset(identifier, 0, sizeof(identifier));
memset(identifier_string, 0, sizeof(identifier_string));
ELF elf64(EM_X86_64, ELFCLASS64, kLittleEndian);
Section text64(kLittleEndian);
for (size_t i = 0; i < kTextSectionSize; ++i) {
text64.D8(i * 3);
}
elf64.AddSection(".text", text64, SHT_PROGBITS);
elf64.Finish();
GetElfContents(elf64);
EXPECT_TRUE(FileID::ElfFileIdentifierFromMappedFile(elfdata, identifier));
FileID::ConvertIdentifierToString(identifier, identifier_string,
sizeof(identifier_string));
EXPECT_STREQ(expected_identifier_string, identifier_string);
}
TEST_F(FileIDTest, BuildID) {
const uint8_t kExpectedIdentifier[sizeof(MDGUID)] =
{0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F};
char expected_identifier_string[] =
"00000000-0000-0000-0000-000000000000";
FileID::ConvertIdentifierToString(kExpectedIdentifier,
expected_identifier_string,
sizeof(expected_identifier_string));
uint8_t identifier[sizeof(MDGUID)];
char identifier_string[sizeof(expected_identifier_string)];
ELF elf32(EM_386, ELFCLASS32, kLittleEndian);
Section text(kLittleEndian);
text.Append(4096, 0);
elf32.AddSection(".text", text, SHT_PROGBITS);
BuildIDNote::AppendSection(elf32,
kExpectedIdentifier,
sizeof(kExpectedIdentifier));
elf32.Finish();
GetElfContents(elf32);
EXPECT_TRUE(FileID::ElfFileIdentifierFromMappedFile(elfdata, identifier));
FileID::ConvertIdentifierToString(identifier, identifier_string,
sizeof(identifier_string));
EXPECT_STREQ(expected_identifier_string, identifier_string);
memset(identifier, 0, sizeof(identifier));
memset(identifier_string, 0, sizeof(identifier_string));
ELF elf64(EM_X86_64, ELFCLASS64, kLittleEndian);
// Re-use empty text section from previous test
elf64.AddSection(".text", text, SHT_PROGBITS);
BuildIDNote::AppendSection(elf64,
kExpectedIdentifier,
sizeof(kExpectedIdentifier));
elf64.Finish();
GetElfContents(elf64);
EXPECT_TRUE(FileID::ElfFileIdentifierFromMappedFile(elfdata, identifier));
FileID::ConvertIdentifierToString(identifier, identifier_string,
sizeof(identifier_string));
EXPECT_STREQ(expected_identifier_string, identifier_string);
}
// Test to make sure two files with different text sections produce
// different hashes when not using a build id.
TEST_F(FileIDTest, UniqueHashes32) {
char identifier_string_1[] =
"00000000-0000-0000-0000-000000000000";
char identifier_string_2[] =
"00000000-0000-0000-0000-000000000000";
uint8_t identifier_1[sizeof(MDGUID)];
uint8_t identifier_2[sizeof(MDGUID)];
{
ELF elf1(EM_386, ELFCLASS32, kLittleEndian);
Section foo_1(kLittleEndian);
PopulateSection(&foo_1, 32, 5);
elf1.AddSection(".foo", foo_1, SHT_PROGBITS);
Section text_1(kLittleEndian);
PopulateSection(&text_1, 4096, 17);
elf1.AddSection(".text", text_1, SHT_PROGBITS);
elf1.Finish();
GetElfContents(elf1);
}
EXPECT_TRUE(FileID::ElfFileIdentifierFromMappedFile(elfdata, identifier_1));
FileID::ConvertIdentifierToString(identifier_1, identifier_string_1,
sizeof(identifier_string_1));
{
ELF elf2(EM_386, ELFCLASS32, kLittleEndian);
Section text_2(kLittleEndian);
Section foo_2(kLittleEndian);
PopulateSection(&foo_2, 32, 5);
elf2.AddSection(".foo", foo_2, SHT_PROGBITS);
PopulateSection(&text_2, 4096, 31);
elf2.AddSection(".text", text_2, SHT_PROGBITS);
elf2.Finish();
GetElfContents(elf2);
}
EXPECT_TRUE(FileID::ElfFileIdentifierFromMappedFile(elfdata, identifier_2));
FileID::ConvertIdentifierToString(identifier_2, identifier_string_2,
sizeof(identifier_string_2));
EXPECT_STRNE(identifier_string_1, identifier_string_2);
}
// Same as UniqueHashes32, for x86-64.
TEST_F(FileIDTest, UniqueHashes64) {
char identifier_string_1[] =
"00000000-0000-0000-0000-000000000000";
char identifier_string_2[] =
"00000000-0000-0000-0000-000000000000";
uint8_t identifier_1[sizeof(MDGUID)];
uint8_t identifier_2[sizeof(MDGUID)];
{
ELF elf1(EM_X86_64, ELFCLASS64, kLittleEndian);
Section foo_1(kLittleEndian);
PopulateSection(&foo_1, 32, 5);
elf1.AddSection(".foo", foo_1, SHT_PROGBITS);
Section text_1(kLittleEndian);
PopulateSection(&text_1, 4096, 17);
elf1.AddSection(".text", text_1, SHT_PROGBITS);
elf1.Finish();
GetElfContents(elf1);
}
EXPECT_TRUE(FileID::ElfFileIdentifierFromMappedFile(elfdata, identifier_1));
FileID::ConvertIdentifierToString(identifier_1, identifier_string_1,
sizeof(identifier_string_1));
{
ELF elf2(EM_X86_64, ELFCLASS64, kLittleEndian);
Section text_2(kLittleEndian);
Section foo_2(kLittleEndian);
PopulateSection(&foo_2, 32, 5);
elf2.AddSection(".foo", foo_2, SHT_PROGBITS);
PopulateSection(&text_2, 4096, 31);
elf2.AddSection(".text", text_2, SHT_PROGBITS);
elf2.Finish();
GetElfContents(elf2);
}
EXPECT_TRUE(FileID::ElfFileIdentifierFromMappedFile(elfdata, identifier_2));
FileID::ConvertIdentifierToString(identifier_2, identifier_string_2,
sizeof(identifier_string_2));
EXPECT_STRNE(identifier_string_1, identifier_string_2);
}
<commit_msg>Refactor file_id_unittest A=Mike Hommey <mh@glandium.org> R=ted at https://breakpad.appspot.com/543003/<commit_after>// Copyright (c) 2010, Google Inc.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
// Unit tests for FileID
#include <elf.h>
#include <stdlib.h>
#include <string>
#include "common/linux/elfutils.h"
#include "common/linux/file_id.h"
#include "common/linux/safe_readlink.h"
#include "common/linux/synth_elf.h"
#include "common/test_assembler.h"
#include "common/tests/auto_tempdir.h"
#include "common/using_std_string.h"
#include "breakpad_googletest_includes.h"
using namespace google_breakpad;
using google_breakpad::ElfClass32;
using google_breakpad::ElfClass64;
using google_breakpad::SafeReadLink;
using google_breakpad::synth_elf::BuildIDNote;
using google_breakpad::synth_elf::ELF;
using google_breakpad::test_assembler::kLittleEndian;
using google_breakpad::test_assembler::Section;
using ::testing::Types;
namespace {
// Simply calling Section::Append(size, byte) produces a uninteresting pattern
// that tends to get hashed to 0000...0000. This populates the section with
// data to produce better hashes.
void PopulateSection(Section* section, int size, int prime_number) {
for (int i = 0; i < size; i++)
section->Append(1, (i % prime_number) % 256);
}
} // namespace
TEST(FileIDStripTest, StripSelf) {
// Calculate the File ID of this binary using
// FileID::ElfFileIdentifier, then make a copy of this binary,
// strip it, and ensure that the result is the same.
char exe_name[PATH_MAX];
ASSERT_TRUE(SafeReadLink("/proc/self/exe", exe_name));
// copy our binary to a temp file, and strip it
AutoTempDir temp_dir;
string templ = temp_dir.path() + "/file-id-unittest";
char cmdline[4096];
sprintf(cmdline, "cp \"%s\" \"%s\"", exe_name, templ.c_str());
ASSERT_EQ(0, system(cmdline)) << "Failed to execute: " << cmdline;
sprintf(cmdline, "chmod u+w \"%s\"", templ.c_str());
ASSERT_EQ(0, system(cmdline)) << "Failed to execute: " << cmdline;
sprintf(cmdline, "strip \"%s\"", templ.c_str());
ASSERT_EQ(0, system(cmdline)) << "Failed to execute: " << cmdline;
uint8_t identifier1[sizeof(MDGUID)];
uint8_t identifier2[sizeof(MDGUID)];
FileID fileid1(exe_name);
EXPECT_TRUE(fileid1.ElfFileIdentifier(identifier1));
FileID fileid2(templ.c_str());
EXPECT_TRUE(fileid2.ElfFileIdentifier(identifier2));
char identifier_string1[37];
char identifier_string2[37];
FileID::ConvertIdentifierToString(identifier1, identifier_string1,
37);
FileID::ConvertIdentifierToString(identifier2, identifier_string2,
37);
EXPECT_STREQ(identifier_string1, identifier_string2);
}
template<typename ElfClass>
class FileIDTest : public testing::Test {
public:
void GetElfContents(ELF& elf) {
string contents;
ASSERT_TRUE(elf.GetContents(&contents));
ASSERT_LT(0U, contents.size());
elfdata_v.clear();
elfdata_v.insert(elfdata_v.begin(), contents.begin(), contents.end());
elfdata = &elfdata_v[0];
}
vector<uint8_t> elfdata_v;
uint8_t* elfdata;
};
typedef Types<ElfClass32, ElfClass64> ElfClasses;
TYPED_TEST_CASE(FileIDTest, ElfClasses);
TYPED_TEST(FileIDTest, ElfClass) {
uint8_t identifier[sizeof(MDGUID)];
const char expected_identifier_string[] =
"80808080-8080-0000-0000-008080808080";
char identifier_string[sizeof(expected_identifier_string)];
const size_t kTextSectionSize = 128;
ELF elf(EM_386, TypeParam::kClass, kLittleEndian);
Section text(kLittleEndian);
for (size_t i = 0; i < kTextSectionSize; ++i) {
text.D8(i * 3);
}
elf.AddSection(".text", text, SHT_PROGBITS);
elf.Finish();
this->GetElfContents(elf);
EXPECT_TRUE(FileID::ElfFileIdentifierFromMappedFile(this->elfdata,
identifier));
FileID::ConvertIdentifierToString(identifier, identifier_string,
sizeof(identifier_string));
EXPECT_STREQ(expected_identifier_string, identifier_string);
}
TYPED_TEST(FileIDTest, BuildID) {
const uint8_t kExpectedIdentifier[sizeof(MDGUID)] =
{0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F};
char expected_identifier_string[] =
"00000000-0000-0000-0000-000000000000";
FileID::ConvertIdentifierToString(kExpectedIdentifier,
expected_identifier_string,
sizeof(expected_identifier_string));
uint8_t identifier[sizeof(MDGUID)];
char identifier_string[sizeof(expected_identifier_string)];
ELF elf(EM_386, TypeParam::kClass, kLittleEndian);
Section text(kLittleEndian);
text.Append(4096, 0);
elf.AddSection(".text", text, SHT_PROGBITS);
BuildIDNote::AppendSection(elf,
kExpectedIdentifier,
sizeof(kExpectedIdentifier));
elf.Finish();
this->GetElfContents(elf);
EXPECT_TRUE(FileID::ElfFileIdentifierFromMappedFile(this->elfdata,
identifier));
FileID::ConvertIdentifierToString(identifier, identifier_string,
sizeof(identifier_string));
EXPECT_STREQ(expected_identifier_string, identifier_string);
}
// Test to make sure two files with different text sections produce
// different hashes when not using a build id.
TYPED_TEST(FileIDTest, UniqueHashes) {
char identifier_string_1[] =
"00000000-0000-0000-0000-000000000000";
char identifier_string_2[] =
"00000000-0000-0000-0000-000000000000";
uint8_t identifier_1[sizeof(MDGUID)];
uint8_t identifier_2[sizeof(MDGUID)];
{
ELF elf1(EM_386, TypeParam::kClass, kLittleEndian);
Section foo_1(kLittleEndian);
PopulateSection(&foo_1, 32, 5);
elf1.AddSection(".foo", foo_1, SHT_PROGBITS);
Section text_1(kLittleEndian);
PopulateSection(&text_1, 4096, 17);
elf1.AddSection(".text", text_1, SHT_PROGBITS);
elf1.Finish();
this->GetElfContents(elf1);
}
EXPECT_TRUE(FileID::ElfFileIdentifierFromMappedFile(this->elfdata,
identifier_1));
FileID::ConvertIdentifierToString(identifier_1, identifier_string_1,
sizeof(identifier_string_1));
{
ELF elf2(EM_386, TypeParam::kClass, kLittleEndian);
Section text_2(kLittleEndian);
Section foo_2(kLittleEndian);
PopulateSection(&foo_2, 32, 5);
elf2.AddSection(".foo", foo_2, SHT_PROGBITS);
PopulateSection(&text_2, 4096, 31);
elf2.AddSection(".text", text_2, SHT_PROGBITS);
elf2.Finish();
this->GetElfContents(elf2);
}
EXPECT_TRUE(FileID::ElfFileIdentifierFromMappedFile(this->elfdata,
identifier_2));
FileID::ConvertIdentifierToString(identifier_2, identifier_string_2,
sizeof(identifier_string_2));
EXPECT_STRNE(identifier_string_1, identifier_string_2);
}
<|endoftext|> |
<commit_before>#include <iostream>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/core/core.hpp>
#include "EvmGdownIIR.hpp"
#include "Pulse.hpp"
#include "Window.hpp"
#include "profiler/Profiler.h"
using std::cout;
using std::endl;
using cv::VideoCapture;
using cv::VideoWriter;
using cv::waitKey;
using cv::flip;
static void writeVideo(VideoCapture& capture, const Mat& frame);
int main(int argc, const char** argv) {
const bool shouldWrite = false;
const bool shouldFlip = true;
// const bool shouldFlip = false;
// VideoCapture capture("../../vidmagSIGGRAPH2012/baby2_source.mp4");
// VideoCapture capture("../../vidmagSIGGRAPH2012/face.wmv");
// VideoCapture capture("../../vidmagSIGGRAPH2012/face2_source.mp4");
// VideoCapture capture("../../vidmagSIGGRAPH2012/face_source.wmv");
// VideoCapture capture("../../videos/eva.mov");
VideoCapture capture(0);
const int WIDTH = capture.get(CV_CAP_PROP_FRAME_WIDTH);
const int HEIGHT = capture.get(CV_CAP_PROP_FRAME_HEIGHT);
const double FPS = capture.get(CV_CAP_PROP_FPS);
cout << "SIZE: " << WIDTH << "x" << HEIGHT << endl;
Pulse pulse;
if (FPS != 0) {
cout << "FPS: " << FPS << endl;
pulse.fps = FPS;
}
pulse.load("res/lbpcascade_frontalface.xml");
pulse.start(WIDTH, HEIGHT);
Window window(pulse);
Mat frame;
while (true) {
PROFILE_SCOPED_DESC("loop");
PROFILE_START_DESC("capture");
capture >> frame;
PROFILE_STOP();
if (frame.empty()) {
PROFILE_PAUSE_SCOPED(); // loop
while (waitKey() != 27) {}
break;
}
PROFILE_START_DESC("flip");
if (shouldFlip)
flip(frame, frame, 1);
PROFILE_STOP();
window.update(frame);
if (shouldWrite) {
writeVideo(capture, frame);
}
PROFILE_START_DESC("wait key");
if (waitKey(1) == 27) {
PROFILE_STOP(); // wait key
break;
}
PROFILE_STOP();
}
Profiler::detect(argc, argv);
Profiler::dumphtml();
return 0;
}
static void writeVideo(VideoCapture& capture, const Mat& frame) {
static VideoWriter writer("out.avi",
CV_FOURCC('X', 'V', 'I', 'D'),
capture.get(CV_CAP_PROP_FPS),
Size(capture.get(CV_CAP_PROP_FRAME_WIDTH),
capture.get(CV_CAP_PROP_FRAME_HEIGHT)));
writer << frame;
}
<commit_msg>High pulse video.<commit_after>#include <iostream>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/core/core.hpp>
#include "EvmGdownIIR.hpp"
#include "Pulse.hpp"
#include "Window.hpp"
#include "profiler/Profiler.h"
using std::cout;
using std::endl;
using cv::VideoCapture;
using cv::VideoWriter;
using cv::waitKey;
using cv::flip;
static void writeVideo(VideoCapture& capture, const Mat& frame);
int main(int argc, const char** argv) {
const bool shouldWrite = false;
const bool shouldFlip = true;
// const bool shouldFlip = false;
// VideoCapture capture("../../vidmagSIGGRAPH2012/baby2_source.mp4");
// VideoCapture capture("../../vidmagSIGGRAPH2012/face.wmv");
// VideoCapture capture("../../vidmagSIGGRAPH2012/face2_source.mp4");
// VideoCapture capture("../../vidmagSIGGRAPH2012/face_source.wmv");
// VideoCapture capture("../../videos/eva.mov");
// VideoCapture capture("../../videos/me-high-pulse.mov");
VideoCapture capture(0);
const int WIDTH = capture.get(CV_CAP_PROP_FRAME_WIDTH);
const int HEIGHT = capture.get(CV_CAP_PROP_FRAME_HEIGHT);
const double FPS = capture.get(CV_CAP_PROP_FPS);
cout << "SIZE: " << WIDTH << "x" << HEIGHT << endl;
Pulse pulse;
if (FPS != 0) {
cout << "FPS: " << FPS << endl;
pulse.fps = FPS;
}
pulse.load("res/lbpcascade_frontalface.xml");
pulse.start(WIDTH, HEIGHT);
Window window(pulse);
Mat frame;
while (true) {
PROFILE_SCOPED_DESC("loop");
PROFILE_START_DESC("capture");
capture >> frame;
PROFILE_STOP();
if (frame.empty()) {
PROFILE_PAUSE_SCOPED(); // loop
while (waitKey() != 27) {}
break;
}
PROFILE_START_DESC("flip");
if (shouldFlip)
flip(frame, frame, 1);
PROFILE_STOP();
window.update(frame);
if (shouldWrite) {
writeVideo(capture, frame);
}
PROFILE_START_DESC("wait key");
if (waitKey(1) == 27) {
PROFILE_STOP(); // wait key
break;
}
PROFILE_STOP();
}
Profiler::detect(argc, argv);
Profiler::dumphtml();
return 0;
}
static void writeVideo(VideoCapture& capture, const Mat& frame) {
static VideoWriter writer("out.avi",
CV_FOURCC('X', 'V', 'I', 'D'),
capture.get(CV_CAP_PROP_FPS),
Size(capture.get(CV_CAP_PROP_FRAME_WIDTH),
capture.get(CV_CAP_PROP_FRAME_HEIGHT)));
writer << frame;
}
<|endoftext|> |
<commit_before>//------------------------------------------------------------------------------
// CLING - the C++ LLVM-based InterpreterG :)
// author: Vassil Vassilev <vasil.georgiev.vasilev@cern.ch>
//
// This file is dual-licensed: you can choose to license it under the University
// of Illinois Open Source License or the GNU Lesser General Public License. See
// LICENSE.TXT for details.
//------------------------------------------------------------------------------
#include "cling/Interpreter/ValuePrinter.h"
#include "cling/Interpreter/CValuePrinter.h"
#include "cling/Interpreter/Interpreter.h"
#include "cling/Interpreter/Transaction.h"
#include "cling/Interpreter/Value.h"
#include "cling/Utils/AST.h"
#include "clang/AST/ASTContext.h"
#include "clang/AST/Decl.h"
#include "clang/AST/DeclCXX.h"
#include "clang/AST/Expr.h"
#include "clang/AST/Type.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/ExecutionEngine/GenericValue.h"
#include <string>
#include <sstream>
#include <cstdio>
// Fragment copied from LLVM's raw_ostream.cpp
#if defined(_MSC_VER)
#ifndef STDIN_FILENO
# define STDIN_FILENO 0
#endif
#ifndef STDOUT_FILENO
# define STDOUT_FILENO 1
#endif
#ifndef STDERR_FILENO
# define STDERR_FILENO 2
#endif
#else
//#if defined(HAVE_UNISTD_H)
# include <unistd.h>
//#endif
#endif
using namespace cling;
// Implements the CValuePrinter interface.
extern "C" void cling_PrintValue(void* /*cling::Value**/ V) {
//Value* value = (Value*)V;
// We need stream that doesn't close its file descriptor, thus we are not
// using llvm::outs. Keeping file descriptor open we will be able to use
// the results in pipes (Savannah #99234).
//llvm::raw_fd_ostream outs (STDOUT_FILENO, /*ShouldClose*/false);
//std::string typeStr = printType(value->getPtr(), value->getPtr(), *value);
//std::string valueStr = printValue(value->getPtr(), value->getPtr(), *value);
}
static void StreamValue(llvm::raw_ostream& o, const void* V, clang::QualType QT,
clang::ASTContext& C);
static void StreamChar(llvm::raw_ostream& o, const char v) {
if (isprint(v))
o << '"' << v << "\"";
else {
o << "\\0x";
o.write_hex(v);
}
}
static void StreamCharPtr(llvm::raw_ostream& o, const char* const v) {
if (!v) {
o << "<<<NULL>>>";
return;
}
o << '"';
const char* p = v;
for (;*p && p - v < 128; ++p) {
o << *p;
}
if (*p) o << "\"...";
else o << "\"";
}
static void StreamRef(llvm::raw_ostream& o, const void** V, clang::QualType Ty,
clang::ASTContext& C){
const clang::ReferenceType* RTy = llvm::dyn_cast<clang::ReferenceType>(Ty);
StreamValue(o, *V, RTy->getPointeeTypeAsWritten(), C);
}
static void StreamPtr(llvm::raw_ostream& o, const void* v) {
o << v;
}
static void StreamArr(llvm::raw_ostream& o, const void* V, clang::QualType Ty,
clang::ASTContext& C) {
const clang::ArrayType* ArrTy = Ty->getAsArrayTypeUnsafe();
clang::QualType ElementTy = ArrTy->getElementType();
if (ElementTy->isCharType())
StreamCharPtr(o, (const char*)V);
else if (Ty->isConstantArrayType()) {
// Stream a constant array by streaming up to 5 elements.
const clang::ConstantArrayType* CArrTy
= C.getAsConstantArrayType(Ty);
const llvm::APInt& APSize = CArrTy->getSize();
size_t ElBytes = C.getTypeSize(ElementTy) / C.getCharWidth();
size_t Size = (size_t)APSize.getZExtValue();
o << "{ ";
for (size_t i = 0; i < Size; ++i) {
StreamValue(o, (const char*) V + i * ElBytes, ElementTy, C);
if (i + 1 < Size) {
if (i == 4) {
o << "...";
break;
}
else o << ", ";
}
}
o << " }";
} else
StreamPtr(o, V);
}
static void StreamFunction(llvm::raw_ostream& o, Value* V) {
o << "Function @" << V->getPtr() << '\n';
Interpreter* interp = V->getInterpreter();
const Transaction* T = interp->getLastTransaction();
assert(T->getWrapperFD() && "Must have a wrapper.");
clang::FunctionDecl* WrapperFD = T->getWrapperFD();
clang::Expr* ExprAttachedTo
= utils::Analyze::GetOrCreateLastExpr(WrapperFD, /*foundAtPos*/0,
/*omitDS*/false, &interp->getSema());
const clang::DeclRefExpr* DeclRefExp
= llvm::dyn_cast_or_null<clang::DeclRefExpr>(ExprAttachedTo);
const clang::FunctionDecl* FD = 0;
if (DeclRefExp)
FD = llvm::dyn_cast_or_null<clang::FunctionDecl>(DeclRefExp->getDecl());
if (FD) {
clang::SourceRange SRange = FD->getSourceRange();
const char* cBegin = 0;
const char* cEnd = 0;
bool Invalid;
if (SRange.isValid()) {
clang::SourceManager& SM = V->getASTContext().getSourceManager();
clang::SourceLocation LocBegin = SRange.getBegin();
LocBegin = SM.getExpansionRange(LocBegin).first;
o << " at " << SM.getFilename(LocBegin);
unsigned LineNo = SM.getSpellingLineNumber(LocBegin, &Invalid);
if (!Invalid)
o << ':' << LineNo;
o << ":\n";
bool Invalid = false;
cBegin = SM.getCharacterData(LocBegin, &Invalid);
if (!Invalid) {
clang::SourceLocation LocEnd = SRange.getEnd();
LocEnd = SM.getExpansionRange(LocEnd).second;
cEnd = SM.getCharacterData(LocEnd, &Invalid);
if (Invalid)
cBegin = 0;
} else {
cBegin = 0;
}
}
if (cBegin && cEnd && cEnd > cBegin && cEnd - cBegin < 16 * 1024) {
o << llvm::StringRef(cBegin, cEnd - cBegin + 1);
} else {
const clang::FunctionDecl* FDef;
if (FD->hasBody(FDef))
FD = FDef;
FD->print(o);
//const clang::FunctionDecl* FD
// = llvm::cast<const clang::FunctionType>(Ty)->getDecl();
}
} else {
o << ":\n";
// type-based printing:
V->getType().print(o, V->getASTContext().getPrintingPolicy());
}
// type-based print() never and decl-based print() sometimes does not include
// a final newline:
o << '\n';
}
static void StreamLongDouble(llvm::raw_ostream& o, const Value* value,
clang::ASTContext& C) {
std::stringstream sstr;
sstr << value->simplisticCastAs<long double>();
o << sstr.str() << 'L';
}
static void StreamClingValue(llvm::raw_ostream& o, const Value* value) {
if (!value || !value->isValid()) {
o << "<<<invalid>>> @" << value;
} else {
clang::ASTContext& C = value->getASTContext();
clang::QualType QT = value->getType();
o << "boxes [";
o << "("
<< QT.getAsString(C.getPrintingPolicy())
<< ") ";
clang::QualType valType = QT.getDesugaredType(C).getNonReferenceType();
if (C.hasSameType(valType, C.LongDoubleTy))
StreamLongDouble(o, value, C);
else if (valType->isFloatingType())
o << value->simplisticCastAs<double>();
else if (valType->isIntegerType()) {
if (valType->hasSignedIntegerRepresentation())
o << value->simplisticCastAs<long long>();
else
o << value->simplisticCastAs<unsigned long long>();
} else if (valType->isBooleanType())
o << (value->simplisticCastAs<bool>() ? "true" : "false");
else {
StreamValue(o, value->getPtr(), valType, value->getASTContext());
}
o << "]";
}
}
static void StreamObj(llvm::raw_ostream& o, const void* V, clang::QualType Ty) {
if (clang::CXXRecordDecl* CXXRD = Ty->getAsCXXRecordDecl()) {
std::string QualName = CXXRD->getQualifiedNameAsString();
if (QualName == "cling::Value"){
StreamClingValue(o, (const cling::Value*)V);
return;
}
} // if CXXRecordDecl
// TODO: Print the object members.
o << "@" << V;
}
static void StreamValue(llvm::raw_ostream& o, const void* V,
clang::QualType Ty, clang::ASTContext& C) {
if (const clang::BuiltinType *BT
= llvm::dyn_cast<clang::BuiltinType>(Ty.getCanonicalType())) {
switch (BT->getKind()) {
case clang::BuiltinType::Bool:
if (*(const bool*)V)
o << "true";
else
o << "false";
break;
case clang::BuiltinType::Char_U: // intentional fall through
case clang::BuiltinType::UChar: // intentional fall through
case clang::BuiltinType::Char_S: // intentional fall through
case clang::BuiltinType::SChar:
StreamChar(o, *(const char*)V); break;
case clang::BuiltinType::Short:
o << *(const short*)V; break;
case clang::BuiltinType::UShort:
o << *(const unsigned short*)V; break;
case clang::BuiltinType::Int:
o << *(const int*)V; break;
case clang::BuiltinType::UInt:
o << *(const unsigned int*)V; break;
case clang::BuiltinType::Long:
o << *(const long*)V; break;
case clang::BuiltinType::ULong:
o << *(const unsigned long*)V; break;
case clang::BuiltinType::LongLong:
o << *(const long long*)V; break;
case clang::BuiltinType::ULongLong:
o << *(const unsigned long long*)V; break;
case clang::BuiltinType::Float:
o << *(const float*)V; break;
case clang::BuiltinType::Double:
o << *(const double*)V; break;
case clang::BuiltinType::LongDouble: {
std::stringstream ssLD;
ssLD << *(const long double*)V;
o << ssLD.str() << 'L'; break;
}
default:
StreamObj(o, V, Ty);
}
}
else if (Ty.getAsString().compare("std::string") == 0) {
StreamObj(o, V, Ty);
o << " "; // force a space
o <<"c_str: ";
StreamCharPtr(o, ((const char*) (*(const std::string*)V).c_str()));
}
else if (Ty->isEnumeralType()) {
clang::EnumDecl* ED = Ty->getAs<clang::EnumType>()->getDecl();
uint64_t value = *(const uint64_t*)V;
bool IsFirst = true;
llvm::APSInt ValAsAPSInt = C.MakeIntValue(value, Ty);
for (clang::EnumDecl::enumerator_iterator I = ED->enumerator_begin(),
E = ED->enumerator_end(); I != E; ++I) {
if (I->getInitVal() == ValAsAPSInt) {
if (!IsFirst) {
o << " ? ";
}
o << "(" << I->getQualifiedNameAsString() << ")";
IsFirst = false;
}
}
o << " : (int) " << ValAsAPSInt.toString(/*Radix = */10);
}
else if (Ty->isReferenceType())
StreamRef(o, (const void**)&V, Ty, C);
else if (Ty->isPointerType()) {
clang::QualType PointeeTy = Ty->getPointeeType();
if (PointeeTy->isCharType())
StreamCharPtr(o, (const char*)V);
else
StreamPtr(o, V);
}
else if (Ty->isArrayType())
StreamArr(o, V, Ty, C);
else if (Ty->isFunctionType())
StreamFunction(o, const_cast<cling::Value*>((const cling::Value*)V));
else
StreamObj(o, V, Ty);
}
namespace cling {
namespace valuePrinterInternal {
void printValue_Default(llvm::raw_ostream& o, const Value& V) {
clang::ASTContext& C = V.getASTContext();
clang::QualType Ty = V.getType().getDesugaredType(C);
if (const clang::BuiltinType *BT
= llvm::dyn_cast<clang::BuiltinType>(Ty.getCanonicalType())) {
switch (BT->getKind()) {
case clang::BuiltinType::Bool: // intentional fall through
case clang::BuiltinType::Char_U: // intentional fall through
case clang::BuiltinType::Char_S: // intentional fall through
case clang::BuiltinType::SChar: // intentional fall through
case clang::BuiltinType::Short: // intentional fall through
case clang::BuiltinType::Int: // intentional fall through
case clang::BuiltinType::Long: // intentional fall through
case clang::BuiltinType::LongLong: {
long long res = V.getLL();
StreamValue(o, (const void*)&res, Ty, C);
}
break;
case clang::BuiltinType::UChar: // intentional fall through
case clang::BuiltinType::UShort: // intentional fall through
case clang::BuiltinType::UInt: // intentional fall through
case clang::BuiltinType::ULong: // intentional fall through
case clang::BuiltinType::ULongLong: {
unsigned long long res = V.getULL();
StreamValue(o, (const void*)&res, Ty, C);
}
break;
case clang::BuiltinType::Float: {
float res = V.getFloat();
StreamValue(o, (const void*)&res, Ty, C);
}
break;
case clang::BuiltinType::Double: {
double res = V.getDouble();
StreamValue(o, (const void*)&res, Ty, C);
}
break;
case clang::BuiltinType::LongDouble: {
long double res = V.getLongDouble();
StreamValue(o, (const void*)&res, Ty, C);
}
break;
default:
StreamValue(o, V.getPtr(), Ty, C);
break;
}
}
else if (Ty->isIntegralOrEnumerationType()) {
long long res = V.getLL();
StreamValue(o, &res, Ty, C);
}
else if (Ty->isFunctionType())
StreamValue(o, &V, Ty, C);
else
StreamValue(o, V.getPtr(), Ty, C);
}
void printType_Default(llvm::raw_ostream& o, const Value& V) {
o << "(";
o << V.getType().getAsString();
o << ") ";
}
void flushToStream(llvm::raw_ostream& o, const std::string& s) {
// We want to keep stdout and o in sync if o is different from stdout.
fflush(stdout);
o << s;
o.flush();
}
} // end namespace valuePrinterInternal
} // end namespace cling
<commit_msg>Use ticks instead of quotes when printing a single char.<commit_after>//------------------------------------------------------------------------------
// CLING - the C++ LLVM-based InterpreterG :)
// author: Vassil Vassilev <vasil.georgiev.vasilev@cern.ch>
//
// This file is dual-licensed: you can choose to license it under the University
// of Illinois Open Source License or the GNU Lesser General Public License. See
// LICENSE.TXT for details.
//------------------------------------------------------------------------------
#include "cling/Interpreter/ValuePrinter.h"
#include "cling/Interpreter/CValuePrinter.h"
#include "cling/Interpreter/Interpreter.h"
#include "cling/Interpreter/Transaction.h"
#include "cling/Interpreter/Value.h"
#include "cling/Utils/AST.h"
#include "clang/AST/ASTContext.h"
#include "clang/AST/Decl.h"
#include "clang/AST/DeclCXX.h"
#include "clang/AST/Expr.h"
#include "clang/AST/Type.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/ExecutionEngine/GenericValue.h"
#include <string>
#include <sstream>
#include <cstdio>
// Fragment copied from LLVM's raw_ostream.cpp
#if defined(_MSC_VER)
#ifndef STDIN_FILENO
# define STDIN_FILENO 0
#endif
#ifndef STDOUT_FILENO
# define STDOUT_FILENO 1
#endif
#ifndef STDERR_FILENO
# define STDERR_FILENO 2
#endif
#else
//#if defined(HAVE_UNISTD_H)
# include <unistd.h>
//#endif
#endif
using namespace cling;
// Implements the CValuePrinter interface.
extern "C" void cling_PrintValue(void* /*cling::Value**/ V) {
//Value* value = (Value*)V;
// We need stream that doesn't close its file descriptor, thus we are not
// using llvm::outs. Keeping file descriptor open we will be able to use
// the results in pipes (Savannah #99234).
//llvm::raw_fd_ostream outs (STDOUT_FILENO, /*ShouldClose*/false);
//std::string typeStr = printType(value->getPtr(), value->getPtr(), *value);
//std::string valueStr = printValue(value->getPtr(), value->getPtr(), *value);
}
static void StreamValue(llvm::raw_ostream& o, const void* V, clang::QualType QT,
clang::ASTContext& C);
static void StreamChar(llvm::raw_ostream& o, const char v) {
if (isprint(v))
o << '\'' << v << '\'';
else {
o << "\\0x";
o.write_hex(v);
}
}
static void StreamCharPtr(llvm::raw_ostream& o, const char* const v) {
if (!v) {
o << "<<<NULL>>>";
return;
}
o << '"';
const char* p = v;
for (;*p && p - v < 128; ++p) {
o << *p;
}
if (*p) o << "\"...";
else o << "\"";
}
static void StreamRef(llvm::raw_ostream& o, const void** V, clang::QualType Ty,
clang::ASTContext& C){
const clang::ReferenceType* RTy = llvm::dyn_cast<clang::ReferenceType>(Ty);
StreamValue(o, *V, RTy->getPointeeTypeAsWritten(), C);
}
static void StreamPtr(llvm::raw_ostream& o, const void* v) {
o << v;
}
static void StreamArr(llvm::raw_ostream& o, const void* V, clang::QualType Ty,
clang::ASTContext& C) {
const clang::ArrayType* ArrTy = Ty->getAsArrayTypeUnsafe();
clang::QualType ElementTy = ArrTy->getElementType();
if (ElementTy->isCharType())
StreamCharPtr(o, (const char*)V);
else if (Ty->isConstantArrayType()) {
// Stream a constant array by streaming up to 5 elements.
const clang::ConstantArrayType* CArrTy
= C.getAsConstantArrayType(Ty);
const llvm::APInt& APSize = CArrTy->getSize();
size_t ElBytes = C.getTypeSize(ElementTy) / C.getCharWidth();
size_t Size = (size_t)APSize.getZExtValue();
o << "{ ";
for (size_t i = 0; i < Size; ++i) {
StreamValue(o, (const char*) V + i * ElBytes, ElementTy, C);
if (i + 1 < Size) {
if (i == 4) {
o << "...";
break;
}
else o << ", ";
}
}
o << " }";
} else
StreamPtr(o, V);
}
static void StreamFunction(llvm::raw_ostream& o, Value* V) {
o << "Function @" << V->getPtr() << '\n';
Interpreter* interp = V->getInterpreter();
const Transaction* T = interp->getLastTransaction();
assert(T->getWrapperFD() && "Must have a wrapper.");
clang::FunctionDecl* WrapperFD = T->getWrapperFD();
clang::Expr* ExprAttachedTo
= utils::Analyze::GetOrCreateLastExpr(WrapperFD, /*foundAtPos*/0,
/*omitDS*/false, &interp->getSema());
const clang::DeclRefExpr* DeclRefExp
= llvm::dyn_cast_or_null<clang::DeclRefExpr>(ExprAttachedTo);
const clang::FunctionDecl* FD = 0;
if (DeclRefExp)
FD = llvm::dyn_cast_or_null<clang::FunctionDecl>(DeclRefExp->getDecl());
if (FD) {
clang::SourceRange SRange = FD->getSourceRange();
const char* cBegin = 0;
const char* cEnd = 0;
bool Invalid;
if (SRange.isValid()) {
clang::SourceManager& SM = V->getASTContext().getSourceManager();
clang::SourceLocation LocBegin = SRange.getBegin();
LocBegin = SM.getExpansionRange(LocBegin).first;
o << " at " << SM.getFilename(LocBegin);
unsigned LineNo = SM.getSpellingLineNumber(LocBegin, &Invalid);
if (!Invalid)
o << ':' << LineNo;
o << ":\n";
bool Invalid = false;
cBegin = SM.getCharacterData(LocBegin, &Invalid);
if (!Invalid) {
clang::SourceLocation LocEnd = SRange.getEnd();
LocEnd = SM.getExpansionRange(LocEnd).second;
cEnd = SM.getCharacterData(LocEnd, &Invalid);
if (Invalid)
cBegin = 0;
} else {
cBegin = 0;
}
}
if (cBegin && cEnd && cEnd > cBegin && cEnd - cBegin < 16 * 1024) {
o << llvm::StringRef(cBegin, cEnd - cBegin + 1);
} else {
const clang::FunctionDecl* FDef;
if (FD->hasBody(FDef))
FD = FDef;
FD->print(o);
//const clang::FunctionDecl* FD
// = llvm::cast<const clang::FunctionType>(Ty)->getDecl();
}
} else {
o << ":\n";
// type-based printing:
V->getType().print(o, V->getASTContext().getPrintingPolicy());
}
// type-based print() never and decl-based print() sometimes does not include
// a final newline:
o << '\n';
}
static void StreamLongDouble(llvm::raw_ostream& o, const Value* value,
clang::ASTContext& C) {
std::stringstream sstr;
sstr << value->simplisticCastAs<long double>();
o << sstr.str() << 'L';
}
static void StreamClingValue(llvm::raw_ostream& o, const Value* value) {
if (!value || !value->isValid()) {
o << "<<<invalid>>> @" << value;
} else {
clang::ASTContext& C = value->getASTContext();
clang::QualType QT = value->getType();
o << "boxes [";
o << "("
<< QT.getAsString(C.getPrintingPolicy())
<< ") ";
clang::QualType valType = QT.getDesugaredType(C).getNonReferenceType();
if (C.hasSameType(valType, C.LongDoubleTy))
StreamLongDouble(o, value, C);
else if (valType->isFloatingType())
o << value->simplisticCastAs<double>();
else if (valType->isIntegerType()) {
if (valType->hasSignedIntegerRepresentation())
o << value->simplisticCastAs<long long>();
else
o << value->simplisticCastAs<unsigned long long>();
} else if (valType->isBooleanType())
o << (value->simplisticCastAs<bool>() ? "true" : "false");
else {
StreamValue(o, value->getPtr(), valType, value->getASTContext());
}
o << "]";
}
}
static void StreamObj(llvm::raw_ostream& o, const void* V, clang::QualType Ty) {
if (clang::CXXRecordDecl* CXXRD = Ty->getAsCXXRecordDecl()) {
std::string QualName = CXXRD->getQualifiedNameAsString();
if (QualName == "cling::Value"){
StreamClingValue(o, (const cling::Value*)V);
return;
}
} // if CXXRecordDecl
// TODO: Print the object members.
o << "@" << V;
}
static void StreamValue(llvm::raw_ostream& o, const void* V,
clang::QualType Ty, clang::ASTContext& C) {
if (const clang::BuiltinType *BT
= llvm::dyn_cast<clang::BuiltinType>(Ty.getCanonicalType())) {
switch (BT->getKind()) {
case clang::BuiltinType::Bool:
if (*(const bool*)V)
o << "true";
else
o << "false";
break;
case clang::BuiltinType::Char_U: // intentional fall through
case clang::BuiltinType::UChar: // intentional fall through
case clang::BuiltinType::Char_S: // intentional fall through
case clang::BuiltinType::SChar:
StreamChar(o, *(const char*)V); break;
case clang::BuiltinType::Short:
o << *(const short*)V; break;
case clang::BuiltinType::UShort:
o << *(const unsigned short*)V; break;
case clang::BuiltinType::Int:
o << *(const int*)V; break;
case clang::BuiltinType::UInt:
o << *(const unsigned int*)V; break;
case clang::BuiltinType::Long:
o << *(const long*)V; break;
case clang::BuiltinType::ULong:
o << *(const unsigned long*)V; break;
case clang::BuiltinType::LongLong:
o << *(const long long*)V; break;
case clang::BuiltinType::ULongLong:
o << *(const unsigned long long*)V; break;
case clang::BuiltinType::Float:
o << *(const float*)V; break;
case clang::BuiltinType::Double:
o << *(const double*)V; break;
case clang::BuiltinType::LongDouble: {
std::stringstream ssLD;
ssLD << *(const long double*)V;
o << ssLD.str() << 'L'; break;
}
default:
StreamObj(o, V, Ty);
}
}
else if (Ty.getAsString().compare("std::string") == 0) {
StreamObj(o, V, Ty);
o << " "; // force a space
o <<"c_str: ";
StreamCharPtr(o, ((const char*) (*(const std::string*)V).c_str()));
}
else if (Ty->isEnumeralType()) {
clang::EnumDecl* ED = Ty->getAs<clang::EnumType>()->getDecl();
uint64_t value = *(const uint64_t*)V;
bool IsFirst = true;
llvm::APSInt ValAsAPSInt = C.MakeIntValue(value, Ty);
for (clang::EnumDecl::enumerator_iterator I = ED->enumerator_begin(),
E = ED->enumerator_end(); I != E; ++I) {
if (I->getInitVal() == ValAsAPSInt) {
if (!IsFirst) {
o << " ? ";
}
o << "(" << I->getQualifiedNameAsString() << ")";
IsFirst = false;
}
}
o << " : (int) " << ValAsAPSInt.toString(/*Radix = */10);
}
else if (Ty->isReferenceType())
StreamRef(o, (const void**)&V, Ty, C);
else if (Ty->isPointerType()) {
clang::QualType PointeeTy = Ty->getPointeeType();
if (PointeeTy->isCharType())
StreamCharPtr(o, (const char*)V);
else
StreamPtr(o, V);
}
else if (Ty->isArrayType())
StreamArr(o, V, Ty, C);
else if (Ty->isFunctionType())
StreamFunction(o, const_cast<cling::Value*>((const cling::Value*)V));
else
StreamObj(o, V, Ty);
}
namespace cling {
namespace valuePrinterInternal {
void printValue_Default(llvm::raw_ostream& o, const Value& V) {
clang::ASTContext& C = V.getASTContext();
clang::QualType Ty = V.getType().getDesugaredType(C);
if (const clang::BuiltinType *BT
= llvm::dyn_cast<clang::BuiltinType>(Ty.getCanonicalType())) {
switch (BT->getKind()) {
case clang::BuiltinType::Bool: // intentional fall through
case clang::BuiltinType::Char_U: // intentional fall through
case clang::BuiltinType::Char_S: // intentional fall through
case clang::BuiltinType::SChar: // intentional fall through
case clang::BuiltinType::Short: // intentional fall through
case clang::BuiltinType::Int: // intentional fall through
case clang::BuiltinType::Long: // intentional fall through
case clang::BuiltinType::LongLong: {
long long res = V.getLL();
StreamValue(o, (const void*)&res, Ty, C);
}
break;
case clang::BuiltinType::UChar: // intentional fall through
case clang::BuiltinType::UShort: // intentional fall through
case clang::BuiltinType::UInt: // intentional fall through
case clang::BuiltinType::ULong: // intentional fall through
case clang::BuiltinType::ULongLong: {
unsigned long long res = V.getULL();
StreamValue(o, (const void*)&res, Ty, C);
}
break;
case clang::BuiltinType::Float: {
float res = V.getFloat();
StreamValue(o, (const void*)&res, Ty, C);
}
break;
case clang::BuiltinType::Double: {
double res = V.getDouble();
StreamValue(o, (const void*)&res, Ty, C);
}
break;
case clang::BuiltinType::LongDouble: {
long double res = V.getLongDouble();
StreamValue(o, (const void*)&res, Ty, C);
}
break;
default:
StreamValue(o, V.getPtr(), Ty, C);
break;
}
}
else if (Ty->isIntegralOrEnumerationType()) {
long long res = V.getLL();
StreamValue(o, &res, Ty, C);
}
else if (Ty->isFunctionType())
StreamValue(o, &V, Ty, C);
else
StreamValue(o, V.getPtr(), Ty, C);
}
void printType_Default(llvm::raw_ostream& o, const Value& V) {
o << "(";
o << V.getType().getAsString();
o << ") ";
}
void flushToStream(llvm::raw_ostream& o, const std::string& s) {
// We want to keep stdout and o in sync if o is different from stdout.
fflush(stdout);
o << s;
o.flush();
}
} // end namespace valuePrinterInternal
} // end namespace cling
<|endoftext|> |
<commit_before>// @(#)root/graf:$Name: $:$Id: TPaveLabel.cxx,v 1.13 2002/10/28 15:38:32 brun Exp $
// Author: Rene Brun 17/10/95
/*************************************************************************
* Copyright (C) 1995-2000, Rene Brun and Fons Rademakers. *
* All rights reserved. *
* *
* For the licensing terms see $ROOTSYS/LICENSE. *
* For the list of contributors see $ROOTSYS/README/CREDITS. *
*************************************************************************/
#include "Riostream.h"
#include "TROOT.h"
#include "TPaveLabel.h"
#include "TLatex.h"
#include "TVirtualPad.h"
ClassImp(TPaveLabel)
//______________________________________________________________________________
//* A PaveLabel is a Pave (see TPave) with a text centered in the Pave.
//Begin_Html
/*
<img src="gif/pavelabel.gif">
*/
//End_Html
//
//______________________________________________________________________________
TPaveLabel::TPaveLabel(): TPave(), TAttText()
{
//*-*-*-*-*-*-*-*-*-*-*pavelabel default constructor*-*-*-*-*-*-*-*-*-*-*-*-*
//*-* =============================
}
//______________________________________________________________________________
TPaveLabel::TPaveLabel(Double_t x1, Double_t y1,Double_t x2, Double_t y2, const char *label, Option_t *option)
:TPave(x1,y1,x2,y2,3,option), TAttText(22,0,1,62,0.99)
{
//*-*-*-*-*-*-*-*-*-*-*pavelabel normal constructor*-*-*-*-*-*-*-*-*-*-*-*-*-*
//*-* ============================
// a PaveLabel is a Pave with a label centered in the Pave
// The Pave is by default defined bith bordersize=5 and option ="br".
// The text size is automatically computed as a function of the pave size.
//
// IMPORTANT NOTE:
// Because TPave objects (and objects deriving from TPave) have their
// master coordinate system in NDC, one cannot use the TBox functions
// SetX1,SetY1,SetX2,SetY2 to change the corner coordinates. One should use
// instead SetX1NDC, SetY1NDC, SetX2NDC, SetY2NDC.
fLabel = label;
}
//______________________________________________________________________________
TPaveLabel::~TPaveLabel()
{
//*-*-*-*-*-*-*-*-*-*-*pavelabel default destructor*-*-*-*-*-*-*-*-*-*-*-*-*-*
//*-* ============================
}
//______________________________________________________________________________
TPaveLabel::TPaveLabel(const TPaveLabel &pavelabel) : TPave(pavelabel), TAttText(pavelabel)
{
((TPaveLabel&)pavelabel).Copy(*this);
}
//______________________________________________________________________________
void TPaveLabel::Copy(TObject &obj) const
{
//*-*-*-*-*-*-*-*-*-*-*Copy this pavelabel to pavelabel*-*-*-*-*-*-*-*-*-*-*-*
//*-* ================================
TPave::Copy(obj);
TAttText::Copy(((TPaveLabel&)obj));
((TPaveLabel&)obj).fLabel = fLabel;
}
//______________________________________________________________________________
void TPaveLabel::Draw(Option_t *option)
{
//*-*-*-*-*-*-*-*-*-*-*Draw this pavelabel with its current attributes*-*-*-*-*
//*-* ===============================================
Option_t *opt;
if (strlen(option)) opt = option;
else opt = GetOption();
AppendPad(opt);
}
//______________________________________________________________________________
void TPaveLabel::DrawPaveLabel(Double_t x1, Double_t y1, Double_t x2, Double_t y2, const char *label, Option_t *option)
{
//*-*-*-*-*-*-*-*-*-*-*Draw this pavelabel with new Doubleinates*-*-*-*-*-*-*-*
//*-* ========================================
TPaveLabel *newpavelabel = new TPaveLabel(x1,y1,x2,y2,label,option);
newpavelabel->SetBit(kCanDelete);
newpavelabel->AppendPad();
}
//______________________________________________________________________________
void TPaveLabel::Paint(Option_t *option)
{
//*-*-*-*-*-*-*-*-*-*-*Paint this pavelabel with its current attributes*-*-*-*
//*-* ================================================
//*-* Convert from NDC to pad coordinates
TPave::ConvertNDCtoPad();
PaintPaveLabel(fX1, fY1, fX2, fY2, GetLabel(), option);
}
//______________________________________________________________________________
void TPaveLabel::PaintPaveLabel(Double_t x1, Double_t y1,Double_t x2, Double_t y2,
const char *label ,Option_t *option)
{
//*-*-*-*-*-*-*-*-*-*-*Draw this pavelabel with new coordinates*-*-*-*-*-*-*-*
//*-* ========================================
Int_t nch = strlen(label);
//*-*- Draw the pave
TPave::PaintPave(x1,y1,x2,y2,GetBorderSize(),option);
Float_t nspecials = 0;
for (Int_t i=0;i<nch;i++) {
if (label[i] == '!') nspecials += 1;
if (label[i] == '?') nspecials += 1.5;
if (label[i] == '#') nspecials += 1;
if (label[i] == '`') nspecials += 1;
if (label[i] == '^') nspecials += 1.5;
if (label[i] == '~') nspecials += 1;
if (label[i] == '&') nspecials += 2;
if (label[i] == '\\') nspecials += 3; // octal characters very likely
}
nch -= Int_t(nspecials + 0.5);
if (nch <= 0) return;
//*-*- Draw label
Double_t wh = (Double_t)gPad->XtoPixel(gPad->GetX2());
Double_t hh = (Double_t)gPad->YtoPixel(gPad->GetY1());
Double_t labelsize, textsize = GetTextSize();
Int_t automat = 0;
if (GetTextFont()%10 > 2) { // fixed size font specified in pixels
labelsize = GetTextSize();
} else {
if (TMath::Abs(textsize -0.99) < 0.001) automat = 1;
if (textsize == 0) { textsize = 0.99; automat = 1;}
Int_t ypixel = TMath::Abs(gPad->YtoPixel(y1) - gPad->YtoPixel(y2));
labelsize = textsize*ypixel/hh;
if (wh < hh) labelsize *= hh/wh;
}
TLatex latex;
latex.SetTextAngle(GetTextAngle());
latex.SetTextFont(GetTextFont());
latex.SetTextAlign(GetTextAlign());
latex.SetTextColor(GetTextColor());
latex.SetTextSize(labelsize);
if (automat) {
UInt_t w,h;
latex.GetTextExtent(w,h,GetTitle());
labelsize = h/hh;
Double_t wxlabel = TMath::Abs(gPad->XtoPixel(x2) - gPad->XtoPixel(x1));
if (w > 0.99*wxlabel) {labelsize *= 0.99*wxlabel/w; h = UInt_t(h*0.99*wxlabel/w);}
if (h < 1) h = 1;
labelsize = Double_t(h)/hh;
if (wh < hh) labelsize *= hh/wh;
latex.SetTextSize(labelsize);
}
Int_t halign = GetTextAlign()/10;
Int_t valign = GetTextAlign()%10;
Double_t x = 0.5*(x1+x2);
if (halign == 1) x = x1 + 0.02*(x2-x1);
if (halign == 3) x = x2 - 0.02*(x2-x1);
Double_t y = 0.5*(y1+y2);
if (valign == 1) y = y1 + 0.02*(y2-y1);
if (valign == 3) y = y2 - 0.02*(y2-y1);
latex.PaintLatex(x, y, GetTextAngle(),labelsize,GetLabel());
}
//______________________________________________________________________________
void TPaveLabel::SavePrimitive(ofstream &out, Option_t *)
{
// Save primitive as a C++ statement(s) on output stream out
char quote = '"';
out<<" "<<endl;
if (gROOT->ClassSaved(TPaveLabel::Class())) {
out<<" ";
} else {
out<<" TPaveLabel *";
}
TString s = fLabel.Data();
s.ReplaceAll("\"","\\\"");
if (fOption.Contains("NDC")) {
out<<"pl = new TPaveLabel("<<fX1NDC<<","<<fY1NDC<<","<<fX2NDC<<","<<fY2NDC
<<","<<quote<<s.Data()<<quote<<","<<quote<<fOption<<quote<<");"<<endl;
} else {
out<<"pl = new TPaveLabel("<<gPad->PadtoX(fX1)<<","<<gPad->PadtoY(fY1)<<","<<gPad->PadtoX(fX2)<<","<<gPad->PadtoY(fY2)
<<","<<quote<<s.Data()<<quote<<","<<quote<<fOption<<quote<<");"<<endl;
}
if (fBorderSize != 3) {
out<<" pt->SetBorderSize("<<fBorderSize<<");"<<endl;
}
SaveFillAttributes(out,"pl",19,1001);
SaveLineAttributes(out,"pl",1,1,1);
SaveTextAttributes(out,"pl",22,0,1,62,0);
out<<" pl->Draw();"<<endl;
}
<commit_msg>In TPaveLabel::Paint, use the internal option GetOption in case the argument option is null.<commit_after>// @(#)root/graf:$Name: $:$Id: TPaveLabel.cxx,v 1.14 2002/10/31 07:27:35 brun Exp $
// Author: Rene Brun 17/10/95
/*************************************************************************
* Copyright (C) 1995-2000, Rene Brun and Fons Rademakers. *
* All rights reserved. *
* *
* For the licensing terms see $ROOTSYS/LICENSE. *
* For the list of contributors see $ROOTSYS/README/CREDITS. *
*************************************************************************/
#include "Riostream.h"
#include "TROOT.h"
#include "TPaveLabel.h"
#include "TLatex.h"
#include "TVirtualPad.h"
ClassImp(TPaveLabel)
//______________________________________________________________________________
//* A PaveLabel is a Pave (see TPave) with a text centered in the Pave.
//Begin_Html
/*
<img src="gif/pavelabel.gif">
*/
//End_Html
//
//______________________________________________________________________________
TPaveLabel::TPaveLabel(): TPave(), TAttText()
{
//*-*-*-*-*-*-*-*-*-*-*pavelabel default constructor*-*-*-*-*-*-*-*-*-*-*-*-*
//*-* =============================
}
//______________________________________________________________________________
TPaveLabel::TPaveLabel(Double_t x1, Double_t y1,Double_t x2, Double_t y2, const char *label, Option_t *option)
:TPave(x1,y1,x2,y2,3,option), TAttText(22,0,1,62,0.99)
{
//*-*-*-*-*-*-*-*-*-*-*pavelabel normal constructor*-*-*-*-*-*-*-*-*-*-*-*-*-*
//*-* ============================
// a PaveLabel is a Pave with a label centered in the Pave
// The Pave is by default defined bith bordersize=5 and option ="br".
// The text size is automatically computed as a function of the pave size.
//
// IMPORTANT NOTE:
// Because TPave objects (and objects deriving from TPave) have their
// master coordinate system in NDC, one cannot use the TBox functions
// SetX1,SetY1,SetX2,SetY2 to change the corner coordinates. One should use
// instead SetX1NDC, SetY1NDC, SetX2NDC, SetY2NDC.
fLabel = label;
}
//______________________________________________________________________________
TPaveLabel::~TPaveLabel()
{
//*-*-*-*-*-*-*-*-*-*-*pavelabel default destructor*-*-*-*-*-*-*-*-*-*-*-*-*-*
//*-* ============================
}
//______________________________________________________________________________
TPaveLabel::TPaveLabel(const TPaveLabel &pavelabel) : TPave(pavelabel), TAttText(pavelabel)
{
((TPaveLabel&)pavelabel).Copy(*this);
}
//______________________________________________________________________________
void TPaveLabel::Copy(TObject &obj) const
{
//*-*-*-*-*-*-*-*-*-*-*Copy this pavelabel to pavelabel*-*-*-*-*-*-*-*-*-*-*-*
//*-* ================================
TPave::Copy(obj);
TAttText::Copy(((TPaveLabel&)obj));
((TPaveLabel&)obj).fLabel = fLabel;
}
//______________________________________________________________________________
void TPaveLabel::Draw(Option_t *option)
{
//*-*-*-*-*-*-*-*-*-*-*Draw this pavelabel with its current attributes*-*-*-*-*
//*-* ===============================================
Option_t *opt;
if (strlen(option)) opt = option;
else opt = GetOption();
AppendPad(opt);
}
//______________________________________________________________________________
void TPaveLabel::DrawPaveLabel(Double_t x1, Double_t y1, Double_t x2, Double_t y2, const char *label, Option_t *option)
{
//*-*-*-*-*-*-*-*-*-*-*Draw this pavelabel with new Doubleinates*-*-*-*-*-*-*-*
//*-* ========================================
TPaveLabel *newpavelabel = new TPaveLabel(x1,y1,x2,y2,label,option);
newpavelabel->SetBit(kCanDelete);
newpavelabel->AppendPad();
}
//______________________________________________________________________________
void TPaveLabel::Paint(Option_t *option)
{
//*-*-*-*-*-*-*-*-*-*-*Paint this pavelabel with its current attributes*-*-*-*
//*-* ================================================
//*-* Convert from NDC to pad coordinates
TPave::ConvertNDCtoPad();
PaintPaveLabel(fX1, fY1, fX2, fY2, GetLabel(), strlen(option)?option:GetOption());
}
//______________________________________________________________________________
void TPaveLabel::PaintPaveLabel(Double_t x1, Double_t y1,Double_t x2, Double_t y2,
const char *label ,Option_t *option)
{
//*-*-*-*-*-*-*-*-*-*-*Draw this pavelabel with new coordinates*-*-*-*-*-*-*-*
//*-* ========================================
Int_t nch = strlen(label);
//*-*- Draw the pave
TPave::PaintPave(x1,y1,x2,y2,GetBorderSize(),option);
Float_t nspecials = 0;
for (Int_t i=0;i<nch;i++) {
if (label[i] == '!') nspecials += 1;
if (label[i] == '?') nspecials += 1.5;
if (label[i] == '#') nspecials += 1;
if (label[i] == '`') nspecials += 1;
if (label[i] == '^') nspecials += 1.5;
if (label[i] == '~') nspecials += 1;
if (label[i] == '&') nspecials += 2;
if (label[i] == '\\') nspecials += 3; // octal characters very likely
}
nch -= Int_t(nspecials + 0.5);
if (nch <= 0) return;
//*-*- Draw label
Double_t wh = (Double_t)gPad->XtoPixel(gPad->GetX2());
Double_t hh = (Double_t)gPad->YtoPixel(gPad->GetY1());
Double_t labelsize, textsize = GetTextSize();
Int_t automat = 0;
if (GetTextFont()%10 > 2) { // fixed size font specified in pixels
labelsize = GetTextSize();
} else {
if (TMath::Abs(textsize -0.99) < 0.001) automat = 1;
if (textsize == 0) { textsize = 0.99; automat = 1;}
Int_t ypixel = TMath::Abs(gPad->YtoPixel(y1) - gPad->YtoPixel(y2));
labelsize = textsize*ypixel/hh;
if (wh < hh) labelsize *= hh/wh;
}
TLatex latex;
latex.SetTextAngle(GetTextAngle());
latex.SetTextFont(GetTextFont());
latex.SetTextAlign(GetTextAlign());
latex.SetTextColor(GetTextColor());
latex.SetTextSize(labelsize);
if (automat) {
UInt_t w,h;
latex.GetTextExtent(w,h,GetTitle());
labelsize = h/hh;
Double_t wxlabel = TMath::Abs(gPad->XtoPixel(x2) - gPad->XtoPixel(x1));
if (w > 0.99*wxlabel) {labelsize *= 0.99*wxlabel/w; h = UInt_t(h*0.99*wxlabel/w);}
if (h < 1) h = 1;
labelsize = Double_t(h)/hh;
if (wh < hh) labelsize *= hh/wh;
latex.SetTextSize(labelsize);
}
Int_t halign = GetTextAlign()/10;
Int_t valign = GetTextAlign()%10;
Double_t x = 0.5*(x1+x2);
if (halign == 1) x = x1 + 0.02*(x2-x1);
if (halign == 3) x = x2 - 0.02*(x2-x1);
Double_t y = 0.5*(y1+y2);
if (valign == 1) y = y1 + 0.02*(y2-y1);
if (valign == 3) y = y2 - 0.02*(y2-y1);
latex.PaintLatex(x, y, GetTextAngle(),labelsize,GetLabel());
}
//______________________________________________________________________________
void TPaveLabel::SavePrimitive(ofstream &out, Option_t *)
{
// Save primitive as a C++ statement(s) on output stream out
char quote = '"';
out<<" "<<endl;
if (gROOT->ClassSaved(TPaveLabel::Class())) {
out<<" ";
} else {
out<<" TPaveLabel *";
}
TString s = fLabel.Data();
s.ReplaceAll("\"","\\\"");
if (fOption.Contains("NDC")) {
out<<"pl = new TPaveLabel("<<fX1NDC<<","<<fY1NDC<<","<<fX2NDC<<","<<fY2NDC
<<","<<quote<<s.Data()<<quote<<","<<quote<<fOption<<quote<<");"<<endl;
} else {
out<<"pl = new TPaveLabel("<<gPad->PadtoX(fX1)<<","<<gPad->PadtoY(fY1)<<","<<gPad->PadtoX(fX2)<<","<<gPad->PadtoY(fY2)
<<","<<quote<<s.Data()<<quote<<","<<quote<<fOption<<quote<<");"<<endl;
}
if (fBorderSize != 3) {
out<<" pt->SetBorderSize("<<fBorderSize<<");"<<endl;
}
SaveFillAttributes(out,"pl",19,1001);
SaveLineAttributes(out,"pl",1,1,1);
SaveTextAttributes(out,"pl",22,0,1,62,0);
out<<" pl->Draw();"<<endl;
}
<|endoftext|> |
<commit_before>/**************************************************************************
** This file is part of LiteIDE
**
** Copyright (c) 2011-2016 LiteIDE Team. All rights reserved.
**
** 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.
**
** In addition, as a special exception, that plugins developed for LiteIDE,
** are allowed to remain closed sourced and can be distributed under any license .
** These rights are included in the file LGPL_EXCEPTION.txt in this package.
**
**************************************************************************/
// Module: debugwidget.cpp
// Creator: visualfc <visualfc@gmail.com>
#include "debugwidget.h"
#include <QTreeView>
#include <QTabWidget>
#include <QVBoxLayout>
#include <QHBoxLayout>
#include <QLineEdit>
#include <QPushButton>
#include <QHeaderView>
#include <QPlainTextEdit>
#include <QVariant>
#include <QDebug>
#include <QFile>
#include <QMenu>
#include <QAction>
#include <QInputDialog>
//lite_memory_check_begin
#if defined(WIN32) && defined(_MSC_VER) && defined(_DEBUG)
#define _CRTDBG_MAP_ALLOC
#include <stdlib.h>
#include <crtdbg.h>
#define DEBUG_NEW new( _NORMAL_BLOCK, __FILE__, __LINE__ )
#define new DEBUG_NEW
#endif
//lite_memory_check_end
DebugWidget::DebugWidget(LiteApi::IApplication *app, QObject *parent) :
QObject(parent),
m_liteApp(app),
m_widget(new QWidget),
m_debugger(0)
{
m_tabWidget = new QTabWidget;
m_asyncView = new QTreeView;
m_varsView = new QTreeView;
m_watchView = new QTreeView;
m_statckView = new QTreeView;
m_libraryView = new QTreeView;
m_asyncView->setEditTriggers(0);
m_varsView->setEditTriggers(0);
m_varsView->setContextMenuPolicy(Qt::CustomContextMenu);
m_watchView->setEditTriggers(0);
m_watchView->setContextMenuPolicy(Qt::CustomContextMenu);
m_statckView->setEditTriggers(0);
#if QT_VERSION >= 0x050000
m_statckView->horizontalHeader()->setSectionResizeMode(1,QHeaderView::ResizeToContents);
#else
m_statckView->header()->setResizeMode(QHeaderView::ResizeToContents);
#endif
m_libraryView->setEditTriggers(0);
m_debugLogEdit = new TerminalEdit;
m_debugLogEdit->setReadOnly(false);
m_debugLogEdit->setMaximumBlockCount(1024);
m_debugLogEdit->setLineWrapMode(QPlainTextEdit::NoWrap);
m_tabWidget->addTab(m_asyncView,tr("Async Record"));
m_tabWidget->addTab(m_varsView,tr("Variables"));
m_tabWidget->addTab(m_watchView,tr("Watch"));
m_tabWidget->addTab(m_statckView,tr("Call Stack"));
m_tabWidget->addTab(m_libraryView,tr("Libraries"));
m_tabWidget->addTab(m_debugLogEdit,tr("Console"));
QVBoxLayout *layout = new QVBoxLayout;
layout->setMargin(0);
layout->addWidget(m_tabWidget);
m_widget->setLayout(layout);
m_watchMenu = new QMenu(m_widget);
m_addWatchAct = new QAction(tr("Add Global Watch"),this);
//m_addLocalWatchAct = new QAction(tr("Add Local Watch"),this);
m_removeWatchAct = new QAction(tr("Remove Watch"),this);
m_removeAllWatchAct = new QAction(tr("Remove All Watches"),this);
m_watchMenu->addAction(m_addWatchAct);
//m_watchMenu->addAction(m_addLocalWatchAct);
m_watchMenu->addSeparator();
m_watchMenu->addAction(m_removeWatchAct);
m_watchMenu->addAction(m_removeAllWatchAct);
connect(m_debugLogEdit,SIGNAL(enterText(QString)),this,SLOT(enterText(QString)));
connect(m_varsView,SIGNAL(expanded(QModelIndex)),this,SLOT(expandedVarsView(QModelIndex)));
connect(m_watchView,SIGNAL(customContextMenuRequested(QPoint)),this,SLOT(watchViewContextMenu(QPoint)));
connect(m_addWatchAct,SIGNAL(triggered()),this,SLOT(addWatch()));
//connect(m_addLocalWatchAct,SIGNAL(triggered()),this,SLOT(addLocalWatch()));
connect(m_removeWatchAct,SIGNAL(triggered()),this,SLOT(removeWatch()));
connect(m_removeAllWatchAct,SIGNAL(triggered()),this,SLOT(removeAllWatchAct()));
connect(m_statckView,SIGNAL(doubleClicked(QModelIndex)),this,SLOT(doubleClickedStack(QModelIndex)));
}
DebugWidget::~DebugWidget()
{
if (m_widget) {
delete m_widget;
}
}
QWidget *DebugWidget::widget()
{
return m_widget;
}
void DebugWidget::enterText(const QString &text)
{
QString cmd = text.simplified();
if (!cmd.isEmpty() && m_debugger && m_debugger->isRunning()) {
emit debugCmdInput();
m_debugger->enterDebugText(cmd);
}
}
void DebugWidget::clearLog()
{
m_debugLogEdit->clear();
}
void DebugWidget::appendLog(const QString &log)
{
m_debugLogEdit->append(log);
}
static void setResizeView(QTreeView *view)
{
QAbstractItemModel *model = view->model();
if (!model) {
return;
}
if (model->columnCount() <= 1) {
view->setHeaderHidden(true);
return;
}
#if QT_VERSION >= 0x050000
view->header()->setSectionResizeMode(0,QHeaderView::ResizeToContents);
#else
view->header()->setResizeMode(0,QHeaderView::ResizeToContents);
#endif
}
void DebugWidget::setDebugger(LiteApi::IDebugger *debug)
{
if (m_debugger == debug) {
return;
}
m_debugger = debug;
if (!m_debugger) {
return;
}
m_asyncView->setModel(debug->debugModel(LiteApi::ASYNC_MODEL));
m_varsView->setModel(debug->debugModel(LiteApi::VARS_MODEL));
m_watchView->setModel(debug->debugModel(LiteApi::WATCHES_MODEL));
m_statckView->setModel(debug->debugModel(LiteApi::CALLSTACK_MODEL));
m_libraryView->setModel(debug->debugModel(LiteApi::LIBRARY_MODEL));
setResizeView(m_asyncView);
setResizeView(m_varsView);
setResizeView(m_watchView);
setResizeView(m_statckView);
setResizeView(m_libraryView);
connect(m_debugger,SIGNAL(setExpand(LiteApi::DEBUG_MODEL_TYPE,QModelIndex,bool)),this,SLOT(setExpand(LiteApi::DEBUG_MODEL_TYPE,QModelIndex,bool)));
connect(m_debugger,SIGNAL(watchCreated(QString,QString)),this,SLOT(watchCreated(QString,QString)));
connect(m_debugger,SIGNAL(watchRemoved(QString)),this,SLOT(watchRemoved(QString)));
}
void DebugWidget::expandedVarsView(QModelIndex index)
{
if (!index.isValid()) {
return;
}
if (!m_debugger) {
return;
}
m_debugger->expandItem(index,LiteApi::VARS_MODEL);
}
void DebugWidget::setExpand(LiteApi::DEBUG_MODEL_TYPE type, const QModelIndex &index, bool expanded)
{
if (!index.isValid()) {
return;
}
if (!m_debugger) {
return;
}
QTreeView *view = 0;
switch (type) {
case LiteApi::VARS_MODEL:
view = m_varsView;
break;
case LiteApi::ASYNC_MODEL:
view = m_asyncView;
break;
case LiteApi::CALLSTACK_MODEL:
view = m_statckView;
break;
case LiteApi::LIBRARY_MODEL:
view = m_libraryView;
break;
default:
view = 0;
}
if (view) {
view->setExpanded(index,expanded);
}
}
void DebugWidget::watchViewContextMenu(QPoint pos)
{
QMenu *contextMenu = m_watchMenu;
if (contextMenu && contextMenu->actions().count() > 0) {
contextMenu->popup(m_watchView->mapToGlobal(pos));
}
}
void DebugWidget::loadDebugInfo(const QString &id)
{
m_watchMap.clear();
m_debugger->setInitWatchList(m_liteApp->settings()->value(id+"/watch").toStringList());
// foreach(QString var, m_liteApp->settings()->value(id+"/watch").toStringList()) {
// if (var.indexOf(".") < 0) {
// //local var
// m_debugger->createWatch(var,true,false);
// }
// m_debugger->createWatch(var,false,true);
// }
}
void DebugWidget::saveDebugInfo(const QString &id)
{
QStringList vars;
foreach(QString var, m_watchMap.values()) {
vars.append(var);
}
m_liteApp->settings()->setValue(id+"/watch",vars);
}
void DebugWidget::addWatch()
{
QString text = QInputDialog::getText(this->m_widget,tr("Add Global Watch"),tr("Watch expression (e.g. main.var os.Stdout):"));
if (text.isEmpty()) {
return;
}
m_debugger->createWatch(text);
}
void DebugWidget::removeWatch()
{
QModelIndex index = m_watchView->currentIndex();
if (!index.isValid()) {
return;
}
QModelIndex head = m_watchView->model()->index(index.row(),0);
if (!head.isValid()) {
return;
}
QString name = head.data(Qt::UserRole + 1).toString();
m_debugger->removeWatch(name);
}
void DebugWidget::removeAllWatchAct()
{
m_debugger->removeAllWatch();
m_watchMap.clear();
}
void DebugWidget::watchCreated(QString var,QString name)
{
if (!m_watchMap.keys().contains(var)) {
m_watchMap.insert(var,name);
}
}
void DebugWidget::watchRemoved(QString var)
{
m_watchMap.remove(var);
}
void DebugWidget::setInputFocus()
{
m_debugLogEdit->setFocus();
}
void DebugWidget::doubleClickedStack(QModelIndex index)
{
if (!index.isValid()) {
return;
}
if (!m_debugger) {
return;
}
m_debugger->showFrame(index);
}
<commit_msg>fix build qt5<commit_after>/**************************************************************************
** This file is part of LiteIDE
**
** Copyright (c) 2011-2016 LiteIDE Team. All rights reserved.
**
** 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.
**
** In addition, as a special exception, that plugins developed for LiteIDE,
** are allowed to remain closed sourced and can be distributed under any license .
** These rights are included in the file LGPL_EXCEPTION.txt in this package.
**
**************************************************************************/
// Module: debugwidget.cpp
// Creator: visualfc <visualfc@gmail.com>
#include "debugwidget.h"
#include <QTreeView>
#include <QTabWidget>
#include <QVBoxLayout>
#include <QHBoxLayout>
#include <QLineEdit>
#include <QPushButton>
#include <QHeaderView>
#include <QPlainTextEdit>
#include <QVariant>
#include <QDebug>
#include <QFile>
#include <QMenu>
#include <QAction>
#include <QInputDialog>
//lite_memory_check_begin
#if defined(WIN32) && defined(_MSC_VER) && defined(_DEBUG)
#define _CRTDBG_MAP_ALLOC
#include <stdlib.h>
#include <crtdbg.h>
#define DEBUG_NEW new( _NORMAL_BLOCK, __FILE__, __LINE__ )
#define new DEBUG_NEW
#endif
//lite_memory_check_end
DebugWidget::DebugWidget(LiteApi::IApplication *app, QObject *parent) :
QObject(parent),
m_liteApp(app),
m_widget(new QWidget),
m_debugger(0)
{
m_tabWidget = new QTabWidget;
m_asyncView = new QTreeView;
m_varsView = new QTreeView;
m_watchView = new QTreeView;
m_statckView = new QTreeView;
m_libraryView = new QTreeView;
m_asyncView->setEditTriggers(0);
m_varsView->setEditTriggers(0);
m_varsView->setContextMenuPolicy(Qt::CustomContextMenu);
m_watchView->setEditTriggers(0);
m_watchView->setContextMenuPolicy(Qt::CustomContextMenu);
m_statckView->setEditTriggers(0);
#if QT_VERSION >= 0x050000
m_statckView->header()->setSectionResizeMode(QHeaderView::ResizeToContents);
#else
m_statckView->header()->setResizeMode(QHeaderView::ResizeToContents);
#endif
m_libraryView->setEditTriggers(0);
m_debugLogEdit = new TerminalEdit;
m_debugLogEdit->setReadOnly(false);
m_debugLogEdit->setMaximumBlockCount(1024);
m_debugLogEdit->setLineWrapMode(QPlainTextEdit::NoWrap);
m_tabWidget->addTab(m_asyncView,tr("Async Record"));
m_tabWidget->addTab(m_varsView,tr("Variables"));
m_tabWidget->addTab(m_watchView,tr("Watch"));
m_tabWidget->addTab(m_statckView,tr("Call Stack"));
m_tabWidget->addTab(m_libraryView,tr("Libraries"));
m_tabWidget->addTab(m_debugLogEdit,tr("Console"));
QVBoxLayout *layout = new QVBoxLayout;
layout->setMargin(0);
layout->addWidget(m_tabWidget);
m_widget->setLayout(layout);
m_watchMenu = new QMenu(m_widget);
m_addWatchAct = new QAction(tr("Add Global Watch"),this);
//m_addLocalWatchAct = new QAction(tr("Add Local Watch"),this);
m_removeWatchAct = new QAction(tr("Remove Watch"),this);
m_removeAllWatchAct = new QAction(tr("Remove All Watches"),this);
m_watchMenu->addAction(m_addWatchAct);
//m_watchMenu->addAction(m_addLocalWatchAct);
m_watchMenu->addSeparator();
m_watchMenu->addAction(m_removeWatchAct);
m_watchMenu->addAction(m_removeAllWatchAct);
connect(m_debugLogEdit,SIGNAL(enterText(QString)),this,SLOT(enterText(QString)));
connect(m_varsView,SIGNAL(expanded(QModelIndex)),this,SLOT(expandedVarsView(QModelIndex)));
connect(m_watchView,SIGNAL(customContextMenuRequested(QPoint)),this,SLOT(watchViewContextMenu(QPoint)));
connect(m_addWatchAct,SIGNAL(triggered()),this,SLOT(addWatch()));
//connect(m_addLocalWatchAct,SIGNAL(triggered()),this,SLOT(addLocalWatch()));
connect(m_removeWatchAct,SIGNAL(triggered()),this,SLOT(removeWatch()));
connect(m_removeAllWatchAct,SIGNAL(triggered()),this,SLOT(removeAllWatchAct()));
connect(m_statckView,SIGNAL(doubleClicked(QModelIndex)),this,SLOT(doubleClickedStack(QModelIndex)));
}
DebugWidget::~DebugWidget()
{
if (m_widget) {
delete m_widget;
}
}
QWidget *DebugWidget::widget()
{
return m_widget;
}
void DebugWidget::enterText(const QString &text)
{
QString cmd = text.simplified();
if (!cmd.isEmpty() && m_debugger && m_debugger->isRunning()) {
emit debugCmdInput();
m_debugger->enterDebugText(cmd);
}
}
void DebugWidget::clearLog()
{
m_debugLogEdit->clear();
}
void DebugWidget::appendLog(const QString &log)
{
m_debugLogEdit->append(log);
}
static void setResizeView(QTreeView *view)
{
QAbstractItemModel *model = view->model();
if (!model) {
return;
}
if (model->columnCount() <= 1) {
view->setHeaderHidden(true);
return;
}
#if QT_VERSION >= 0x050000
view->header()->setSectionResizeMode(0,QHeaderView::ResizeToContents);
#else
view->header()->setResizeMode(0,QHeaderView::ResizeToContents);
#endif
}
void DebugWidget::setDebugger(LiteApi::IDebugger *debug)
{
if (m_debugger == debug) {
return;
}
m_debugger = debug;
if (!m_debugger) {
return;
}
m_asyncView->setModel(debug->debugModel(LiteApi::ASYNC_MODEL));
m_varsView->setModel(debug->debugModel(LiteApi::VARS_MODEL));
m_watchView->setModel(debug->debugModel(LiteApi::WATCHES_MODEL));
m_statckView->setModel(debug->debugModel(LiteApi::CALLSTACK_MODEL));
m_libraryView->setModel(debug->debugModel(LiteApi::LIBRARY_MODEL));
setResizeView(m_asyncView);
setResizeView(m_varsView);
setResizeView(m_watchView);
setResizeView(m_statckView);
setResizeView(m_libraryView);
connect(m_debugger,SIGNAL(setExpand(LiteApi::DEBUG_MODEL_TYPE,QModelIndex,bool)),this,SLOT(setExpand(LiteApi::DEBUG_MODEL_TYPE,QModelIndex,bool)));
connect(m_debugger,SIGNAL(watchCreated(QString,QString)),this,SLOT(watchCreated(QString,QString)));
connect(m_debugger,SIGNAL(watchRemoved(QString)),this,SLOT(watchRemoved(QString)));
}
void DebugWidget::expandedVarsView(QModelIndex index)
{
if (!index.isValid()) {
return;
}
if (!m_debugger) {
return;
}
m_debugger->expandItem(index,LiteApi::VARS_MODEL);
}
void DebugWidget::setExpand(LiteApi::DEBUG_MODEL_TYPE type, const QModelIndex &index, bool expanded)
{
if (!index.isValid()) {
return;
}
if (!m_debugger) {
return;
}
QTreeView *view = 0;
switch (type) {
case LiteApi::VARS_MODEL:
view = m_varsView;
break;
case LiteApi::ASYNC_MODEL:
view = m_asyncView;
break;
case LiteApi::CALLSTACK_MODEL:
view = m_statckView;
break;
case LiteApi::LIBRARY_MODEL:
view = m_libraryView;
break;
default:
view = 0;
}
if (view) {
view->setExpanded(index,expanded);
}
}
void DebugWidget::watchViewContextMenu(QPoint pos)
{
QMenu *contextMenu = m_watchMenu;
if (contextMenu && contextMenu->actions().count() > 0) {
contextMenu->popup(m_watchView->mapToGlobal(pos));
}
}
void DebugWidget::loadDebugInfo(const QString &id)
{
m_watchMap.clear();
m_debugger->setInitWatchList(m_liteApp->settings()->value(id+"/watch").toStringList());
// foreach(QString var, m_liteApp->settings()->value(id+"/watch").toStringList()) {
// if (var.indexOf(".") < 0) {
// //local var
// m_debugger->createWatch(var,true,false);
// }
// m_debugger->createWatch(var,false,true);
// }
}
void DebugWidget::saveDebugInfo(const QString &id)
{
QStringList vars;
foreach(QString var, m_watchMap.values()) {
vars.append(var);
}
m_liteApp->settings()->setValue(id+"/watch",vars);
}
void DebugWidget::addWatch()
{
QString text = QInputDialog::getText(this->m_widget,tr("Add Global Watch"),tr("Watch expression (e.g. main.var os.Stdout):"));
if (text.isEmpty()) {
return;
}
m_debugger->createWatch(text);
}
void DebugWidget::removeWatch()
{
QModelIndex index = m_watchView->currentIndex();
if (!index.isValid()) {
return;
}
QModelIndex head = m_watchView->model()->index(index.row(),0);
if (!head.isValid()) {
return;
}
QString name = head.data(Qt::UserRole + 1).toString();
m_debugger->removeWatch(name);
}
void DebugWidget::removeAllWatchAct()
{
m_debugger->removeAllWatch();
m_watchMap.clear();
}
void DebugWidget::watchCreated(QString var,QString name)
{
if (!m_watchMap.keys().contains(var)) {
m_watchMap.insert(var,name);
}
}
void DebugWidget::watchRemoved(QString var)
{
m_watchMap.remove(var);
}
void DebugWidget::setInputFocus()
{
m_debugLogEdit->setFocus();
}
void DebugWidget::doubleClickedStack(QModelIndex index)
{
if (!index.isValid()) {
return;
}
if (!m_debugger) {
return;
}
m_debugger->showFrame(index);
}
<|endoftext|> |
<commit_before>//===- lib/ReaderWriter/FileArchive.cpp -----------------------------------===//
//
// The LLVM Linker
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "lld/Core/ArchiveLibraryFile.h"
#include "lld/Core/File.h"
#include "lld/Core/LLVM.h"
#include "lld/Core/Reader.h"
#include "llvm/ADT/StringRef.h"
#include "llvm/Object/Archive.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/MemoryBuffer.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/Object/Error.h"
#include "llvm/Support/ErrorOr.h"
#include "llvm/Support/FileSystem.h"
#include "llvm/Support/raw_ostream.h"
#include <memory>
#include <set>
#include <string>
#include <system_error>
#include <unordered_map>
#include <utility>
#include <vector>
using llvm::object::Archive;
namespace lld {
namespace {
/// \brief The FileArchive class represents an Archive Library file
class FileArchive : public lld::ArchiveLibraryFile {
public:
FileArchive(std::unique_ptr<MemoryBuffer> mb, const Registry ®,
StringRef path, bool logLoading)
: ArchiveLibraryFile(path), _mb(std::shared_ptr<MemoryBuffer>(mb.release())),
_registry(reg), _logLoading(logLoading) {}
/// \brief Check if any member of the archive contains an Atom with the
/// specified name and return the File object for that member, or nullptr.
File *find(StringRef name) override {
auto member = _symbolMemberMap.find(name);
if (member == _symbolMemberMap.end())
return nullptr;
Archive::child_iterator ci = member->second;
if (ci->getError())
return nullptr;
// Don't return a member already returned
ErrorOr<StringRef> buf = (*ci)->getBuffer();
if (!buf)
return nullptr;
const char *memberStart = buf->data();
if (_membersInstantiated.count(memberStart))
return nullptr;
_membersInstantiated.insert(memberStart);
std::unique_ptr<File> result;
if (instantiateMember(ci, result))
return nullptr;
File *file = result.get();
_filesReturned.push_back(std::move(result));
// Give up the file pointer. It was stored and will be destroyed with destruction of FileArchive
return file;
}
/// \brief parse each member
std::error_code
parseAllMembers(std::vector<std::unique_ptr<File>> &result) override {
if (std::error_code ec = parse())
return ec;
for (auto mf = _archive->child_begin(), me = _archive->child_end();
mf != me; ++mf) {
std::unique_ptr<File> file;
if (std::error_code ec = instantiateMember(mf, file))
return ec;
result.push_back(std::move(file));
}
return std::error_code();
}
const AtomRange<DefinedAtom> defined() const override {
return _noDefinedAtoms;
}
const AtomRange<UndefinedAtom> undefined() const override {
return _noUndefinedAtoms;
}
const AtomRange<SharedLibraryAtom> sharedLibrary() const override {
return _noSharedLibraryAtoms;
}
const AtomRange<AbsoluteAtom> absolute() const override {
return _noAbsoluteAtoms;
}
void clearAtoms() override {
_noDefinedAtoms.clear();
_noUndefinedAtoms.clear();
_noSharedLibraryAtoms.clear();
_noAbsoluteAtoms.clear();
}
protected:
std::error_code doParse() override {
// Make Archive object which will be owned by FileArchive object.
std::error_code ec;
_archive.reset(new Archive(_mb->getMemBufferRef(), ec));
if (ec)
return ec;
if ((ec = buildTableOfContents()))
return ec;
return std::error_code();
}
private:
std::error_code instantiateMember(Archive::child_iterator cOrErr,
std::unique_ptr<File> &result) const {
if (std::error_code ec = cOrErr->getError())
return ec;
Archive::child_iterator member = cOrErr->get();
ErrorOr<llvm::MemoryBufferRef> mbOrErr = (*member)->getMemoryBufferRef();
if (std::error_code ec = mbOrErr.getError())
return ec;
llvm::MemoryBufferRef mb = mbOrErr.get();
std::string memberPath = (_archive->getFileName() + "("
+ mb.getBufferIdentifier() + ")").str();
if (_logLoading)
llvm::errs() << memberPath << "\n";
std::unique_ptr<MemoryBuffer> memberMB(MemoryBuffer::getMemBuffer(
mb.getBuffer(), mb.getBufferIdentifier(), false));
ErrorOr<std::unique_ptr<File>> fileOrErr =
_registry.loadFile(std::move(memberMB));
if (std::error_code ec = fileOrErr.getError())
return ec;
result = std::move(fileOrErr.get());
if (std::error_code ec = result->parse())
return ec;
result->setArchivePath(_archive->getFileName());
// The memory buffer is co-owned by the archive file and the children,
// so that the bufffer is deallocated when all the members are destructed.
result->setSharedMemoryBuffer(_mb);
return std::error_code();
}
std::error_code buildTableOfContents() {
DEBUG_WITH_TYPE("FileArchive", llvm::dbgs()
<< "Table of contents for archive '"
<< _archive->getFileName() << "':\n");
for (const Archive::Symbol &sym : _archive->symbols()) {
StringRef name = sym.getName();
ErrorOr<Archive::child_iterator> memberOrErr = sym.getMember();
if (std::error_code ec = memberOrErr.getError())
return ec;
Archive::child_iterator member = memberOrErr.get();
DEBUG_WITH_TYPE("FileArchive",
llvm::dbgs()
<< llvm::format("0x%08llX ",
(*member)->getBuffer()->data())
<< "'" << name << "'\n");
_symbolMemberMap.insert(std::make_pair(name, member));
}
return std::error_code();
}
typedef std::unordered_map<StringRef, Archive::child_iterator> MemberMap;
typedef std::set<const char *> InstantiatedSet;
std::shared_ptr<MemoryBuffer> _mb;
const Registry &_registry;
std::unique_ptr<Archive> _archive;
MemberMap _symbolMemberMap;
InstantiatedSet _membersInstantiated;
bool _logLoading;
std::vector<std::unique_ptr<MemoryBuffer>> _memberBuffers;
std::vector<std::unique_ptr<File>> _filesReturned;
};
class ArchiveReader : public Reader {
public:
ArchiveReader(bool logLoading) : _logLoading(logLoading) {}
bool canParse(file_magic magic, MemoryBufferRef) const override {
return magic == llvm::sys::fs::file_magic::archive;
}
ErrorOr<std::unique_ptr<File>> loadFile(std::unique_ptr<MemoryBuffer> mb,
const Registry ®) const override {
StringRef path = mb->getBufferIdentifier();
std::unique_ptr<File> ret =
llvm::make_unique<FileArchive>(std::move(mb), reg, path, _logLoading);
return std::move(ret);
}
private:
bool _logLoading;
};
} // anonymous namespace
void Registry::addSupportArchives(bool logLoading) {
add(std::unique_ptr<Reader>(new ArchiveReader(logLoading)));
}
} // namespace lld
<commit_msg>Fix builds broken in r267008.<commit_after>//===- lib/ReaderWriter/FileArchive.cpp -----------------------------------===//
//
// The LLVM Linker
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "lld/Core/ArchiveLibraryFile.h"
#include "lld/Core/File.h"
#include "lld/Core/LLVM.h"
#include "lld/Core/Reader.h"
#include "llvm/ADT/StringRef.h"
#include "llvm/Object/Archive.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/Format.h"
#include "llvm/Support/MemoryBuffer.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/Object/Error.h"
#include "llvm/Support/ErrorOr.h"
#include "llvm/Support/FileSystem.h"
#include "llvm/Support/raw_ostream.h"
#include <memory>
#include <set>
#include <string>
#include <system_error>
#include <unordered_map>
#include <utility>
#include <vector>
using llvm::object::Archive;
namespace lld {
namespace {
/// \brief The FileArchive class represents an Archive Library file
class FileArchive : public lld::ArchiveLibraryFile {
public:
FileArchive(std::unique_ptr<MemoryBuffer> mb, const Registry ®,
StringRef path, bool logLoading)
: ArchiveLibraryFile(path), _mb(std::shared_ptr<MemoryBuffer>(mb.release())),
_registry(reg), _logLoading(logLoading) {}
/// \brief Check if any member of the archive contains an Atom with the
/// specified name and return the File object for that member, or nullptr.
File *find(StringRef name) override {
auto member = _symbolMemberMap.find(name);
if (member == _symbolMemberMap.end())
return nullptr;
Archive::child_iterator ci = member->second;
if (ci->getError())
return nullptr;
// Don't return a member already returned
ErrorOr<StringRef> buf = (*ci)->getBuffer();
if (!buf)
return nullptr;
const char *memberStart = buf->data();
if (_membersInstantiated.count(memberStart))
return nullptr;
_membersInstantiated.insert(memberStart);
std::unique_ptr<File> result;
if (instantiateMember(ci, result))
return nullptr;
File *file = result.get();
_filesReturned.push_back(std::move(result));
// Give up the file pointer. It was stored and will be destroyed with destruction of FileArchive
return file;
}
/// \brief parse each member
std::error_code
parseAllMembers(std::vector<std::unique_ptr<File>> &result) override {
if (std::error_code ec = parse())
return ec;
for (auto mf = _archive->child_begin(), me = _archive->child_end();
mf != me; ++mf) {
std::unique_ptr<File> file;
if (std::error_code ec = instantiateMember(mf, file))
return ec;
result.push_back(std::move(file));
}
return std::error_code();
}
const AtomRange<DefinedAtom> defined() const override {
return _noDefinedAtoms;
}
const AtomRange<UndefinedAtom> undefined() const override {
return _noUndefinedAtoms;
}
const AtomRange<SharedLibraryAtom> sharedLibrary() const override {
return _noSharedLibraryAtoms;
}
const AtomRange<AbsoluteAtom> absolute() const override {
return _noAbsoluteAtoms;
}
void clearAtoms() override {
_noDefinedAtoms.clear();
_noUndefinedAtoms.clear();
_noSharedLibraryAtoms.clear();
_noAbsoluteAtoms.clear();
}
protected:
std::error_code doParse() override {
// Make Archive object which will be owned by FileArchive object.
std::error_code ec;
_archive.reset(new Archive(_mb->getMemBufferRef(), ec));
if (ec)
return ec;
if ((ec = buildTableOfContents()))
return ec;
return std::error_code();
}
private:
std::error_code instantiateMember(Archive::child_iterator cOrErr,
std::unique_ptr<File> &result) const {
if (std::error_code ec = cOrErr->getError())
return ec;
Archive::child_iterator member = cOrErr->get();
ErrorOr<llvm::MemoryBufferRef> mbOrErr = (*member)->getMemoryBufferRef();
if (std::error_code ec = mbOrErr.getError())
return ec;
llvm::MemoryBufferRef mb = mbOrErr.get();
std::string memberPath = (_archive->getFileName() + "("
+ mb.getBufferIdentifier() + ")").str();
if (_logLoading)
llvm::errs() << memberPath << "\n";
std::unique_ptr<MemoryBuffer> memberMB(MemoryBuffer::getMemBuffer(
mb.getBuffer(), mb.getBufferIdentifier(), false));
ErrorOr<std::unique_ptr<File>> fileOrErr =
_registry.loadFile(std::move(memberMB));
if (std::error_code ec = fileOrErr.getError())
return ec;
result = std::move(fileOrErr.get());
if (std::error_code ec = result->parse())
return ec;
result->setArchivePath(_archive->getFileName());
// The memory buffer is co-owned by the archive file and the children,
// so that the bufffer is deallocated when all the members are destructed.
result->setSharedMemoryBuffer(_mb);
return std::error_code();
}
std::error_code buildTableOfContents() {
DEBUG_WITH_TYPE("FileArchive", llvm::dbgs()
<< "Table of contents for archive '"
<< _archive->getFileName() << "':\n");
for (const Archive::Symbol &sym : _archive->symbols()) {
StringRef name = sym.getName();
ErrorOr<Archive::child_iterator> memberOrErr = sym.getMember();
if (std::error_code ec = memberOrErr.getError())
return ec;
Archive::child_iterator member = memberOrErr.get();
DEBUG_WITH_TYPE("FileArchive",
llvm::dbgs()
<< llvm::format("0x%08llX ",
(*member)->getBuffer()->data())
<< "'" << name << "'\n");
_symbolMemberMap.insert(std::make_pair(name, member));
}
return std::error_code();
}
typedef std::unordered_map<StringRef, Archive::child_iterator> MemberMap;
typedef std::set<const char *> InstantiatedSet;
std::shared_ptr<MemoryBuffer> _mb;
const Registry &_registry;
std::unique_ptr<Archive> _archive;
MemberMap _symbolMemberMap;
InstantiatedSet _membersInstantiated;
bool _logLoading;
std::vector<std::unique_ptr<MemoryBuffer>> _memberBuffers;
std::vector<std::unique_ptr<File>> _filesReturned;
};
class ArchiveReader : public Reader {
public:
ArchiveReader(bool logLoading) : _logLoading(logLoading) {}
bool canParse(file_magic magic, MemoryBufferRef) const override {
return magic == llvm::sys::fs::file_magic::archive;
}
ErrorOr<std::unique_ptr<File>> loadFile(std::unique_ptr<MemoryBuffer> mb,
const Registry ®) const override {
StringRef path = mb->getBufferIdentifier();
std::unique_ptr<File> ret =
llvm::make_unique<FileArchive>(std::move(mb), reg, path, _logLoading);
return std::move(ret);
}
private:
bool _logLoading;
};
} // anonymous namespace
void Registry::addSupportArchives(bool logLoading) {
add(std::unique_ptr<Reader>(new ArchiveReader(logLoading)));
}
} // namespace lld
<|endoftext|> |
<commit_before>#include "neovimconnector.h"
#include <QtGlobal>
#include <QMetaMethod>
#include <QLocalSocket>
#include <QTcpSocket>
#include "msgpackrequest.h"
#include "neovimconnectorhelper.h"
#include "msgpackiodevice.h"
namespace NeovimQt {
/**
* \class NeovimQt::NeovimConnector
*
* \brief A Connection to a Neovim instance
*
*/
/**
* Create a new Neovim API connection from an open IO device
*/
NeovimConnector::NeovimConnector(QIODevice *dev)
:NeovimConnector(new MsgpackIODevice(dev))
{
}
NeovimConnector::NeovimConnector(MsgpackIODevice *dev)
:QObject(), m_dev(dev), m_helper(0), m_error(NoError), m_api0(NULL), m_api1(NULL), m_api2(NULL),
m_channel(0), m_api_compat(0), m_api_supported(0), m_ctype(OtherConnection), m_ready(false), m_timeout(10000)
{
m_helper = new NeovimConnectorHelper(this);
qRegisterMetaType<NeovimError>("NeovimError");
connect(m_dev, &MsgpackIODevice::error,
this, &NeovimConnector::msgpackError);
if ( !m_dev->isOpen() ) {
return;
}
discoverMetadata();
}
void NeovimConnector::setRequestTimeout(int ms)
{
this->m_timeout = ms;
}
/**
* Sets latest error code and message for this connector
*/
void NeovimConnector::setError(NeovimError err, const QString& msg)
{
m_ready = false;
if (m_error == NoError && err != NoError) {
m_error = err;
m_errorString = msg;
qWarning() << "Neovim fatal error" << m_errorString;
emit error(m_error);
} else {
// Only the first error is raised
qDebug() << "(Ignored) Neovim fatal error" << msg;
}
}
/** Reset error state */
void NeovimConnector::clearError()
{
m_error = NoError;
m_errorString = "";
}
/**
* Called when an error takes place
*/
NeovimConnector::NeovimError NeovimConnector::errorCause()
{
return m_error;
}
/**
* An human readable error message for the last error
*/
QString NeovimConnector::errorString()
{
return m_errorString;
}
/**
* Returns the channel id used by Neovim to identify this connection
*/
uint64_t NeovimConnector::channel()
{
return m_channel;
}
/**
* Request API information from Neovim
*/
void NeovimConnector::discoverMetadata()
{
MsgpackRequest *r = m_dev->startRequestUnchecked("vim_get_api_info", 0);
connect(r, &MsgpackRequest::finished,
m_helper, &NeovimConnectorHelper::handleMetadata);
connect(r, &MsgpackRequest::error,
m_helper, &NeovimConnectorHelper::handleMetadataError);
connect(r, &MsgpackRequest::timeout,
this, &NeovimConnector::fatalTimeout);
r->setTimeout(m_timeout);
}
/**
* True if the Neovim instance is ready
* @see ready
*/
bool NeovimConnector::isReady()
{
return m_ready;
}
/**
* Decode a byte array as a string according to 'encoding'
*/
QString NeovimConnector::decode(const QByteArray& in)
{
return m_dev->decode(in);
}
/**
* Encode a string into the appropriate encoding for this Neovim instance
*
* see :h 'encoding'
*/
QByteArray NeovimConnector::encode(const QString& in)
{
return m_dev->encode(in);
}
/**
* @warning Do not call this before NeovimConnector::ready as been signaled
* @see NeovimConnector::isReady
*/
NeovimApi0* NeovimConnector::api0()
{
if ( !m_api0 ) {
if (m_api_compat <= 0) {
m_api0 = new NeovimApi0(this);
} else {
qDebug() << "This instance of neovim DOES NOT not support api level 0";
}
}
return m_api0;
}
/**
* @warning Do not call this before NeovimConnector::ready as been signaled
* @see NeovimConnector::isReady
*/
NeovimApi1* NeovimConnector::api1()
{
if ( !m_api1 ) {
if (m_api_compat <= 1 && 1 <= m_api_supported) {
m_api1 = new NeovimApi1(this);
} else {
qDebug() << "This instance of neovim DOES NOT not support api level 1";
}
}
return m_api1;
}
/** For compatibility with older versions */
NeovimApi1* NeovimConnector::neovimObject()
{
return api1();
}
/**
* @warning Do not call this before NeovimConnector::ready as been signaled
* @see NeovimConnector::isReady
*/
NeovimApi2* NeovimConnector::api2()
{
if ( !m_api2 ) {
if (m_api_compat <= 2 && 2 <= m_api_supported) {
m_api2 = new NeovimApi2(this);
} else {
qWarning() << "This instance of neovim not support api level 2";
}
}
return m_api2;
}
/**
* Launch an embedded Neovim process
* @see processExited
*/
NeovimConnector* NeovimConnector::spawn(const QStringList& params, const QString& exe)
{
QProcess *p = new QProcess();
QStringList args;
if (params.indexOf("--") == -1) {
args.append(params);
args << "--embed" << "--headless";
} else {
// Neovim accepts a -- argument after which only
// filenames are passed
int idx = params.indexOf("--");
args.append(params.mid(0, idx));
args << "--embed" << "--headless";
args.append(params.mid(idx));
}
NeovimConnector *c = new NeovimConnector(p);
c->m_ctype = SpawnedConnection;
c->m_spawnArgs = params;
c->m_spawnExe = exe;
connect(p, SIGNAL(error(QProcess::ProcessError)),
c, SLOT(processError(QProcess::ProcessError)));
connect(p, SIGNAL(finished(int, QProcess::ExitStatus)),
c, SIGNAL(processExited(int)));
connect(p, &QProcess::started,
c, &NeovimConnector::discoverMetadata);
p->start(exe, args);
return c;
}
/**
* Connect to Neovim using a local UNIX socket.
*
* This method also works in Windows, using named pipes.
*
* @see QLocalSocket
*/
NeovimConnector* NeovimConnector::connectToSocket(const QString& path)
{
QLocalSocket *s = new QLocalSocket();
NeovimConnector *c = new NeovimConnector(s);
c->m_ctype = SocketConnection;
c->m_connSocket = path;
connect(s, SIGNAL(error(QLocalSocket::LocalSocketError)),
c, SLOT(socketError()));
connect(s, &QLocalSocket::connected,
c, &NeovimConnector::discoverMetadata);
s->connectToServer(path);
return c;
}
/**
* Connect to a Neovim through a TCP connection
*
* @param host is a valid hostname or IP address
* @param port is the TCP port
*/
NeovimConnector* NeovimConnector::connectToHost(const QString& host, int port)
{
QTcpSocket *s = new QTcpSocket();
NeovimConnector *c = new NeovimConnector(s);
c->m_ctype = HostConnection;
c->m_connHost = host;
c->m_connPort = port;
connect(s, SIGNAL(error(QAbstractSocket::SocketError)),
c, SLOT(socketError()));
connect(s, &QAbstractSocket::connected,
c, &NeovimConnector::discoverMetadata);
s->connectToHost(host, port);
return c;
}
/**
* Connect to a running instance of Neovim (if available).
*
* This method gets the Neovim endpoint from the NVIM_LISTEN_ADDRESS environment
* variable, if it is not available a new Neovim instance is spawned().
*
* @see spawn()
*/
NeovimConnector* NeovimConnector::connectToNeovim(const QString& server)
{
QString addr = server;
if (addr.isEmpty()) {
addr = QString::fromLocal8Bit(qgetenv("NVIM_LISTEN_ADDRESS"));
}
if (addr.isEmpty()) {
return spawn();
}
int colon_pos = addr.lastIndexOf(':');
if (colon_pos != -1 && colon_pos != 0 && addr[colon_pos-1] != ':') {
bool ok;
int port = addr.mid(colon_pos+1).toInt(&ok);
if (ok) {
QString host = addr.mid(0, colon_pos);
return connectToHost(host, port);
}
}
return connectToSocket(addr);
}
NeovimConnector* NeovimConnector::fromStdinOut()
{
return new NeovimConnector(MsgpackIODevice::fromStdinOut());
}
/**
* Called when running embedded Neovim to report an error
* with the Neovim process
*/
void NeovimConnector::processError(QProcess::ProcessError err)
{
switch(err) {
case QProcess::FailedToStart:
setError(FailedToStart, m_dev->errorString());
break;
case QProcess::Crashed:
setError(Crashed, "The Neovim process has crashed");
break;
default:
// In practice we should be able to catch other types of
// errors from the QIODevice
qDebug() << "Neovim process error " << m_dev->errorString();
}
}
/** Handle errors from QLocalSocket or QTcpSocket */
void NeovimConnector::socketError()
{
setError(SocketError, m_dev->errorString());
}
/** Handle errors in MsgpackIODevice */
void NeovimConnector::msgpackError()
{
setError(MsgpackError, m_dev->errorString());
}
/**
* Raise a fatal error for a Neovim timeout
*
* Sometimes Neovim takes too long to respond to some requests, or maybe
* the channel is stuck. In such cases it is preferable to raise and error,
* internally this is what discoverMetadata does if Neovim does not reply.
*/
void NeovimConnector::fatalTimeout()
{
setError(RuntimeMsgpackError, "Neovim is taking too long to respond");
}
/**
* True if NeovimConnector::reconnect can be called to reconnect with Neovim. This
* is true unless you built the NeovimConnector ctor directly instead
* of using on of the static methods.
*/
bool NeovimConnector::canReconnect()
{
return m_ctype != OtherConnection;
}
/** @see NeovimConnector::NeovimConnectionType */
NeovimConnector::NeovimConnectionType NeovimConnector::connectionType()
{
return m_ctype;
}
/**
* Create a new connection using the same parameters as the current one.
*
* This is the equivalent of creating a new object with spawn(), connectToHost(),
* or connectToSocket()
*
* If canReconnect() returns false, this function will return NULL.
*/
NeovimConnector* NeovimConnector::reconnect()
{
switch(m_ctype) {
case SpawnedConnection:
return NeovimConnector::spawn(m_spawnArgs, m_spawnExe);
case HostConnection:
return NeovimConnector::connectToHost(m_connHost, m_connPort);
case SocketConnection:
return NeovimConnector::connectToSocket(m_connSocket);
default:
return NULL;
}
// NOT-REACHED
return NULL;
}
/** The minimum API level supported by this instance */
quint64 NeovimConnector::apiCompatibility()
{
return m_api_compat;
}
/** The maximum API level supported by this instance */
quint64 NeovimConnector::apiLevel()
{
return m_api_supported;
}
/**
* \fn NeovimQt::NeovimConnector::error(NeovimError)
*
* This signal is emitted when an error occurs. Use NeovimConnector::errorString
* to get an error message.
*/
/**
* \fn NeovimQt::NeovimConnector::processExited(int exitStatus)
*
* If the Neovim process was started using NeovimQt::NeovimConnector::spawn this signal
* is emitted when the process exits.
*/
} // namespace NeovimQt
#include "moc_neovimconnector.cpp"
<commit_msg>Keep arguments to nvim before any filenames: #417<commit_after>#include "neovimconnector.h"
#include <QtGlobal>
#include <QMetaMethod>
#include <QLocalSocket>
#include <QTcpSocket>
#include "msgpackrequest.h"
#include "neovimconnectorhelper.h"
#include "msgpackiodevice.h"
namespace NeovimQt {
/**
* \class NeovimQt::NeovimConnector
*
* \brief A Connection to a Neovim instance
*
*/
/**
* Create a new Neovim API connection from an open IO device
*/
NeovimConnector::NeovimConnector(QIODevice *dev)
:NeovimConnector(new MsgpackIODevice(dev))
{
}
NeovimConnector::NeovimConnector(MsgpackIODevice *dev)
:QObject(), m_dev(dev), m_helper(0), m_error(NoError), m_api0(NULL), m_api1(NULL), m_api2(NULL),
m_channel(0), m_api_compat(0), m_api_supported(0), m_ctype(OtherConnection), m_ready(false), m_timeout(10000)
{
m_helper = new NeovimConnectorHelper(this);
qRegisterMetaType<NeovimError>("NeovimError");
connect(m_dev, &MsgpackIODevice::error,
this, &NeovimConnector::msgpackError);
if ( !m_dev->isOpen() ) {
return;
}
discoverMetadata();
}
void NeovimConnector::setRequestTimeout(int ms)
{
this->m_timeout = ms;
}
/**
* Sets latest error code and message for this connector
*/
void NeovimConnector::setError(NeovimError err, const QString& msg)
{
m_ready = false;
if (m_error == NoError && err != NoError) {
m_error = err;
m_errorString = msg;
qWarning() << "Neovim fatal error" << m_errorString;
emit error(m_error);
} else {
// Only the first error is raised
qDebug() << "(Ignored) Neovim fatal error" << msg;
}
}
/** Reset error state */
void NeovimConnector::clearError()
{
m_error = NoError;
m_errorString = "";
}
/**
* Called when an error takes place
*/
NeovimConnector::NeovimError NeovimConnector::errorCause()
{
return m_error;
}
/**
* An human readable error message for the last error
*/
QString NeovimConnector::errorString()
{
return m_errorString;
}
/**
* Returns the channel id used by Neovim to identify this connection
*/
uint64_t NeovimConnector::channel()
{
return m_channel;
}
/**
* Request API information from Neovim
*/
void NeovimConnector::discoverMetadata()
{
MsgpackRequest *r = m_dev->startRequestUnchecked("vim_get_api_info", 0);
connect(r, &MsgpackRequest::finished,
m_helper, &NeovimConnectorHelper::handleMetadata);
connect(r, &MsgpackRequest::error,
m_helper, &NeovimConnectorHelper::handleMetadataError);
connect(r, &MsgpackRequest::timeout,
this, &NeovimConnector::fatalTimeout);
r->setTimeout(m_timeout);
}
/**
* True if the Neovim instance is ready
* @see ready
*/
bool NeovimConnector::isReady()
{
return m_ready;
}
/**
* Decode a byte array as a string according to 'encoding'
*/
QString NeovimConnector::decode(const QByteArray& in)
{
return m_dev->decode(in);
}
/**
* Encode a string into the appropriate encoding for this Neovim instance
*
* see :h 'encoding'
*/
QByteArray NeovimConnector::encode(const QString& in)
{
return m_dev->encode(in);
}
/**
* @warning Do not call this before NeovimConnector::ready as been signaled
* @see NeovimConnector::isReady
*/
NeovimApi0* NeovimConnector::api0()
{
if ( !m_api0 ) {
if (m_api_compat <= 0) {
m_api0 = new NeovimApi0(this);
} else {
qDebug() << "This instance of neovim DOES NOT not support api level 0";
}
}
return m_api0;
}
/**
* @warning Do not call this before NeovimConnector::ready as been signaled
* @see NeovimConnector::isReady
*/
NeovimApi1* NeovimConnector::api1()
{
if ( !m_api1 ) {
if (m_api_compat <= 1 && 1 <= m_api_supported) {
m_api1 = new NeovimApi1(this);
} else {
qDebug() << "This instance of neovim DOES NOT not support api level 1";
}
}
return m_api1;
}
/** For compatibility with older versions */
NeovimApi1* NeovimConnector::neovimObject()
{
return api1();
}
/**
* @warning Do not call this before NeovimConnector::ready as been signaled
* @see NeovimConnector::isReady
*/
NeovimApi2* NeovimConnector::api2()
{
if ( !m_api2 ) {
if (m_api_compat <= 2 && 2 <= m_api_supported) {
m_api2 = new NeovimApi2(this);
} else {
qWarning() << "This instance of neovim not support api level 2";
}
}
return m_api2;
}
/**
* Launch an embedded Neovim process
* @see processExited
*/
NeovimConnector* NeovimConnector::spawn(const QStringList& params, const QString& exe)
{
QProcess *p = new QProcess();
QStringList args;
// Neovim accepts a `--' argument after which only filenames are passed.
// If the user has supplied it, our arguments must appear before.
if (params.indexOf("--") == -1) {
args << "--embed" << "--headless";
args.append(params);
} else {
int idx = params.indexOf("--");
args.append(params.mid(0, idx));
args << "--embed" << "--headless";
args.append(params.mid(idx));
}
NeovimConnector *c = new NeovimConnector(p);
c->m_ctype = SpawnedConnection;
c->m_spawnArgs = params;
c->m_spawnExe = exe;
connect(p, SIGNAL(error(QProcess::ProcessError)),
c, SLOT(processError(QProcess::ProcessError)));
connect(p, SIGNAL(finished(int, QProcess::ExitStatus)),
c, SIGNAL(processExited(int)));
connect(p, &QProcess::started,
c, &NeovimConnector::discoverMetadata);
p->start(exe, args);
return c;
}
/**
* Connect to Neovim using a local UNIX socket.
*
* This method also works in Windows, using named pipes.
*
* @see QLocalSocket
*/
NeovimConnector* NeovimConnector::connectToSocket(const QString& path)
{
QLocalSocket *s = new QLocalSocket();
NeovimConnector *c = new NeovimConnector(s);
c->m_ctype = SocketConnection;
c->m_connSocket = path;
connect(s, SIGNAL(error(QLocalSocket::LocalSocketError)),
c, SLOT(socketError()));
connect(s, &QLocalSocket::connected,
c, &NeovimConnector::discoverMetadata);
s->connectToServer(path);
return c;
}
/**
* Connect to a Neovim through a TCP connection
*
* @param host is a valid hostname or IP address
* @param port is the TCP port
*/
NeovimConnector* NeovimConnector::connectToHost(const QString& host, int port)
{
QTcpSocket *s = new QTcpSocket();
NeovimConnector *c = new NeovimConnector(s);
c->m_ctype = HostConnection;
c->m_connHost = host;
c->m_connPort = port;
connect(s, SIGNAL(error(QAbstractSocket::SocketError)),
c, SLOT(socketError()));
connect(s, &QAbstractSocket::connected,
c, &NeovimConnector::discoverMetadata);
s->connectToHost(host, port);
return c;
}
/**
* Connect to a running instance of Neovim (if available).
*
* This method gets the Neovim endpoint from the NVIM_LISTEN_ADDRESS environment
* variable, if it is not available a new Neovim instance is spawned().
*
* @see spawn()
*/
NeovimConnector* NeovimConnector::connectToNeovim(const QString& server)
{
QString addr = server;
if (addr.isEmpty()) {
addr = QString::fromLocal8Bit(qgetenv("NVIM_LISTEN_ADDRESS"));
}
if (addr.isEmpty()) {
return spawn();
}
int colon_pos = addr.lastIndexOf(':');
if (colon_pos != -1 && colon_pos != 0 && addr[colon_pos-1] != ':') {
bool ok;
int port = addr.mid(colon_pos+1).toInt(&ok);
if (ok) {
QString host = addr.mid(0, colon_pos);
return connectToHost(host, port);
}
}
return connectToSocket(addr);
}
NeovimConnector* NeovimConnector::fromStdinOut()
{
return new NeovimConnector(MsgpackIODevice::fromStdinOut());
}
/**
* Called when running embedded Neovim to report an error
* with the Neovim process
*/
void NeovimConnector::processError(QProcess::ProcessError err)
{
switch(err) {
case QProcess::FailedToStart:
setError(FailedToStart, m_dev->errorString());
break;
case QProcess::Crashed:
setError(Crashed, "The Neovim process has crashed");
break;
default:
// In practice we should be able to catch other types of
// errors from the QIODevice
qDebug() << "Neovim process error " << m_dev->errorString();
}
}
/** Handle errors from QLocalSocket or QTcpSocket */
void NeovimConnector::socketError()
{
setError(SocketError, m_dev->errorString());
}
/** Handle errors in MsgpackIODevice */
void NeovimConnector::msgpackError()
{
setError(MsgpackError, m_dev->errorString());
}
/**
* Raise a fatal error for a Neovim timeout
*
* Sometimes Neovim takes too long to respond to some requests, or maybe
* the channel is stuck. In such cases it is preferable to raise and error,
* internally this is what discoverMetadata does if Neovim does not reply.
*/
void NeovimConnector::fatalTimeout()
{
setError(RuntimeMsgpackError, "Neovim is taking too long to respond");
}
/**
* True if NeovimConnector::reconnect can be called to reconnect with Neovim. This
* is true unless you built the NeovimConnector ctor directly instead
* of using on of the static methods.
*/
bool NeovimConnector::canReconnect()
{
return m_ctype != OtherConnection;
}
/** @see NeovimConnector::NeovimConnectionType */
NeovimConnector::NeovimConnectionType NeovimConnector::connectionType()
{
return m_ctype;
}
/**
* Create a new connection using the same parameters as the current one.
*
* This is the equivalent of creating a new object with spawn(), connectToHost(),
* or connectToSocket()
*
* If canReconnect() returns false, this function will return NULL.
*/
NeovimConnector* NeovimConnector::reconnect()
{
switch(m_ctype) {
case SpawnedConnection:
return NeovimConnector::spawn(m_spawnArgs, m_spawnExe);
case HostConnection:
return NeovimConnector::connectToHost(m_connHost, m_connPort);
case SocketConnection:
return NeovimConnector::connectToSocket(m_connSocket);
default:
return NULL;
}
// NOT-REACHED
return NULL;
}
/** The minimum API level supported by this instance */
quint64 NeovimConnector::apiCompatibility()
{
return m_api_compat;
}
/** The maximum API level supported by this instance */
quint64 NeovimConnector::apiLevel()
{
return m_api_supported;
}
/**
* \fn NeovimQt::NeovimConnector::error(NeovimError)
*
* This signal is emitted when an error occurs. Use NeovimConnector::errorString
* to get an error message.
*/
/**
* \fn NeovimQt::NeovimConnector::processExited(int exitStatus)
*
* If the Neovim process was started using NeovimQt::NeovimConnector::spawn this signal
* is emitted when the process exits.
*/
} // namespace NeovimQt
#include "moc_neovimconnector.cpp"
<|endoftext|> |
<commit_before>/* bzflag
* Copyright (c) 1993 - 2005 Tim Riker
*
* This package is free software; you can redistribute it and/or
* modify it under the terms of the license found in the file
* named LICENSE that should have accompanied this file.
*
* THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
* WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.
*/
#ifdef HAVE_ADNS_H
/* interface header */
#include "AdnsHandler.h"
/* system implementation headers */
#include <errno.h>
/* common implementation headers */
#include "network.h"
adns_state AdnsHandler::adnsState;
AdnsHandler::AdnsHandler(int _index, struct sockaddr *clientAddr)
: index(_index), hostname(NULL), adnsQuery(NULL) {
// launch the asynchronous query to look up this hostname
if (adns_submit_reverse
(adnsState, clientAddr, adns_r_ptr,
(adns_queryflags)(adns_qf_quoteok_cname|adns_qf_cname_loose), 0,
&adnsQuery) != 0) {
DEBUG1("Player [%d] failed to submit reverse resolve query: errno %d\n",
index, getErrno());
adnsQuery = NULL;
} else {
DEBUG2("Player [%d] submitted reverse resolve query\n", index);
}
}
AdnsHandler::~AdnsHandler() {
if (adnsQuery) {
adns_cancel(adnsQuery);
adnsQuery = NULL;
}
if (hostname) {
free(hostname);
hostname = NULL;
}
}
// return true if host is resolved
bool AdnsHandler::checkDNSResolution() {
if (!adnsQuery)
return false;
// check to see if query has completed
adns_answer *answer;
if (adns_check(adnsState, &adnsQuery, &answer, 0) != 0) {
if (getErrno() != EAGAIN) {
DEBUG1("Player [%d] failed to resolve: errno %d\n", index, getErrno());
adnsQuery = NULL;
}
return false;
}
// we got our reply.
if (answer->status != adns_s_ok) {
DEBUG1("Player [%d] got bad status from resolver: %s\n", index,
adns_strerror(answer->status));
free(answer);
adnsQuery = NULL;
return false;
}
if (hostname)
free(hostname); // shouldn't happen, but just in case
hostname = strdup(*answer->rrs.str);
DEBUG1("Player [%d] resolved to hostname: %s\n", index, hostname);
free(answer);
adnsQuery = NULL;
return true;
}
const char *AdnsHandler::getHostname() {
return hostname;
}
void AdnsHandler::startupResolver() {
/* start up our resolver if we have ADNS */
if (adns_init(&adnsState, adns_if_nosigpipe, 0) < 0) {
perror("ADNS init failed");
exit(1);
}
}
#endif
// Local Variables: ***
// mode:C++ ***
// tab-width: 8 ***
// c-basic-offset: 2 ***
// indent-tabs-mode: t ***
// End: ***
// ex: shiftwidth=2 tabstop=8
<commit_msg>tee hee.. guess that wasn't so safe to put up there without common.h first<commit_after>/* bzflag
* Copyright (c) 1993 - 2005 Tim Riker
*
* This package is free software; you can redistribute it and/or
* modify it under the terms of the license found in the file
* named LICENSE that should have accompanied this file.
*
* THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
* WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.
*/
/* interface header */
#include "AdnsHandler.h"
/* system implementation headers */
#include <errno.h>
/* common implementation headers */
#include "network.h"
#ifdef HAVE_ADNS_H
adns_state AdnsHandler::adnsState;
AdnsHandler::AdnsHandler(int _index, struct sockaddr *clientAddr)
: index(_index), hostname(NULL), adnsQuery(NULL) {
// launch the asynchronous query to look up this hostname
if (adns_submit_reverse
(adnsState, clientAddr, adns_r_ptr,
(adns_queryflags)(adns_qf_quoteok_cname|adns_qf_cname_loose), 0,
&adnsQuery) != 0) {
DEBUG1("Player [%d] failed to submit reverse resolve query: errno %d\n",
index, getErrno());
adnsQuery = NULL;
} else {
DEBUG2("Player [%d] submitted reverse resolve query\n", index);
}
}
AdnsHandler::~AdnsHandler() {
if (adnsQuery) {
adns_cancel(adnsQuery);
adnsQuery = NULL;
}
if (hostname) {
free(hostname);
hostname = NULL;
}
}
// return true if host is resolved
bool AdnsHandler::checkDNSResolution() {
if (!adnsQuery)
return false;
// check to see if query has completed
adns_answer *answer;
if (adns_check(adnsState, &adnsQuery, &answer, 0) != 0) {
if (getErrno() != EAGAIN) {
DEBUG1("Player [%d] failed to resolve: errno %d\n", index, getErrno());
adnsQuery = NULL;
}
return false;
}
// we got our reply.
if (answer->status != adns_s_ok) {
DEBUG1("Player [%d] got bad status from resolver: %s\n", index,
adns_strerror(answer->status));
free(answer);
adnsQuery = NULL;
return false;
}
if (hostname)
free(hostname); // shouldn't happen, but just in case
hostname = strdup(*answer->rrs.str);
DEBUG1("Player [%d] resolved to hostname: %s\n", index, hostname);
free(answer);
adnsQuery = NULL;
return true;
}
const char *AdnsHandler::getHostname() {
return hostname;
}
void AdnsHandler::startupResolver() {
/* start up our resolver if we have ADNS */
if (adns_init(&adnsState, adns_if_nosigpipe, 0) < 0) {
perror("ADNS init failed");
exit(1);
}
}
#endif
// Local Variables: ***
// mode:C++ ***
// tab-width: 8 ***
// c-basic-offset: 2 ***
// indent-tabs-mode: t ***
// End: ***
// ex: shiftwidth=2 tabstop=8
<|endoftext|> |
<commit_before>//
// Created by kirill on 17.03.17.
//
#include <string.h>
#include <errno.h>
#include <unistd.h>
#include <dirent.h>
#include <dlfcn.h>
#include <stdlib.h>
#include <fcntl.h>
#include <sys/wait.h>
#include <sys/stat.h>
#include <utils/Utils.h>
#include "dirty/common/logging.h"
#include "input_device/InputReader.h"
#include "ControlReader.h"
#include "utils/Reanimator.h"
typedef int getcon_t(char** con);
// TODO: figure out how to get this info from CMake script and pass it here
#define PKNAME "org.leyfer.thesis.touchlogger_dirty"
#define ACTIVITY ".activity.MainActivity"
#define BOOLEAN_EXTRA_KEY "org.leyfer.thesis.extra.started_by_payload"
#define SERVICE_PROCESS_NAME "touchlogger.here"
#define SERVICE ".service.PayloadWaitingService"
#define ACTION "org.leyfer.thesis.touchlogger_dirty.service.action.WAIT_FOR_PAYLOAD"
#define CONTROL_PORT 10500
#define HEARTBEAT_INTERVAL_MS 100 * 1000 // 100 ms
static const std::string heartbeatCommand = "heartbeat\n";
static const std::string pauseCommand = "pause\n";
static const std::string resumeCommand = "resume\n";
InputReader* inputReader;
Reanimator* reanimator;
int isServiceProcessActive()
{
DIR* dir = opendir("/proc");
if (dir == NULL)
{
LOGV("Couldn't open /proc");
return -1;
}
struct dirent* de;
char cmdline_path[PATH_MAX];
char buf[128];
bool found = false;
while ((de = readdir(dir)))
{
if (!strcmp(de->d_name, ".") || !strcmp(de->d_name, ".."))
{
continue;
}
// Only inspect directories that are PID numbers
char* endptr;
long int pid = strtol(de->d_name, &endptr, 10);
if (*endptr != '\0')
{
continue;
}
memset(cmdline_path, 0, PATH_MAX);
snprintf(cmdline_path, PATH_MAX, "/proc/%lu/cmdline", pid);
int fd = open(cmdline_path, O_RDONLY);
if (fd == -1)
{
LOGV("Unable to open %s: %s!", cmdline_path, strerror(errno));
continue;
}
memset(buf, 0, 128);
if (read(fd, buf, 128) == -1)
{
LOGV("Unable to read from %s: %s!", cmdline_path, strerror(errno));
close(fd);
continue;
}
if (strcmp(SERVICE_PROCESS_NAME, buf) == 0)
{
LOGV("Touchlogger found!");
found = true;
close(fd);
break;
}
else
{
close(fd);
}
}
closedir(dir);
if (found)
{
return 0;
}
else
{
return -1;
}
}
int getSelinuxContext(char** context)
{
dlerror();
#ifdef __aarch64__
void* selinux = dlopen("/system/lib64/libselinux.so", RTLD_LAZY);
#else
void* selinux = dlopen("/system/lib/libselinux.so", RTLD_LAZY);
#endif
if (selinux)
{
void* getcon = dlsym(selinux, "getcon");
const char* error = dlerror();
if (error)
{
LOGV("dlsym error %s", error);
dlclose(selinux);
return -1;
}
else
{
getcon_t* getcon_p = (getcon_t*) getcon;
int res = (*getcon_p)(context);
dlclose(selinux);
return res;
}
}
else
{
const char* result = "No selinux";
*context = (char*) calloc(strlen(result) + 1, sizeof(char));
strcpy(*context, result);
dlclose(selinux);
return 0;
}
}
int checkConditions()
{
int fd = open("/dev/input/event0", O_RDONLY);
if (fd == -1)
{
LOGV("Unable to get access to input device: %s!", strerror(errno));
return -1;
}
else
{
LOGV("Input device access OK!");
close(fd);
}
struct stat st;
if (stat("/sdcard/", &st) == -1)
{
LOGV("Unable to access SD card: %s!", strerror(errno));
return -1;
}
else
{
LOGV("SD card access OK!");
}
return 0;
}
int startServceAndWaitForItToBecomeOnline()
{
while (1)
{
if (isServiceProcessActive() == 0)
{
LOGV("Touchlogger android app started!");
int start_touchlogger_res = system(
"am start -n " PKNAME "/" ACTIVITY " --ez " BOOLEAN_EXTRA_KEY " true");
if (start_touchlogger_res == -1)
{
LOGV("Unable to start touchlogger!");
return -1;
}
else if (WEXITSTATUS(start_touchlogger_res) == 0)
{
LOGV("Touchlogger started successfully!");
return 0;
}
else
{
LOGV("Unable to start activity!");
return -1;
}
}
else
{
LOGV("No touchlogger process!");
system("am startservice -n " PKNAME "/" SERVICE " -a " ACTION);
sleep(1);
}
}
}
int onPause()
{
if (inputReader != nullptr)
{
inputReader->pause();
return 0;
}
else
{
LOGV("Unable to pause input reader as it is not available!");
return -1;
}
}
int onResume()
{
if (inputReader != nullptr)
{
inputReader->resume();
return 0;
}
else
{
LOGV("Unable to resume input reader as it is not available!");
return -1;
}
}
int onHeartBeat()
{
if (reanimator != nullptr)
{
reanimator->onHeartBeat();
return 0;
}
else
{
LOGV("Unable to send heartbeat event to reanimator as it is not available!");
return -1;
}
}
int main(int argc, const char** argv)
{
LOGV("Uid: %d", getuid());
char* context;
if (getSelinuxContext(&context) == -1)
{
LOGV("Unable to get selinux context")
}
else
{
LOGV("Selinux context: %s", context);
free(context);
}
if (daemon(0, 0) == -1)
{
LOGV("Unable to daemonize process: %s!", strerror(errno));
}
if (checkConditions() == -1)
{
LOGV("Unable to start daemon, exiting...");
return -1;
}
if (startServceAndWaitForItToBecomeOnline() == -1)
{
LOGV("Unable to wait for Android service, exiting...");
return -1;
}
InputDevice* inputDevice = findTouchscreen();
if (inputDevice == nullptr)
{
LOGV("Unable to find input touchscreen!");
return -1;
}
LOGV("Starting reanimator...");
reanimator = new Reanimator(HEARTBEAT_INTERVAL_MS, startServceAndWaitForItToBecomeOnline);
LOGV("Starting control server thread...");
std::map<std::string, control_callback> callbackMap;
callbackMap.emplace(pauseCommand, &onPause);
callbackMap.emplace(resumeCommand, &onResume);
callbackMap.emplace(heartbeatCommand, &onHeartBeat);
ControlReader* controlReader = new ControlReader(CONTROL_PORT, callbackMap);
controlReader->start();
LOGV("Collecting input data & sending it to Android service...");
EventFileWriter* eventFileWriter = new EventFileWriter(EVENT_DATA_DIR);
inputReader = new InputReader(eventFileWriter, inputDevice);
inputReader->start();
LOGV("Finish inputReader...");
delete (inputReader);
LOGV("Stopping control server...");
controlReader->stop();
LOGV("Stopping service reanimator...");
reanimator->stop();
return 0;
}
<commit_msg>Start server earlier than java service to have listening port by the time java service is launched.<commit_after>//
// Created by kirill on 17.03.17.
//
#include <string.h>
#include <errno.h>
#include <unistd.h>
#include <dirent.h>
#include <dlfcn.h>
#include <stdlib.h>
#include <fcntl.h>
#include <sys/wait.h>
#include <sys/stat.h>
#include <utils/Utils.h>
#include "dirty/common/logging.h"
#include "input_device/InputReader.h"
#include "ControlReader.h"
#include "utils/Reanimator.h"
typedef int getcon_t(char** con);
// TODO: figure out how to get this info from CMake script and pass it here
#define PKNAME "org.leyfer.thesis.touchlogger_dirty"
#define ACTIVITY ".activity.MainActivity"
#define BOOLEAN_EXTRA_KEY "org.leyfer.thesis.extra.started_by_payload"
#define SERVICE_PROCESS_NAME "touchlogger.here"
#define SERVICE ".service.PayloadWaitingService"
#define ACTION "org.leyfer.thesis.touchlogger_dirty.service.action.WAIT_FOR_PAYLOAD"
#define CONTROL_PORT 10500
#define HEARTBEAT_INTERVAL_MS 100 * 1000 // 100 ms
static const std::string heartbeatCommand = "heartbeat\n";
static const std::string pauseCommand = "pause\n";
static const std::string resumeCommand = "resume\n";
InputReader* inputReader;
Reanimator* reanimator;
int isServiceProcessActive()
{
DIR* dir = opendir("/proc");
if (dir == NULL)
{
LOGV("Couldn't open /proc");
return -1;
}
struct dirent* de;
char cmdline_path[PATH_MAX];
char buf[128];
bool found = false;
while ((de = readdir(dir)))
{
if (!strcmp(de->d_name, ".") || !strcmp(de->d_name, ".."))
{
continue;
}
// Only inspect directories that are PID numbers
char* endptr;
long int pid = strtol(de->d_name, &endptr, 10);
if (*endptr != '\0')
{
continue;
}
memset(cmdline_path, 0, PATH_MAX);
snprintf(cmdline_path, PATH_MAX, "/proc/%lu/cmdline", pid);
int fd = open(cmdline_path, O_RDONLY);
if (fd == -1)
{
LOGV("Unable to open %s: %s!", cmdline_path, strerror(errno));
continue;
}
memset(buf, 0, 128);
if (read(fd, buf, 128) == -1)
{
LOGV("Unable to read from %s: %s!", cmdline_path, strerror(errno));
close(fd);
continue;
}
if (strcmp(SERVICE_PROCESS_NAME, buf) == 0)
{
LOGV("Touchlogger found!");
found = true;
close(fd);
break;
}
else
{
close(fd);
}
}
closedir(dir);
if (found)
{
return 0;
}
else
{
return -1;
}
}
int getSelinuxContext(char** context)
{
dlerror();
#ifdef __aarch64__
void* selinux = dlopen("/system/lib64/libselinux.so", RTLD_LAZY);
#else
void* selinux = dlopen("/system/lib/libselinux.so", RTLD_LAZY);
#endif
if (selinux)
{
void* getcon = dlsym(selinux, "getcon");
const char* error = dlerror();
if (error)
{
LOGV("dlsym error %s", error);
dlclose(selinux);
return -1;
}
else
{
getcon_t* getcon_p = (getcon_t*) getcon;
int res = (*getcon_p)(context);
dlclose(selinux);
return res;
}
}
else
{
const char* result = "No selinux";
*context = (char*) calloc(strlen(result) + 1, sizeof(char));
strcpy(*context, result);
dlclose(selinux);
return 0;
}
}
int checkConditions()
{
int fd = open("/dev/input/event0", O_RDONLY);
if (fd == -1)
{
LOGV("Unable to get access to input device: %s!", strerror(errno));
return -1;
}
else
{
LOGV("Input device access OK!");
close(fd);
}
struct stat st;
if (stat("/sdcard/", &st) == -1)
{
LOGV("Unable to access SD card: %s!", strerror(errno));
return -1;
}
else
{
LOGV("SD card access OK!");
}
return 0;
}
int startServceAndWaitForItToBecomeOnline()
{
while (1)
{
if (isServiceProcessActive() == 0)
{
LOGV("Touchlogger android app started!");
int start_touchlogger_res = system(
"am start -n " PKNAME "/" ACTIVITY " --ez " BOOLEAN_EXTRA_KEY " true");
if (start_touchlogger_res == -1)
{
LOGV("Unable to start touchlogger!");
return -1;
}
else if (WEXITSTATUS(start_touchlogger_res) == 0)
{
LOGV("Touchlogger started successfully!");
return 0;
}
else
{
LOGV("Unable to start activity!");
return -1;
}
}
else
{
LOGV("No touchlogger process!");
system("am startservice -n " PKNAME "/" SERVICE " -a " ACTION);
sleep(1);
}
}
}
int onPause()
{
if (inputReader != nullptr)
{
inputReader->pause();
return 0;
}
else
{
LOGV("Unable to pause input reader as it is not available!");
return -1;
}
}
int onResume()
{
if (inputReader != nullptr)
{
inputReader->resume();
return 0;
}
else
{
LOGV("Unable to resume input reader as it is not available!");
return -1;
}
}
int onHeartBeat()
{
if (reanimator != nullptr)
{
reanimator->onHeartBeat();
return 0;
}
else
{
LOGV("Unable to send heartbeat event to reanimator as it is not available!");
return -1;
}
}
int main(int argc, const char** argv)
{
LOGV("Uid: %d", getuid());
char* context;
if (getSelinuxContext(&context) == -1)
{
LOGV("Unable to get selinux context")
}
else
{
LOGV("Selinux context: %s", context);
free(context);
}
if (daemon(0, 0) == -1)
{
LOGV("Unable to daemonize process: %s!", strerror(errno));
}
if (checkConditions() == -1)
{
LOGV("Unable to start daemon, exiting...");
return -1;
}
LOGV("Starting control server thread...");
std::map<std::string, control_callback> callbackMap;
callbackMap.emplace(pauseCommand, &onPause);
callbackMap.emplace(resumeCommand, &onResume);
callbackMap.emplace(heartbeatCommand, &onHeartBeat);
ControlReader* controlReader = new ControlReader(CONTROL_PORT, callbackMap);
controlReader->start();
if (startServceAndWaitForItToBecomeOnline() == -1)
{
LOGV("Unable to wait for Android service, exiting...");
return -1;
}
InputDevice* inputDevice = findTouchscreen();
if (inputDevice == nullptr)
{
LOGV("Unable to find input touchscreen!");
return -1;
}
LOGV("Starting reanimator...");
reanimator = new Reanimator(HEARTBEAT_INTERVAL_MS, startServceAndWaitForItToBecomeOnline);
LOGV("Collecting input data & sending it to Android service...");
EventFileWriter* eventFileWriter = new EventFileWriter(EVENT_DATA_DIR);
inputReader = new InputReader(eventFileWriter, inputDevice);
inputReader->start();
LOGV("Finish inputReader...");
delete (inputReader);
LOGV("Stopping control server...");
controlReader->stop();
LOGV("Stopping service reanimator...");
reanimator->stop();
return 0;
}
<|endoftext|> |
<commit_before>// -*- Mode: C++; tab-width: 2; -*-
// vi: set ts=2:
//
// $Id: atomBondModelBaseProcessor.C,v 1.10 2004/07/12 16:56:54 amoll Exp $
#include <BALL/VIEW/MODELS/atomBondModelBaseProcessor.h>
#include <BALL/KERNEL/forEach.h>
#include <BALL/KERNEL/bond.h>
#include <BALL/QSAR/ringPerceptionProcessor.h>
using namespace std;
namespace BALL
{
namespace VIEW
{
AtomBondModelBaseProcessor::AtomBondModelBaseProcessor()
throw()
: ModelProcessor(),
used_atoms_(),
atom_set_()
{
}
AtomBondModelBaseProcessor::AtomBondModelBaseProcessor(const AtomBondModelBaseProcessor& processor)
throw()
: ModelProcessor(processor),
used_atoms_(),
atom_set_()
{
}
AtomBondModelBaseProcessor::~AtomBondModelBaseProcessor()
throw()
{
#ifdef BALL_VIEW_DEBUG
Log.info() << "Destructing object " << (void *)this
<< " of class " << RTTI::getName<AtomBondModelBaseProcessor>() << std::endl;
#endif
}
void AtomBondModelBaseProcessor::clear()
throw()
{
ModelProcessor::clear();
atom_set_.clear();
used_atoms_.clear();
}
void AtomBondModelBaseProcessor::set(const AtomBondModelBaseProcessor& processor)
throw()
{
clear();
ModelProcessor::set(processor);
}
const AtomBondModelBaseProcessor& AtomBondModelBaseProcessor::operator = (const AtomBondModelBaseProcessor& processor)
throw()
{
set(processor);
return *this;
}
void AtomBondModelBaseProcessor::swap(AtomBondModelBaseProcessor& processor)
throw()
{
ModelProcessor::swap(processor);
}
bool AtomBondModelBaseProcessor::start()
{
return ModelProcessor::start();
}
void AtomBondModelBaseProcessor::clearComposites()
throw()
{
atom_set_.clear();
used_atoms_.clear();
}
void AtomBondModelBaseProcessor::dump(ostream& s, Size depth) const
throw()
{
BALL_DUMP_STREAM_PREFIX(s);
BALL_DUMP_DEPTH(s, depth);
BALL_DUMP_HEADER(s, this, this);
ModelProcessor::dump(s, depth + 1);
BALL_DUMP_DEPTH(s, depth);
s << "used atoms: " << used_atoms_.size() << endl;
BALL_DUMP_STREAM_SUFFIX(s);
}
void AtomBondModelBaseProcessor::buildBondModels_()
{
// generate bond primitive
const Atom* second_atom_ptr = 0;
AtomBondConstIterator bond_it;
List<const Atom*>::ConstIterator atom_it;
// for all used atoms
for (atom_it = getAtomList_().begin();
atom_it != getAtomList_().end(); ++atom_it)
{
// for all bonds connected from first- to second atom
BALL_FOREACH_ATOM_BOND(**atom_it, bond_it)
{
if (*atom_it != bond_it->getSecondAtom())
{
second_atom_ptr = bond_it->getSecondAtom();
}
else
{
second_atom_ptr = bond_it->getFirstAtom();
}
// use only atoms with greater handles than first atom
// or
// second atom not a used atom, but smaller as the first atom
// process bond between them
if (**atom_it < *second_atom_ptr && getAtomSet_().has(second_atom_ptr))
{
visualiseBond_(*bond_it);
}
}
}
}
void AtomBondModelBaseProcessor::visualiseBond_(const Bond& /*bond*/)
throw()
{
}
bool AtomBondModelBaseProcessor::createGeometricObjects()
throw()
{
buildBondModels_();
visualiseRings_();
rings_.clear();
return true;
}
Processor::Result AtomBondModelBaseProcessor::operator () (Composite& composite)
{
if (!RTTI::isKindOf<Molecule>(composite)) return Processor::CONTINUE;
RingPerceptionProcessor rpp;
rpp.calculateSSSR(rings_, (*reinterpret_cast<Molecule*>(&composite)));
return Processor::CONTINUE;
}
# ifdef BALL_NO_INLINE_FUNCTIONS
# include <BALL/VIEW/MODELS/atomBondModelBaseProcessor.iC>
# endif
} // namespace VIEW
} // namespace BALL
<commit_msg>no message<commit_after>// -*- Mode: C++; tab-width: 2; -*-
// vi: set ts=2:
//
// $Id: atomBondModelBaseProcessor.C,v 1.11 2004/07/12 19:51:37 amoll Exp $
#include <BALL/VIEW/MODELS/atomBondModelBaseProcessor.h>
#include <BALL/KERNEL/forEach.h>
#include <BALL/KERNEL/bond.h>
#include <BALL/KERNEL/residue.h>
#include <BALL/QSAR/ringPerceptionProcessor.h>
using namespace std;
namespace BALL
{
namespace VIEW
{
AtomBondModelBaseProcessor::AtomBondModelBaseProcessor()
throw()
: ModelProcessor(),
used_atoms_(),
atom_set_()
{
}
AtomBondModelBaseProcessor::AtomBondModelBaseProcessor(const AtomBondModelBaseProcessor& processor)
throw()
: ModelProcessor(processor),
used_atoms_(),
atom_set_()
{
}
AtomBondModelBaseProcessor::~AtomBondModelBaseProcessor()
throw()
{
#ifdef BALL_VIEW_DEBUG
Log.info() << "Destructing object " << (void *)this
<< " of class " << RTTI::getName<AtomBondModelBaseProcessor>() << std::endl;
#endif
}
void AtomBondModelBaseProcessor::clear()
throw()
{
ModelProcessor::clear();
atom_set_.clear();
used_atoms_.clear();
}
void AtomBondModelBaseProcessor::set(const AtomBondModelBaseProcessor& processor)
throw()
{
clear();
ModelProcessor::set(processor);
}
const AtomBondModelBaseProcessor& AtomBondModelBaseProcessor::operator = (const AtomBondModelBaseProcessor& processor)
throw()
{
set(processor);
return *this;
}
void AtomBondModelBaseProcessor::swap(AtomBondModelBaseProcessor& processor)
throw()
{
ModelProcessor::swap(processor);
}
bool AtomBondModelBaseProcessor::start()
{
return ModelProcessor::start();
}
void AtomBondModelBaseProcessor::clearComposites()
throw()
{
atom_set_.clear();
used_atoms_.clear();
}
void AtomBondModelBaseProcessor::dump(ostream& s, Size depth) const
throw()
{
BALL_DUMP_STREAM_PREFIX(s);
BALL_DUMP_DEPTH(s, depth);
BALL_DUMP_HEADER(s, this, this);
ModelProcessor::dump(s, depth + 1);
BALL_DUMP_DEPTH(s, depth);
s << "used atoms: " << used_atoms_.size() << endl;
BALL_DUMP_STREAM_SUFFIX(s);
}
void AtomBondModelBaseProcessor::buildBondModels_()
{
// generate bond primitive
const Atom* second_atom_ptr = 0;
AtomBondConstIterator bond_it;
List<const Atom*>::ConstIterator atom_it;
// for all used atoms
for (atom_it = getAtomList_().begin();
atom_it != getAtomList_().end(); ++atom_it)
{
// for all bonds connected from first- to second atom
BALL_FOREACH_ATOM_BOND(**atom_it, bond_it)
{
if (*atom_it != bond_it->getSecondAtom())
{
second_atom_ptr = bond_it->getSecondAtom();
}
else
{
second_atom_ptr = bond_it->getFirstAtom();
}
// use only atoms with greater handles than first atom
// or
// second atom not a used atom, but smaller as the first atom
// process bond between them
if (**atom_it < *second_atom_ptr && getAtomSet_().has(second_atom_ptr))
{
visualiseBond_(*bond_it);
}
}
}
}
void AtomBondModelBaseProcessor::visualiseBond_(const Bond& /*bond*/)
throw()
{
}
bool AtomBondModelBaseProcessor::createGeometricObjects()
throw()
{
buildBondModels_();
visualiseRings_();
rings_.clear();
return true;
}
Processor::Result AtomBondModelBaseProcessor::operator () (Composite& composite)
{
if (!RTTI::isKindOf<Residue>(composite)) return Processor::CONTINUE;
RingPerceptionProcessor rpp;
rpp.calculateSSSR(rings_, (*reinterpret_cast<Residue*>(&composite)));
return Processor::CONTINUE;
}
# ifdef BALL_NO_INLINE_FUNCTIONS
# include <BALL/VIEW/MODELS/atomBondModelBaseProcessor.iC>
# endif
} // namespace VIEW
} // namespace BALL
<|endoftext|> |
<commit_before>/*
* Copyright 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 <fcntl.h>
#include <netinet/in.h>
#include <sys/socket.h>
#include <assert.h>
#include <xapian.h>
#include "utils.h"
#include "xapiand.h"
#include "server.h"
#include "client_http.h"
#include "client_binary.h"
const int MSECS_IDLE_TIMEOUT_DEFAULT = 60000;
const int MSECS_ACTIVE_TIMEOUT_DEFAULT = 15000;
//
// Xapian Server
//
int XapiandServer::total_clients = 0;
XapiandServer::XapiandServer(XapiandManager *manager_, ev::loop_ref *loop_, int http_sock_, int binary_sock_, DatabasePool *database_pool_, ThreadPool *thread_pool_)
: manager(manager_),
iterator(manager_->attach_server(this)),
loop(loop_ ? loop_: &dynamic_loop),
http_io(*loop),
binary_io(*loop),
break_loop(*loop),
http_sock(http_sock_),
binary_sock(binary_sock_),
database_pool(database_pool_),
thread_pool(thread_pool_)
{
pthread_mutex_init(&clients_mutex, 0);
break_loop.set<XapiandServer, &XapiandServer::break_loop_cb>(this);
break_loop.start();
http_io.set<XapiandServer, &XapiandServer::io_accept_http>(this);
http_io.start(http_sock, ev::READ);
binary_io.set<XapiandServer, &XapiandServer::io_accept_binary>(this);
binary_io.start(binary_sock, ev::READ);
LOG_OBJ(this, "CREATED SERVER!\n");
}
XapiandServer::~XapiandServer()
{
http_io.stop();
binary_io.stop();
break_loop.stop();
pthread_mutex_destroy(&clients_mutex);
manager->detach_server(this);
LOG_OBJ(this, "DELETED SERVER!\n");
}
void XapiandServer::run()
{
LOG_OBJ(this, "Starting server loop...\n");
loop->run(0);
LOG_OBJ(this, "Server loop ended!\n");
}
void XapiandServer::io_accept_http(ev::io &watcher, int revents)
{
if (EV_ERROR & revents) {
LOG_EV(this, "ERROR: got invalid http event (sock=%d): %s\n", http_sock, strerror(errno));
return;
}
struct sockaddr_in client_addr;
socklen_t client_len = sizeof(client_addr);
int client_sock = ::accept(watcher.fd, (struct sockaddr *)&client_addr, &client_len);
if (client_sock < 0) {
if (errno != EAGAIN) {
LOG_CONN(this, "ERROR: accept http error (sock=%d): %s\n", http_sock, strerror(errno));
}
} else {
fcntl(client_sock, F_SETFL, fcntl(client_sock, F_GETFL, 0) | O_NONBLOCK);
double active_timeout = MSECS_ACTIVE_TIMEOUT_DEFAULT * 1e-3;
double idle_timeout = MSECS_IDLE_TIMEOUT_DEFAULT * 1e-3;
new HttpClient(this, loop, client_sock, database_pool, thread_pool, active_timeout, idle_timeout);
}
}
void XapiandServer::io_accept_binary(ev::io &watcher, int revents)
{
if (EV_ERROR & revents) {
LOG_EV(this, "ERROR: got invalid binary event (sock=%d): %s\n", binary_sock, strerror(errno));
return;
}
struct sockaddr_in client_addr;
socklen_t client_len = sizeof(client_addr);
int client_sock = ::accept(watcher.fd, (struct sockaddr *)&client_addr, &client_len);
if (client_sock < 0) {
if (errno != EAGAIN) {
LOG_CONN(this, "ERROR: accept binary error (sock=%d): %s\n", binary_sock, strerror(errno));
}
} else {
fcntl(client_sock, F_SETFL, fcntl(client_sock, F_GETFL, 0) | O_NONBLOCK);
double active_timeout = MSECS_ACTIVE_TIMEOUT_DEFAULT * 1e-3;
double idle_timeout = MSECS_IDLE_TIMEOUT_DEFAULT * 1e-3;
new BinaryClient(this, loop, client_sock, database_pool, thread_pool, active_timeout, idle_timeout);
}
}
void XapiandServer::destroy()
{
if (http_sock == -1 && binary_sock == -1) {
return;
}
http_sock = -1;
binary_sock = -1;
http_io.stop();
binary_io.stop();
// http and binary sockets are closed in the manager.
LOG_OBJ(this, "DESTROYED SERVER!\n");
}
void XapiandServer::break_loop_cb(ev::async &watcher, int revents)
{
LOG_OBJ(this, "Breaking server loop!\n");
loop->break_loop();
}
std::list<BaseClient *>::const_iterator XapiandServer::attach_client(BaseClient *client)
{
pthread_mutex_lock(&clients_mutex);
std::list<BaseClient *>::const_iterator iterator = clients.insert(clients.end(), client);
pthread_mutex_unlock(&clients_mutex);
return iterator;
}
void XapiandServer::detach_client(BaseClient *client)
{
pthread_mutex_lock(&clients_mutex);
if (client->iterator != clients.end()) {
clients.erase(client->iterator);
client->iterator = clients.end();
}
pthread_mutex_unlock(&clients_mutex);
}
void XapiandServer::shutdown()
{
std::list<BaseClient *>::const_iterator it(clients.begin());
while (it != clients.end()) {
(*it)->shutdown();
it = clients.begin();
}
if (manager->shutdown_asap) {
destroy();
if (total_clients == 0) {
manager->shutdown_now = manager->shutdown_asap;
}
}
if (manager->shutdown_now) {
break_loop.send();
}
}
<commit_msg>Destroy server after setting shutdown_now (if set)<commit_after>/*
* Copyright 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 <fcntl.h>
#include <netinet/in.h>
#include <sys/socket.h>
#include <assert.h>
#include <xapian.h>
#include "utils.h"
#include "xapiand.h"
#include "server.h"
#include "client_http.h"
#include "client_binary.h"
const int MSECS_IDLE_TIMEOUT_DEFAULT = 60000;
const int MSECS_ACTIVE_TIMEOUT_DEFAULT = 15000;
//
// Xapian Server
//
int XapiandServer::total_clients = 0;
XapiandServer::XapiandServer(XapiandManager *manager_, ev::loop_ref *loop_, int http_sock_, int binary_sock_, DatabasePool *database_pool_, ThreadPool *thread_pool_)
: manager(manager_),
iterator(manager_->attach_server(this)),
loop(loop_ ? loop_: &dynamic_loop),
http_io(*loop),
binary_io(*loop),
break_loop(*loop),
http_sock(http_sock_),
binary_sock(binary_sock_),
database_pool(database_pool_),
thread_pool(thread_pool_)
{
pthread_mutex_init(&clients_mutex, 0);
break_loop.set<XapiandServer, &XapiandServer::break_loop_cb>(this);
break_loop.start();
http_io.set<XapiandServer, &XapiandServer::io_accept_http>(this);
http_io.start(http_sock, ev::READ);
binary_io.set<XapiandServer, &XapiandServer::io_accept_binary>(this);
binary_io.start(binary_sock, ev::READ);
LOG_OBJ(this, "CREATED SERVER!\n");
}
XapiandServer::~XapiandServer()
{
http_io.stop();
binary_io.stop();
break_loop.stop();
pthread_mutex_destroy(&clients_mutex);
manager->detach_server(this);
LOG_OBJ(this, "DELETED SERVER!\n");
}
void XapiandServer::run()
{
LOG_OBJ(this, "Starting server loop...\n");
loop->run(0);
LOG_OBJ(this, "Server loop ended!\n");
}
void XapiandServer::io_accept_http(ev::io &watcher, int revents)
{
if (EV_ERROR & revents) {
LOG_EV(this, "ERROR: got invalid http event (sock=%d): %s\n", http_sock, strerror(errno));
return;
}
struct sockaddr_in client_addr;
socklen_t client_len = sizeof(client_addr);
int client_sock = ::accept(watcher.fd, (struct sockaddr *)&client_addr, &client_len);
if (client_sock < 0) {
if (errno != EAGAIN) {
LOG_CONN(this, "ERROR: accept http error (sock=%d): %s\n", http_sock, strerror(errno));
}
} else {
fcntl(client_sock, F_SETFL, fcntl(client_sock, F_GETFL, 0) | O_NONBLOCK);
double active_timeout = MSECS_ACTIVE_TIMEOUT_DEFAULT * 1e-3;
double idle_timeout = MSECS_IDLE_TIMEOUT_DEFAULT * 1e-3;
new HttpClient(this, loop, client_sock, database_pool, thread_pool, active_timeout, idle_timeout);
}
}
void XapiandServer::io_accept_binary(ev::io &watcher, int revents)
{
if (EV_ERROR & revents) {
LOG_EV(this, "ERROR: got invalid binary event (sock=%d): %s\n", binary_sock, strerror(errno));
return;
}
struct sockaddr_in client_addr;
socklen_t client_len = sizeof(client_addr);
int client_sock = ::accept(watcher.fd, (struct sockaddr *)&client_addr, &client_len);
if (client_sock < 0) {
if (errno != EAGAIN) {
LOG_CONN(this, "ERROR: accept binary error (sock=%d): %s\n", binary_sock, strerror(errno));
}
} else {
fcntl(client_sock, F_SETFL, fcntl(client_sock, F_GETFL, 0) | O_NONBLOCK);
double active_timeout = MSECS_ACTIVE_TIMEOUT_DEFAULT * 1e-3;
double idle_timeout = MSECS_IDLE_TIMEOUT_DEFAULT * 1e-3;
new BinaryClient(this, loop, client_sock, database_pool, thread_pool, active_timeout, idle_timeout);
}
}
void XapiandServer::destroy()
{
if (http_sock == -1 && binary_sock == -1) {
return;
}
http_sock = -1;
binary_sock = -1;
http_io.stop();
binary_io.stop();
// http and binary sockets are closed in the manager.
LOG_OBJ(this, "DESTROYED SERVER!\n");
}
void XapiandServer::break_loop_cb(ev::async &watcher, int revents)
{
LOG_OBJ(this, "Breaking server loop!\n");
loop->break_loop();
}
std::list<BaseClient *>::const_iterator XapiandServer::attach_client(BaseClient *client)
{
pthread_mutex_lock(&clients_mutex);
std::list<BaseClient *>::const_iterator iterator = clients.insert(clients.end(), client);
pthread_mutex_unlock(&clients_mutex);
return iterator;
}
void XapiandServer::detach_client(BaseClient *client)
{
pthread_mutex_lock(&clients_mutex);
if (client->iterator != clients.end()) {
clients.erase(client->iterator);
client->iterator = clients.end();
}
pthread_mutex_unlock(&clients_mutex);
}
void XapiandServer::shutdown()
{
std::list<BaseClient *>::const_iterator it(clients.begin());
while (it != clients.end()) {
(*it)->shutdown();
it = clients.begin();
}
if (manager->shutdown_asap) {
if (total_clients == 0) {
manager->shutdown_now = manager->shutdown_asap;
}
destroy();
}
if (manager->shutdown_now) {
break_loop.send();
}
}
<|endoftext|> |
<commit_before>//////////////////////////////////////////////////////////////////////////////
//
// File: XmlToVtk.cpp
//
// For more information, please see: http://www.nektar.info
//
// The MIT License
//
// Copyright (c) 2006 Division of Applied Mathematics, Brown University (USA),
// Department of Aeronautics, Imperial College London (UK), and Scientific
// Computing and Imaging Institute, University of Utah (USA).
//
// License for the specific language governing rights and limitations under
// 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.
//
// Description: Output VTK file of XML mesh, optionally with Jacobian.
//
///////////////////////////////////////////////////////////////////////////////
#include <cstdlib>
#include <iomanip>
#include <MultiRegions/ExpList.h>
#include <MultiRegions/ExpList1D.h>
#include <MultiRegions/ExpList2D.h>
#include <MultiRegions/ExpList2DHomogeneous1D.h>
#include <MultiRegions/ExpList3D.h>
#include <MultiRegions/ExpList3DHomogeneous1D.h>
using namespace Nektar;
int main(int argc, char *argv[])
{
if(argc < 2)
{
cerr << "Usage: XmlToVtk meshfile" << endl;
exit(1);
}
LibUtilities::SessionReader::RegisterCmdLineFlag(
"jacobian", "j", "Output Jacobian as scalar field");
LibUtilities::SessionReader::RegisterCmdLineFlag(
"quality", "q", "Output distribution of scaled Jacobians");
LibUtilities::SessionReaderSharedPtr vSession
= LibUtilities::SessionReader::CreateInstance(argc, argv);
bool jac = vSession->DefinesCmdLineArgument("jacobian");
bool quality = vSession->DefinesCmdLineArgument("quality");
jac = quality ? true : jac;
// Read in mesh from input file
string meshfile(argv[argc-1]);
SpatialDomains::MeshGraphSharedPtr graphShPt =
SpatialDomains::MeshGraph::Read(vSession); //meshfile);
// Set up Expansion information
SpatialDomains::ExpansionMap emap = graphShPt->GetExpansions();
SpatialDomains::ExpansionMapIter it;
for (it = emap.begin(); it != emap.end(); ++it)
{
for (int i = 0; i < it->second->m_basisKeyVector.size(); ++i)
{
LibUtilities::BasisKey tmp1 = it->second->m_basisKeyVector[i];
LibUtilities::PointsKey tmp2 = tmp1.GetPointsKey();
it->second->m_basisKeyVector[i] = LibUtilities::BasisKey(
tmp1.GetBasisType(), tmp1.GetNumModes(),
LibUtilities::PointsKey(tmp1.GetNumModes(),
LibUtilities::ePolyEvenlySpaced));
}
}
// Define Expansion
int expdim = graphShPt->GetMeshDimension();
Array<OneD, MultiRegions::ExpListSharedPtr> Exp(1);
switch(expdim)
{
case 1:
{
if(vSession->DefinesSolverInfo("HOMOGENEOUS"))
{
std::string HomoStr = vSession->GetSolverInfo("HOMOGENEOUS");
MultiRegions::ExpList2DHomogeneous1DSharedPtr Exp2DH1;
ASSERTL0(
HomoStr == "HOMOGENEOUS1D" || HomoStr == "Homogeneous1D" ||
HomoStr == "1D" || HomoStr == "Homo1D",
"Only 3DH1D supported for XML output currently.");
int nplanes;
vSession->LoadParameter("HomModesZ", nplanes);
// choose points to be at evenly spaced points at nplanes + 1
// points
const LibUtilities::PointsKey Pkey(
nplanes + 1, LibUtilities::ePolyEvenlySpaced);
const LibUtilities::BasisKey Bkey(
LibUtilities::eFourier, nplanes, Pkey);
NekDouble lz = vSession->GetParameter("LZ");
Exp2DH1 = MemoryManager<MultiRegions::ExpList2DHomogeneous1D>
::AllocateSharedPtr(
vSession, Bkey, lz, false, false, graphShPt);
Exp[0] = Exp2DH1;
}
else
{
MultiRegions::ExpList1DSharedPtr Exp1D;
Exp1D = MemoryManager<MultiRegions::ExpList1D>
::AllocateSharedPtr(vSession,graphShPt);
Exp[0] = Exp1D;
}
break;
}
case 2:
{
if(vSession->DefinesSolverInfo("HOMOGENEOUS"))
{
std::string HomoStr = vSession->GetSolverInfo("HOMOGENEOUS");
MultiRegions::ExpList3DHomogeneous1DSharedPtr Exp3DH1;
ASSERTL0(
HomoStr == "HOMOGENEOUS1D" || HomoStr == "Homogeneous1D" ||
HomoStr == "1D" || HomoStr == "Homo1D",
"Only 3DH1D supported for XML output currently.");
int nplanes;
vSession->LoadParameter("HomModesZ", nplanes);
// choose points to be at evenly spaced points at nplanes + 1
// points
const LibUtilities::PointsKey Pkey(
nplanes + 1, LibUtilities::ePolyEvenlySpaced);
const LibUtilities::BasisKey Bkey(
LibUtilities::eFourier, nplanes, Pkey);
NekDouble lz = vSession->GetParameter("LZ");
Exp3DH1 = MemoryManager<MultiRegions::ExpList3DHomogeneous1D>
::AllocateSharedPtr(
vSession, Bkey, lz, false, false, graphShPt);
Exp[0] = Exp3DH1;
}
else
{
MultiRegions::ExpList2DSharedPtr Exp2D;
Exp2D = MemoryManager<MultiRegions::ExpList2D>
::AllocateSharedPtr(vSession,graphShPt);
Exp[0] = Exp2D;
}
break;
}
case 3:
{
MultiRegions::ExpList3DSharedPtr Exp3D;
Exp3D = MemoryManager<MultiRegions::ExpList3D>
::AllocateSharedPtr(vSession,graphShPt);
Exp[0] = Exp3D;
break;
}
default:
{
ASSERTL0(false,"Expansion dimension not recognised");
break;
}
}
// Write out VTK file.
string outname(strtok(argv[argc-1],"."));
outname += ".vtu";
ofstream outfile(outname.c_str());
Exp[0]->WriteVtkHeader(outfile);
if (jac)
{
// Find minimum Jacobian.
Array<OneD, NekDouble> tmp;
Array<OneD, NekDouble> x0 (Exp[0]->GetNpoints());
Array<OneD, NekDouble> x1 (Exp[0]->GetNpoints());
Array<OneD, NekDouble> x2 (Exp[0]->GetNpoints());
Exp[0]->GetCoords(x0, x1, x2);
vector<NekDouble> jacDist;
if (quality)
{
jacDist.resize(Exp[0]->GetExpSize());
}
// Write out field containing Jacobian.
for(int i = 0; i < Exp[0]->GetExpSize(); ++i)
{
LocalRegions::ExpansionSharedPtr e = Exp[0]->GetExp(i);
SpatialDomains::GeomFactorsSharedPtr g = e->GetMetricInfo();
LibUtilities::PointsKeyVector ptsKeys = e->GetPointsKeys();
unsigned int npts = e->GetTotPoints();
NekDouble scaledJac = 1.0;
if (g->GetGtype() == SpatialDomains::eDeformed)
{
const Array<OneD, const NekDouble> &jacobian
= g->GetJac(ptsKeys);
if (!quality)
{
Vmath::Vcopy(npts, jacobian, 1,
tmp = Exp[0]->UpdatePhys()
+ Exp[0]->GetPhys_Offset(i), 1);
}
else
{
scaledJac = Vmath::Vmin(npts, jacobian, 1) /
Vmath::Vmax(npts, jacobian, 1);
Vmath::Fill(npts, scaledJac,
tmp = Exp[0]->UpdatePhys()
+ Exp[0]->GetPhys_Offset(i), 1);
}
}
else
{
Vmath::Fill (npts, g->GetJac(ptsKeys)[0],
tmp = Exp[0]->UpdatePhys()
+ Exp[0]->GetPhys_Offset(i), 1);
}
if (quality)
{
jacDist[i] = scaledJac;
}
Exp[0]->WriteVtkPieceHeader(outfile, i);
Exp[0]->WriteVtkPieceData (outfile, i, "Jac");
Exp[0]->WriteVtkPieceFooter(outfile, i);
}
unsigned int n
= Vmath::Imin(Exp[0]->GetNpoints(), Exp[0]->GetPhys(), 1);
cout << "- Minimum Jacobian: "
<< Vmath::Vmin(Exp[0]->GetNpoints(), Exp[0]->GetPhys(), 1)
<< " at coords (" << x0[n] << ", " << x1[n] << ", " << x2[n] << ")"
<< endl;
if (quality)
{
string distName = vSession->GetSessionName() + ".jac";
ofstream dist(distName);
dist.setf (ios::scientific, ios::floatfield);
for (int i = 0; i < Exp[0]->GetExpSize(); ++i)
{
dist << setw(10) << i << " "
<< setw(20) << setprecision(15) << jacDist[i] << endl;
}
dist.close();
cout << "- Minimum/maximum scaled Jacobian: "
<< Vmath::Vmin(Exp[0]->GetExpSize(), &jacDist[0], 1) << " "
<< Vmath::Vmax(Exp[0]->GetExpSize(), &jacDist[0], 1)
<< endl;
}
}
else
{
// For each field write header and footer, since there is no field data.
for(int i = 0; i < Exp[0]->GetExpSize(); ++i)
{
Exp[0]->WriteVtkPieceHeader(outfile, i);
Exp[0]->WriteVtkPieceFooter(outfile, i);
}
}
Exp[0]->WriteVtkFooter(outfile);
return 0;
}
<commit_msg>Fix for XmlToVtk<commit_after>//////////////////////////////////////////////////////////////////////////////
//
// File: XmlToVtk.cpp
//
// For more information, please see: http://www.nektar.info
//
// The MIT License
//
// Copyright (c) 2006 Division of Applied Mathematics, Brown University (USA),
// Department of Aeronautics, Imperial College London (UK), and Scientific
// Computing and Imaging Institute, University of Utah (USA).
//
// License for the specific language governing rights and limitations under
// 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.
//
// Description: Output VTK file of XML mesh, optionally with Jacobian.
//
///////////////////////////////////////////////////////////////////////////////
#include <cstdlib>
#include <iomanip>
#include <MultiRegions/ExpList.h>
#include <MultiRegions/ExpList1D.h>
#include <MultiRegions/ExpList2D.h>
#include <MultiRegions/ExpList2DHomogeneous1D.h>
#include <MultiRegions/ExpList3D.h>
#include <MultiRegions/ExpList3DHomogeneous1D.h>
using namespace Nektar;
int main(int argc, char *argv[])
{
if(argc < 2)
{
cerr << "Usage: XmlToVtk meshfile" << endl;
exit(1);
}
LibUtilities::SessionReader::RegisterCmdLineFlag(
"jacobian", "j", "Output Jacobian as scalar field");
LibUtilities::SessionReader::RegisterCmdLineFlag(
"quality", "q", "Output distribution of scaled Jacobians");
LibUtilities::SessionReaderSharedPtr vSession
= LibUtilities::SessionReader::CreateInstance(argc, argv);
bool jac = vSession->DefinesCmdLineArgument("jacobian");
bool quality = vSession->DefinesCmdLineArgument("quality");
jac = quality ? true : jac;
// Read in mesh from input file
string meshfile(argv[argc-1]);
SpatialDomains::MeshGraphSharedPtr graphShPt =
SpatialDomains::MeshGraph::Read(vSession); //meshfile);
// Set up Expansion information
SpatialDomains::ExpansionMap emap = graphShPt->GetExpansions();
SpatialDomains::ExpansionMapIter it;
for (it = emap.begin(); it != emap.end(); ++it)
{
for (int i = 0; i < it->second->m_basisKeyVector.size(); ++i)
{
LibUtilities::BasisKey tmp1 = it->second->m_basisKeyVector[i];
LibUtilities::PointsKey tmp2 = tmp1.GetPointsKey();
it->second->m_basisKeyVector[i] = LibUtilities::BasisKey(
tmp1.GetBasisType(), tmp1.GetNumModes(),
LibUtilities::PointsKey(tmp1.GetNumModes(),
LibUtilities::ePolyEvenlySpaced));
}
}
// Define Expansion
int expdim = graphShPt->GetMeshDimension();
Array<OneD, MultiRegions::ExpListSharedPtr> Exp(1);
switch(expdim)
{
case 1:
{
if(vSession->DefinesSolverInfo("HOMOGENEOUS"))
{
std::string HomoStr = vSession->GetSolverInfo("HOMOGENEOUS");
MultiRegions::ExpList2DHomogeneous1DSharedPtr Exp2DH1;
ASSERTL0(
HomoStr == "HOMOGENEOUS1D" || HomoStr == "Homogeneous1D" ||
HomoStr == "1D" || HomoStr == "Homo1D",
"Only 3DH1D supported for XML output currently.");
int nplanes;
vSession->LoadParameter("HomModesZ", nplanes);
// choose points to be at evenly spaced points at nplanes + 1
// points
const LibUtilities::PointsKey Pkey(
nplanes + 1, LibUtilities::ePolyEvenlySpaced);
const LibUtilities::BasisKey Bkey(
LibUtilities::eFourier, nplanes, Pkey);
NekDouble lz = vSession->GetParameter("LZ");
Exp2DH1 = MemoryManager<MultiRegions::ExpList2DHomogeneous1D>
::AllocateSharedPtr(
vSession, Bkey, lz, false, false, graphShPt);
Exp[0] = Exp2DH1;
}
else
{
MultiRegions::ExpList1DSharedPtr Exp1D;
Exp1D = MemoryManager<MultiRegions::ExpList1D>
::AllocateSharedPtr(vSession,graphShPt);
Exp[0] = Exp1D;
}
break;
}
case 2:
{
if(vSession->DefinesSolverInfo("HOMOGENEOUS"))
{
std::string HomoStr = vSession->GetSolverInfo("HOMOGENEOUS");
MultiRegions::ExpList3DHomogeneous1DSharedPtr Exp3DH1;
ASSERTL0(
HomoStr == "HOMOGENEOUS1D" || HomoStr == "Homogeneous1D" ||
HomoStr == "1D" || HomoStr == "Homo1D",
"Only 3DH1D supported for XML output currently.");
int nplanes;
vSession->LoadParameter("HomModesZ", nplanes);
// choose points to be at evenly spaced points at nplanes + 1
// points
const LibUtilities::PointsKey Pkey(
nplanes + 1, LibUtilities::ePolyEvenlySpaced);
const LibUtilities::BasisKey Bkey(
LibUtilities::eFourier, nplanes, Pkey);
NekDouble lz = vSession->GetParameter("LZ");
Exp3DH1 = MemoryManager<MultiRegions::ExpList3DHomogeneous1D>
::AllocateSharedPtr(
vSession, Bkey, lz, false, false, graphShPt);
Exp[0] = Exp3DH1;
}
else
{
MultiRegions::ExpList2DSharedPtr Exp2D;
Exp2D = MemoryManager<MultiRegions::ExpList2D>
::AllocateSharedPtr(vSession,graphShPt);
Exp[0] = Exp2D;
}
break;
}
case 3:
{
MultiRegions::ExpList3DSharedPtr Exp3D;
Exp3D = MemoryManager<MultiRegions::ExpList3D>
::AllocateSharedPtr(vSession,graphShPt);
Exp[0] = Exp3D;
break;
}
default:
{
ASSERTL0(false,"Expansion dimension not recognised");
break;
}
}
// Write out VTK file.
string outname(strtok(argv[argc-1],"."));
outname += ".vtu";
ofstream outfile(outname.c_str());
Exp[0]->WriteVtkHeader(outfile);
if (jac)
{
// Find minimum Jacobian.
Array<OneD, NekDouble> tmp;
Array<OneD, NekDouble> x0 (Exp[0]->GetNpoints());
Array<OneD, NekDouble> x1 (Exp[0]->GetNpoints());
Array<OneD, NekDouble> x2 (Exp[0]->GetNpoints());
Exp[0]->GetCoords(x0, x1, x2);
vector<NekDouble> jacDist;
if (quality)
{
jacDist.resize(Exp[0]->GetExpSize());
}
// Write out field containing Jacobian.
for(int i = 0; i < Exp[0]->GetExpSize(); ++i)
{
LocalRegions::ExpansionSharedPtr e = Exp[0]->GetExp(i);
SpatialDomains::GeomFactorsSharedPtr g = e->GetMetricInfo();
LibUtilities::PointsKeyVector ptsKeys = e->GetPointsKeys();
unsigned int npts = e->GetTotPoints();
NekDouble scaledJac = 1.0;
if (g->GetGtype() == SpatialDomains::eDeformed)
{
const Array<OneD, const NekDouble> &jacobian
= g->GetJac(ptsKeys);
if (!quality)
{
Vmath::Vcopy(npts, jacobian, 1,
tmp = Exp[0]->UpdatePhys()
+ Exp[0]->GetPhys_Offset(i), 1);
}
else
{
scaledJac = Vmath::Vmin(npts, jacobian, 1) /
Vmath::Vmax(npts, jacobian, 1);
Vmath::Fill(npts, scaledJac,
tmp = Exp[0]->UpdatePhys()
+ Exp[0]->GetPhys_Offset(i), 1);
}
}
else
{
Vmath::Fill (npts, g->GetJac(ptsKeys)[0],
tmp = Exp[0]->UpdatePhys()
+ Exp[0]->GetPhys_Offset(i), 1);
}
if (quality)
{
jacDist[i] = scaledJac;
}
Exp[0]->WriteVtkPieceHeader(outfile, i);
Exp[0]->WriteVtkPieceData (outfile, i, "Jac");
Exp[0]->WriteVtkPieceFooter(outfile, i);
}
unsigned int n
= Vmath::Imin(Exp[0]->GetNpoints(), Exp[0]->GetPhys(), 1);
cout << "- Minimum Jacobian: "
<< Vmath::Vmin(Exp[0]->GetNpoints(), Exp[0]->GetPhys(), 1)
<< " at coords (" << x0[n] << ", " << x1[n] << ", " << x2[n] << ")"
<< endl;
if (quality)
{
string distName = vSession->GetSessionName() + ".jac";
ofstream dist(distName.c_str());
dist.setf (ios::scientific, ios::floatfield);
for (int i = 0; i < Exp[0]->GetExpSize(); ++i)
{
dist << setw(10) << i << " "
<< setw(20) << setprecision(15) << jacDist[i] << endl;
}
dist.close();
cout << "- Minimum/maximum scaled Jacobian: "
<< Vmath::Vmin(Exp[0]->GetExpSize(), &jacDist[0], 1) << " "
<< Vmath::Vmax(Exp[0]->GetExpSize(), &jacDist[0], 1)
<< endl;
}
}
else
{
// For each field write header and footer, since there is no field data.
for(int i = 0; i < Exp[0]->GetExpSize(); ++i)
{
Exp[0]->WriteVtkPieceHeader(outfile, i);
Exp[0]->WriteVtkPieceFooter(outfile, i);
}
}
Exp[0]->WriteVtkFooter(outfile);
return 0;
}
<|endoftext|> |
<commit_before>/*
* Copyright (c) 2008 Digital Bazaar, Inc. All rights reserved.
*/
#include "db/validation/Each.h"
#include "db/rt/DynamicObjectIterator.h"
using namespace db::rt;
using namespace db::validation;
Each::Each(Validator* validator) :
mValidator(validator)
{
}
Each::~Each()
{
}
bool Each::isArrayValid(
DynamicObject& obj,
DynamicObject* state,
std::vector<const char*>* path)
{
bool rval = true;
DynamicObjectIterator doi = obj.getIterator();
int i = -1;
while(doi->hasNext())
{
DynamicObject& member = doi->next();
i++;
// add [#] indexing to path even if at root
char idx[23];
snprintf(idx, 23, "[%d]", i);
path->push_back(idx);
rval &= mValidator->isValid(member, state, path);
path->pop_back();
}
return rval;
}
bool Each::isMapValid(
DynamicObject& obj,
DynamicObject* state,
std::vector<const char*>* path)
{
bool rval = true;
DynamicObjectIterator doi = obj.getIterator();
int i = -1;
while(doi->hasNext())
{
DynamicObject& member = doi->next();
i++;
// only add a "." if this is not a root map
if(path->size() != 0)
{
path->push_back(".");
}
path->push_back(doi->getName());
rval &= mValidator->isValid(member, state, path);
path->pop_back();
if(path->size() == 1)
{
path->pop_back();
}
}
return rval;
}
bool Each::isValid(
DynamicObject& obj,
DynamicObject* state,
std::vector<const char*>* path)
{
bool rval = true;
bool madePath = false;
// create a path if there isn't one yet
if(!path)
{
madePath = true;
path = new std::vector<const char*>;
}
switch(obj->getType())
{
case Array:
rval = isArrayValid(obj, state, path);
break;
case Map:
rval = isMapValid(obj, state, path);
break;
default:
rval = false;
DynamicObject detail = addError(path, "db.validation.TypeError");
char exp[100];
snprintf(exp, 100, "%s | %s",
DynamicObject::descriptionForType(Map),
DynamicObject::descriptionForType(Array));
detail["expectedType"] = exp;
break;
}
if(madePath)
{
delete path;
}
return rval;
}
<commit_msg>Fix mem leak.<commit_after>/*
* Copyright (c) 2008 Digital Bazaar, Inc. All rights reserved.
*/
#include "db/validation/Each.h"
#include "db/rt/DynamicObjectIterator.h"
using namespace db::rt;
using namespace db::validation;
Each::Each(Validator* validator) :
mValidator(validator)
{
}
Each::~Each()
{
delete mValidator;
}
bool Each::isArrayValid(
DynamicObject& obj,
DynamicObject* state,
std::vector<const char*>* path)
{
bool rval = true;
DynamicObjectIterator doi = obj.getIterator();
int i = -1;
while(doi->hasNext())
{
DynamicObject& member = doi->next();
i++;
// add [#] indexing to path even if at root
char idx[23];
snprintf(idx, 23, "[%d]", i);
path->push_back(idx);
rval &= mValidator->isValid(member, state, path);
path->pop_back();
}
return rval;
}
bool Each::isMapValid(
DynamicObject& obj,
DynamicObject* state,
std::vector<const char*>* path)
{
bool rval = true;
DynamicObjectIterator doi = obj.getIterator();
int i = -1;
while(doi->hasNext())
{
DynamicObject& member = doi->next();
i++;
// only add a "." if this is not a root map
if(path->size() != 0)
{
path->push_back(".");
}
path->push_back(doi->getName());
rval &= mValidator->isValid(member, state, path);
path->pop_back();
if(path->size() == 1)
{
path->pop_back();
}
}
return rval;
}
bool Each::isValid(
DynamicObject& obj,
DynamicObject* state,
std::vector<const char*>* path)
{
bool rval = true;
bool madePath = false;
// create a path if there isn't one yet
if(!path)
{
madePath = true;
path = new std::vector<const char*>;
}
switch(obj->getType())
{
case Array:
rval = isArrayValid(obj, state, path);
break;
case Map:
rval = isMapValid(obj, state, path);
break;
default:
rval = false;
DynamicObject detail = addError(path, "db.validation.TypeError");
char exp[100];
snprintf(exp, 100, "%s | %s",
DynamicObject::descriptionForType(Map),
DynamicObject::descriptionForType(Array));
detail["expectedType"] = exp;
break;
}
if(madePath)
{
delete path;
}
return rval;
}
<|endoftext|> |
<commit_before>#include "StudentTRand.h"
StudentTRand::StudentTRand(int degree)
{
setDegree(degree);
}
std::string StudentTRand::name()
{
return "Student's t(" + toStringWithPrecision(getDegree()) + ")";
}
void StudentTRand::setDegree(int degree)
{
v = std::max(degree, 1);
Y.setDegree(v);
pdfCoef = std::tgamma(.5 * (v + 1));
pdfCoef /= (std::sqrt(v * M_PI) * std::tgamma(.5 * v));
}
double StudentTRand::f(double x) const
{
double y = 1 + x * x / v;
y = std::pow(y, -.5 * (v + 1));
return pdfCoef * y;
}
double StudentTRand::F(double x) const
{
return x;
}
double StudentTRand::variate() const
{
//v = 1 -> cauchy
//v = inf -> normal
return NormalRand::standardVariate() / std::sqrt(Y.variate() / v);
}
<commit_msg>Added cdf for student's t distribution<commit_after>#include "StudentTRand.h"
StudentTRand::StudentTRand(int degree)
{
setDegree(degree);
}
std::string StudentTRand::name()
{
return "Student's t(" + toStringWithPrecision(getDegree()) + ")";
}
void StudentTRand::setDegree(int degree)
{
v = std::max(degree, 1);
Y.setDegree(v);
pdfCoef = std::tgamma(.5 * (v + 1));
pdfCoef /= (std::sqrt(v * M_PI) * std::tgamma(.5 * v));
}
double StudentTRand::f(double x) const
{
double y = 1 + x * x / v;
y = std::pow(y, -.5 * (v + 1));
return pdfCoef * y;
}
double StudentTRand::F(double x) const
{
double absY = RandMath::integral([this] (double t)
{
return f(t);
},
0, std::fabs(x));
return (x > 0) ? 0.5 + absY : 0.5 - absY;
}
double StudentTRand::variate() const
{
//v = 1 -> cauchy
//v = inf -> normal
return NormalRand::standardVariate() / std::sqrt(Y.variate() / v);
}
<|endoftext|> |
<commit_before>/*
* Copyright (C) 2008-2012 J-P Nurmi <jpnurmi@gmail.com>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 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.
*/
#include "messageformatter.h"
#include <ircsender.h>
#include <ircutil.h>
#include <irc.h>
#include <QHash>
#include <QTime>
#include <QColor>
MessageFormatter::MessageFormatter(QObject* parent) : QObject(parent)
{
d.highlight = false;
d.timeStamp = false;
}
MessageFormatter::~MessageFormatter()
{
}
QStringList MessageFormatter::highlights() const
{
return d.highlights;
}
void MessageFormatter::setHighlights(const QStringList& highlights)
{
d.highlights = highlights;
}
bool MessageFormatter::timeStamp() const
{
return d.timeStamp;
}
void MessageFormatter::setTimeStamp(bool timeStamp)
{
d.timeStamp = timeStamp;
}
QString MessageFormatter::timeStampFormat() const
{
return d.timeStampFormat;
}
void MessageFormatter::setTimeStampFormat(const QString& format)
{
d.timeStampFormat = format;
}
QString MessageFormatter::messageFormat() const
{
return d.messageFormat;
}
void MessageFormatter::setMessageFormat(const QString& format)
{
d.messageFormat = format;
}
QString MessageFormatter::eventFormat() const
{
return d.prefixedFormats.value("!");
}
void MessageFormatter::setEventFormat(const QString& format)
{
d.prefixedFormats.insert("!", format);
}
QString MessageFormatter::noticeFormat() const
{
return d.prefixedFormats.value("[");
}
void MessageFormatter::setNoticeFormat(const QString& format)
{
d.prefixedFormats.insert("[", format);
}
QString MessageFormatter::actionFormat() const
{
return d.prefixedFormats.value("*");
}
void MessageFormatter::setActionFormat(const QString& format)
{
d.prefixedFormats.insert("*", format);
}
QString MessageFormatter::unknownFormat() const
{
return d.prefixedFormats.value("?");
}
void MessageFormatter::setUnknownFormat(const QString& format)
{
d.prefixedFormats.insert("?", format);
}
QString MessageFormatter::highlightFormat() const
{
return d.highlightFormat;
}
void MessageFormatter::setHighlightFormat(const QString& format)
{
d.highlightFormat = format;
}
QString MessageFormatter::formatMessage(IrcMessage* message) const
{
QString formatted;
d.highlight = false;
switch (message->type())
{
case IrcMessage::Invite:
formatted = formatInviteMessage(static_cast<IrcInviteMessage*>(message));
break;
case IrcMessage::Join:
formatted = formatJoinMessage(static_cast<IrcJoinMessage*>(message));
break;
case IrcMessage::Kick:
formatted = formatKickMessage(static_cast<IrcKickMessage*>(message));
break;
case IrcMessage::Mode:
formatted = formatModeMessage(static_cast<IrcModeMessage*>(message));
break;
case IrcMessage::Nick:
formatted = formatNickMessage(static_cast<IrcNickMessage*>(message));
break;
case IrcMessage::Notice:
formatted = formatNoticeMessage(static_cast<IrcNoticeMessage*>(message));
break;
case IrcMessage::Numeric:
formatted = formatNumericMessage(static_cast<IrcNumericMessage*>(message));
break;
case IrcMessage::Part:
formatted = formatPartMessage(static_cast<IrcPartMessage*>(message));
break;
case IrcMessage::Pong:
formatted = formatPongMessage(static_cast<IrcPongMessage*>(message));
break;
case IrcMessage::Private:
formatted = formatPrivateMessage(static_cast<IrcPrivateMessage*>(message));
break;
case IrcMessage::Quit:
formatted = formatQuitMessage(static_cast<IrcQuitMessage*>(message));
break;
case IrcMessage::Topic:
formatted = formatTopicMessage(static_cast<IrcTopicMessage*>(message));
break;
case IrcMessage::Unknown:
formatted = formatUnknownMessage(static_cast<IrcMessage*>(message));
break;
default:
break;
}
return formatMessage(formatted);
}
QString MessageFormatter::formatMessage(const QString& message) const
{
QString formatted = message;
if (formatted.isEmpty())
return QString();
QString format = d.messageFormat;
if (d.highlight && !d.highlightFormat.isEmpty())
format = d.highlightFormat;
else if (d.prefixedFormats.contains(formatted.left(1)))
format = d.prefixedFormats.value(formatted.left(1));
if (d.timeStamp)
formatted = tr("<span %1>[%2]</span> %3").arg(d.timeStampFormat, QTime::currentTime().toString(), formatted);
if (!format.isNull())
formatted = tr("<span %1>%2</span>").arg(format, formatted);
return formatted;
}
QString MessageFormatter::formatInviteMessage(IrcInviteMessage* message) const
{
const QString sender = prettyUser(message->sender());
return tr("! %1 invited to %3").arg(sender, message->channel());
}
QString MessageFormatter::formatJoinMessage(IrcJoinMessage* message) const
{
const QString sender = prettyUser(message->sender());
return tr("! %1 joined %2").arg(sender, message->channel());
}
QString MessageFormatter::formatKickMessage(IrcKickMessage* message) const
{
const QString sender = prettyUser(message->sender());
const QString user = prettyUser(message->user());
if (!message->reason().isEmpty())
return tr("! %1 kicked %2 (%3)").arg(sender, user, message->reason());
else
return tr("! %1 kicked %2").arg(sender, user);
}
QString MessageFormatter::formatModeMessage(IrcModeMessage* message) const
{
const QString sender = prettyUser(message->sender());
return tr("! %1 sets mode %2 %3").arg(sender, message->mode(), message->argument());
}
QString MessageFormatter::formatNickMessage(IrcNickMessage* message) const
{
const QString sender = prettyUser(message->sender());
const QString nick = prettyUser(message->nick());
return tr("! %1 changed nick to %2").arg(sender, nick);
}
QString MessageFormatter::formatNoticeMessage(IrcNoticeMessage* message) const
{
if (message->isReply())
{
const QStringList params = message->message().split(" ", QString::SkipEmptyParts);
const QString cmd = params.value(0);
const QString arg = params.value(1);
if (cmd.toUpper() == "PING")
return formatPingReply(message->sender(), arg);
else if (cmd.toUpper() == "TIME")
return tr("! %1 time is %2").arg(prettyUser(message->sender()), QStringList(params.mid(1)).join(" "));
else if (cmd.toUpper() == "VERSION")
return tr("! %1 version is %2").arg(prettyUser(message->sender()), QStringList(params.mid(1)).join(" "));
}
foreach (const QString& hilite, d.highlights)
if (message->message().contains(hilite))
d.highlight = true;
const QString sender = prettyUser(message->sender());
const QString msg = IrcUtil::messageToHtml(message->message());
return tr("[%1] %2").arg(sender, msg);
}
#define P_(x) message->parameters().value(x)
#define MID_(x) QStringList(message->parameters().mid(x)).join(" ")
QString MessageFormatter::formatNumericMessage(IrcNumericMessage* message) const
{
if (message->code() < 300)
return tr("[INFO] %1").arg(IrcUtil::messageToHtml(MID_(1)));
if (QByteArray(Irc::toString(message->code())).startsWith("ERR_"))
return tr("[ERROR] %1").arg(IrcUtil::messageToHtml(MID_(1)));
switch (message->code())
{
case Irc::RPL_MOTDSTART:
case Irc::RPL_MOTD:
return tr("[MOTD] %1").arg(IrcUtil::messageToHtml(MID_(1)));
case Irc::RPL_ENDOFMOTD:
return QString();
case Irc::RPL_AWAY:
return tr("! %1 is away (%2)").arg(P_(1), MID_(2));
case Irc::RPL_ENDOFWHOIS:
return QString();
case Irc::RPL_WHOISOPERATOR:
case Irc::RPL_WHOISMODES: // "is using modes"
case Irc::RPL_WHOISREGNICK: // "is a registered nick"
case Irc::RPL_WHOISHELPOP: // "is available for help"
case Irc::RPL_WHOISSPECIAL: // "is identified to services"
case Irc::RPL_WHOISHOST: // nick is connecting from <...>
case Irc::RPL_WHOISSECURE: // nick is using a secure connection
return tr("! %1").arg(MID_(1));
case Irc::RPL_WHOISUSER:
return tr("! %1 is %2@%3 (%4)").arg(P_(1), P_(2), P_(3), IrcUtil::messageToHtml(MID_(5)));
case Irc::RPL_WHOISSERVER:
return tr("! %1 is online via %2 (%3)").arg(P_(1), P_(2), P_(3));
case Irc::RPL_WHOISACCOUNT: // nick user is logged in as
return tr("! %1 %3 %2").arg(P_(1), P_(2), P_(3));
case Irc::RPL_WHOWASUSER:
return tr("! %1 was %2@%3 %4 %5").arg(P_(1), P_(2), P_(3), P_(4), P_(5));
case Irc::RPL_WHOISIDLE: {
QDateTime signon = QDateTime::fromTime_t(P_(3).toInt());
QTime idle = QTime().addSecs(P_(2).toInt());
return tr("! %1 has been online since %2 (idle for %3)").arg(P_(1), signon.toString(), idle.toString());
}
case Irc::RPL_WHOISCHANNELS:
return tr("! %1 is on channels %2").arg(P_(1), P_(2));
case Irc::RPL_CHANNELMODEIS:
return tr("! %1 mode is %2").arg(P_(1), P_(2));
case Irc::RPL_CHANNEL_URL:
return tr("! %1 url is %2").arg(P_(1), IrcUtil::messageToHtml(P_(2)));
case Irc::RPL_CREATIONTIME: {
QDateTime dateTime = QDateTime::fromTime_t(P_(2).toInt());
return tr("! %1 was created %2").arg(P_(1), dateTime.toString());
}
case Irc::RPL_NOTOPIC:
return tr("! %1 has no topic set").arg(P_(1));
case Irc::RPL_TOPIC:
return tr("! %1 topic is \"%2\"").arg(P_(1), IrcUtil::messageToHtml(P_(2)));
case Irc::RPL_TOPICWHOTIME: {
QDateTime dateTime = QDateTime::fromTime_t(P_(3).toInt());
return tr("! %1 topic was set %2 by %3").arg(P_(1), dateTime.toString(), P_(2));
}
case Irc::RPL_INVITING:
return tr("! inviting %1 to %2").arg(prettyUser(P_(1)), P_(2));
case Irc::RPL_VERSION:
return tr("! %1 version is %2").arg(prettyUser(message->sender()), P_(1));
case Irc::RPL_TIME:
return tr("! %1 time is %2").arg(prettyUser(P_(1)), P_(2));
case Irc::RPL_UNAWAY:
case Irc::RPL_NOWAWAY:
return tr("! %1").arg(P_(1));
case Irc::RPL_NAMREPLY: {
int count = message->parameters().count();
QString channel = message->parameters().value(count - 2);
QStringList names;
foreach (const QString& name, message->parameters().value(count - 1).split(" ", QString::SkipEmptyParts))
names += IrcSender(name).name();
return tr("! %1 users: %2").arg(channel).arg(names.join(" "));
}
case Irc::RPL_ENDOFNAMES:
return QString();
default:
return tr("[%1] %2").arg(message->code()).arg(QStringList(message->parameters().mid(1)).join(" "));
}
}
QString MessageFormatter::formatPartMessage(IrcPartMessage* message) const
{
const QString sender = prettyUser(message->sender());
if (!message->reason().isEmpty())
return tr("! %1 parted %2 (%3)").arg(sender, message->channel(), IrcUtil::messageToHtml(message->reason()));
else
return tr("! %1 parted %2").arg(sender, message->channel());
}
QString MessageFormatter::formatPongMessage(IrcPongMessage* message) const
{
return formatPingReply(message->sender(), message->argument());
}
QString MessageFormatter::formatPrivateMessage(IrcPrivateMessage* message) const
{
foreach (const QString& hilite, d.highlights)
if (message->message().contains(hilite))
d.highlight = true;
const QString sender = prettyUser(message->sender());
const QString msg = IrcUtil::messageToHtml(message->message());
if (message->isAction())
return tr("* %1 %2").arg(sender, msg);
else if (message->isRequest())
return tr("! %1 requested %2").arg(sender, msg.split(" ").value(0).toLower());
else
return tr("<%1> %2").arg(sender, msg);
}
QString MessageFormatter::formatQuitMessage(IrcQuitMessage* message) const
{
const QString sender = prettyUser(message->sender());
if (!message->reason().isEmpty())
return tr("! %1 has quit (%2)").arg(sender, IrcUtil::messageToHtml(message->reason()));
else
return tr("! %1 has quit").arg(sender);
}
QString MessageFormatter::formatTopicMessage(IrcTopicMessage* message) const
{
const QString sender = prettyUser(message->sender());
const QString topic = IrcUtil::messageToHtml(message->topic());
return tr("! %1 sets topic \"%2\" on %3").arg(sender, topic, message->channel());
}
QString MessageFormatter::formatUnknownMessage(IrcMessage* message) const
{
const QString sender = prettyUser(message->sender());
return tr("? %1 %2 %3").arg(sender, message->command(), message->parameters().join(" "));
}
QString MessageFormatter::formatPingReply(const IrcSender& sender, const QString& arg)
{
bool ok;
int seconds = arg.toInt(&ok);
if (ok)
{
QDateTime time = QDateTime::fromTime_t(seconds);
QString result = QString::number(time.secsTo(QDateTime::currentDateTime()));
return tr("! %1 replied in %2s").arg(prettyUser(sender), result);
}
return QString();
}
QString MessageFormatter::prettyUser(const IrcSender& sender)
{
const QString name = sender.name();
if (sender.isValid())
return colorize(name);
return name;
}
QString MessageFormatter::prettyUser(const QString& user)
{
return prettyUser(IrcSender(user));
}
QString MessageFormatter::colorize(const QString& str)
{
QColor color = QColor::fromHsl(qHash(str) % 359, 255, 64);
return QString("<span style='color:%1'>%2</span>").arg(color.name()).arg(str);
}
<commit_msg>MessageFormatter: block colored nicks for better readability<commit_after>/*
* Copyright (C) 2008-2012 J-P Nurmi <jpnurmi@gmail.com>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 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.
*/
#include "messageformatter.h"
#include <ircsender.h>
#include <ircutil.h>
#include <irc.h>
#include <QHash>
#include <QTime>
#include <QColor>
MessageFormatter::MessageFormatter(QObject* parent) : QObject(parent)
{
d.highlight = false;
d.timeStamp = false;
}
MessageFormatter::~MessageFormatter()
{
}
QStringList MessageFormatter::highlights() const
{
return d.highlights;
}
void MessageFormatter::setHighlights(const QStringList& highlights)
{
d.highlights = highlights;
}
bool MessageFormatter::timeStamp() const
{
return d.timeStamp;
}
void MessageFormatter::setTimeStamp(bool timeStamp)
{
d.timeStamp = timeStamp;
}
QString MessageFormatter::timeStampFormat() const
{
return d.timeStampFormat;
}
void MessageFormatter::setTimeStampFormat(const QString& format)
{
d.timeStampFormat = format;
}
QString MessageFormatter::messageFormat() const
{
return d.messageFormat;
}
void MessageFormatter::setMessageFormat(const QString& format)
{
d.messageFormat = format;
}
QString MessageFormatter::eventFormat() const
{
return d.prefixedFormats.value("!");
}
void MessageFormatter::setEventFormat(const QString& format)
{
d.prefixedFormats.insert("!", format);
}
QString MessageFormatter::noticeFormat() const
{
return d.prefixedFormats.value("[");
}
void MessageFormatter::setNoticeFormat(const QString& format)
{
d.prefixedFormats.insert("[", format);
}
QString MessageFormatter::actionFormat() const
{
return d.prefixedFormats.value("*");
}
void MessageFormatter::setActionFormat(const QString& format)
{
d.prefixedFormats.insert("*", format);
}
QString MessageFormatter::unknownFormat() const
{
return d.prefixedFormats.value("?");
}
void MessageFormatter::setUnknownFormat(const QString& format)
{
d.prefixedFormats.insert("?", format);
}
QString MessageFormatter::highlightFormat() const
{
return d.highlightFormat;
}
void MessageFormatter::setHighlightFormat(const QString& format)
{
d.highlightFormat = format;
}
QString MessageFormatter::formatMessage(IrcMessage* message) const
{
QString formatted;
d.highlight = false;
switch (message->type())
{
case IrcMessage::Invite:
formatted = formatInviteMessage(static_cast<IrcInviteMessage*>(message));
break;
case IrcMessage::Join:
formatted = formatJoinMessage(static_cast<IrcJoinMessage*>(message));
break;
case IrcMessage::Kick:
formatted = formatKickMessage(static_cast<IrcKickMessage*>(message));
break;
case IrcMessage::Mode:
formatted = formatModeMessage(static_cast<IrcModeMessage*>(message));
break;
case IrcMessage::Nick:
formatted = formatNickMessage(static_cast<IrcNickMessage*>(message));
break;
case IrcMessage::Notice:
formatted = formatNoticeMessage(static_cast<IrcNoticeMessage*>(message));
break;
case IrcMessage::Numeric:
formatted = formatNumericMessage(static_cast<IrcNumericMessage*>(message));
break;
case IrcMessage::Part:
formatted = formatPartMessage(static_cast<IrcPartMessage*>(message));
break;
case IrcMessage::Pong:
formatted = formatPongMessage(static_cast<IrcPongMessage*>(message));
break;
case IrcMessage::Private:
formatted = formatPrivateMessage(static_cast<IrcPrivateMessage*>(message));
break;
case IrcMessage::Quit:
formatted = formatQuitMessage(static_cast<IrcQuitMessage*>(message));
break;
case IrcMessage::Topic:
formatted = formatTopicMessage(static_cast<IrcTopicMessage*>(message));
break;
case IrcMessage::Unknown:
formatted = formatUnknownMessage(static_cast<IrcMessage*>(message));
break;
default:
break;
}
return formatMessage(formatted);
}
QString MessageFormatter::formatMessage(const QString& message) const
{
QString formatted = message;
if (formatted.isEmpty())
return QString();
QString format = d.messageFormat;
if (d.highlight && !d.highlightFormat.isEmpty())
format = d.highlightFormat;
else if (d.prefixedFormats.contains(formatted.left(1)))
format = d.prefixedFormats.value(formatted.left(1));
if (d.timeStamp)
formatted = tr("<span %1>[%2]</span> %3").arg(d.timeStampFormat, QTime::currentTime().toString(), formatted);
if (!format.isNull())
formatted = tr("<span %1>%2</span>").arg(format, formatted);
return formatted;
}
QString MessageFormatter::formatInviteMessage(IrcInviteMessage* message) const
{
const QString sender = prettyUser(message->sender());
return tr("! %1 invited to %3").arg(sender, message->channel());
}
QString MessageFormatter::formatJoinMessage(IrcJoinMessage* message) const
{
const QString sender = prettyUser(message->sender());
return tr("! %1 joined %2").arg(sender, message->channel());
}
QString MessageFormatter::formatKickMessage(IrcKickMessage* message) const
{
const QString sender = prettyUser(message->sender());
const QString user = prettyUser(message->user());
if (!message->reason().isEmpty())
return tr("! %1 kicked %2 (%3)").arg(sender, user, message->reason());
else
return tr("! %1 kicked %2").arg(sender, user);
}
QString MessageFormatter::formatModeMessage(IrcModeMessage* message) const
{
const QString sender = prettyUser(message->sender());
return tr("! %1 sets mode %2 %3").arg(sender, message->mode(), message->argument());
}
QString MessageFormatter::formatNickMessage(IrcNickMessage* message) const
{
const QString sender = prettyUser(message->sender());
const QString nick = prettyUser(message->nick());
return tr("! %1 changed nick to %2").arg(sender, nick);
}
QString MessageFormatter::formatNoticeMessage(IrcNoticeMessage* message) const
{
if (message->isReply())
{
const QStringList params = message->message().split(" ", QString::SkipEmptyParts);
const QString cmd = params.value(0);
const QString arg = params.value(1);
if (cmd.toUpper() == "PING")
return formatPingReply(message->sender(), arg);
else if (cmd.toUpper() == "TIME")
return tr("! %1 time is %2").arg(prettyUser(message->sender()), QStringList(params.mid(1)).join(" "));
else if (cmd.toUpper() == "VERSION")
return tr("! %1 version is %2").arg(prettyUser(message->sender()), QStringList(params.mid(1)).join(" "));
}
foreach (const QString& hilite, d.highlights)
if (message->message().contains(hilite))
d.highlight = true;
const QString sender = prettyUser(message->sender());
const QString msg = IrcUtil::messageToHtml(message->message());
return tr("[%1] %2").arg(sender, msg);
}
#define P_(x) message->parameters().value(x)
#define MID_(x) QStringList(message->parameters().mid(x)).join(" ")
QString MessageFormatter::formatNumericMessage(IrcNumericMessage* message) const
{
if (message->code() < 300)
return tr("[INFO] %1").arg(IrcUtil::messageToHtml(MID_(1)));
if (QByteArray(Irc::toString(message->code())).startsWith("ERR_"))
return tr("[ERROR] %1").arg(IrcUtil::messageToHtml(MID_(1)));
switch (message->code())
{
case Irc::RPL_MOTDSTART:
case Irc::RPL_MOTD:
return tr("[MOTD] %1").arg(IrcUtil::messageToHtml(MID_(1)));
case Irc::RPL_ENDOFMOTD:
return QString();
case Irc::RPL_AWAY:
return tr("! %1 is away (%2)").arg(P_(1), MID_(2));
case Irc::RPL_ENDOFWHOIS:
return QString();
case Irc::RPL_WHOISOPERATOR:
case Irc::RPL_WHOISMODES: // "is using modes"
case Irc::RPL_WHOISREGNICK: // "is a registered nick"
case Irc::RPL_WHOISHELPOP: // "is available for help"
case Irc::RPL_WHOISSPECIAL: // "is identified to services"
case Irc::RPL_WHOISHOST: // nick is connecting from <...>
case Irc::RPL_WHOISSECURE: // nick is using a secure connection
return tr("! %1").arg(MID_(1));
case Irc::RPL_WHOISUSER:
return tr("! %1 is %2@%3 (%4)").arg(P_(1), P_(2), P_(3), IrcUtil::messageToHtml(MID_(5)));
case Irc::RPL_WHOISSERVER:
return tr("! %1 is online via %2 (%3)").arg(P_(1), P_(2), P_(3));
case Irc::RPL_WHOISACCOUNT: // nick user is logged in as
return tr("! %1 %3 %2").arg(P_(1), P_(2), P_(3));
case Irc::RPL_WHOWASUSER:
return tr("! %1 was %2@%3 %4 %5").arg(P_(1), P_(2), P_(3), P_(4), P_(5));
case Irc::RPL_WHOISIDLE: {
QDateTime signon = QDateTime::fromTime_t(P_(3).toInt());
QTime idle = QTime().addSecs(P_(2).toInt());
return tr("! %1 has been online since %2 (idle for %3)").arg(P_(1), signon.toString(), idle.toString());
}
case Irc::RPL_WHOISCHANNELS:
return tr("! %1 is on channels %2").arg(P_(1), P_(2));
case Irc::RPL_CHANNELMODEIS:
return tr("! %1 mode is %2").arg(P_(1), P_(2));
case Irc::RPL_CHANNEL_URL:
return tr("! %1 url is %2").arg(P_(1), IrcUtil::messageToHtml(P_(2)));
case Irc::RPL_CREATIONTIME: {
QDateTime dateTime = QDateTime::fromTime_t(P_(2).toInt());
return tr("! %1 was created %2").arg(P_(1), dateTime.toString());
}
case Irc::RPL_NOTOPIC:
return tr("! %1 has no topic set").arg(P_(1));
case Irc::RPL_TOPIC:
return tr("! %1 topic is \"%2\"").arg(P_(1), IrcUtil::messageToHtml(P_(2)));
case Irc::RPL_TOPICWHOTIME: {
QDateTime dateTime = QDateTime::fromTime_t(P_(3).toInt());
return tr("! %1 topic was set %2 by %3").arg(P_(1), dateTime.toString(), P_(2));
}
case Irc::RPL_INVITING:
return tr("! inviting %1 to %2").arg(prettyUser(P_(1)), P_(2));
case Irc::RPL_VERSION:
return tr("! %1 version is %2").arg(prettyUser(message->sender()), P_(1));
case Irc::RPL_TIME:
return tr("! %1 time is %2").arg(prettyUser(P_(1)), P_(2));
case Irc::RPL_UNAWAY:
case Irc::RPL_NOWAWAY:
return tr("! %1").arg(P_(1));
case Irc::RPL_NAMREPLY: {
int count = message->parameters().count();
QString channel = message->parameters().value(count - 2);
QStringList names;
foreach (const QString& name, message->parameters().value(count - 1).split(" ", QString::SkipEmptyParts))
names += IrcSender(name).name();
return tr("! %1 users: %2").arg(channel).arg(names.join(" "));
}
case Irc::RPL_ENDOFNAMES:
return QString();
default:
return tr("[%1] %2").arg(message->code()).arg(QStringList(message->parameters().mid(1)).join(" "));
}
}
QString MessageFormatter::formatPartMessage(IrcPartMessage* message) const
{
const QString sender = prettyUser(message->sender());
if (!message->reason().isEmpty())
return tr("! %1 parted %2 (%3)").arg(sender, message->channel(), IrcUtil::messageToHtml(message->reason()));
else
return tr("! %1 parted %2").arg(sender, message->channel());
}
QString MessageFormatter::formatPongMessage(IrcPongMessage* message) const
{
return formatPingReply(message->sender(), message->argument());
}
QString MessageFormatter::formatPrivateMessage(IrcPrivateMessage* message) const
{
foreach (const QString& hilite, d.highlights)
if (message->message().contains(hilite))
d.highlight = true;
const QString sender = prettyUser(message->sender());
const QString msg = IrcUtil::messageToHtml(message->message());
if (message->isAction())
return tr("* %1 %2").arg(sender, msg);
else if (message->isRequest())
return tr("! %1 requested %2").arg(sender, msg.split(" ").value(0).toLower());
else
return tr("<%1> %2").arg(sender, msg);
}
QString MessageFormatter::formatQuitMessage(IrcQuitMessage* message) const
{
const QString sender = prettyUser(message->sender());
if (!message->reason().isEmpty())
return tr("! %1 has quit (%2)").arg(sender, IrcUtil::messageToHtml(message->reason()));
else
return tr("! %1 has quit").arg(sender);
}
QString MessageFormatter::formatTopicMessage(IrcTopicMessage* message) const
{
const QString sender = prettyUser(message->sender());
const QString topic = IrcUtil::messageToHtml(message->topic());
return tr("! %1 sets topic \"%2\" on %3").arg(sender, topic, message->channel());
}
QString MessageFormatter::formatUnknownMessage(IrcMessage* message) const
{
const QString sender = prettyUser(message->sender());
return tr("? %1 %2 %3").arg(sender, message->command(), message->parameters().join(" "));
}
QString MessageFormatter::formatPingReply(const IrcSender& sender, const QString& arg)
{
bool ok;
int seconds = arg.toInt(&ok);
if (ok)
{
QDateTime time = QDateTime::fromTime_t(seconds);
QString result = QString::number(time.secsTo(QDateTime::currentDateTime()));
return tr("! %1 replied in %2s").arg(prettyUser(sender), result);
}
return QString();
}
QString MessageFormatter::prettyUser(const IrcSender& sender)
{
const QString name = sender.name();
if (sender.isValid())
return colorize(name);
return name;
}
QString MessageFormatter::prettyUser(const QString& user)
{
return prettyUser(IrcSender(user));
}
QString MessageFormatter::colorize(const QString& str)
{
QColor color = QColor::fromHsl(qHash(str) % 359, 255, 64);
return QString("<strong style='color:%1'>%2</strong>").arg(color.name()).arg(str);
}
<|endoftext|> |
<commit_before>// ==Montelight==
// Tegan Brennan, Stephen Merity, Taiyo Wilson
#include <cmath>
#include <string>
#include <iostream>
#include <fstream>
#include <vector>
#define EPSILON 0.001f
using namespace std;
struct Vector {
double x, y, z;
//
Vector(const Vector &o) : x(o.x), y(o.y), z(o.z) {}
Vector(double x_=0, double y_=0, double z_=0) : x(x_), y(y_), z(z_) {}
inline Vector operator+(const Vector &o) const {
return Vector(x + o.x, y + o.y, z + o.z);
}
inline Vector &operator+=(const Vector &rhs) {
x += rhs.x; y += rhs.y; z += rhs.z;
return *this;
}
inline Vector operator-(const Vector &o) const {
return Vector(x - o.x, y - o.y, z - o.z);
}
inline Vector operator*(const Vector &o) const {
return Vector(x * o.x, y * o.y, z * o.z);
}
inline Vector operator/(double o) const {
return Vector(x / o, y / o, z / o);
}
inline Vector operator*(double o) const {
return Vector(x * o, y * o, z * o);
}
inline double dot(const Vector &o) const {
return x * o.x + y * o.y + z * o.z;
}
inline Vector &norm(){
return *this = *this * (1 / sqrt(x * x + y * y + z * z));
}
inline Vector cross(Vector &o){
return Vector(y * o.z - z * o.y, z * o.x - x * o.z, x * o.y - y * o.x);
}
inline double min() {
return fmin(x, fmin(y, z));
}
inline double max() {
return fmax(x, fmax(y, z));
}
};
struct Ray {
Vector origin, direction;
Ray(const Vector &o_, const Vector &d_) : origin(o_), direction(d_) {}
};
struct Image {
unsigned int width, height;
Vector *pixels;
unsigned int *samples;
//
Image(unsigned int w, unsigned int h) : width(w), height(h) {
pixels = new Vector[width * height];
samples = new unsigned int[width * height];
}
void setPixel(unsigned int x, unsigned int y, const Vector &v) {
unsigned int index = (height - y - 1) * width + x;
pixels[index] += v;
samples[index] += 1;
}
inline double clamp(double x) {
if (x < 0) return 0;
if (x > 1) return 1;
return x;
}
inline double toInt(double x) {
return pow(clamp(x), 1 / 2.2f) * 255;
}
void save(std::string filePrefix) {
std::string filename = filePrefix + ".ppm";
std::ofstream f;
f.open(filename.c_str(), std::ofstream::out);
// PPM header: P3 => RGB, width, height, and max RGB value
f << "P3 " << width << " " << height << " " << 255 << std::endl;
// For each pixel, write the space separated RGB values
for (int i=0; i < width * height; i++) {
auto p = pixels[i] / samples[i];
unsigned int r = fmin(255, toInt(p.x)), g = fmin(255, toInt(p.y)), b = fmin(255, toInt(p.z));
f << r << " " << g << " " << b << std::endl;
}
}
~Image() {
delete[] pixels;
delete[] samples;
}
};
struct Shape {
Vector color, emit;
//
Shape(const Vector color_, const Vector emit_) : color(color_), emit(emit_) {}
virtual double intersects(const Ray &r) const { return 0; }
virtual Vector randomPoint() const { return Vector(); }
virtual Vector getNormal(const Vector &p) const { return Vector(); }
};
struct Sphere : Shape {
Vector center;
double radius;
//
Sphere(const Vector center_, double radius_, const Vector color_, const Vector emit_) :
Shape(color_, emit_), center(center_), radius(radius_) {}
double intersects(const Ray &r) const {
// Find if, and at what distance, the ray intersects with this object
// Equation follows from solving quadratic equation of (r - c) ^ 2
// http://wiki.cgsociety.org/index.php/Ray_Sphere_Intersection
Vector offset = r.origin - center;
double a = r.direction.dot(r.direction);
double b = 2 * offset.dot(r.direction);
double c = offset.dot(offset) - radius * radius;
// Find discriminant for use in quadratic equation (b^2 - 4ac)
double disc = b * b - 4 * a * c;
// If the discriminant is negative, there are no real roots
// (ray misses sphere)
if (disc < 0) {
return 0;
}
// The smallest positive root is the closest intersection point
disc = sqrt(disc);
double t = - b - disc;
if (t > EPSILON) {
return t / 2;
}
t = - b + disc;
if (t > EPSILON) {
return t / 2;
}
return 0;
}
Vector randomPoint() const {
// TODO: get random point on sphere surface
// (try not sampling points that are not visible in the scene)
return center;
}
Vector getNormal(const Vector &p) const {
// Normalize the normal by using radius instead of a sqrt call
return (p - center) / radius;
}
};
struct Tracer {
std::vector<Shape *> scene;
//
Tracer(const std::vector<Shape *> &scene_) : scene(scene_) {}
std::pair<Shape *, double> getIntersection(const Ray &r) const {
Shape *hitObj = NULL;
double closest = 1e20f;
for (Shape *obj : scene) {
double distToHit = obj->intersects(r);
if (distToHit > 0 && distToHit < closest) {
hitObj = obj;
closest = distToHit;
}
}
return std::make_pair(hitObj, closest);
}
Vector getRadiance(const Ray &r, int depth) {
bool _EMITTER_SAMPLING = true;
// Work out what (if anything) was hit
auto result = getIntersection(r);
Shape *hitObj = result.first;
// Russian Roulette sampling based on reflectance of material
double U = drand48();
if (depth > 4 && (depth > 20 || U > hitObj->color.max())) {
return Vector();
}
Vector hitPos = r.origin + r.direction * result.second;
Vector norm = hitObj->getNormal(hitPos);
// Orient the normal according to how the ray struck the object
if (norm.dot(r.direction) > 0) {
norm = norm * -1;
}
// Work out the contribution from directly sampling the emitters
Vector lightSampling;
if (_EMITTER_SAMPLING) {
for (Shape *light : scene) {
// Skip any objects that don't emit light
if (light->emit.max() == 0) {
continue;
}
Vector lightPos = light->randomPoint();
Vector lightDirection = (lightPos - hitPos).norm();
Ray rayToLight = Ray(hitPos, lightDirection);
auto lightHit = getIntersection(rayToLight);
if (light == lightHit.first) {
double wi = lightDirection.dot(norm);
if (wi > 0) {
double srad = 1.5;
//double srad = 600;
double cos_a_max = sqrt(1-srad*srad/(hitPos - lightPos).dot(hitPos - lightPos));
double omega = 2*M_PI*(1-cos_a_max);
lightSampling += light->emit * wi * omega * M_1_PI;
}
}
}
}
// Work out contribution from reflected light
// Diffuse reflection condition:
// Create orthogonal coordinate system defined by (x=u, y=v, z=norm)
double angle = 2 * M_PI * drand48();
double dist_cen = sqrt(drand48());
Vector u;
if (fabs(norm.x) > 0.1) {
u = Vector(0, 1, 0);
}
else {
u = Vector(1, 0, 0);
}
u = u.cross(norm).norm();
Vector v = norm.cross(u);
// Direction of reflection
Vector d = (u * cos(angle) * dist_cen + v * sin(angle) * dist_cen + norm * sqrt(1 - dist_cen * dist_cen)).norm();
// Recurse
Vector reflected = getRadiance(Ray(hitPos, d), depth + 1);
//
if (!_EMITTER_SAMPLING || depth == 0) {
return hitObj->emit + hitObj->color * lightSampling + hitObj->color * reflected;
}
return hitObj->color * lightSampling + hitObj->color * reflected;
}
};
int main(int argc, const char *argv[]) {
// Initialize the image
int w = 256, h = 256;
Image img(w, h);
// Set up the scene
// Cornell box inspired: http://graphics.ucsd.edu/~henrik/images/cbox.html
std::vector<Shape *> scene = {//Scene: position, radius, color, emission; not yet added: material
new Sphere(Vector(1e5+1,40.8,81.6), 1e5f, Vector(.75,.25,.25), Vector()),//Left
new Sphere(Vector(-1e5+99,40.8,81.6), 1e5f, Vector(.25,.25,.75), Vector()),//Rght
new Sphere(Vector(50,40.8, 1e5), 1e5f, Vector(.75,.75,.75), Vector()),//Back
new Sphere(Vector(50,40.8,-1e5+170), 1e5f, Vector(), Vector()),//Frnt
new Sphere(Vector(50, 1e5, 81.6), 1e5f, Vector(.75,.75,.75), Vector()),//Botm
new Sphere(Vector(50,-1e5+81.6,81.6), 1e5f, Vector(.75,.75,.75), Vector()),//Top
new Sphere(Vector(27,16.5,47), 16.5f, Vector(1,1,1) * 0.799, Vector()),//Mirr
new Sphere(Vector(73,16.5,78), 16.5f, Vector(1,1,1) * 0.799, Vector()),//Glas
//new Sphere(Vector(50,681.6-.27,81.6), 600, Vector(1,1,1) * 0.5, Vector(12,12,12)) //Light
new Sphere(Vector(50,65.1,81.6), 1.5, Vector(), Vector(4,4,4) * 100) //Light
};
Tracer tracer = Tracer(scene);
// Set up the camera
Ray camera = Ray(Vector(50, 52, 295.6), Vector(0, -0.042612, -1).norm());
// Upright camera with field of view angle set by 0.5135
Vector cx = Vector((w * 0.5135) / h, 0, 0);
// Cross product gets the vector perpendicular to cx and the "gaze" direction
Vector cy = (cx.cross(camera.direction)).norm() * 0.5135;
// Take a set number of samples per pixel
unsigned int SAMPLES = 50;
for (int sample = 0; sample < SAMPLES; ++sample) {
std::cout << "Taking sample " << sample << "\r" << std::flush;
// For each pixel, sample a ray in that direction
#pragma omp parallel for schedule(dynamic, 1)
for (int y = 0; y < h; ++y) {
for (int x = 0; x < w; ++x) {
// Jitter pixel randomly in dx and dy according to the tent filter
double Ux = 2 * drand48();
double Uy = 2 * drand48();
double dx;
if (Ux < 1) {
dx = sqrt(Ux) - 1;
} else {
dx = 1 - sqrt(2 - Ux);
}
double dy;
if (Uy < 1) {
dy = sqrt(Uy) - 1;
} else {
dy = 1 - sqrt(2 - Uy);
}
// Calculate the direction of the camera ray
Vector d = (cx * (((x+dx) / float(w)) - 0.5)) + (cy * (((y+dy) / float(h)) - 0.5)) + camera.direction;
Ray ray = Ray(camera.origin + d * 140, d.norm());
Vector rads = tracer.getRadiance(ray, 0);
// Add result of sample to image
img.setPixel(x, y, rads);
}
}
}
// Save the resulting raytraced image
img.save("render");
return 0;
}
<commit_msg>Variance reduction attempt using neighbouring pixels<commit_after>// ==Montelight==
// Tegan Brennan, Stephen Merity, Taiyo Wilson
#include <cmath>
#include <string>
#include <iostream>
#include <fstream>
#include <vector>
#define EPSILON 0.001f
using namespace std;
struct Vector {
double x, y, z;
//
Vector(const Vector &o) : x(o.x), y(o.y), z(o.z) {}
Vector(double x_=0, double y_=0, double z_=0) : x(x_), y(y_), z(z_) {}
inline Vector operator+(const Vector &o) const {
return Vector(x + o.x, y + o.y, z + o.z);
}
inline Vector &operator+=(const Vector &rhs) {
x += rhs.x; y += rhs.y; z += rhs.z;
return *this;
}
inline Vector operator-(const Vector &o) const {
return Vector(x - o.x, y - o.y, z - o.z);
}
inline Vector operator*(const Vector &o) const {
return Vector(x * o.x, y * o.y, z * o.z);
}
inline Vector operator/(double o) const {
return Vector(x / o, y / o, z / o);
}
inline Vector operator*(double o) const {
return Vector(x * o, y * o, z * o);
}
inline double dot(const Vector &o) const {
return x * o.x + y * o.y + z * o.z;
}
inline Vector &norm(){
return *this = *this * (1 / sqrt(x * x + y * y + z * z));
}
inline Vector cross(Vector &o){
return Vector(y * o.z - z * o.y, z * o.x - x * o.z, x * o.y - y * o.x);
}
inline double min() {
return fmin(x, fmin(y, z));
}
inline double max() {
return fmax(x, fmax(y, z));
}
inline Vector &abs() {
x = fabs(x); y = fabs(y); z = fabs(z);
return *this;
}
};
struct Ray {
Vector origin, direction;
Ray(const Vector &o_, const Vector &d_) : origin(o_), direction(d_) {}
};
struct Image {
unsigned int width, height;
Vector *pixels, *current;
unsigned int *samples;
std::vector<Vector> *raw_samples;
//
Image(unsigned int w, unsigned int h) : width(w), height(h) {
pixels = new Vector[width * height];
samples = new unsigned int[width * height];
current = new Vector[width * height];
//raw_samples = new std::vector<Vector>[width * height];
}
Vector getPixel(unsigned int x, unsigned int y) {
unsigned int index = (height - y - 1) * width + x;
return current[index];
}
void setPixel(unsigned int x, unsigned int y, const Vector &v) {
unsigned int index = (height - y - 1) * width + x;
pixels[index] += v;
samples[index] += 1;
current[index] = pixels[index] / samples[index];
//raw_samples[index].push_back(v);
}
Vector getSurroundingAverage(int x, int y, int pattern=0) {
unsigned int index = (height - y - 1) * width + x;
Vector avg;
int total;
for (int dy = -1; dy < 2; ++dy) {
for (int dx = -1; dx < 2; ++dx) {
if (pattern == 0 && (dx != 0 && dy != 0)) continue;
if (pattern == 1 && (dx == 0 || dy == 0)) continue;
if (dx == 0 && dy == 0) {
continue;
}
if (x + dx < 0 || x + dx > width - 1) continue;
if (y + dy < 0 || y + dy > height - 1) continue;
index = (height - (y + dy) - 1) * width + (x + dx);
avg += current[index];
total += 1;
}
}
return avg / total;
}
inline double clamp(double x) {
if (x < 0) return 0;
if (x > 1) return 1;
return x;
}
inline double toInt(double x) {
return pow(clamp(x), 1 / 2.2f) * 255;
}
void save(std::string filePrefix) {
std::string filename = filePrefix + ".ppm";
std::ofstream f;
f.open(filename.c_str(), std::ofstream::out);
// PPM header: P3 => RGB, width, height, and max RGB value
f << "P3 " << width << " " << height << " " << 255 << std::endl;
// For each pixel, write the space separated RGB values
for (int i=0; i < width * height; i++) {
auto p = pixels[i] / samples[i];
unsigned int r = fmin(255, toInt(p.x)), g = fmin(255, toInt(p.y)), b = fmin(255, toInt(p.z));
f << r << " " << g << " " << b << std::endl;
}
}
void saveHistogram(std::string filePrefix, int maxIters) {
std::string filename = filePrefix + ".ppm";
std::ofstream f;
f.open(filename.c_str(), std::ofstream::out);
// PPM header: P3 => RGB, width, height, and max RGB value
f << "P3 " << width << " " << height << " " << 255 << std::endl;
// For each pixel, write the space separated RGB values
for (int i=0; i < width * height; i++) {
auto p = samples[i] / maxIters;
unsigned int r, g, b;
r= g = b = fmin(255, 255 * p);
f << r << " " << g << " " << b << std::endl;
}
}
~Image() {
delete[] pixels;
delete[] samples;
}
};
struct Shape {
Vector color, emit;
//
Shape(const Vector color_, const Vector emit_) : color(color_), emit(emit_) {}
virtual double intersects(const Ray &r) const { return 0; }
virtual Vector randomPoint() const { return Vector(); }
virtual Vector getNormal(const Vector &p) const { return Vector(); }
};
struct Sphere : Shape {
Vector center;
double radius;
//
Sphere(const Vector center_, double radius_, const Vector color_, const Vector emit_) :
Shape(color_, emit_), center(center_), radius(radius_) {}
double intersects(const Ray &r) const {
// Find if, and at what distance, the ray intersects with this object
// Equation follows from solving quadratic equation of (r - c) ^ 2
// http://wiki.cgsociety.org/index.php/Ray_Sphere_Intersection
Vector offset = r.origin - center;
double a = r.direction.dot(r.direction);
double b = 2 * offset.dot(r.direction);
double c = offset.dot(offset) - radius * radius;
// Find discriminant for use in quadratic equation (b^2 - 4ac)
double disc = b * b - 4 * a * c;
// If the discriminant is negative, there are no real roots
// (ray misses sphere)
if (disc < 0) {
return 0;
}
// The smallest positive root is the closest intersection point
disc = sqrt(disc);
double t = - b - disc;
if (t > EPSILON) {
return t / 2;
}
t = - b + disc;
if (t > EPSILON) {
return t / 2;
}
return 0;
}
Vector randomPoint() const {
// TODO: get random point on sphere surface
// (try not sampling points that are not visible in the scene)
// https://www.jasondavies.com/maps/random-points/
return center;
}
Vector getNormal(const Vector &p) const {
// Normalize the normal by using radius instead of a sqrt call
return (p - center) / radius;
}
};
struct Tracer {
std::vector<Shape *> scene;
//
Tracer(const std::vector<Shape *> &scene_) : scene(scene_) {}
std::pair<Shape *, double> getIntersection(const Ray &r) const {
Shape *hitObj = NULL;
double closest = 1e20f;
for (Shape *obj : scene) {
double distToHit = obj->intersects(r);
if (distToHit > 0 && distToHit < closest) {
hitObj = obj;
closest = distToHit;
}
}
return std::make_pair(hitObj, closest);
}
Vector getRadiance(const Ray &r, int depth) {
bool _EMITTER_SAMPLING = false;
// Work out what (if anything) was hit
auto result = getIntersection(r);
Shape *hitObj = result.first;
// Russian Roulette sampling based on reflectance of material
double U = drand48();
if (depth > 4 && (depth > 20 || U > hitObj->color.max())) {
return Vector();
}
Vector hitPos = r.origin + r.direction * result.second;
Vector norm = hitObj->getNormal(hitPos);
// Orient the normal according to how the ray struck the object
if (norm.dot(r.direction) > 0) {
norm = norm * -1;
}
// Work out the contribution from directly sampling the emitters
Vector lightSampling;
if (_EMITTER_SAMPLING) {
for (Shape *light : scene) {
// Skip any objects that don't emit light
if (light->emit.max() == 0) {
continue;
}
Vector lightPos = light->randomPoint();
Vector lightDirection = (lightPos - hitPos).norm();
Ray rayToLight = Ray(hitPos, lightDirection);
auto lightHit = getIntersection(rayToLight);
if (light == lightHit.first) {
double wi = lightDirection.dot(norm);
if (wi > 0) {
double srad = 1.5;
//double srad = 600;
double cos_a_max = sqrt(1-srad*srad/(hitPos - lightPos).dot(hitPos - lightPos));
double omega = 2*M_PI*(1-cos_a_max);
lightSampling += light->emit * wi * omega * M_1_PI;
}
}
}
}
// Work out contribution from reflected light
// Diffuse reflection condition:
// Create orthogonal coordinate system defined by (x=u, y=v, z=norm)
double angle = 2 * M_PI * drand48();
double dist_cen = sqrt(drand48());
Vector u;
if (fabs(norm.x) > 0.1) {
u = Vector(0, 1, 0);
} else {
u = Vector(1, 0, 0);
}
u = u.cross(norm).norm();
Vector v = norm.cross(u);
// Direction of reflection
Vector d = (u * cos(angle) * dist_cen + v * sin(angle) * dist_cen + norm * sqrt(1 - dist_cen * dist_cen)).norm();
// Recurse
Vector reflected = getRadiance(Ray(hitPos, d), depth + 1);
//
if (!_EMITTER_SAMPLING || depth == 0) {
return hitObj->emit + hitObj->color * lightSampling + hitObj->color * reflected;
}
return hitObj->color * lightSampling + hitObj->color * reflected;
}
};
int main(int argc, const char *argv[]) {
// Initialize the image
int w = 256, h = 256;
Image img(w, h);
// Set up the scene
// Cornell box inspired: http://graphics.ucsd.edu/~henrik/images/cbox.html
std::vector<Shape *> scene = {//Scene: position, radius, color, emission; not yet added: material
new Sphere(Vector(1e5+1,40.8,81.6), 1e5f, Vector(.75,.25,.25), Vector()),//Left
new Sphere(Vector(-1e5+99,40.8,81.6), 1e5f, Vector(.25,.25,.75), Vector()),//Rght
new Sphere(Vector(50,40.8, 1e5), 1e5f, Vector(.75,.75,.75), Vector()),//Back
new Sphere(Vector(50,40.8,-1e5+170), 1e5f, Vector(), Vector()),//Frnt
new Sphere(Vector(50, 1e5, 81.6), 1e5f, Vector(.75,.75,.75), Vector()),//Botm
new Sphere(Vector(50,-1e5+81.6,81.6), 1e5f, Vector(.75,.75,.75), Vector()),//Top
new Sphere(Vector(27,16.5,47), 16.5f, Vector(1,1,1) * 0.799, Vector()),//Mirr
new Sphere(Vector(73,16.5,78), 16.5f, Vector(1,1,1) * 0.799, Vector()),//Glas
new Sphere(Vector(50,681.6-.27,81.6), 600, Vector(1,1,1) * 0.5, Vector(12,12,12)) //Light
//new Sphere(Vector(50,65.1,81.6), 1.5, Vector(), Vector(4,4,4) * 100) //Light
};
Tracer tracer = Tracer(scene);
// Set up the camera
Ray camera = Ray(Vector(50, 52, 295.6), Vector(0, -0.042612, -1).norm());
// Upright camera with field of view angle set by 0.5135
Vector cx = Vector((w * 0.5135) / h, 0, 0);
// Cross product gets the vector perpendicular to cx and the "gaze" direction
Vector cy = (cx.cross(camera.direction)).norm() * 0.5135;
// Take a set number of samples per pixel
unsigned int SAMPLES = 800;
unsigned int updated;
for (int sample = 0; sample < SAMPLES; ++sample) {
std::cout << "Taking sample " << sample << ": " << updated << " pixels updated\r" << std::flush;
if (sample && sample % 50 == 0) {
img.save("temp/render_" + std::to_string(sample));
img.saveHistogram("temp/hist" + std::to_string(sample), sample / 2.0);
}
updated = 0;
// For each pixel, sample a ray in that direction
for (int y = 0; y < h; ++y) {
for (int x = 0; x < w; ++x) {
Vector target = img.getPixel(x, y);
double A = (target - img.getSurroundingAverage(x, y, sample % 2)).abs().max() / (100 / 255.0);
if (sample > 10 && drand48() > A) {
continue;
}
++updated;
// Jitter pixel randomly in dx and dy according to the tent filter
double Ux = 2 * drand48();
double Uy = 2 * drand48();
double dx;
if (Ux < 1) {
dx = sqrt(Ux) - 1;
} else {
dx = 1 - sqrt(2 - Ux);
}
double dy;
if (Uy < 1) {
dy = sqrt(Uy) - 1;
} else {
dy = 1 - sqrt(2 - Uy);
}
// Calculate the direction of the camera ray
Vector d = (cx * (((x+dx) / float(w)) - 0.5)) + (cy * (((y+dy) / float(h)) - 0.5)) + camera.direction;
Ray ray = Ray(camera.origin + d * 140, d.norm());
Vector rads = tracer.getRadiance(ray, 0);
// Add result of sample to image
img.setPixel(x, y, rads);
}
}
}
// Save the resulting raytraced image
img.save("render");
img.saveHistogram("hist", SAMPLES / 2.);
return 0;
}
<|endoftext|> |
<commit_before>/****************************************************************************
* Copyright (c) 2012-2018 by the DataTransferKit authors *
* All rights reserved. *
* *
* This file is part of the DataTransferKit library. DataTransferKit is *
* distributed under a BSD 3-clause license. For the licensing terms see *
* the LICENSE file in the top-level directory. *
* *
* SPDX-License-Identifier: BSD-3-Clause *
****************************************************************************/
#include <DTK_LinearBVH.hpp>
#include <Kokkos_DefaultNode.hpp>
#include <Teuchos_CommandLineProcessor.hpp>
#include <Teuchos_StandardCatchMacros.hpp>
#include <chrono>
#include <cmath> // cbrt
#include <random>
template <class NO>
int main_( Teuchos::CommandLineProcessor &clp, int argc, char *argv[] )
{
using DeviceType = typename NO::device_type;
using ExecutionSpace = typename DeviceType::execution_space;
int n_values = 50000;
int n_queries = 20000;
int n_neighbors = 10;
clp.setOption( "values", &n_values, "number of indexable values (source)" );
clp.setOption( "queries", &n_queries, "number of queries (target)" );
clp.setOption( "neighbors", &n_neighbors,
"desired number of results per query" );
clp.recogniseAllOptions( true );
switch ( clp.parse( argc, argv ) )
{
case Teuchos::CommandLineProcessor::PARSE_HELP_PRINTED:
return EXIT_SUCCESS;
case Teuchos::CommandLineProcessor::PARSE_ERROR:
case Teuchos::CommandLineProcessor::PARSE_UNRECOGNIZED_OPTION:
return EXIT_FAILURE;
case Teuchos::CommandLineProcessor::PARSE_SUCCESSFUL:
break;
}
Kokkos::View<DataTransferKit::Point *, DeviceType> random_points(
"random_points" );
{
auto n = std::max( n_values, n_queries );
Kokkos::resize( random_points, n );
auto random_points_host = Kokkos::create_mirror_view( random_points );
// edge length chosen such that object density will remain constant as
// problem size is changed
auto const a = std::cbrt( n_values );
std::uniform_real_distribution<double> distribution( -a, +a );
std::default_random_engine generator;
auto random = [&distribution, &generator]() {
return distribution( generator );
};
for ( int i = 0; i < n; ++i )
random_points_host( i ) = {{random(), random(), random()}};
Kokkos::deep_copy( random_points, random_points_host );
}
Kokkos::View<DataTransferKit::Box *, DeviceType> bounding_boxes(
"bounding_boxes", n_values );
Kokkos::parallel_for( Kokkos::RangePolicy<ExecutionSpace>( 0, n_values ),
KOKKOS_LAMBDA( int i ) {
double const x = random_points( i )[0];
double const y = random_points( i )[1];
double const z = random_points( i )[2];
bounding_boxes( i ) = {
{{x - 1., y - 1., z - 1.}},
{{x + 1., y + 1., z + 1.}}};
} );
Kokkos::fence();
std::ostream &os = std::cout;
auto start = std::chrono::high_resolution_clock::now();
DataTransferKit::BVH<DeviceType> bvh( bounding_boxes );
auto end = std::chrono::high_resolution_clock::now();
std::chrono::duration<double> elapsed_seconds = end - start;
os << "construction " << elapsed_seconds.count() << "\n";
{
Kokkos::View<
DataTransferKit::Details::Nearest<DataTransferKit::Point> *,
DeviceType>
queries( "queries", n_queries );
Kokkos::parallel_for(
Kokkos::RangePolicy<ExecutionSpace>( 0, n_queries ),
KOKKOS_LAMBDA( int i ) {
queries( i ) =
DataTransferKit::Details::nearest<DataTransferKit::Point>(
random_points( i ), n_neighbors );
} );
Kokkos::fence();
Kokkos::View<int *, DeviceType> offset( "offset" );
Kokkos::View<int *, DeviceType> indices( "indices" );
start = std::chrono::high_resolution_clock::now();
bvh.query( queries, indices, offset );
end = std::chrono::high_resolution_clock::now();
elapsed_seconds = end - start;
os << "knn " << elapsed_seconds.count() << "\n";
}
{
Kokkos::View<DataTransferKit::Details::Within *, DeviceType> queries(
"queries", n_queries );
// radius chosen in order to control the number of results per query
// NOTE: minus "1+sqrt(3)/2 \approx 1.37" matches the size of the boxes
// inserted into the tree (mid-point between half-edge and
// half-diagonal)
double const pi = 3.14159265359;
double const r = 2. * std::cbrt( static_cast<double>( n_neighbors ) *
3. / ( 4. * pi ) ) -
( 1. + std::sqrt( 3. ) ) / 2.;
Kokkos::parallel_for(
Kokkos::RangePolicy<ExecutionSpace>( 0, n_queries ),
KOKKOS_LAMBDA( int i ) {
queries( i ) =
DataTransferKit::Details::within( random_points( i ), r );
} );
Kokkos::fence();
Kokkos::View<int *, DeviceType> offset( "offset" );
Kokkos::View<int *, DeviceType> indices( "indices" );
start = std::chrono::high_resolution_clock::now();
bvh.query( queries, indices, offset );
end = std::chrono::high_resolution_clock::now();
elapsed_seconds = end - start;
os << "radius " << elapsed_seconds.count() << "\n";
}
return 0;
}
int main( int argc, char *argv[] )
{
Kokkos::initialize( argc, argv );
bool success = true;
bool verbose = true;
try
{
const bool throwExceptions = false;
Teuchos::CommandLineProcessor clp( throwExceptions );
std::string node = "";
clp.setOption( "node", &node, "node type (serial | openmp | cuda)" );
clp.recogniseAllOptions( false );
switch ( clp.parse( argc, argv, NULL ) )
{
case Teuchos::CommandLineProcessor::PARSE_ERROR:
success = false;
case Teuchos::CommandLineProcessor::PARSE_HELP_PRINTED:
case Teuchos::CommandLineProcessor::PARSE_UNRECOGNIZED_OPTION:
case Teuchos::CommandLineProcessor::PARSE_SUCCESSFUL:
break;
}
if ( !success )
{
// do nothing, just skip other if clauses
}
else if ( node == "" )
{
typedef KokkosClassic::DefaultNode::DefaultNodeType Node;
main_<Node>( clp, argc, argv );
}
else if ( node == "serial" )
{
#ifdef KOKKOS_HAVE_SERIAL
typedef Kokkos::Compat::KokkosSerialWrapperNode Node;
main_<Node>( clp, argc, argv );
#else
throw std::runtime_error( "Serial node type is disabled" );
#endif
}
else if ( node == "openmp" )
{
#ifdef KOKKOS_HAVE_OPENMP
typedef Kokkos::Compat::KokkosOpenMPWrapperNode Node;
main_<Node>( clp, argc, argv );
#else
throw std::runtime_error( "OpenMP node type is disabled" );
#endif
}
else if ( node == "cuda" )
{
#ifdef KOKKOS_HAVE_CUDA
typedef Kokkos::Compat::KokkosCudaWrapperNode Node;
main_<Node>( clp, argc, argv );
#else
throw std::runtime_error( "CUDA node type is disabled" );
#endif
}
else
{
throw std::runtime_error( "Unrecognized node type" );
}
}
TEUCHOS_STANDARD_CATCH_STATEMENTS( verbose, std::cerr, success );
Kokkos::finalize();
return ( success ? EXIT_SUCCESS : EXIT_FAILURE );
}
<commit_msg>Add/improve comments on the problem setup<commit_after>/****************************************************************************
* Copyright (c) 2012-2018 by the DataTransferKit authors *
* All rights reserved. *
* *
* This file is part of the DataTransferKit library. DataTransferKit is *
* distributed under a BSD 3-clause license. For the licensing terms see *
* the LICENSE file in the top-level directory. *
* *
* SPDX-License-Identifier: BSD-3-Clause *
****************************************************************************/
#include <DTK_LinearBVH.hpp>
#include <Kokkos_DefaultNode.hpp>
#include <Teuchos_CommandLineProcessor.hpp>
#include <Teuchos_StandardCatchMacros.hpp>
#include <chrono>
#include <cmath> // cbrt
#include <random>
template <class NO>
int main_( Teuchos::CommandLineProcessor &clp, int argc, char *argv[] )
{
using DeviceType = typename NO::device_type;
using ExecutionSpace = typename DeviceType::execution_space;
int n_values = 50000;
int n_queries = 20000;
int n_neighbors = 10;
clp.setOption( "values", &n_values, "number of indexable values (source)" );
clp.setOption( "queries", &n_queries, "number of queries (target)" );
clp.setOption( "neighbors", &n_neighbors,
"desired number of results per query" );
clp.recogniseAllOptions( true );
switch ( clp.parse( argc, argv ) )
{
case Teuchos::CommandLineProcessor::PARSE_HELP_PRINTED:
return EXIT_SUCCESS;
case Teuchos::CommandLineProcessor::PARSE_ERROR:
case Teuchos::CommandLineProcessor::PARSE_UNRECOGNIZED_OPTION:
return EXIT_FAILURE;
case Teuchos::CommandLineProcessor::PARSE_SUCCESSFUL:
break;
}
Kokkos::View<DataTransferKit::Point *, DeviceType> random_points(
"random_points" );
{
// Random points are "reused" between building the tree and performing
// queries. You may change it if you have a problem with it. These
// don't really need to be stored in the 1st place. What is needed is
// indexable objects/values (here boxes) to build a tree and queries
// (here kNN and radius searches) with mean to control the amount of
// work per query as the problem size varies.
auto n = std::max( n_values, n_queries );
Kokkos::resize( random_points, n );
auto random_points_host = Kokkos::create_mirror_view( random_points );
// Generate random points uniformely distributed within a box. The
// edge length of the box chosen such that object density (here objects
// will be boxes 2x2x2 centered around a random point) will remain
// constant as problem size is changed.
auto const a = std::cbrt( n_values );
std::uniform_real_distribution<double> distribution( -a, +a );
std::default_random_engine generator;
auto random = [&distribution, &generator]() {
return distribution( generator );
};
for ( int i = 0; i < n; ++i )
random_points_host( i ) = {{random(), random(), random()}};
Kokkos::deep_copy( random_points, random_points_host );
}
Kokkos::View<DataTransferKit::Box *, DeviceType> bounding_boxes(
"bounding_boxes", n_values );
Kokkos::parallel_for( Kokkos::RangePolicy<ExecutionSpace>( 0, n_values ),
KOKKOS_LAMBDA( int i ) {
double const x = random_points( i )[0];
double const y = random_points( i )[1];
double const z = random_points( i )[2];
bounding_boxes( i ) = {
{{x - 1., y - 1., z - 1.}},
{{x + 1., y + 1., z + 1.}}};
} );
Kokkos::fence();
std::ostream &os = std::cout;
auto start = std::chrono::high_resolution_clock::now();
DataTransferKit::BVH<DeviceType> bvh( bounding_boxes );
auto end = std::chrono::high_resolution_clock::now();
std::chrono::duration<double> elapsed_seconds = end - start;
os << "construction " << elapsed_seconds.count() << "\n";
{
Kokkos::View<
DataTransferKit::Details::Nearest<DataTransferKit::Point> *,
DeviceType>
queries( "queries", n_queries );
Kokkos::parallel_for(
Kokkos::RangePolicy<ExecutionSpace>( 0, n_queries ),
KOKKOS_LAMBDA( int i ) {
queries( i ) =
DataTransferKit::Details::nearest<DataTransferKit::Point>(
random_points( i ), n_neighbors );
} );
Kokkos::fence();
Kokkos::View<int *, DeviceType> offset( "offset" );
Kokkos::View<int *, DeviceType> indices( "indices" );
start = std::chrono::high_resolution_clock::now();
bvh.query( queries, indices, offset );
end = std::chrono::high_resolution_clock::now();
elapsed_seconds = end - start;
os << "knn " << elapsed_seconds.count() << "\n";
}
{
Kokkos::View<DataTransferKit::Details::Within *, DeviceType> queries(
"queries", n_queries );
// radius chosen in order to control the number of results per query
// NOTE: minus "1+sqrt(3)/2 \approx 1.37" matches the size of the boxes
// inserted into the tree (mid-point between half-edge and
// half-diagonal)
double const pi = 3.14159265359;
double const r = 2. * std::cbrt( static_cast<double>( n_neighbors ) *
3. / ( 4. * pi ) ) -
( 1. + std::sqrt( 3. ) ) / 2.;
Kokkos::parallel_for(
Kokkos::RangePolicy<ExecutionSpace>( 0, n_queries ),
KOKKOS_LAMBDA( int i ) {
queries( i ) =
DataTransferKit::Details::within( random_points( i ), r );
} );
Kokkos::fence();
Kokkos::View<int *, DeviceType> offset( "offset" );
Kokkos::View<int *, DeviceType> indices( "indices" );
start = std::chrono::high_resolution_clock::now();
bvh.query( queries, indices, offset );
end = std::chrono::high_resolution_clock::now();
elapsed_seconds = end - start;
os << "radius " << elapsed_seconds.count() << "\n";
}
return 0;
}
int main( int argc, char *argv[] )
{
Kokkos::initialize( argc, argv );
bool success = true;
bool verbose = true;
try
{
const bool throwExceptions = false;
Teuchos::CommandLineProcessor clp( throwExceptions );
std::string node = "";
clp.setOption( "node", &node, "node type (serial | openmp | cuda)" );
clp.recogniseAllOptions( false );
switch ( clp.parse( argc, argv, NULL ) )
{
case Teuchos::CommandLineProcessor::PARSE_ERROR:
success = false;
case Teuchos::CommandLineProcessor::PARSE_HELP_PRINTED:
case Teuchos::CommandLineProcessor::PARSE_UNRECOGNIZED_OPTION:
case Teuchos::CommandLineProcessor::PARSE_SUCCESSFUL:
break;
}
if ( !success )
{
// do nothing, just skip other if clauses
}
else if ( node == "" )
{
typedef KokkosClassic::DefaultNode::DefaultNodeType Node;
main_<Node>( clp, argc, argv );
}
else if ( node == "serial" )
{
#ifdef KOKKOS_HAVE_SERIAL
typedef Kokkos::Compat::KokkosSerialWrapperNode Node;
main_<Node>( clp, argc, argv );
#else
throw std::runtime_error( "Serial node type is disabled" );
#endif
}
else if ( node == "openmp" )
{
#ifdef KOKKOS_HAVE_OPENMP
typedef Kokkos::Compat::KokkosOpenMPWrapperNode Node;
main_<Node>( clp, argc, argv );
#else
throw std::runtime_error( "OpenMP node type is disabled" );
#endif
}
else if ( node == "cuda" )
{
#ifdef KOKKOS_HAVE_CUDA
typedef Kokkos::Compat::KokkosCudaWrapperNode Node;
main_<Node>( clp, argc, argv );
#else
throw std::runtime_error( "CUDA node type is disabled" );
#endif
}
else
{
throw std::runtime_error( "Unrecognized node type" );
}
}
TEUCHOS_STANDARD_CATCH_STATEMENTS( verbose, std::cerr, success );
Kokkos::finalize();
return ( success ? EXIT_SUCCESS : EXIT_FAILURE );
}
<|endoftext|> |
<commit_before>///
/// @file pod_vector.hpp
///
/// Copyright (C) 2022 Kim Walisch, <kim.walisch@gmail.com>
///
/// This file is distributed under the BSD License. See the COPYING
/// file in the top level directory.
///
#ifndef POD_VECTOR_HPP
#define POD_VECTOR_HPP
#include "macros.hpp"
#include <algorithm>
#include <cassert>
#include <cstddef>
#include <type_traits>
#include <utility>
namespace primesieve {
/// pod_vector is a dynamically growing array.
/// It has the same API (though not complete) as std::vector but its
/// resize() method does not default initialize memory for built-in
/// integer types. It does however default initialize classes and
/// struct types if they have a constructor. It also prevents
/// bounds checks which is important for primesieve's performance, e.g.
/// the Fedora Linux distribution compiles with -D_GLIBCXX_ASSERTIONS
/// which enables std::vector bounds checks.
///
template <typename T>
class pod_vector
{
public:
static_assert(std::is_trivially_destructible<T>::value,
"pod_vector<T> only supports types with trivial destructors!");
using value_type = T;
pod_vector() noexcept = default;
pod_vector(std::size_t size)
{
resize(size);
}
~pod_vector()
{
delete [] array_;
}
/// Free all memory, the pod_vector
/// can be reused afterwards.
void free() noexcept
{
delete [] array_;
array_ = nullptr;
end_ = nullptr;
capacity_ = nullptr;
}
/// Reset the pod_vector, but do not free its
/// memory. Same as std::vector.clear().
void clear() noexcept
{
end_ = array_;
}
/// Copying is slow, we prevent it
pod_vector(const pod_vector&) = delete;
pod_vector& operator=(const pod_vector&) = delete;
/// Move constructor
pod_vector(pod_vector&& other) noexcept
{
std::swap(array_, other.array_);
std::swap(end_, other.end_);
std::swap(capacity_, other.capacity_);
}
/// Move assignment operator
pod_vector& operator=(pod_vector&& other) noexcept
{
if (this != &other)
{
std::swap(array_, other.array_);
std::swap(end_, other.end_);
std::swap(capacity_, other.capacity_);
}
return *this;
}
bool empty() const noexcept
{
return array_ == end_;
}
T& operator[] (std::size_t pos) noexcept
{
// For performance reasons primesieve is allowed to access
// memory with pos > size() but <= capacity().
assert(pos <= capacity());
return array_[pos];
}
T& operator[] (std::size_t pos) const noexcept
{
// For performance reasons primesieve is allowed to access
// memory with pos > size() but <= capacity().
assert(pos <= capacity());
return array_[pos];
}
T* data() noexcept
{
return array_;
}
T* data() const noexcept
{
return array_;
}
std::size_t size() const noexcept
{
assert(end_ >= array_);
return (std::size_t)(end_ - array_);
}
std::size_t capacity() const noexcept
{
assert(capacity_ >= array_);
return (std::size_t)(capacity_ - array_);
}
T* begin() noexcept
{
return array_;
}
T* begin() const noexcept
{
return array_;
}
T* end() noexcept
{
return end_;
}
T* end() const noexcept
{
return end_;
}
T& front() noexcept
{
return *array_;
}
T& front() const noexcept
{
return *array_;
}
T& back() noexcept
{
assert(end_ != nullptr);
return *(end_ - 1);
}
T& back() const noexcept
{
assert(end_ != nullptr);
return *(end_ - 1);
}
ALWAYS_INLINE void push_back(const T& value)
{
if_unlikely(end_ == capacity_)
reserve(std::max((std::size_t) 1, capacity() * 2));
*end_++ = value;
}
ALWAYS_INLINE void push_back(T&& value)
{
if_unlikely(end_ == capacity_)
reserve(std::max((std::size_t) 1, capacity() * 2));
*end_++ = value;
}
template <class... Args>
ALWAYS_INLINE void emplace_back(Args&&... args)
{
if_unlikely(end_ == capacity_)
reserve(std::max((std::size_t) 1, capacity() * 2));
*end_++ = T(std::forward<Args>(args)...);
}
void reserve(std::size_t n)
{
if (n > capacity())
{
T* old = array_;
std::size_t old_size = size();
std::size_t new_capacity = get_new_capacity<T>(n);
assert(new_capacity >= n);
assert(new_capacity > old_size);
// This default initializes memory of classes and
// structs with constructors. But it does not default
// initialize memory for POD types like int, long.
array_ = new T[new_capacity];
end_ = array_ + old_size;
capacity_ = array_ + new_capacity;
if (old)
{
std::copy_n(old, old_size, array_);
delete [] old;
}
}
}
/// Resize without default initializing memory.
/// If the pod_vector is not empty the current content
/// will be copied into the new array.
///
void resize(std::size_t n)
{
if (n == size())
return;
else if (n <= capacity())
{
assert(capacity() > 0);
// This will only be used for classes
// and structs with constructors.
if (n > size())
default_initialize_range(end_, array_ + n);
end_ = array_ + n;
}
else
{
T* old = array_;
std::size_t old_size = size();
std::size_t new_capacity = get_new_capacity<T>(n);
assert(new_capacity >= n);
assert(new_capacity > old_size);
// This default initializes memory of classes and
// structs with constructors. But it does not default
// initialize memory for POD types like int, long.
array_ = new T[new_capacity];
end_ = array_ + n;
capacity_ = array_ + new_capacity;
if (old)
{
std::copy_n(old, old_size, array_);
delete [] old;
}
}
}
private:
T* array_ = nullptr;
T* end_ = nullptr;
T* capacity_ = nullptr;
template <typename U>
ALWAYS_INLINE typename std::enable_if<std::is_trivial<U>::value>::type
default_initialize_range(U*, U*)
{ }
template <typename U>
ALWAYS_INLINE typename std::enable_if<!std::is_trivial<U>::value>::type
default_initialize_range(U* first, U* last)
{
std::fill(first, last, U());
}
template <typename U>
ALWAYS_INLINE typename std::enable_if<std::is_trivial<U>::value, std::size_t>::type
get_new_capacity(std::size_t size)
{
assert(size > 0);
// GCC & Clang's std::vector grow the capacity by at least
// 2x for every call to resize() with n > capacity(). We
// grow by at least 1.5x as we tend to accurately calculate
// the amount of memory we need upfront.
std::size_t new_capacity = (std::size_t)(capacity() * 1.5);
constexpr std::size_t min_alignment = sizeof(long) * 2;
constexpr std::size_t min_capacity = min_alignment / sizeof(U);
return std::max({min_capacity, size, new_capacity});
}
template <typename U>
ALWAYS_INLINE typename std::enable_if<!std::is_trivial<U>::value, std::size_t>::type
get_new_capacity(std::size_t size)
{
assert(size > 0);
// GCC & Clang's std::vector grow the capacity by at least
// 2x for every call to resize() with n > capacity(). We
// grow by at least 1.5x as we tend to accurately calculate
// the amount of memory we need upfront.
std::size_t new_capacity = (std::size_t)(capacity() * 1.5);
return std::max(size, new_capacity);
}
};
} // namespace
#endif
<commit_msg>Update to latest libprimesieve<commit_after>///
/// @file pod_vector.hpp
///
/// Copyright (C) 2022 Kim Walisch, <kim.walisch@gmail.com>
///
/// This file is distributed under the BSD License. See the COPYING
/// file in the top level directory.
///
#ifndef POD_VECTOR_HPP
#define POD_VECTOR_HPP
#include "macros.hpp"
#include <algorithm>
#include <cassert>
#include <cstddef>
#include <type_traits>
#include <utility>
namespace primesieve {
/// pod_vector is a dynamically growing array.
/// It has the same API (though not complete) as std::vector but its
/// resize() method does not default initialize memory for built-in
/// integer types. It does however default initialize classes and
/// struct types if they have a constructor. It also prevents
/// bounds checks which is important for primesieve's performance, e.g.
/// the Fedora Linux distribution compiles with -D_GLIBCXX_ASSERTIONS
/// which enables std::vector bounds checks.
///
template <typename T>
class pod_vector
{
public:
static_assert(std::is_trivially_destructible<T>::value,
"pod_vector<T> only supports types with trivial destructors!");
using value_type = T;
pod_vector() noexcept = default;
pod_vector(std::size_t size)
{
resize(size);
}
~pod_vector()
{
delete [] array_;
}
/// Free all memory, the pod_vector
/// can be reused afterwards.
void free() noexcept
{
delete [] array_;
array_ = nullptr;
end_ = nullptr;
capacity_ = nullptr;
}
/// Reset the pod_vector, but do not free its
/// memory. Same as std::vector.clear().
void clear() noexcept
{
end_ = array_;
}
/// Copying is slow, we prevent it
pod_vector(const pod_vector&) = delete;
pod_vector& operator=(const pod_vector&) = delete;
/// Move constructor
pod_vector(pod_vector&& other) noexcept
{
std::swap(array_, other.array_);
std::swap(end_, other.end_);
std::swap(capacity_, other.capacity_);
}
/// Move assignment operator
pod_vector& operator=(pod_vector&& other) noexcept
{
if (this != &other)
{
std::swap(array_, other.array_);
std::swap(end_, other.end_);
std::swap(capacity_, other.capacity_);
}
return *this;
}
bool empty() const noexcept
{
return array_ == end_;
}
T& operator[](std::size_t pos) noexcept
{
// For performance reasons primesieve is allowed to access
// memory with pos > size() but <= capacity().
assert(pos <= capacity());
return array_[pos];
}
T& operator[](std::size_t pos) const noexcept
{
// For performance reasons primesieve is allowed to access
// memory with pos > size() but <= capacity().
assert(pos <= capacity());
return array_[pos];
}
T* data() noexcept
{
return array_;
}
T* data() const noexcept
{
return array_;
}
std::size_t size() const noexcept
{
assert(end_ >= array_);
return (std::size_t)(end_ - array_);
}
std::size_t capacity() const noexcept
{
assert(capacity_ >= array_);
return (std::size_t)(capacity_ - array_);
}
T* begin() noexcept
{
return array_;
}
T* begin() const noexcept
{
return array_;
}
T* end() noexcept
{
return end_;
}
T* end() const noexcept
{
return end_;
}
T& front() noexcept
{
return *array_;
}
T& front() const noexcept
{
return *array_;
}
T& back() noexcept
{
assert(end_ != nullptr);
return *(end_ - 1);
}
T& back() const noexcept
{
assert(end_ != nullptr);
return *(end_ - 1);
}
ALWAYS_INLINE void push_back(const T& value)
{
if_unlikely(end_ == capacity_)
reserve_unchecked(std::max((std::size_t) 1, capacity() * 2));
*end_++ = value;
}
ALWAYS_INLINE void push_back(T&& value)
{
if_unlikely(end_ == capacity_)
reserve_unchecked(std::max((std::size_t) 1, capacity() * 2));
*end_++ = value;
}
template <class... Args>
ALWAYS_INLINE void emplace_back(Args&&... args)
{
if_unlikely(end_ == capacity_)
reserve_unchecked(std::max((std::size_t) 1, capacity() * 2));
*end_++ = T(std::forward<Args>(args)...);
}
void reserve(std::size_t n)
{
if (n > capacity())
reserve_unchecked(n);
}
/// Resize without default initializing memory.
/// If the pod_vector is not empty the current content
/// will be copied into the new array.
///
void resize(std::size_t n)
{
if (n > capacity())
reserve_unchecked(n);
else if (!std::is_trivial<T>::value && n > size())
{
// This will only be used for classes
// and structs with constructors.
assert(n <= capacity());
std::fill(end_, array_ + n, T());
}
end_ = array_ + n;
}
private:
T* array_ = nullptr;
T* end_ = nullptr;
T* capacity_ = nullptr;
void reserve_unchecked(std::size_t n)
{
assert(n > capacity());
std::size_t new_capacity = get_new_capacity<T>(n);
std::size_t old_size = size();
assert(new_capacity >= n);
assert(new_capacity > old_size);
// This default initializes memory of classes and
// structs with constructors. But it does not default
// initialize memory for POD types like int, long.
T* old = array_;
array_ = new T[new_capacity];
end_ = array_ + old_size;
capacity_ = array_ + new_capacity;
if (old)
{
std::copy_n(old, old_size, array_);
delete [] old;
}
}
template <typename U>
ALWAYS_INLINE typename std::enable_if<std::is_trivial<U>::value, std::size_t>::type
get_new_capacity(std::size_t size)
{
assert(size > 0);
// GCC & Clang's std::vector grow the capacity by at least
// 2x for every call to resize() with n > capacity(). We
// grow by at least 1.5x as we tend to accurately calculate
// the amount of memory we need upfront.
std::size_t new_capacity = (std::size_t)(capacity() * 1.5);
constexpr std::size_t min_alignment = sizeof(long) * 2;
constexpr std::size_t min_capacity = min_alignment / sizeof(U);
return std::max({min_capacity, size, new_capacity});
}
template <typename U>
ALWAYS_INLINE typename std::enable_if<!std::is_trivial<U>::value, std::size_t>::type
get_new_capacity(std::size_t size)
{
assert(size > 0);
// GCC & Clang's std::vector grow the capacity by at least
// 2x for every call to resize() with n > capacity(). We
// grow by at least 1.5x as we tend to accurately calculate
// the amount of memory we need upfront.
std::size_t new_capacity = (std::size_t)(capacity() * 1.5);
return std::max(size, new_capacity);
}
};
} // namespace
#endif
<|endoftext|> |
<commit_before>/*
* Copyright 2017 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "SkColorFilter.h"
#include "SkColorSpaceXformCanvas.h"
#include "SkColorSpaceXformer.h"
#include "SkGradientShader.h"
#include "SkImage_Base.h"
#include "SkImagePriv.h"
#include "SkMakeUnique.h"
#include "SkNoDrawCanvas.h"
#include "SkSurface.h"
class SkColorSpaceXformCanvas : public SkNoDrawCanvas {
public:
SkColorSpaceXformCanvas(SkCanvas* target, sk_sp<SkColorSpace> targetCS,
std::unique_ptr<SkColorSpaceXformer> xformer)
: SkNoDrawCanvas(SkIRect::MakeSize(target->getBaseLayerSize()))
, fTarget(target)
, fTargetCS(targetCS)
, fXformer(std::move(xformer))
{
// Set the matrix and clip to match |fTarget|. Otherwise, we'll answer queries for
// bounds/matrix differently than |fTarget| would.
SkCanvas::onClipRect(SkRect::Make(fTarget->getDeviceClipBounds()),
SkClipOp::kIntersect, kHard_ClipEdgeStyle);
SkCanvas::setMatrix(fTarget->getTotalMatrix());
}
SkImageInfo onImageInfo() const override {
return fTarget->imageInfo();
}
void onDrawPaint(const SkPaint& paint) override {
fTarget->drawPaint(fXformer->apply(paint));
}
void onDrawRect(const SkRect& rect, const SkPaint& paint) override {
fTarget->drawRect(rect, fXformer->apply(paint));
}
void onDrawOval(const SkRect& oval, const SkPaint& paint) override {
fTarget->drawOval(oval, fXformer->apply(paint));
}
void onDrawRRect(const SkRRect& rrect, const SkPaint& paint) override {
fTarget->drawRRect(rrect, fXformer->apply(paint));
}
void onDrawDRRect(const SkRRect& outer, const SkRRect& inner, const SkPaint& paint) override {
fTarget->drawDRRect(outer, inner, fXformer->apply(paint));
}
void onDrawPath(const SkPath& path, const SkPaint& paint) override {
fTarget->drawPath(path, fXformer->apply(paint));
}
void onDrawArc(const SkRect& oval, SkScalar start, SkScalar sweep, bool useCenter,
const SkPaint& paint) override {
fTarget->drawArc(oval, start, sweep, useCenter, fXformer->apply(paint));
}
void onDrawRegion(const SkRegion& region, const SkPaint& paint) override {
fTarget->drawRegion(region, fXformer->apply(paint));
}
void onDrawPatch(const SkPoint cubics[12], const SkColor colors[4], const SkPoint texs[4],
SkBlendMode mode, const SkPaint& paint) override {
SkColor xformed[4];
if (colors) {
fXformer->apply(xformed, colors, 4);
colors = xformed;
}
fTarget->drawPatch(cubics, colors, texs, mode, fXformer->apply(paint));
}
void onDrawPoints(PointMode mode, size_t count, const SkPoint* pts,
const SkPaint& paint) override {
fTarget->drawPoints(mode, count, pts, fXformer->apply(paint));
}
void onDrawVerticesObject(const SkVertices* vertices, SkBlendMode mode,
const SkPaint& paint) override {
sk_sp<SkVertices> copy;
if (vertices->hasColors()) {
int count = vertices->vertexCount();
SkSTArray<8, SkColor> xformed(count);
fXformer->apply(xformed.begin(), vertices->colors(), count);
copy = SkVertices::MakeCopy(vertices->mode(), count, vertices->positions(),
vertices->texCoords(), xformed.begin(),
vertices->indexCount(), vertices->indices());
vertices = copy.get();
}
fTarget->drawVertices(vertices, mode, fXformer->apply(paint));
}
void onDrawText(const void* ptr, size_t len,
SkScalar x, SkScalar y,
const SkPaint& paint) override {
fTarget->drawText(ptr, len, x, y, fXformer->apply(paint));
}
void onDrawPosText(const void* ptr, size_t len,
const SkPoint* xys,
const SkPaint& paint) override {
fTarget->drawPosText(ptr, len, xys, fXformer->apply(paint));
}
void onDrawPosTextH(const void* ptr, size_t len,
const SkScalar* xs, SkScalar y,
const SkPaint& paint) override {
fTarget->drawPosTextH(ptr, len, xs, y, fXformer->apply(paint));
}
void onDrawTextOnPath(const void* ptr, size_t len,
const SkPath& path, const SkMatrix* matrix,
const SkPaint& paint) override {
fTarget->drawTextOnPath(ptr, len, path, matrix, fXformer->apply(paint));
}
void onDrawTextRSXform(const void* ptr, size_t len,
const SkRSXform* xforms, const SkRect* cull,
const SkPaint& paint) override {
fTarget->drawTextRSXform(ptr, len, xforms, cull, fXformer->apply(paint));
}
void onDrawTextBlob(const SkTextBlob* blob,
SkScalar x, SkScalar y,
const SkPaint& paint) override {
fTarget->drawTextBlob(blob, x, y, fXformer->apply(paint));
}
void onDrawImage(const SkImage* img,
SkScalar l, SkScalar t,
const SkPaint* paint) override {
fTarget->drawImage(fXformer->apply(img).get(),
l, t,
fXformer->apply(paint));
}
void onDrawImageRect(const SkImage* img,
const SkRect* src, const SkRect& dst,
const SkPaint* paint, SrcRectConstraint constraint) override {
fTarget->drawImageRect(fXformer->apply(img).get(),
src ? *src : SkRect::MakeIWH(img->width(), img->height()), dst,
fXformer->apply(paint), constraint);
}
void onDrawImageNine(const SkImage* img,
const SkIRect& center, const SkRect& dst,
const SkPaint* paint) override {
fTarget->drawImageNine(fXformer->apply(img).get(),
center, dst,
fXformer->apply(paint));
}
void onDrawImageLattice(const SkImage* img,
const Lattice& lattice, const SkRect& dst,
const SkPaint* paint) override {
fTarget->drawImageLattice(fXformer->apply(img).get(),
lattice, dst,
fXformer->apply(paint));
}
void onDrawAtlas(const SkImage* atlas, const SkRSXform* xforms, const SkRect* tex,
const SkColor* colors, int count, SkBlendMode mode,
const SkRect* cull, const SkPaint* paint) override {
SkSTArray<8, SkColor> xformed;
if (colors) {
xformed.reset(count);
fXformer->apply(xformed.begin(), colors, count);
colors = xformed.begin();
}
fTarget->drawAtlas(fXformer->apply(atlas).get(), xforms, tex, colors, count, mode, cull,
fXformer->apply(paint));
}
void onDrawBitmap(const SkBitmap& bitmap,
SkScalar l, SkScalar t,
const SkPaint* paint) override {
if (this->skipXform(bitmap)) {
return fTarget->drawBitmap(bitmap, l, t, fXformer->apply(paint));
}
fTarget->drawImage(fXformer->apply(bitmap).get(), l, t, fXformer->apply(paint));
}
void onDrawBitmapRect(const SkBitmap& bitmap,
const SkRect* src, const SkRect& dst,
const SkPaint* paint, SrcRectConstraint constraint) override {
if (this->skipXform(bitmap)) {
return fTarget->drawBitmapRect(bitmap,
src ? *src : SkRect::MakeIWH(bitmap.width(), bitmap.height()), dst,
fXformer->apply(paint), constraint);
}
fTarget->drawImageRect(fXformer->apply(bitmap).get(),
src ? *src : SkRect::MakeIWH(bitmap.width(), bitmap.height()), dst,
fXformer->apply(paint), constraint);
}
void onDrawBitmapNine(const SkBitmap& bitmap,
const SkIRect& center, const SkRect& dst,
const SkPaint* paint) override {
if (this->skipXform(bitmap)) {
return fTarget->drawBitmapNine(bitmap, center, dst, fXformer->apply(paint));
}
fTarget->drawImageNine(fXformer->apply(bitmap).get(), center, dst, fXformer->apply(paint));
}
void onDrawBitmapLattice(const SkBitmap& bitmap,
const Lattice& lattice, const SkRect& dst,
const SkPaint* paint) override {
if (this->skipXform(bitmap)) {
return fTarget->drawBitmapLattice(bitmap, lattice, dst, fXformer->apply(paint));
}
fTarget->drawImageLattice(fXformer->apply(bitmap).get(), lattice, dst,
fXformer->apply(paint));
}
// TODO: May not be ideal to unfurl pictures.
void onDrawPicture(const SkPicture* pic,
const SkMatrix* matrix,
const SkPaint* paint) override {
SkCanvas::onDrawPicture(pic, matrix, fXformer->apply(paint));
}
void onDrawDrawable(SkDrawable* drawable, const SkMatrix* matrix) override {
SkCanvas::onDrawDrawable(drawable, matrix);
}
SaveLayerStrategy getSaveLayerStrategy(const SaveLayerRec& rec) override {
fTarget->saveLayer({
rec.fBounds,
fXformer->apply(rec.fPaint),
rec.fBackdrop, // TODO: this is an image filter
rec.fSaveLayerFlags,
});
return kNoLayer_SaveLayerStrategy;
}
// Everything from here on should be uninteresting strictly proxied state-change calls.
void willSave() override { fTarget->save(); }
void willRestore() override { fTarget->restore(); }
void didConcat (const SkMatrix& m) override { fTarget->concat (m); }
void didSetMatrix(const SkMatrix& m) override { fTarget->setMatrix(m); }
void onClipRect(const SkRect& clip, SkClipOp op, ClipEdgeStyle style) override {
SkCanvas::onClipRect(clip, op, style);
fTarget->clipRect(clip, op, style);
}
void onClipRRect(const SkRRect& clip, SkClipOp op, ClipEdgeStyle style) override {
SkCanvas::onClipRRect(clip, op, style);
fTarget->clipRRect(clip, op, style);
}
void onClipPath(const SkPath& clip, SkClipOp op, ClipEdgeStyle style) override {
SkCanvas::onClipPath(clip, op, style);
fTarget->clipPath(clip, op, style);
}
void onClipRegion(const SkRegion& clip, SkClipOp op) override {
SkCanvas::onClipRegion(clip, op);
fTarget->clipRegion(clip, op);
}
void onDrawAnnotation(const SkRect& rect, const char* key, SkData* val) override {
fTarget->drawAnnotation(rect, key, val);
}
sk_sp<SkSurface> onNewSurface(const SkImageInfo& info, const SkSurfaceProps& props) override {
return fTarget->makeSurface(info, &props);
}
SkISize getBaseLayerSize() const override { return fTarget->getBaseLayerSize(); }
SkRect onGetLocalClipBounds() const override { return fTarget->getLocalClipBounds(); }
SkIRect onGetDeviceClipBounds() const override { return fTarget->getDeviceClipBounds(); }
bool isClipEmpty() const override { return fTarget->isClipEmpty(); }
bool isClipRect() const override { return fTarget->isClipRect(); }
bool onPeekPixels(SkPixmap* pixmap) override { return fTarget->peekPixels(pixmap); }
bool onAccessTopLayerPixels(SkPixmap* pixmap) override {
SkImageInfo info;
size_t rowBytes;
SkIPoint* origin = nullptr;
void* addr = fTarget->accessTopLayerPixels(&info, &rowBytes, origin);
if (addr) {
*pixmap = SkPixmap(info, addr, rowBytes);
return true;
}
return false;
}
bool onGetProps(SkSurfaceProps* props) const override { return fTarget->getProps(props); }
void onFlush() override { return fTarget->flush(); }
private:
bool skipXform(const SkBitmap& bitmap) {
return (!bitmap.colorSpace() && fTargetCS->isSRGB()) ||
(SkColorSpace::Equals(bitmap.colorSpace(), fTargetCS.get())) ||
(kAlpha_8_SkColorType == bitmap.colorType());
}
SkCanvas* fTarget;
sk_sp<SkColorSpace> fTargetCS;
std::unique_ptr<SkColorSpaceXformer> fXformer;
};
std::unique_ptr<SkCanvas> SkCreateColorSpaceXformCanvas(SkCanvas* target,
sk_sp<SkColorSpace> targetCS) {
std::unique_ptr<SkColorSpaceXformer> xformer = SkColorSpaceXformer::Make(targetCS);
if (!xformer) {
return nullptr;
}
return skstd::make_unique<SkColorSpaceXformCanvas>(target, std::move(targetCS),
std::move(xformer));
}
<commit_msg>Override setDrawFilter() in SkColorSpaceXformCanvas<commit_after>/*
* Copyright 2017 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "SkColorFilter.h"
#include "SkColorSpaceXformCanvas.h"
#include "SkColorSpaceXformer.h"
#include "SkGradientShader.h"
#include "SkImage_Base.h"
#include "SkImagePriv.h"
#include "SkMakeUnique.h"
#include "SkNoDrawCanvas.h"
#include "SkSurface.h"
class SkColorSpaceXformCanvas : public SkNoDrawCanvas {
public:
SkColorSpaceXformCanvas(SkCanvas* target, sk_sp<SkColorSpace> targetCS,
std::unique_ptr<SkColorSpaceXformer> xformer)
: SkNoDrawCanvas(SkIRect::MakeSize(target->getBaseLayerSize()))
, fTarget(target)
, fTargetCS(targetCS)
, fXformer(std::move(xformer))
{
// Set the matrix and clip to match |fTarget|. Otherwise, we'll answer queries for
// bounds/matrix differently than |fTarget| would.
SkCanvas::onClipRect(SkRect::Make(fTarget->getDeviceClipBounds()),
SkClipOp::kIntersect, kHard_ClipEdgeStyle);
SkCanvas::setMatrix(fTarget->getTotalMatrix());
}
SkImageInfo onImageInfo() const override {
return fTarget->imageInfo();
}
void onDrawPaint(const SkPaint& paint) override {
fTarget->drawPaint(fXformer->apply(paint));
}
void onDrawRect(const SkRect& rect, const SkPaint& paint) override {
fTarget->drawRect(rect, fXformer->apply(paint));
}
void onDrawOval(const SkRect& oval, const SkPaint& paint) override {
fTarget->drawOval(oval, fXformer->apply(paint));
}
void onDrawRRect(const SkRRect& rrect, const SkPaint& paint) override {
fTarget->drawRRect(rrect, fXformer->apply(paint));
}
void onDrawDRRect(const SkRRect& outer, const SkRRect& inner, const SkPaint& paint) override {
fTarget->drawDRRect(outer, inner, fXformer->apply(paint));
}
void onDrawPath(const SkPath& path, const SkPaint& paint) override {
fTarget->drawPath(path, fXformer->apply(paint));
}
void onDrawArc(const SkRect& oval, SkScalar start, SkScalar sweep, bool useCenter,
const SkPaint& paint) override {
fTarget->drawArc(oval, start, sweep, useCenter, fXformer->apply(paint));
}
void onDrawRegion(const SkRegion& region, const SkPaint& paint) override {
fTarget->drawRegion(region, fXformer->apply(paint));
}
void onDrawPatch(const SkPoint cubics[12], const SkColor colors[4], const SkPoint texs[4],
SkBlendMode mode, const SkPaint& paint) override {
SkColor xformed[4];
if (colors) {
fXformer->apply(xformed, colors, 4);
colors = xformed;
}
fTarget->drawPatch(cubics, colors, texs, mode, fXformer->apply(paint));
}
void onDrawPoints(PointMode mode, size_t count, const SkPoint* pts,
const SkPaint& paint) override {
fTarget->drawPoints(mode, count, pts, fXformer->apply(paint));
}
void onDrawVerticesObject(const SkVertices* vertices, SkBlendMode mode,
const SkPaint& paint) override {
sk_sp<SkVertices> copy;
if (vertices->hasColors()) {
int count = vertices->vertexCount();
SkSTArray<8, SkColor> xformed(count);
fXformer->apply(xformed.begin(), vertices->colors(), count);
copy = SkVertices::MakeCopy(vertices->mode(), count, vertices->positions(),
vertices->texCoords(), xformed.begin(),
vertices->indexCount(), vertices->indices());
vertices = copy.get();
}
fTarget->drawVertices(vertices, mode, fXformer->apply(paint));
}
void onDrawText(const void* ptr, size_t len,
SkScalar x, SkScalar y,
const SkPaint& paint) override {
fTarget->drawText(ptr, len, x, y, fXformer->apply(paint));
}
void onDrawPosText(const void* ptr, size_t len,
const SkPoint* xys,
const SkPaint& paint) override {
fTarget->drawPosText(ptr, len, xys, fXformer->apply(paint));
}
void onDrawPosTextH(const void* ptr, size_t len,
const SkScalar* xs, SkScalar y,
const SkPaint& paint) override {
fTarget->drawPosTextH(ptr, len, xs, y, fXformer->apply(paint));
}
void onDrawTextOnPath(const void* ptr, size_t len,
const SkPath& path, const SkMatrix* matrix,
const SkPaint& paint) override {
fTarget->drawTextOnPath(ptr, len, path, matrix, fXformer->apply(paint));
}
void onDrawTextRSXform(const void* ptr, size_t len,
const SkRSXform* xforms, const SkRect* cull,
const SkPaint& paint) override {
fTarget->drawTextRSXform(ptr, len, xforms, cull, fXformer->apply(paint));
}
void onDrawTextBlob(const SkTextBlob* blob,
SkScalar x, SkScalar y,
const SkPaint& paint) override {
fTarget->drawTextBlob(blob, x, y, fXformer->apply(paint));
}
void onDrawImage(const SkImage* img,
SkScalar l, SkScalar t,
const SkPaint* paint) override {
fTarget->drawImage(fXformer->apply(img).get(),
l, t,
fXformer->apply(paint));
}
void onDrawImageRect(const SkImage* img,
const SkRect* src, const SkRect& dst,
const SkPaint* paint, SrcRectConstraint constraint) override {
fTarget->drawImageRect(fXformer->apply(img).get(),
src ? *src : SkRect::MakeIWH(img->width(), img->height()), dst,
fXformer->apply(paint), constraint);
}
void onDrawImageNine(const SkImage* img,
const SkIRect& center, const SkRect& dst,
const SkPaint* paint) override {
fTarget->drawImageNine(fXformer->apply(img).get(),
center, dst,
fXformer->apply(paint));
}
void onDrawImageLattice(const SkImage* img,
const Lattice& lattice, const SkRect& dst,
const SkPaint* paint) override {
fTarget->drawImageLattice(fXformer->apply(img).get(),
lattice, dst,
fXformer->apply(paint));
}
void onDrawAtlas(const SkImage* atlas, const SkRSXform* xforms, const SkRect* tex,
const SkColor* colors, int count, SkBlendMode mode,
const SkRect* cull, const SkPaint* paint) override {
SkSTArray<8, SkColor> xformed;
if (colors) {
xformed.reset(count);
fXformer->apply(xformed.begin(), colors, count);
colors = xformed.begin();
}
fTarget->drawAtlas(fXformer->apply(atlas).get(), xforms, tex, colors, count, mode, cull,
fXformer->apply(paint));
}
void onDrawBitmap(const SkBitmap& bitmap,
SkScalar l, SkScalar t,
const SkPaint* paint) override {
if (this->skipXform(bitmap)) {
return fTarget->drawBitmap(bitmap, l, t, fXformer->apply(paint));
}
fTarget->drawImage(fXformer->apply(bitmap).get(), l, t, fXformer->apply(paint));
}
void onDrawBitmapRect(const SkBitmap& bitmap,
const SkRect* src, const SkRect& dst,
const SkPaint* paint, SrcRectConstraint constraint) override {
if (this->skipXform(bitmap)) {
return fTarget->drawBitmapRect(bitmap,
src ? *src : SkRect::MakeIWH(bitmap.width(), bitmap.height()), dst,
fXformer->apply(paint), constraint);
}
fTarget->drawImageRect(fXformer->apply(bitmap).get(),
src ? *src : SkRect::MakeIWH(bitmap.width(), bitmap.height()), dst,
fXformer->apply(paint), constraint);
}
void onDrawBitmapNine(const SkBitmap& bitmap,
const SkIRect& center, const SkRect& dst,
const SkPaint* paint) override {
if (this->skipXform(bitmap)) {
return fTarget->drawBitmapNine(bitmap, center, dst, fXformer->apply(paint));
}
fTarget->drawImageNine(fXformer->apply(bitmap).get(), center, dst, fXformer->apply(paint));
}
void onDrawBitmapLattice(const SkBitmap& bitmap,
const Lattice& lattice, const SkRect& dst,
const SkPaint* paint) override {
if (this->skipXform(bitmap)) {
return fTarget->drawBitmapLattice(bitmap, lattice, dst, fXformer->apply(paint));
}
fTarget->drawImageLattice(fXformer->apply(bitmap).get(), lattice, dst,
fXformer->apply(paint));
}
// TODO: May not be ideal to unfurl pictures.
void onDrawPicture(const SkPicture* pic,
const SkMatrix* matrix,
const SkPaint* paint) override {
SkCanvas::onDrawPicture(pic, matrix, fXformer->apply(paint));
}
void onDrawDrawable(SkDrawable* drawable, const SkMatrix* matrix) override {
SkCanvas::onDrawDrawable(drawable, matrix);
}
SaveLayerStrategy getSaveLayerStrategy(const SaveLayerRec& rec) override {
fTarget->saveLayer({
rec.fBounds,
fXformer->apply(rec.fPaint),
rec.fBackdrop, // TODO: this is an image filter
rec.fSaveLayerFlags,
});
return kNoLayer_SaveLayerStrategy;
}
#ifdef SK_SUPPORT_LEGACY_DRAWFILTER
SkDrawFilter* setDrawFilter(SkDrawFilter* filter) override {
SkCanvas::setDrawFilter(filter);
return fTarget->setDrawFilter(filter);
}
#endif
// Everything from here on should be uninteresting strictly proxied state-change calls.
void willSave() override { fTarget->save(); }
void willRestore() override { fTarget->restore(); }
void didConcat (const SkMatrix& m) override { fTarget->concat (m); }
void didSetMatrix(const SkMatrix& m) override { fTarget->setMatrix(m); }
void onClipRect(const SkRect& clip, SkClipOp op, ClipEdgeStyle style) override {
SkCanvas::onClipRect(clip, op, style);
fTarget->clipRect(clip, op, style);
}
void onClipRRect(const SkRRect& clip, SkClipOp op, ClipEdgeStyle style) override {
SkCanvas::onClipRRect(clip, op, style);
fTarget->clipRRect(clip, op, style);
}
void onClipPath(const SkPath& clip, SkClipOp op, ClipEdgeStyle style) override {
SkCanvas::onClipPath(clip, op, style);
fTarget->clipPath(clip, op, style);
}
void onClipRegion(const SkRegion& clip, SkClipOp op) override {
SkCanvas::onClipRegion(clip, op);
fTarget->clipRegion(clip, op);
}
void onDrawAnnotation(const SkRect& rect, const char* key, SkData* val) override {
fTarget->drawAnnotation(rect, key, val);
}
sk_sp<SkSurface> onNewSurface(const SkImageInfo& info, const SkSurfaceProps& props) override {
return fTarget->makeSurface(info, &props);
}
SkISize getBaseLayerSize() const override { return fTarget->getBaseLayerSize(); }
SkRect onGetLocalClipBounds() const override { return fTarget->getLocalClipBounds(); }
SkIRect onGetDeviceClipBounds() const override { return fTarget->getDeviceClipBounds(); }
bool isClipEmpty() const override { return fTarget->isClipEmpty(); }
bool isClipRect() const override { return fTarget->isClipRect(); }
bool onPeekPixels(SkPixmap* pixmap) override { return fTarget->peekPixels(pixmap); }
bool onAccessTopLayerPixels(SkPixmap* pixmap) override {
SkImageInfo info;
size_t rowBytes;
SkIPoint* origin = nullptr;
void* addr = fTarget->accessTopLayerPixels(&info, &rowBytes, origin);
if (addr) {
*pixmap = SkPixmap(info, addr, rowBytes);
return true;
}
return false;
}
bool onGetProps(SkSurfaceProps* props) const override { return fTarget->getProps(props); }
void onFlush() override { return fTarget->flush(); }
private:
bool skipXform(const SkBitmap& bitmap) {
return (!bitmap.colorSpace() && fTargetCS->isSRGB()) ||
(SkColorSpace::Equals(bitmap.colorSpace(), fTargetCS.get())) ||
(kAlpha_8_SkColorType == bitmap.colorType());
}
SkCanvas* fTarget;
sk_sp<SkColorSpace> fTargetCS;
std::unique_ptr<SkColorSpaceXformer> fXformer;
};
std::unique_ptr<SkCanvas> SkCreateColorSpaceXformCanvas(SkCanvas* target,
sk_sp<SkColorSpace> targetCS) {
std::unique_ptr<SkColorSpaceXformer> xformer = SkColorSpaceXformer::Make(targetCS);
if (!xformer) {
return nullptr;
}
return skstd::make_unique<SkColorSpaceXformCanvas>(target, std::move(targetCS),
std::move(xformer));
}
<|endoftext|> |
<commit_before>/* Copyright 2019 Google LLC
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#include "jaxlib/rocm_gpu_kernel_helpers.h"
#include <stdexcept>
#include "absl/memory/memory.h"
#include "absl/strings/str_cat.h"
namespace jax {
absl::Status AsStatus(hipError_t error) {
if (error != hipSuccess) {
return absl::InternalError(
absl::StrCat("ROCm operation failed: ", hipGetErrorString(error)));
}
return absl::OkStatus();
}
absl::StatusOr<std::unique_ptr<void* []>> MakeBatchPointers(
hipStream_t stream, void* buffer, void* dev_ptrs, int batch,
int batch_elem_size) {
char* ptr = static_cast<char*>(buffer);
auto host_ptrs = absl::make_unique<void*[]>(batch);
for (int i = 0; i < batch; ++i) {
host_ptrs[i] = ptr;
ptr += batch_elem_size;
}
JAX_RETURN_IF_ERROR(
AsStatus(hipMemcpyAsync(dev_ptrs, host_ptrs.get(), sizeof(void*) * batch,
hipMemcpyHostToDevice, stream)));
return host_ptrs;
}
} // namespace jax
<commit_msg>fix custom_call_status for rocm<commit_after>/* Copyright 2019 Google LLC
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#include "jaxlib/rocm_gpu_kernel_helpers.h"
#include <stdexcept>
#include "absl/memory/memory.h"
#include "absl/strings/str_cat.h"
namespace jax {
absl::Status AsStatus(hipError_t error) {
if (error != hipSuccess) {
return absl::InternalError(
absl::StrCat("ROCm operation failed: ", hipGetErrorString(error)));
}
return absl::OkStatus();
}
absl::StatusOr<std::unique_ptr<void* []>> MakeBatchPointers(
hipStream_t stream, void* buffer, void* dev_ptrs, int batch,
int batch_elem_size) {
char* ptr = static_cast<char*>(buffer);
auto host_ptrs = absl::make_unique<void*[]>(batch);
for (int i = 0; i < batch; ++i) {
host_ptrs[i] = ptr;
ptr += batch_elem_size;
}
JAX_RETURN_IF_ERROR(
AsStatus(hipMemcpyAsync(dev_ptrs, host_ptrs.get(), sizeof(void*) * batch,
hipMemcpyHostToDevice, stream)));
return std::move(host_ptrs);
}
} // namespace jax
<|endoftext|> |
<commit_before>#include "CommonData.hpp"
#include "EventInputQueue.hpp"
#include "EventOutputQueue.hpp"
#include "IOLogWrapper.hpp"
#include "KeyToKey.hpp"
#include "KeyboardRepeat.hpp"
#include "VirtualKey.hpp"
namespace org_pqrs_Karabiner {
namespace RemapFunc {
void
KeyToKey::add(AddDataType datatype, AddValue newval) {
switch (datatype) {
case BRIDGE_DATATYPE_KEYCODE:
case BRIDGE_DATATYPE_CONSUMERKEYCODE:
case BRIDGE_DATATYPE_POINTINGBUTTON: {
switch (index_) {
case 0:
fromEvent_ = FromEvent(datatype, newval);
break;
default:
getCurrentToEvent().push_back(ToEvent(datatype, newval));
break;
}
++index_;
break;
}
case BRIDGE_DATATYPE_MODIFIERFLAG:
case BRIDGE_DATATYPE_MODIFIERFLAGS_END: {
switch (index_) {
case 0:
IOLOG_ERROR("Invalid KeyToKey::add\n");
break;
case 1: {
ModifierFlag modifierFlag(datatype, newval);
fromModifierFlags_.push_back(modifierFlag);
if (fromEvent_.getModifierFlag() != modifierFlag) {
pureFromModifierFlags_.push_back(modifierFlag);
}
break;
}
default:
if (!getCurrentToEvent().empty()) {
getCurrentToEvent().back().addModifierFlag(datatype, newval);
}
break;
}
break;
}
case BRIDGE_DATATYPE_OPTION: {
Option option(newval);
if (Option::NOREPEAT == option) {
isRepeatEnabled_ = false;
} else if (Option::KEYTOKEY_BEFORE_KEYDOWN == option) {
currentToEvent_ = CurrentToEvent::BEFOREKEYS;
} else if (Option::KEYTOKEY_AFTER_KEYUP == option) {
currentToEvent_ = CurrentToEvent::AFTERKEYS;
} else if (Option::USE_SEPARATOR == option ||
Option::SEPARATOR == option) {
// do nothing
} else {
IOLOG_ERROR("KeyToKey::add unknown option:%u\n", static_cast<unsigned int>(newval));
}
break;
}
case BRIDGE_DATATYPE_DELAYUNTILREPEAT: {
// Use 1ms if newval == 0 because Terminal.app cannot treat too rapid key repeat events.)
delayUntilRepeat_ = max(newval, 1);
break;
}
case BRIDGE_DATATYPE_KEYREPEAT: {
// Use 1ms if newval == 0 because Terminal.app cannot treat too rapid key repeat events.)
keyRepeat_ = max(newval, 1);
break;
}
default:
IOLOG_ERROR("KeyToKey::add invalid datatype:%u\n", static_cast<unsigned int>(datatype));
break;
}
}
void
KeyToKey::clearToKeys(void) {
if (index_ > 1) {
index_ = 1;
}
toKeys_.clear();
beforeKeys_.clear();
afterKeys_.clear();
currentToEvent_ = CurrentToEvent::TOKEYS;
}
bool
KeyToKey::remap(RemapParams& remapParams) {
if (remapParams.isremapped) return false;
if (!fromEvent_.changePressingState(remapParams.paramsBase,
FlagStatus::globalFlagStatus(),
fromModifierFlags_)) return false;
remapParams.isremapped = true;
// ------------------------------------------------------------
// handle EventType & Modifiers
// Let's consider the following setting.
// __KeyToKey__ KeyCode::SHIFT_R, ModifierFlag::SHIFT_R | ModifierFlag::NONE, KeyCode::A, ModifierFlag::SHIFT_R
// In this setting, we need decrease SHIFT_R only once.
// So, we use pureFromModifierFlags_.
//
// [before]
// fromEvent_ : KeyCode::SHIFT_R
// fromModifierFlags_ : ModifierFlag::SHIFT_R | ModifierFlag::NONE
//
// [after]
// fromEvent_ : KeyCode::SHIFT_R
// pureFromModifierFlags_ : ModifierFlag::NONE
//
// Note: we need to use pureFromModifierFlags_ after calling fromEvent_.changePressingState.
if (fromEvent_.isPressing()) {
FlagStatus::globalFlagStatus().decrease(fromEvent_.getModifierFlag());
ButtonStatus::decrease(fromEvent_.getPointingButton());
} else {
FlagStatus::globalFlagStatus().increase(fromEvent_.getModifierFlag());
ButtonStatus::increase(fromEvent_.getPointingButton());
}
// ----------------------------------------
// Handle beforeKeys_
if (fromEvent_.isPressing()) {
FlagStatus::globalFlagStatus().temporary_decrease(pureFromModifierFlags_);
for (size_t i = 0; i < beforeKeys_.size(); ++i) {
FlagStatus::globalFlagStatus().temporary_increase(beforeKeys_[i].getModifierFlags());
beforeKeys_[i].fire_downup();
FlagStatus::globalFlagStatus().temporary_decrease(beforeKeys_[i].getModifierFlags());
}
FlagStatus::globalFlagStatus().temporary_increase(pureFromModifierFlags_);
}
// ----------------------------------------
// Handle toKeys_
bool add_to_keyrepeat = true;
if (fromEvent_.isPressing() && !isRepeatEnabled_) {
add_to_keyrepeat = false;
}
switch (toKeys_.size()) {
case 0:
break;
case 1: {
EventType newEventType = fromEvent_.isPressing() ? EventType::DOWN : EventType::UP;
ModifierFlag toModifierFlag = toKeys_[0].getModifierFlag();
if (toModifierFlag == ModifierFlag::ZERO && !toKeys_[0].isEventLikeModifier()) {
// toKey
// Consider "Change Shift-P to Control-P".
//
// Case 1:
// Actual input:
// 1. shift down
// 2. p down
// 3. p up
// 4. p down
// 5. p up
// 6. shift up
//
// Excepted results:
// 1. shift down
// 2. shift up, control down, p down
// 3. p up
// 4. p down
// 5. p up
// 6. control up
//
// In this case, in step 3 and 5, we should not release control and do not restore shift.
// (== temporary_decrease shift and temporary_increase control in 2,3,4,5.)
//
FlagStatus::globalFlagStatus().temporary_decrease(pureFromModifierFlags_);
FlagStatus::globalFlagStatus().temporary_increase(toKeys_[0].getModifierFlags());
} else {
// toModifier or VirtualKey::isKeyLikeModifier
if (toModifierFlag != ModifierFlag::ZERO) {
newEventType = EventType::MODIFY;
}
if (fromEvent_.isPressing()) {
FlagStatus::globalFlagStatus().increase(toModifierFlag, toKeys_[0].getModifierFlags());
FlagStatus::globalFlagStatus().decrease(pureFromModifierFlags_);
} else {
FlagStatus::globalFlagStatus().decrease(toModifierFlag, toKeys_[0].getModifierFlags());
FlagStatus::globalFlagStatus().increase(pureFromModifierFlags_);
}
}
toKeys_[0].fire(newEventType, FlagStatus::globalFlagStatus().makeFlags(),
add_to_keyrepeat, getDelayUntilRepeat(), getKeyRepeat());
if (!add_to_keyrepeat) {
KeyboardRepeat::cancel();
}
break;
}
default:
ToEvent& lastToEvent = toKeys_[toKeys_.size() - 1];
ModifierFlag lastToEventModifierFlag = lastToEvent.getModifierFlag();
bool isLastToEventModifierKey = (lastToEventModifierFlag != ModifierFlag::ZERO);
bool isLastToEventLikeModifier = lastToEvent.isEventLikeModifier();
if (fromEvent_.isPressing()) {
KeyboardRepeat::cancel();
FlagStatus::globalFlagStatus().temporary_decrease(pureFromModifierFlags_);
size_t size = toKeys_.size();
// If the last key is modifier, we give it special treatment.
// - Don't fire key repeat.
// - Synchronous the key press status and the last modifier status.
if (isLastToEventModifierKey || isLastToEventLikeModifier) {
--size;
}
for (size_t i = 0; i < size; ++i) {
FlagStatus::globalFlagStatus().temporary_increase(toKeys_[i].getModifierFlags());
toKeys_[i].fire_downup(true);
FlagStatus::globalFlagStatus().temporary_decrease(toKeys_[i].getModifierFlags());
}
if (isLastToEventModifierKey || isLastToEventLikeModifier) {
// restore temporary flag.
FlagStatus::globalFlagStatus().temporary_increase(pureFromModifierFlags_);
FlagStatus::globalFlagStatus().increase(lastToEventModifierFlag, lastToEvent.getModifierFlags());
FlagStatus::globalFlagStatus().decrease(pureFromModifierFlags_);
if (isLastToEventLikeModifier) {
// Don't call EventOutputQueue::FireModifiers::fire here.
//
// Intentionally VK_LAZY_* stop sending MODIFY events.
// EventOutputQueue::FireModifiers::fire destroys this behavior.
lastToEvent.fire(EventType::DOWN, FlagStatus::globalFlagStatus().makeFlags(), false);
} else {
EventOutputQueue::FireModifiers::fire();
}
}
if (isLastToEventModifierKey || isLastToEventLikeModifier) {
KeyboardRepeat::cancel();
} else {
if (isRepeatEnabled_) {
keyboardRepeatID_ = KeyboardRepeat::primitive_start(getDelayUntilRepeat(), getKeyRepeat());
} else {
keyboardRepeatID_ = -1;
}
}
} else {
if (isLastToEventModifierKey || isLastToEventLikeModifier) {
// For Lazy-Modifiers (KeyCode::VK_LAZY_*),
// we need to handle these keys before restoring pureFromModifierFlags_, lastKeyFlags and lastKeyModifierFlag.
// The unnecessary modifier events occur unless we do it.
if (isLastToEventLikeModifier) {
lastToEvent.fire(EventType::UP, FlagStatus::globalFlagStatus().makeFlags(), false);
}
FlagStatus::globalFlagStatus().decrease(lastToEventModifierFlag, lastToEvent.getModifierFlags());
FlagStatus::globalFlagStatus().increase(pureFromModifierFlags_);
EventOutputQueue::FireModifiers::fire();
} else {
if (KeyboardRepeat::getID() == keyboardRepeatID_) {
KeyboardRepeat::cancel();
}
}
}
break;
}
// ----------------------------------------
// Handle afterKeys_
if (!fromEvent_.isPressing()) {
// We need to keep temporary flags for "general.lazy_modifiers_with_mouse_event" when afterKeys_ is empty.
if (afterKeys_.size() > 0) {
// clear temporary flags.
FlagStatus::globalFlagStatus().globalFlagStatus().set();
FlagStatus::globalFlagStatus().temporary_decrease(pureFromModifierFlags_);
for (size_t i = 0; i < afterKeys_.size(); ++i) {
FlagStatus::globalFlagStatus().temporary_increase(afterKeys_[i].getModifierFlags());
afterKeys_[i].fire_downup();
FlagStatus::globalFlagStatus().temporary_decrease(afterKeys_[i].getModifierFlags());
}
FlagStatus::globalFlagStatus().temporary_increase(pureFromModifierFlags_);
}
}
return true;
}
bool
KeyToKey::call_remap_with_VK_PSEUDO_KEY(EventType eventType) {
bool result = false;
// ----------------------------------------
if (eventType == EventType::DOWN) {
FlagStatus::globalFlagStatus().lazy_enable();
} else {
FlagStatus::globalFlagStatus().lazy_disable_if_off();
}
// ----------------------------------------
Params_KeyboardEventCallBack params(eventType,
FlagStatus::globalFlagStatus().makeFlags(),
KeyCode::VK_PSEUDO_KEY,
CommonData::getcurrent_keyboardType(),
false);
RemapParams rp(params);
result = remap(rp);
return result;
}
int
KeyToKey::getDelayUntilRepeat(void) {
if (delayUntilRepeat_ >= 0) {
return delayUntilRepeat_;
} else {
// If all ToEvent is consumer, use repeat.consumer_initial_wait.
for (size_t i = 0; i < toKeys_.size(); ++i) {
if (toKeys_[i].getType() != ToEvent::Type::CONSUMER_KEY) {
return Config::get_repeat_initial_wait();
}
}
return Config::get_repeat_consumer_initial_wait();
}
}
int
KeyToKey::getKeyRepeat(void) {
if (keyRepeat_ >= 0) {
return keyRepeat_;
} else {
// If all ToEvent is consumer, use repeat.consumer_wait.
for (size_t i = 0; i < toKeys_.size(); ++i) {
if (toKeys_[i].getType() != ToEvent::Type::CONSUMER_KEY) {
return Config::get_repeat_wait();
}
}
return Config::get_repeat_wait();
}
}
}
}
<commit_msg>improved ModifierFlag manipulation when key up<commit_after>#include "CommonData.hpp"
#include "EventInputQueue.hpp"
#include "EventOutputQueue.hpp"
#include "IOLogWrapper.hpp"
#include "KeyToKey.hpp"
#include "KeyboardRepeat.hpp"
#include "VirtualKey.hpp"
namespace org_pqrs_Karabiner {
namespace RemapFunc {
void
KeyToKey::add(AddDataType datatype, AddValue newval) {
switch (datatype) {
case BRIDGE_DATATYPE_KEYCODE:
case BRIDGE_DATATYPE_CONSUMERKEYCODE:
case BRIDGE_DATATYPE_POINTINGBUTTON: {
switch (index_) {
case 0:
fromEvent_ = FromEvent(datatype, newval);
break;
default:
getCurrentToEvent().push_back(ToEvent(datatype, newval));
break;
}
++index_;
break;
}
case BRIDGE_DATATYPE_MODIFIERFLAG:
case BRIDGE_DATATYPE_MODIFIERFLAGS_END: {
switch (index_) {
case 0:
IOLOG_ERROR("Invalid KeyToKey::add\n");
break;
case 1: {
ModifierFlag modifierFlag(datatype, newval);
fromModifierFlags_.push_back(modifierFlag);
if (fromEvent_.getModifierFlag() != modifierFlag) {
pureFromModifierFlags_.push_back(modifierFlag);
}
break;
}
default:
if (!getCurrentToEvent().empty()) {
getCurrentToEvent().back().addModifierFlag(datatype, newval);
}
break;
}
break;
}
case BRIDGE_DATATYPE_OPTION: {
Option option(newval);
if (Option::NOREPEAT == option) {
isRepeatEnabled_ = false;
} else if (Option::KEYTOKEY_BEFORE_KEYDOWN == option) {
currentToEvent_ = CurrentToEvent::BEFOREKEYS;
} else if (Option::KEYTOKEY_AFTER_KEYUP == option) {
currentToEvent_ = CurrentToEvent::AFTERKEYS;
} else if (Option::USE_SEPARATOR == option ||
Option::SEPARATOR == option) {
// do nothing
} else {
IOLOG_ERROR("KeyToKey::add unknown option:%u\n", static_cast<unsigned int>(newval));
}
break;
}
case BRIDGE_DATATYPE_DELAYUNTILREPEAT: {
// Use 1ms if newval == 0 because Terminal.app cannot treat too rapid key repeat events.)
delayUntilRepeat_ = max(newval, 1);
break;
}
case BRIDGE_DATATYPE_KEYREPEAT: {
// Use 1ms if newval == 0 because Terminal.app cannot treat too rapid key repeat events.)
keyRepeat_ = max(newval, 1);
break;
}
default:
IOLOG_ERROR("KeyToKey::add invalid datatype:%u\n", static_cast<unsigned int>(datatype));
break;
}
}
void
KeyToKey::clearToKeys(void) {
if (index_ > 1) {
index_ = 1;
}
toKeys_.clear();
beforeKeys_.clear();
afterKeys_.clear();
currentToEvent_ = CurrentToEvent::TOKEYS;
}
bool
KeyToKey::remap(RemapParams& remapParams) {
if (remapParams.isremapped) return false;
if (!fromEvent_.changePressingState(remapParams.paramsBase,
FlagStatus::globalFlagStatus(),
fromModifierFlags_)) return false;
remapParams.isremapped = true;
// ------------------------------------------------------------
// handle EventType & Modifiers
// Let's consider the following setting.
// __KeyToKey__ KeyCode::SHIFT_R, ModifierFlag::SHIFT_R | ModifierFlag::NONE, KeyCode::A, ModifierFlag::SHIFT_R
// In this setting, we need decrease SHIFT_R only once.
// So, we use pureFromModifierFlags_.
//
// [before]
// fromEvent_ : KeyCode::SHIFT_R
// fromModifierFlags_ : ModifierFlag::SHIFT_R | ModifierFlag::NONE
//
// [after]
// fromEvent_ : KeyCode::SHIFT_R
// pureFromModifierFlags_ : ModifierFlag::NONE
//
// Note: we need to use pureFromModifierFlags_ after calling fromEvent_.changePressingState.
if (fromEvent_.isPressing()) {
FlagStatus::globalFlagStatus().decrease(fromEvent_.getModifierFlag());
ButtonStatus::decrease(fromEvent_.getPointingButton());
} else {
FlagStatus::globalFlagStatus().increase(fromEvent_.getModifierFlag());
ButtonStatus::increase(fromEvent_.getPointingButton());
}
// ----------------------------------------
// Handle beforeKeys_
if (fromEvent_.isPressing()) {
FlagStatus::globalFlagStatus().temporary_decrease(pureFromModifierFlags_);
for (size_t i = 0; i < beforeKeys_.size(); ++i) {
FlagStatus::globalFlagStatus().temporary_increase(beforeKeys_[i].getModifierFlags());
beforeKeys_[i].fire_downup();
FlagStatus::globalFlagStatus().temporary_decrease(beforeKeys_[i].getModifierFlags());
}
FlagStatus::globalFlagStatus().temporary_increase(pureFromModifierFlags_);
}
// ----------------------------------------
// Handle toKeys_
bool add_to_keyrepeat = true;
if (fromEvent_.isPressing() && !isRepeatEnabled_) {
add_to_keyrepeat = false;
}
switch (toKeys_.size()) {
case 0:
break;
case 1: {
EventType newEventType = fromEvent_.isPressing() ? EventType::DOWN : EventType::UP;
ModifierFlag toModifierFlag = toKeys_[0].getModifierFlag();
if (toModifierFlag == ModifierFlag::ZERO && !toKeys_[0].isEventLikeModifier()) {
// toKey
// Consider these rules:
//
// * Change Shift-P to Control-P
// * Change Shift-N to Control-N
//
// Case 1:
// Actual input:
// 1. shift down
// 2. p down
// 3. p up
// 4. n down
// 5. n up
// 6. shift up
//
// Desirable results:
// 1. shift down
// 2. shift up, control down, p down
// 3. p up
// 4. n down
// 5. n up
// 6. control up
//
// *** ModifierFlag manipulation when key up ***
// In this case, in step 3 and 5, we should increase control and decrease shift.
// (== temporary_decrease shift and temporary_increase control in 2,3,4,5.)
//
//
// Case 2:
// Actual input:
// 1. shift down
// 2. p down
// 3. command down
// 4. p up
// 5. shift up
// 6. command up
//
// Desirable results:
// 1. shift down
// 2. shift up, control down, p down
// 3. control up, command down, shift down (== shift-command)
// 4. p up
// 5. shift up
// 6. command up
//
// *** ModifierFlag manipulation when key up ***
// In this case, in step 4, we should not increase control and not decrease shift.
// (== Do not temporary_decrease shift and temporary_increase control in 4.)
//
//
// Case 3:
// Actual input:
// 1. shift down
// 2. p down
// 3. shift up
// 4. p up
//
// Desirable results:
// 1. shift down
// 2. shift up, control down, p down
// 3. control up
// 4. p up
//
// *** ModifierFlag manipulation when key up ***
// In this case, in step 4, we should not increase control and not decrease shift.
// (== Do not temporary_decrease shift and temporary_increase control in 4.)
//
//
// *** Summary of ModifierFlag manipulation ***
//
// If the last sent modifierflag contains toflags, we should keep flags.
// (temporary_decrease pureFromModifierFlags_ and temporary_increase toflags)
//
// Otherwise, we should not manipulate modifiers.
bool needToManipulateModifiers = false;
if (fromEvent_.isPressing()) {
needToManipulateModifiers = true;
} else {
Flags toFlags(toKeys_[0].getModifierFlags());
if ((EventOutputQueue::FireModifiers::getLastFlags() & toFlags) == toFlags) {
needToManipulateModifiers = true;
}
}
if (needToManipulateModifiers) {
FlagStatus::globalFlagStatus().temporary_decrease(pureFromModifierFlags_);
FlagStatus::globalFlagStatus().temporary_increase(toKeys_[0].getModifierFlags());
}
} else {
// toModifier or VirtualKey::isKeyLikeModifier
if (toModifierFlag != ModifierFlag::ZERO) {
newEventType = EventType::MODIFY;
}
if (fromEvent_.isPressing()) {
FlagStatus::globalFlagStatus().increase(toModifierFlag, toKeys_[0].getModifierFlags());
FlagStatus::globalFlagStatus().decrease(pureFromModifierFlags_);
} else {
FlagStatus::globalFlagStatus().decrease(toModifierFlag, toKeys_[0].getModifierFlags());
FlagStatus::globalFlagStatus().increase(pureFromModifierFlags_);
}
}
toKeys_[0].fire(newEventType, FlagStatus::globalFlagStatus().makeFlags(),
add_to_keyrepeat, getDelayUntilRepeat(), getKeyRepeat());
if (!add_to_keyrepeat) {
KeyboardRepeat::cancel();
}
break;
}
default:
ToEvent& lastToEvent = toKeys_[toKeys_.size() - 1];
ModifierFlag lastToEventModifierFlag = lastToEvent.getModifierFlag();
bool isLastToEventModifierKey = (lastToEventModifierFlag != ModifierFlag::ZERO);
bool isLastToEventLikeModifier = lastToEvent.isEventLikeModifier();
if (fromEvent_.isPressing()) {
KeyboardRepeat::cancel();
FlagStatus::globalFlagStatus().temporary_decrease(pureFromModifierFlags_);
size_t size = toKeys_.size();
// If the last key is modifier, we give it special treatment.
// - Don't fire key repeat.
// - Synchronous the key press status and the last modifier status.
if (isLastToEventModifierKey || isLastToEventLikeModifier) {
--size;
}
for (size_t i = 0; i < size; ++i) {
FlagStatus::globalFlagStatus().temporary_increase(toKeys_[i].getModifierFlags());
toKeys_[i].fire_downup(true);
FlagStatus::globalFlagStatus().temporary_decrease(toKeys_[i].getModifierFlags());
}
if (isLastToEventModifierKey || isLastToEventLikeModifier) {
// restore temporary flag.
FlagStatus::globalFlagStatus().temporary_increase(pureFromModifierFlags_);
FlagStatus::globalFlagStatus().increase(lastToEventModifierFlag, lastToEvent.getModifierFlags());
FlagStatus::globalFlagStatus().decrease(pureFromModifierFlags_);
if (isLastToEventLikeModifier) {
// Don't call EventOutputQueue::FireModifiers::fire here.
//
// Intentionally VK_LAZY_* stop sending MODIFY events.
// EventOutputQueue::FireModifiers::fire destroys this behavior.
lastToEvent.fire(EventType::DOWN, FlagStatus::globalFlagStatus().makeFlags(), false);
} else {
EventOutputQueue::FireModifiers::fire();
}
}
if (isLastToEventModifierKey || isLastToEventLikeModifier) {
KeyboardRepeat::cancel();
} else {
if (isRepeatEnabled_) {
keyboardRepeatID_ = KeyboardRepeat::primitive_start(getDelayUntilRepeat(), getKeyRepeat());
} else {
keyboardRepeatID_ = -1;
}
}
} else {
if (isLastToEventModifierKey || isLastToEventLikeModifier) {
// For Lazy-Modifiers (KeyCode::VK_LAZY_*),
// we need to handle these keys before restoring pureFromModifierFlags_, lastKeyFlags and lastKeyModifierFlag.
// The unnecessary modifier events occur unless we do it.
if (isLastToEventLikeModifier) {
lastToEvent.fire(EventType::UP, FlagStatus::globalFlagStatus().makeFlags(), false);
}
FlagStatus::globalFlagStatus().decrease(lastToEventModifierFlag, lastToEvent.getModifierFlags());
FlagStatus::globalFlagStatus().increase(pureFromModifierFlags_);
EventOutputQueue::FireModifiers::fire();
} else {
if (KeyboardRepeat::getID() == keyboardRepeatID_) {
KeyboardRepeat::cancel();
}
}
}
break;
}
// ----------------------------------------
// Handle afterKeys_
if (!fromEvent_.isPressing()) {
// We need to keep temporary flags for "general.lazy_modifiers_with_mouse_event" when afterKeys_ is empty.
if (afterKeys_.size() > 0) {
// clear temporary flags.
FlagStatus::globalFlagStatus().globalFlagStatus().set();
FlagStatus::globalFlagStatus().temporary_decrease(pureFromModifierFlags_);
for (size_t i = 0; i < afterKeys_.size(); ++i) {
FlagStatus::globalFlagStatus().temporary_increase(afterKeys_[i].getModifierFlags());
afterKeys_[i].fire_downup();
FlagStatus::globalFlagStatus().temporary_decrease(afterKeys_[i].getModifierFlags());
}
FlagStatus::globalFlagStatus().temporary_increase(pureFromModifierFlags_);
}
}
return true;
}
bool
KeyToKey::call_remap_with_VK_PSEUDO_KEY(EventType eventType) {
bool result = false;
// ----------------------------------------
if (eventType == EventType::DOWN) {
FlagStatus::globalFlagStatus().lazy_enable();
} else {
FlagStatus::globalFlagStatus().lazy_disable_if_off();
}
// ----------------------------------------
Params_KeyboardEventCallBack params(eventType,
FlagStatus::globalFlagStatus().makeFlags(),
KeyCode::VK_PSEUDO_KEY,
CommonData::getcurrent_keyboardType(),
false);
RemapParams rp(params);
result = remap(rp);
return result;
}
int
KeyToKey::getDelayUntilRepeat(void) {
if (delayUntilRepeat_ >= 0) {
return delayUntilRepeat_;
} else {
// If all ToEvent is consumer, use repeat.consumer_initial_wait.
for (size_t i = 0; i < toKeys_.size(); ++i) {
if (toKeys_[i].getType() != ToEvent::Type::CONSUMER_KEY) {
return Config::get_repeat_initial_wait();
}
}
return Config::get_repeat_consumer_initial_wait();
}
}
int
KeyToKey::getKeyRepeat(void) {
if (keyRepeat_ >= 0) {
return keyRepeat_;
} else {
// If all ToEvent is consumer, use repeat.consumer_wait.
for (size_t i = 0; i < toKeys_.size(); ++i) {
if (toKeys_[i].getType() != ToEvent::Type::CONSUMER_KEY) {
return Config::get_repeat_wait();
}
}
return Config::get_repeat_wait();
}
}
}
}
<|endoftext|> |
<commit_before>#include <SDL2/SDL.h>
#include <SDL2/SDL_image.h>
#include <iostream>
#include <fstream>
#include <vector>
#include <float.h>
#include <math.h>
#include <glm/glm.hpp>
using namespace std;
#define WIDTH 500
#define HEIGHT 500
struct Ray
{
glm::vec3 origin;
glm::vec3 direction;
};
struct Sphere
{
glm::vec3 center;
float radius;
glm::vec3 color;
glm::vec3 hitPoint;
glm::vec3 hitNormal;
};
struct Plane
{
glm::vec3 normal;
glm::vec3 p0;
glm::vec3 color;
glm::vec3 hitPoint;
glm::vec3 hitNormal;
};
// TODO(ralntdir): Check if this type of light is correct
struct Light
{
glm::vec3 position;
glm::vec3 color;
};
SDL_Window* window = NULL;
SDL_Renderer* renderer = NULL;
SDL_Texture* texture = NULL;
glm::vec3 color = {255.0, 0.0, 0.0};
glm::vec3 black = {0.0, 0.0, 0.0};
void printV3(glm::vec3 vector)
{
cout << vector.x << ", " << vector.y << ", " << vector.z << endl;
}
bool init()
{
bool success = true;
if (SDL_Init(SDL_INIT_VIDEO) < 0)
{
cout << "Error initializing SDL: " << SDL_GetError() << endl;
success = false;
}
else
{
window = SDL_CreateWindow("Devember", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, WIDTH, HEIGHT, SDL_WINDOW_SHOWN);
if (window == NULL)
{
cout << "Problem creating the window: " << SDL_GetError() << endl;
success = false;
}
else
{
renderer = SDL_CreateRenderer(window, -1, 0);
if (renderer == NULL)
{
cout << "Problem creating the renderer: " << SDL_GetError() << endl;
}
else
{
if (IMG_Init(0) < 0)
{
cout << "Problem loading image lib: " << IMG_GetError() << endl;
success = false;
}
else
{
SDL_SetRenderDrawColor(renderer, 0, 255, 255, 255);
SDL_RenderClear(renderer);
SDL_RenderPresent(renderer);
}
}
}
}
return success;
}
void close()
{
SDL_DestroyTexture(texture);
SDL_DestroyRenderer(renderer);
SDL_DestroyWindow(window);
window = NULL;
IMG_Quit();
SDL_Quit();
}
bool intersectSphere(glm::vec3 center, float radius, Ray ray, glm::vec3 *hitPoint, glm::vec3 *hitNormal)
{
// first version for an intersect method
// we just need the hit point for the intersection
bool success;
glm::vec3 originCenter = ray.origin - center;
float a = glm::dot(ray.direction, ray.direction);
//cout << a << endl;
float b = 2 * glm::dot(ray.direction, originCenter);
//cout << b << endl;
float c = glm::dot(originCenter, originCenter) -
(radius * radius);
//cout << c << endl;
float discriminant = b * b - 4 * a * c;
//cout << discriminant << endl;
// If the discriminant is less than cero, we have complex roots
if (discriminant < 0)
{
success = false;
}
else
{
float t, t1, t2;
t1 = (-b + sqrt(discriminant)) / (2 * a);
t2 = (-b - sqrt(discriminant)) / (2 * a);
//cout << "t1: " << t1 << ", t2: " << t2 << endl;
// If both roots are negative -> no solution
if ((t1 < 0) && (t2 < 0))
{
success = false;
}
// Otherwise, we have solution. Which one?
else
{
success = true;
// Refactor this
if ((t1 > 0) && (t2 < 0))
{
t = t1;
}
else if ((t1 < 0) && (t2 > 0))
{
t = t2;
}
else if (t1 <= t2)
{
t = t1;
}
else if (t1 >= t2)
{
t = t2;
}
//*hitPoint = ray.origin + ray.direction * t;
*hitPoint = ray.origin + ray.direction * (t - 0.001f);
*hitNormal = glm::normalize(*hitPoint - center);
}
}
return success;
}
bool intersectPlane(glm::vec3 p0, glm::vec3 normal, Ray ray, glm::vec3 *hitPoint, glm::vec3 *hitNormal)
{
// t = (p_0 - rayOrigin).normal / rayDirection.n
bool success;
float denom = glm::dot(ray.direction, normal);
if (denom > 1e-6)
{
glm::vec3 p0rayOrigin = p0 - ray.origin;
float t = glm::dot(p0rayOrigin, normal) / denom;
*hitPoint = ray.origin + ray.direction * (t - 0.001f);
// normal for a point in the plane is the normal of the plane...? I think so.
*hitNormal = normal;
if (t >= 0)
{
success = true;
}
else
{
success = false;
}
}
return success;
}
void render()
{
// Creates an image using the ray tracing method.
// The first prototype will have only spheres and flat shading.
// Then I will add diffuse shading (lights) and after that
// shadows.
// TODO(ralntdir): I need to define the camera and the plane
// I'm projecting the scene on!!!
// NOTE(ralntdir): For the moment, the camera is at (0, 0, 0) and pointing
// to -Z and the plane is an XY plane at Z=-1;
// NOTE(ralntdir): I'm working with a right handed one coordinate
// system
vector<Sphere> sceneSpheres;
vector<Plane> scenePlanes;
glm::vec3 eyePosition = {0.0f, 0.0f, 0.0f};
glm::vec3 ambient = {25.5f, 25.5f, 25.5f};
Light testLight = {};
testLight.position = {0.0f, 30.0f, -10.0f};
testLight.color = {255.0f, 255.0f, 255.0f};
glm::vec3 image[WIDTH][HEIGHT] = {};
// prepare the scene
Sphere testSphere = {};
testSphere.center = {0.0f, -4.0f, -10.0f};
testSphere.radius = 3.0f;
testSphere.color = {0.0f, 0.0f, 255.0f};
sceneSpheres.push_back(testSphere);
testSphere.center = {1.0f, 1.5f, -10.0f};
testSphere.radius = 2.0f;
testSphere.color = {0.0f, 255.0f, 0.0f};
sceneSpheres.push_back(testSphere);
/*testSphere.center = {0.0f, 5.0f, -7.0f};
testSphere.radius = 2.0f;
testSphere.color = {0.0f, 255.0f, 0.0f};
sceneSpheres.push_back(testSphere);*/
// In degrees
float fov = 80.0f;
float aspectRatio = (float)WIDTH / (float)HEIGHT;
// trace rays
for (int y = 0; y < HEIGHT; y++)
{
for (int x = 0; x < WIDTH; x++)
{
// create the ray based in eye position, x and y
Ray ray;
ray.origin = eyePosition;
float pX = (2 * ((x + 0.5) / WIDTH) - 1) * tan(fov / 2 * M_PI / 180) * aspectRatio;
float pY = (1 - 2 * ((y + 0.5) / HEIGHT)) * tan(fov / 2 * M_PI / 180);
// As the origin is (0, 0, 0), I don't need to do the subtraction
ray.direction = {pX, pY, -1.0f};
ray.direction = glm::normalize(ray.direction);
//printV3(ray.direction);
//glm::vec3 hitPoint;
//glm::vec3 hitNormal;
float minDistanceSpheres = FLT_MAX;
float minDistancePlanes = FLT_MAX;
Sphere *closerObjectSpheres = NULL;
Plane *closerObjectPlanes = NULL;
for (int k = 0; k < sceneSpheres.size(); k++)
{
if (intersectSphere(sceneSpheres[k].center, sceneSpheres[k].radius, ray, &sceneSpheres[k].hitPoint, &sceneSpheres[k].hitNormal))
{
//cout << "FOO" << endl;
// Calculate the distance between hitPoint and eye
// If it is less than the previous one, this is
// the closer object, and we have to store it in order
// to take its color as the color for this pixel
float dist = glm::distance(eyePosition, sceneSpheres[k].hitPoint);
if (dist < minDistanceSpheres)
{
closerObjectSpheres = &sceneSpheres[k];
minDistanceSpheres = dist;
}
}
}
for (int k = 0; k < scenePlanes.size(); k++)
{
if (intersectPlane(scenePlanes[k].p0, scenePlanes[k].normal, ray, &scenePlanes[k].hitPoint, &scenePlanes[k].hitNormal))
{
//cout << "FOO" << endl;
// Calculate the distance between hitPoint and eye
// If it is less than the previous one, this is
// the closer object, and we have to store it in order
// to take its color as the color for this pixel
float dist = glm::distance(eyePosition, scenePlanes[k].hitPoint);
if (dist < minDistancePlanes)
{
closerObjectPlanes = &scenePlanes[k];
minDistancePlanes = dist;
}
}
}
// For the moment is going to be always NULL
if (closerObjectSpheres == NULL)
{
image[x][y] = color;
}
else
{
Ray shadowRay;
glm::vec3 hitPointS;
glm::vec3 hitNormalS;
shadowRay.direction = glm::normalize(testLight.position - closerObjectSpheres->hitPoint);
shadowRay.origin = closerObjectSpheres->hitPoint;
bool inShadow = false;
for (int k = 0; k < sceneSpheres.size(); k++)
{
if (intersectSphere(sceneSpheres[k].center, sceneSpheres[k].radius, shadowRay, &hitPointS, &hitNormalS))
{
inShadow = true;
break;
}
}
for (int k = 0; k < scenePlanes.size(); k++)
{
if (intersectPlane(scenePlanes[k].p0, scenePlanes[k].normal, shadowRay, &hitPointS, &hitNormalS))
{
inShadow = true;
break;
}
}
if (!inShadow)
{
//image[x][y] = testLight.color * (closerObject->color * max(glm::dot(hitNormal, shadowRay.direction), 0.0f));
image[x][y] = closerObjectSpheres->color * max(glm::dot(closerObjectSpheres->hitNormal, shadowRay.direction), 0.0f);
}
else
{
//cout << "IN SHADOW" << endl;
image[x][y] = black;// + ambient;
}
}
}
}
std::ofstream ofs("./untitled.ppm", std::ios::out | std::ios::binary);
ofs << "P6\n" << WIDTH << " " << HEIGHT << "\n255\n";
for (unsigned y = 0; y < HEIGHT; y++)
{
for (unsigned x = 0; x < WIDTH; x++)
{
ofs << (unsigned char)(image[x][y].x) <<
(unsigned char)(image[x][y].y) <<
(unsigned char)(image[x][y].z);
}
}
ofs.close();
}
int main(int argc, char* argv[])
{
if (!init())
{
return (1);
}
bool quit = false;
SDL_Event event;
while (!quit)
{
while (SDL_PollEvent(&event) != 0)
{
if (event.type == SDL_QUIT)
{
quit = true;
}
else if (event.type == SDL_KEYDOWN)
{
switch (event.key.keysym.sym)
{
case SDLK_1:
{
color = {255.0, 0.0, 0.0};
break;
}
case SDLK_2:
{
color = {0.0, 255.0, 0.0};
break;
}
case SDLK_3:
{
color = {0.0, 0.0, 255.0};
break;
}
case SDLK_r:
{
render();
SDL_Surface* surface = IMG_Load("untitled.ppm");
if (!surface)
{
cout << "Problem loading the image: " << IMG_GetError() << endl;
}
texture = SDL_CreateTextureFromSurface(renderer, surface);
SDL_FreeSurface(surface);
SDL_RenderClear(renderer);
SDL_RenderCopy(renderer, texture, 0, 0);
SDL_RenderPresent(renderer);
break;
}
}
}
}
}
close();
return (0);
}
<commit_msg>Working in adding planes<commit_after>#include <SDL2/SDL.h>
#include <SDL2/SDL_image.h>
#include <iostream>
#include <fstream>
#include <vector>
#include <float.h>
#include <math.h>
#include <glm/glm.hpp>
using namespace std;
#define WIDTH 500
#define HEIGHT 500
enum meshType
{
sphere,
plane
};
typedef enum meshType meshType;
struct Ray
{
glm::vec3 origin;
glm::vec3 direction;
};
struct Mesh
{
glm::vec3 color;
glm::vec3 hitPoint;
glm::vec3 hitNormal;
meshType type;
union
{
glm::vec3 center;
glm::vec3 p0;
};
union
{
glm::vec3 normal;
float radius;
};
};
struct Sphere
{
glm::vec3 center;
float radius;
glm::vec3 color;
glm::vec3 hitPoint;
glm::vec3 hitNormal;
};
struct Plane
{
glm::vec3 normal;
glm::vec3 p0;
glm::vec3 color;
glm::vec3 hitPoint;
glm::vec3 hitNormal;
};
// TODO(ralntdir): Check if this type of light is correct
struct Light
{
glm::vec3 position;
glm::vec3 color;
};
SDL_Window* window = NULL;
SDL_Renderer* renderer = NULL;
SDL_Texture* texture = NULL;
glm::vec3 color = {255.0, 0.0, 0.0};
glm::vec3 black = {0.0, 0.0, 0.0};
void printV3(glm::vec3 vector)
{
cout << vector.x << ", " << vector.y << ", " << vector.z << endl;
}
bool init()
{
bool success = true;
if (SDL_Init(SDL_INIT_VIDEO) < 0)
{
cout << "Error initializing SDL: " << SDL_GetError() << endl;
success = false;
}
else
{
window = SDL_CreateWindow("Devember", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, WIDTH, HEIGHT, SDL_WINDOW_SHOWN);
if (window == NULL)
{
cout << "Problem creating the window: " << SDL_GetError() << endl;
success = false;
}
else
{
renderer = SDL_CreateRenderer(window, -1, 0);
if (renderer == NULL)
{
cout << "Problem creating the renderer: " << SDL_GetError() << endl;
}
else
{
if (IMG_Init(0) < 0)
{
cout << "Problem loading image lib: " << IMG_GetError() << endl;
success = false;
}
else
{
SDL_SetRenderDrawColor(renderer, 0, 255, 255, 255);
SDL_RenderClear(renderer);
SDL_RenderPresent(renderer);
}
}
}
}
return success;
}
void close()
{
SDL_DestroyTexture(texture);
SDL_DestroyRenderer(renderer);
SDL_DestroyWindow(window);
window = NULL;
IMG_Quit();
SDL_Quit();
}
bool intersectSphere(glm::vec3 center, float radius, Ray ray, glm::vec3 *hitPoint, glm::vec3 *hitNormal)
{
// first version for an intersect method
// we just need the hit point for the intersection
bool success;
glm::vec3 originCenter = ray.origin - center;
float a = glm::dot(ray.direction, ray.direction);
//cout << a << endl;
float b = 2 * glm::dot(ray.direction, originCenter);
//cout << b << endl;
float c = glm::dot(originCenter, originCenter) -
(radius * radius);
//cout << c << endl;
float discriminant = b * b - 4 * a * c;
//cout << discriminant << endl;
// If the discriminant is less than cero, we have complex roots
if (discriminant < 0)
{
success = false;
}
else
{
float t, t1, t2;
t1 = (-b + sqrt(discriminant)) / (2 * a);
t2 = (-b - sqrt(discriminant)) / (2 * a);
//cout << "t1: " << t1 << ", t2: " << t2 << endl;
// If both roots are negative -> no solution
if ((t1 < 0) && (t2 < 0))
{
success = false;
}
// Otherwise, we have solution. Which one?
else
{
success = true;
// Refactor this
if ((t1 > 0) && (t2 < 0))
{
t = t1;
}
else if ((t1 < 0) && (t2 > 0))
{
t = t2;
}
else if (t1 <= t2)
{
t = t1;
}
else if (t1 >= t2)
{
t = t2;
}
//*hitPoint = ray.origin + ray.direction * t;
*hitPoint = ray.origin + ray.direction * (t - 0.001f);
*hitNormal = glm::normalize(*hitPoint - center);
}
}
return success;
}
bool intersectPlane(glm::vec3 p0, glm::vec3 normal, Ray ray, glm::vec3 *hitPoint, glm::vec3 *hitNormal)
{
// t = (p_0 - rayOrigin).normal / rayDirection.n
bool success = false;
float denom = glm::dot(ray.direction, normal);
if (denom > 1e-6)
{
glm::vec3 p0rayOrigin = p0 - ray.origin;
float t = glm::dot(p0rayOrigin, normal) / denom;
*hitPoint = ray.origin + ray.direction * (t - 0.001f);
// normal for a point in the plane is the normal of the plane...? I think so.
*hitNormal = normal;
if (t >= 0)
{
success = true;
}
else
{
success = false;
}
}
return success;
}
bool intersect(Mesh *mesh, Ray ray)
{
if (mesh->type == sphere)
{
return intersectSphere(mesh->center, mesh->radius, ray, &mesh->hitPoint, &mesh->hitNormal);
}
else if (mesh->type == plane)
{
return intersectPlane(mesh->p0, mesh->normal, ray, &mesh->hitPoint, &mesh->hitNormal);
}
}
void render()
{
// Creates an image using the ray tracing method.
// The first prototype will have only spheres and flat shading.
// Then I will add diffuse shading (lights) and after that
// shadows.
// TODO(ralntdir): I need to define the camera and the plane
// I'm projecting the scene on!!!
// NOTE(ralntdir): For the moment, the camera is at (0, 0, 0) and pointing
// to -Z and the plane is an XY plane at Z=-1;
// NOTE(ralntdir): I'm working with a right handed one coordinate
// system
vector<Mesh> scene;
glm::vec3 eyePosition = {0.0f, 0.0f, 0.0f};
glm::vec3 ambient = {25.5f, 25.5f, 25.5f};
Light testLight = {};
testLight.position = {0.0f, 30.0f, -10.0f};
testLight.color = {255.0f, 255.0f, 255.0f};
glm::vec3 image[WIDTH][HEIGHT] = {};
// prepare the scene
Mesh testMesh = {};
testMesh.center = {0.0f, -4.0f, -10.0f};
testMesh.radius = 3.0f;
testMesh.color = {0.0f, 0.0f, 255.0f};
testMesh.type = sphere;
scene.push_back(testMesh);
testMesh.center = {1.0f, 1.5f, -10.0f};
testMesh.radius = 2.0f;
testMesh.color = {0.0f, 255.0f, 0.0f};
scene.push_back(testMesh);
testMesh.p0 = {0.0f, 0.0f, -20.0f};
testMesh.normal = {0.0f, 0.0f, 1.0f};
testMesh.color = {255.0f, 255.0f, 0.0f};
testMesh.type = plane;
scene.push_back(testMesh);
/*testMesh.center = {0.0f, 5.0f, -7.0f};
testMesh.radius = 2.0f;
testMesh.color = {0.0f, 255.0f, 0.0f};
sceneSpheres.push_back(testMesh);*/
// In degrees
float fov = 80.0f;
float aspectRatio = (float)WIDTH / (float)HEIGHT;
// trace rays
for (int y = 0; y < HEIGHT; y++)
{
for (int x = 0; x < WIDTH; x++)
{
// create the ray based in eye position, x and y
Ray ray;
ray.origin = eyePosition;
float pX = (2 * ((x + 0.5) / WIDTH) - 1) * tan(fov / 2 * M_PI / 180) * aspectRatio;
float pY = (1 - 2 * ((y + 0.5) / HEIGHT)) * tan(fov / 2 * M_PI / 180);
// As the origin is (0, 0, 0), I don't need to do the subtraction
ray.direction = {pX, pY, -1.0f};
ray.direction = glm::normalize(ray.direction);
//printV3(ray.direction);
//glm::vec3 hitPoint;
//glm::vec3 hitNormal;
float minDistance= FLT_MAX;
Mesh *closerObject= NULL;
for (int k = 0; k < scene.size(); k++)
{
if (intersect(&scene[k], ray))
{
//cout << "FOO" << endl;
// Calculate the distance between hitPoint and eye
// If it is less than the previous one, this is
// the closer object, and we have to store it in order
// to take its color as the color for this pixel
float dist = glm::distance(eyePosition, scene[k].hitPoint);
if (dist < minDistance)
{
closerObject= &scene[k];
minDistance= dist;
}
}
}
// For the moment is going to be always NULL
if (closerObject== NULL)
{
image[x][y] = color;
}
else
{
Ray shadowRay;
glm::vec3 hitPointS;
glm::vec3 hitNormalS;
shadowRay.direction = glm::normalize(testLight.position - closerObject->hitPoint);
shadowRay.origin = closerObject->hitPoint;
bool inShadow = false;
for (int k = 0; k < scene.size(); k++)
{
if (intersect(&scene[k], shadowRay))
{
inShadow = true;
break;
}
}
if (!inShadow)
{
//image[x][y] = testLight.color * (closerObject->color * max(glm::dot(hitNormal, shadowRay.direction), 0.0f));
image[x][y] = closerObject->color * max(glm::dot(closerObject->hitNormal, shadowRay.direction), 0.0f);
}
else
{
//cout << "IN SHADOW" << endl;
image[x][y] = black;// + ambient;
}
}
}
}
std::ofstream ofs("./untitled.ppm", std::ios::out | std::ios::binary);
ofs << "P6\n" << WIDTH << " " << HEIGHT << "\n255\n";
for (unsigned y = 0; y < HEIGHT; y++)
{
for (unsigned x = 0; x < WIDTH; x++)
{
ofs << (unsigned char)(image[x][y].x) <<
(unsigned char)(image[x][y].y) <<
(unsigned char)(image[x][y].z);
}
}
ofs.close();
}
int main(int argc, char* argv[])
{
if (!init())
{
return (1);
}
bool quit = false;
SDL_Event event;
while (!quit)
{
while (SDL_PollEvent(&event) != 0)
{
if (event.type == SDL_QUIT)
{
quit = true;
}
else if (event.type == SDL_KEYDOWN)
{
switch (event.key.keysym.sym)
{
case SDLK_1:
{
color = {255.0, 0.0, 0.0};
break;
}
case SDLK_2:
{
color = {0.0, 255.0, 0.0};
break;
}
case SDLK_3:
{
color = {0.0, 0.0, 255.0};
break;
}
case SDLK_r:
{
render();
SDL_Surface* surface = IMG_Load("untitled.ppm");
if (!surface)
{
cout << "Problem loading the image: " << IMG_GetError() << endl;
}
texture = SDL_CreateTextureFromSurface(renderer, surface);
SDL_FreeSurface(surface);
SDL_RenderClear(renderer);
SDL_RenderCopy(renderer, texture, 0, 0);
SDL_RenderPresent(renderer);
break;
}
}
}
}
}
close();
return (0);
}
<|endoftext|> |
<commit_before>/****************************************************************************
**
** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the QtCore module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** GNU Lesser General Public License Usage
** This file may be used under the terms of the GNU Lesser General Public
** License version 2.1 as published by the Free Software Foundation and
** appearing in the file LICENSE.LGPL included in the packaging of this
** file. Please review the following information to ensure the GNU Lesser
** General Public License version 2.1 requirements will be met:
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU General
** Public License version 3.0 as published by the Free Software Foundation
** and appearing in the file LICENSE.GPL included in the packaging of this
** file. Please review the following information to ensure the GNU General
** Public License version 3.0 requirements will be met:
** http://www.gnu.org/copyleft/gpl.html.
**
** Other Usage
** Alternatively, this file may be used in accordance with the terms and
** conditions contained in a signed written agreement between you and Nokia.
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include "qplatformdefs.h"
#include <qfile.h>
#include "qlibrary_p.h"
#include <qfileinfo.h>
#include <qcoreapplication.h>
#ifndef QT_NO_LIBRARY
#ifdef Q_OS_MAC
# include <private/qcore_mac_p.h>
#endif
#if defined(QT_AOUT_UNDERSCORE)
#include <string.h>
#endif
#if defined(Q_OS_VXWORKS) || defined (Q_OS_NACL)
#define QT_NO_DYNAMIC_LIBRARY
#endif
QT_BEGIN_NAMESPACE
#if !defined(QT_HPUX_LD) && !defined(QT_NO_DYNAMIC_LIBRARY)
QT_BEGIN_INCLUDE_NAMESPACE
#include <dlfcn.h>
QT_END_INCLUDE_NAMESPACE
#endif
static QString qdlerror()
{
#if defined(QT_NO_DYNAMIC_LIBRARY)
const char *err = "This platform does not support dynamic libraries.";
#elif !defined(QT_HPUX_LD)
const char *err = dlerror();
#else
const char *err = strerror(errno);
#endif
return err ? QLatin1Char('(') + QString::fromLocal8Bit(err) + QLatin1Char(')'): QString();
}
bool QLibraryPrivate::load_sys()
{
QString attempt;
#if !defined(QT_NO_DYNAMIC_LIBRARY)
QFileInfo fi(fileName);
#if defined(Q_OS_SYMBIAN)
QString path; // In Symbian, always resolve with just the filename
QString name;
// Replace possible ".qtplugin" suffix with ".dll"
if (fi.suffix() == QLatin1String("qtplugin"))
name = fi.completeBaseName() + QLatin1String(".dll");
else
name = fi.fileName();
#else
QString path = fi.path();
QString name = fi.fileName();
if (path == QLatin1String(".") && !fileName.startsWith(path))
path.clear();
else
path += QLatin1Char('/');
#endif
// The first filename we want to attempt to load is the filename as the callee specified.
// Thus, the first attempt we do must be with an empty prefix and empty suffix.
QStringList suffixes(QLatin1String("")), prefixes(QLatin1String(""));
if (pluginState != IsAPlugin) {
#if !defined(Q_OS_SYMBIAN)
prefixes << QLatin1String("lib");
#endif
#if defined(Q_OS_HPUX)
// according to
// http://docs.hp.com/en/B2355-90968/linkerdifferencesiapa.htm
// In PA-RISC (PA-32 and PA-64) shared libraries are suffixed
// with .sl. In IPF (32-bit and 64-bit), the shared libraries
// are suffixed with .so. For compatibility, the IPF linker
// also supports the .sl suffix.
// But since we don't know if we are built on HPUX or HPUXi,
// we support both .sl (and .<version>) and .so suffixes but
// .so is preferred.
# if defined(__ia64)
if (!fullVersion.isEmpty()) {
suffixes << QString::fromLatin1(".so.%1").arg(fullVersion);
} else {
suffixes << QLatin1String(".so");
}
# endif
if (!fullVersion.isEmpty()) {
suffixes << QString::fromLatin1(".sl.%1").arg(fullVersion);
suffixes << QString::fromLatin1(".%1").arg(fullVersion);
} else {
suffixes << QLatin1String(".sl");
}
#elif defined(Q_OS_SYMBIAN)
suffixes << QLatin1String(".dll");
#else
#ifdef Q_OS_AIX
suffixes << ".a";
#endif // Q_OS_AIX
if (!fullVersion.isEmpty()) {
suffixes << QString::fromLatin1(".so.%1").arg(fullVersion);
} else {
suffixes << QLatin1String(".so");
}
#endif
# ifdef Q_OS_MAC
if (!fullVersion.isEmpty()) {
suffixes << QString::fromLatin1(".%1.bundle").arg(fullVersion);
suffixes << QString::fromLatin1(".%1.dylib").arg(fullVersion);
} else {
suffixes << QLatin1String(".bundle") << QLatin1String(".dylib");
}
#endif
}
int dlFlags = 0;
#if defined(QT_HPUX_LD)
dlFlags = DYNAMIC_PATH | BIND_NONFATAL;
if (loadHints & QLibrary::ResolveAllSymbolsHint) {
dlFlags |= BIND_IMMEDIATE;
} else {
dlFlags |= BIND_DEFERRED;
}
#else
if (loadHints & QLibrary::ResolveAllSymbolsHint) {
dlFlags |= RTLD_NOW;
} else {
dlFlags |= RTLD_LAZY;
}
if (loadHints & QLibrary::ExportExternalSymbolsHint) {
dlFlags |= RTLD_GLOBAL;
}
#if !defined(Q_OS_CYGWIN)
else {
#if defined(Q_OS_MAC)
if (QSysInfo::MacintoshVersion >= QSysInfo::MV_10_4)
#endif
dlFlags |= RTLD_LOCAL;
}
#endif
#if defined(Q_OS_AIX) // Not sure if any other platform actually support this thing.
if (loadHints & QLibrary::LoadArchiveMemberHint) {
dlFlags |= RTLD_MEMBER;
}
#endif
#endif // QT_HPUX_LD
bool retry = true;
for(int prefix = 0; retry && !pHnd && prefix < prefixes.size(); prefix++) {
for(int suffix = 0; retry && !pHnd && suffix < suffixes.size(); suffix++) {
if (!prefixes.at(prefix).isEmpty() && name.startsWith(prefixes.at(prefix)))
continue;
if (!suffixes.at(suffix).isEmpty() && name.endsWith(suffixes.at(suffix)))
continue;
if (loadHints & QLibrary::LoadArchiveMemberHint) {
attempt = name;
int lparen = attempt.indexOf(QLatin1Char('('));
if (lparen == -1)
lparen = attempt.count();
attempt = path + prefixes.at(prefix) + attempt.insert(lparen, suffixes.at(suffix));
} else {
attempt = path + prefixes.at(prefix) + name + suffixes.at(suffix);
}
#if defined(QT_HPUX_LD)
pHnd = (void*)shl_load(QFile::encodeName(attempt), dlFlags, 0);
#else
pHnd = dlopen(QFile::encodeName(attempt), dlFlags);
#endif
#if defined(Q_OS_SYMBIAN)
// Never try again in symbian, dlopen already handles the library search logic,
// and there is only one possible suffix.
retry = false;
#else
if (!pHnd && fileName.startsWith(QLatin1Char('/')) && QFile::exists(attempt)) {
// We only want to continue if dlopen failed due to that the shared library did not exist.
// However, we are only able to apply this check for absolute filenames (since they are
// not influenced by the content of LD_LIBRARY_PATH, /etc/ld.so.cache, DT_RPATH etc...)
// This is all because dlerror is flawed and cannot tell us the reason why it failed.
retry = false;
}
#endif
}
}
#ifdef Q_OS_MAC
if (!pHnd) {
QByteArray utf8Bundle = fileName.toUtf8();
QCFType<CFURLRef> bundleUrl = CFURLCreateFromFileSystemRepresentation(NULL, reinterpret_cast<const UInt8*>(utf8Bundle.data()), utf8Bundle.length(), true);
QCFType<CFBundleRef> bundle = CFBundleCreate(NULL, bundleUrl);
if(bundle) {
QCFType<CFURLRef> url = CFBundleCopyExecutableURL(bundle);
char executableFile[FILENAME_MAX];
CFURLGetFileSystemRepresentation(url, true, reinterpret_cast<UInt8*>(executableFile), FILENAME_MAX);
attempt = QString::fromUtf8(executableFile);
pHnd = dlopen(QFile::encodeName(attempt), dlFlags);
}
}
#endif
#endif // QT_NO_DYNAMIC_LIBRARY
if (!pHnd) {
errorString = QLibrary::tr("Cannot load library %1: %2").arg(fileName).arg(qdlerror());
}
if (pHnd) {
qualifiedFileName = attempt;
errorString.clear();
}
return (pHnd != 0);
}
bool QLibraryPrivate::unload_sys()
{
#if !defined(QT_NO_DYNAMIC_LIBRARY)
# if defined(QT_HPUX_LD)
if (shl_unload((shl_t)pHnd)) {
# else
if (dlclose(pHnd)) {
# endif
errorString = QLibrary::tr("Cannot unload library %1: %2").arg(fileName).arg(qdlerror());
return false;
}
#endif
errorString.clear();
return true;
}
#ifdef Q_OS_MAC
Q_CORE_EXPORT void *qt_mac_resolve_sys(void *handle, const char *symbol)
{
return dlsym(handle, symbol);
}
#endif
void* QLibraryPrivate::resolve_sys(const char* symbol)
{
#if defined(QT_AOUT_UNDERSCORE)
// older a.out systems add an underscore in front of symbols
char* undrscr_symbol = new char[strlen(symbol)+2];
undrscr_symbol[0] = '_';
strcpy(undrscr_symbol+1, symbol);
void* address = dlsym(pHnd, undrscr_symbol);
delete [] undrscr_symbol;
#elif defined(QT_HPUX_LD)
void* address = 0;
if (shl_findsym((shl_t*)&pHnd, symbol, TYPE_UNDEFINED, &address) < 0)
address = 0;
#elif defined (QT_NO_DYNAMIC_LIBRARY)
void *address = 0;
#else
void* address = dlsym(pHnd, symbol);
#endif
if (!address) {
errorString = QLibrary::tr("Cannot resolve symbol \"%1\" in %2: %3").arg(
QString::fromAscii(symbol)).arg(fileName).arg(qdlerror());
} else {
errorString.clear();
}
return address;
}
QT_END_NAMESPACE
#endif // QT_NO_LIBRARY
<commit_msg>dlclose is buggy on leopard<commit_after>/****************************************************************************
**
** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the QtCore module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** GNU Lesser General Public License Usage
** This file may be used under the terms of the GNU Lesser General Public
** License version 2.1 as published by the Free Software Foundation and
** appearing in the file LICENSE.LGPL included in the packaging of this
** file. Please review the following information to ensure the GNU Lesser
** General Public License version 2.1 requirements will be met:
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU General
** Public License version 3.0 as published by the Free Software Foundation
** and appearing in the file LICENSE.GPL included in the packaging of this
** file. Please review the following information to ensure the GNU General
** Public License version 3.0 requirements will be met:
** http://www.gnu.org/copyleft/gpl.html.
**
** Other Usage
** Alternatively, this file may be used in accordance with the terms and
** conditions contained in a signed written agreement between you and Nokia.
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include "qplatformdefs.h"
#include <qfile.h>
#include "qlibrary_p.h"
#include <qfileinfo.h>
#include <qcoreapplication.h>
#ifndef QT_NO_LIBRARY
#ifdef Q_OS_MAC
# include <private/qcore_mac_p.h>
#endif
#if defined(QT_AOUT_UNDERSCORE)
#include <string.h>
#endif
#if defined(Q_OS_VXWORKS) || defined (Q_OS_NACL)
#define QT_NO_DYNAMIC_LIBRARY
#endif
QT_BEGIN_NAMESPACE
#if !defined(QT_HPUX_LD) && !defined(QT_NO_DYNAMIC_LIBRARY)
QT_BEGIN_INCLUDE_NAMESPACE
#include <dlfcn.h>
QT_END_INCLUDE_NAMESPACE
#endif
static QString qdlerror()
{
#if defined(QT_NO_DYNAMIC_LIBRARY)
const char *err = "This platform does not support dynamic libraries.";
#elif !defined(QT_HPUX_LD)
const char *err = dlerror();
#else
const char *err = strerror(errno);
#endif
return err ? QLatin1Char('(') + QString::fromLocal8Bit(err) + QLatin1Char(')'): QString();
}
bool QLibraryPrivate::load_sys()
{
QString attempt;
#if !defined(QT_NO_DYNAMIC_LIBRARY)
QFileInfo fi(fileName);
#if defined(Q_OS_SYMBIAN)
QString path; // In Symbian, always resolve with just the filename
QString name;
// Replace possible ".qtplugin" suffix with ".dll"
if (fi.suffix() == QLatin1String("qtplugin"))
name = fi.completeBaseName() + QLatin1String(".dll");
else
name = fi.fileName();
#else
QString path = fi.path();
QString name = fi.fileName();
if (path == QLatin1String(".") && !fileName.startsWith(path))
path.clear();
else
path += QLatin1Char('/');
#endif
// The first filename we want to attempt to load is the filename as the callee specified.
// Thus, the first attempt we do must be with an empty prefix and empty suffix.
QStringList suffixes(QLatin1String("")), prefixes(QLatin1String(""));
if (pluginState != IsAPlugin) {
#if !defined(Q_OS_SYMBIAN)
prefixes << QLatin1String("lib");
#endif
#if defined(Q_OS_HPUX)
// according to
// http://docs.hp.com/en/B2355-90968/linkerdifferencesiapa.htm
// In PA-RISC (PA-32 and PA-64) shared libraries are suffixed
// with .sl. In IPF (32-bit and 64-bit), the shared libraries
// are suffixed with .so. For compatibility, the IPF linker
// also supports the .sl suffix.
// But since we don't know if we are built on HPUX or HPUXi,
// we support both .sl (and .<version>) and .so suffixes but
// .so is preferred.
# if defined(__ia64)
if (!fullVersion.isEmpty()) {
suffixes << QString::fromLatin1(".so.%1").arg(fullVersion);
} else {
suffixes << QLatin1String(".so");
}
# endif
if (!fullVersion.isEmpty()) {
suffixes << QString::fromLatin1(".sl.%1").arg(fullVersion);
suffixes << QString::fromLatin1(".%1").arg(fullVersion);
} else {
suffixes << QLatin1String(".sl");
}
#elif defined(Q_OS_SYMBIAN)
suffixes << QLatin1String(".dll");
#else
#ifdef Q_OS_AIX
suffixes << ".a";
#endif // Q_OS_AIX
if (!fullVersion.isEmpty()) {
suffixes << QString::fromLatin1(".so.%1").arg(fullVersion);
} else {
suffixes << QLatin1String(".so");
}
#endif
# ifdef Q_OS_MAC
if (!fullVersion.isEmpty()) {
suffixes << QString::fromLatin1(".%1.bundle").arg(fullVersion);
suffixes << QString::fromLatin1(".%1.dylib").arg(fullVersion);
} else {
suffixes << QLatin1String(".bundle") << QLatin1String(".dylib");
}
#endif
}
int dlFlags = 0;
#if defined(QT_HPUX_LD)
dlFlags = DYNAMIC_PATH | BIND_NONFATAL;
if (loadHints & QLibrary::ResolveAllSymbolsHint) {
dlFlags |= BIND_IMMEDIATE;
} else {
dlFlags |= BIND_DEFERRED;
}
#else
if (loadHints & QLibrary::ResolveAllSymbolsHint) {
dlFlags |= RTLD_NOW;
} else {
dlFlags |= RTLD_LAZY;
}
if (loadHints & QLibrary::ExportExternalSymbolsHint) {
dlFlags |= RTLD_GLOBAL;
}
#if !defined(Q_OS_CYGWIN)
else {
#if defined(Q_OS_MAC)
if (QSysInfo::MacintoshVersion >= QSysInfo::MV_10_4)
#endif
dlFlags |= RTLD_LOCAL;
}
#endif
#if defined(Q_OS_AIX) // Not sure if any other platform actually support this thing.
if (loadHints & QLibrary::LoadArchiveMemberHint) {
dlFlags |= RTLD_MEMBER;
}
#endif
#endif // QT_HPUX_LD
bool retry = true;
for(int prefix = 0; retry && !pHnd && prefix < prefixes.size(); prefix++) {
for(int suffix = 0; retry && !pHnd && suffix < suffixes.size(); suffix++) {
if (!prefixes.at(prefix).isEmpty() && name.startsWith(prefixes.at(prefix)))
continue;
if (!suffixes.at(suffix).isEmpty() && name.endsWith(suffixes.at(suffix)))
continue;
if (loadHints & QLibrary::LoadArchiveMemberHint) {
attempt = name;
int lparen = attempt.indexOf(QLatin1Char('('));
if (lparen == -1)
lparen = attempt.count();
attempt = path + prefixes.at(prefix) + attempt.insert(lparen, suffixes.at(suffix));
} else {
attempt = path + prefixes.at(prefix) + name + suffixes.at(suffix);
}
#if defined(QT_HPUX_LD)
pHnd = (void*)shl_load(QFile::encodeName(attempt), dlFlags, 0);
#else
pHnd = dlopen(QFile::encodeName(attempt), dlFlags);
#endif
#if defined(Q_OS_SYMBIAN)
// Never try again in symbian, dlopen already handles the library search logic,
// and there is only one possible suffix.
retry = false;
#else
if (!pHnd && fileName.startsWith(QLatin1Char('/')) && QFile::exists(attempt)) {
// We only want to continue if dlopen failed due to that the shared library did not exist.
// However, we are only able to apply this check for absolute filenames (since they are
// not influenced by the content of LD_LIBRARY_PATH, /etc/ld.so.cache, DT_RPATH etc...)
// This is all because dlerror is flawed and cannot tell us the reason why it failed.
retry = false;
}
#endif
}
}
#ifdef Q_OS_MAC
if (!pHnd) {
QByteArray utf8Bundle = fileName.toUtf8();
QCFType<CFURLRef> bundleUrl = CFURLCreateFromFileSystemRepresentation(NULL, reinterpret_cast<const UInt8*>(utf8Bundle.data()), utf8Bundle.length(), true);
QCFType<CFBundleRef> bundle = CFBundleCreate(NULL, bundleUrl);
if(bundle) {
QCFType<CFURLRef> url = CFBundleCopyExecutableURL(bundle);
char executableFile[FILENAME_MAX];
CFURLGetFileSystemRepresentation(url, true, reinterpret_cast<UInt8*>(executableFile), FILENAME_MAX);
attempt = QString::fromUtf8(executableFile);
pHnd = dlopen(QFile::encodeName(attempt), dlFlags);
}
}
#endif
#endif // QT_NO_DYNAMIC_LIBRARY
if (!pHnd) {
errorString = QLibrary::tr("Cannot load library %1: %2").arg(fileName).arg(qdlerror());
}
if (pHnd) {
qualifiedFileName = attempt;
errorString.clear();
}
return (pHnd != 0);
}
bool QLibraryPrivate::unload_sys()
{
#if !defined(QT_NO_DYNAMIC_LIBRARY)
# if defined(QT_HPUX_LD)
if (shl_unload((shl_t)pHnd)) {
# else
# if defined(Q_OS_MAC)
if (QSysInfo::MacintoshVersion > QSysInfo::MV_10_5 &&
# else
if (
# endif
dlclose(pHnd)) {
# endif
errorString = QLibrary::tr("Cannot unload library %1: %2").arg(fileName).arg(qdlerror());
return false;
}
#endif
errorString.clear();
return true;
}
#ifdef Q_OS_MAC
Q_CORE_EXPORT void *qt_mac_resolve_sys(void *handle, const char *symbol)
{
return dlsym(handle, symbol);
}
#endif
void* QLibraryPrivate::resolve_sys(const char* symbol)
{
#if defined(QT_AOUT_UNDERSCORE)
// older a.out systems add an underscore in front of symbols
char* undrscr_symbol = new char[strlen(symbol)+2];
undrscr_symbol[0] = '_';
strcpy(undrscr_symbol+1, symbol);
void* address = dlsym(pHnd, undrscr_symbol);
delete [] undrscr_symbol;
#elif defined(QT_HPUX_LD)
void* address = 0;
if (shl_findsym((shl_t*)&pHnd, symbol, TYPE_UNDEFINED, &address) < 0)
address = 0;
#elif defined (QT_NO_DYNAMIC_LIBRARY)
void *address = 0;
#else
void* address = dlsym(pHnd, symbol);
#endif
if (!address) {
errorString = QLibrary::tr("Cannot resolve symbol \"%1\" in %2: %3").arg(
QString::fromAscii(symbol)).arg(fileName).arg(qdlerror());
} else {
errorString.clear();
}
return address;
}
QT_END_NAMESPACE
#endif // QT_NO_LIBRARY
<|endoftext|> |
<commit_before>/*
* ProcessTests.cpp
*
* Copyright (C) 2017 by RStudio, Inc.
*
* Unless you have received this program directly from RStudio pursuant
* to the terms of a commercial license agreement with RStudio, then
* this program is licensed to you under the terms of version 3 of the
* GNU Affero General Public License. This program is distributed WITHOUT
* ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT,
* MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the
* AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details.
*
*/
#ifndef _WIN32
#include <atomic>
#include <boost/bind.hpp>
#include <boost/foreach.hpp>
#include <boost/thread.hpp>
#include <core/SafeConvert.hpp>
#include <core/system/PosixProcess.hpp>
#include <core/system/PosixChildProcess.hpp>
#include <core/system/PosixSystem.hpp>
#include <core/Thread.hpp>
#include <tests/TestThat.hpp>
namespace rstudio {
namespace core {
namespace system {
namespace tests {
void checkExitCode(int exitCode, int* outExitCode)
{
*outExitCode = exitCode;
}
void signalExit(int exitCode, int* outExitCode, boost::mutex* mutex, boost::condition_variable* signal)
{
*outExitCode = exitCode;
LOCK_MUTEX(*mutex)
{
signal->notify_all();
}
END_LOCK_MUTEX
}
void appendOutput(const std::string& output, std::string* pOutput)
{
pOutput->append(output);
}
struct IoServiceFixture
{
boost::asio::io_service ioService;
boost::asio::io_service::work work;
std::vector<boost::shared_ptr<boost::thread> > threads;
void runServiceThread()
{
ioService.run();
}
IoServiceFixture() :
ioService(), work(ioService)
{
for (int i = 0; i < 4; ++i)
{
boost::shared_ptr<boost::thread> pThread(
new boost::thread(boost::bind(&IoServiceFixture::runServiceThread, this)));
threads.push_back(pThread);
}
}
~IoServiceFixture()
{
ioService.stop();
for (const boost::shared_ptr<boost::thread>& thread : threads)
thread->join();
}
};
context("ProcessTests")
{
test_that("AsioProcessSupervisor can run program")
{
IoServiceFixture fixture;
// create new supervisor
AsioProcessSupervisor supervisor(fixture.ioService);
// create process options and callbacks
ProcessOptions options;
options.threadSafe = true;
ProcessCallbacks callbacks;
int exitCode = -1;
callbacks.onExit = boost::bind(&checkExitCode, _1, &exitCode);
// construct program arguments
std::vector<std::string> args;
args.push_back("Hello, world! This is a string to echo!");
// run program
supervisor.runProgram("/bin/echo", args, options, callbacks);
// wait for it to exit
bool success = supervisor.wait(boost::posix_time::seconds(5));
// verify process exited successfully
CHECK(success);
CHECK(exitCode == 0);
}
test_that("AsioProcessSupervisor returns correct output from stdout")
{
IoServiceFixture fixture;
// create new supervisor
AsioProcessSupervisor supervisor(fixture.ioService);
// create process options and callbacks
ProcessOptions options;
options.threadSafe = true;
ProcessCallbacks callbacks;
int exitCode = -1;
std::string output;
callbacks.onExit = boost::bind(&checkExitCode, _1, &exitCode);
callbacks.onStdout = boost::bind(&appendOutput, _2, &output);
// run command
std::string command = "bash -c \"python -c $'for i in range(10):\n print(i)'\"";
supervisor.runCommand(command, options, callbacks);
// wait for it to exit
bool success = supervisor.wait(boost::posix_time::seconds(5));
// verify process exited successfully and we got the expected output
std::string expectedOutput = "0\n1\n2\n3\n4\n5\n6\n7\n8\n9\n";
CHECK(success);
CHECK(exitCode == 0);
CHECK(output == expectedOutput);
}
/* test running child process as another user
* commented out due to users being different on every machine
test_that("AsioProcessSupervisor can run process as another user")
{
IoServiceFixture fixture;
// create new supervisor
AsioProcessSupervisor supervisor(fixture.ioService);
// create process options and callbacks
ProcessOptions options;
options.runAsUser = "jdoe1";
ProcessCallbacks callbacks;
int exitCode = -1;
std::string output;
callbacks.onExit = boost::bind(&checkExitCode, _1, &exitCode);
callbacks.onStdout = boost::bind(&appendOutput, _2, &output);
// run command
std::string command = "whoami";
supervisor.runCommand(command, options, callbacks);
// wait for it to exit
bool success = supervisor.wait(boost::posix_time::seconds(5));
// verify process exited successfully and we got the expected output
std::string expectedOutput = "jdoe1\n";
CHECK(success);
CHECK(exitCode == 0);
CHECK(output == expectedOutput);
}
*/
test_that("AsioProcessSupervisor returns correct error code for failure exit")
{
IoServiceFixture fixture;
// create new supervisor
AsioProcessSupervisor supervisor(fixture.ioService);
// create process options and callbacks
ProcessOptions options;
options.threadSafe = true;
ProcessCallbacks callbacks;
int exitCode = -1;
std::string output;
callbacks.onExit = boost::bind(&checkExitCode, _1, &exitCode);
// run command
std::string command = "this is not a valid command";
supervisor.runCommand(command, options, callbacks);
// wait for it to exit
bool success = supervisor.wait(boost::posix_time::seconds(5));
CHECK(success);
CHECK(exitCode == 127);
}
test_that("AsioAsyncChildProcess can write to std in")
{
IoServiceFixture fixture;
ProcessOptions options;
options.threadSafe = true;
options.threadSafe = true;
ProcessCallbacks callbacks;
int exitCode = -1;
std::string output;
boost::condition_variable signal;
boost::mutex mutex;
callbacks.onExit = boost::bind(&signalExit, _1, &exitCode, &mutex, &signal);
callbacks.onStdout = boost::bind(&appendOutput, _2, &output);
AsioAsyncChildProcess proc(fixture.ioService, "cat", options);
proc.run(callbacks);
proc.asyncWriteToStdin("Hello\n", false);
proc.asyncWriteToStdin("world!\n", true);
std::string expectedOutput = "Hello\nworld!\n";
boost::unique_lock<boost::mutex> lock(mutex);
bool timedOut = !signal.timed_wait<boost::posix_time::seconds>(lock, boost::posix_time::seconds(5),
[&](){return exitCode == 0;});
CHECK(!timedOut);
CHECK(exitCode == 0);
CHECK(output == expectedOutput);
}
test_that("Can spawn multiple sync processes and they all return correct results")
{
// create new supervisor
ProcessSupervisor supervisor;
int exitCodes[10];
std::string outputs[10];
for (int i = 0; i < 10; ++i)
{
// construct program arguments
std::vector<std::string> args;
args.push_back("Hello, " + safe_convert::numberToString(i));
// create process options and callbacks
ProcessOptions options;
options.threadSafe = true;
ProcessCallbacks callbacks;
callbacks.onExit = boost::bind(&checkExitCode, _1, exitCodes + i);
callbacks.onStdout = boost::bind(&appendOutput, _2, outputs + i);
// run program
supervisor.runProgram("/bin/echo", args, options, callbacks);
}
// wait for processes to exit
bool success = supervisor.wait();
// verify correct exit statuses and outputs
for (int i = 0; i < 10; ++i)
{
CHECK(exitCodes[i] == 0);
CHECK(outputs[i] == "Hello, " + safe_convert::numberToString(i) + "\n");
}
}
test_that("Can spawn multiple async processes and they all return correct results")
{
IoServiceFixture fixture;
std::string asioType;
#if defined(BOOST_ASIO_HAS_IOCP)
asioType = "iocp" ;
#elif defined(BOOST_ASIO_HAS_EPOLL)
asioType = "epoll" ;
#elif defined(BOOST_ASIO_HAS_KQUEUE)
asioType = "kqueue" ;
#elif defined(BOOST_ASIO_HAS_DEV_POLL)
asioType = "/dev/poll" ;
#else
asioType = "select" ;
#endif
std::cout << "Using asio type: " << asioType << std::endl;
// determine open files limit
RLimitType soft, hard;
Error error = core::system::getResourceLimit(core::system::FilesLimit, &soft, &hard);
REQUIRE_FALSE(error);
// ensure we set the hard limit
error = core::system::setResourceLimit(core::system::FilesLimit, ::fmin(10000, hard));
REQUIRE_FALSE(error);
// spawn amount of processes proportional to the hard limit
const int numProcs = ::fmin(hard / 6, 1000);
std::cout << "Spawning " << numProcs << " child procs" << std::endl;
// create new supervisor
AsioProcessSupervisor supervisor(fixture.ioService);
int exitCodes[numProcs];
std::string outputs[numProcs];
std::atomic<int> numExited(0);
int numError = 0;
Error lastError;
for (int i = 0; i < numProcs; ++i)
{
// set exit code to some initial bad value to ensure it is properly set when
// the process exits
exitCodes[i] = -1;
// construct program arguments
std::vector<std::string> args;
args.push_back("Hello, " + safe_convert::numberToString(i));
// create process options and callbacks
ProcessOptions options;
options.threadSafe = true;
ProcessCallbacks callbacks;
callbacks.onExit = [&exitCodes, &numExited, i](int exitCode) {
exitCodes[i] = exitCode;
numExited++;
};
callbacks.onStdout = boost::bind(&appendOutput, _2, outputs + i);
// run program
Error error = supervisor.runProgram("/bin/echo", args, options, callbacks);
if (error)
{
numError++;
lastError = error;
}
}
if (lastError)
std::cout << lastError.summary() << " " << lastError.location().asString() << std::endl;
CHECK(numError == 0);
// wait for processes to exit
bool success = supervisor.wait(boost::posix_time::seconds(60));
CHECK(success);
// check to make sure all processes really exited
CHECK(numExited == numProcs);
// verify correct exit statuses and outputs
for (int i = 0; i < numProcs; ++i)
{
CHECK(exitCodes[i] == 0);
CHECK(outputs[i] == "Hello, " + safe_convert::numberToString(i) + "\n");
}
}
}
} // end namespace tests
} // end namespace system
} // end namespace core
} // end namespace rstudio
#endif // !_WIN32
<commit_msg>Fixed ProcessTests unit tests - was using a variable-length array which crashes the latest clang compiler. Also it is not standard C++ and should not be used.<commit_after>/*
* ProcessTests.cpp
*
* Copyright (C) 2017 by RStudio, Inc.
*
* Unless you have received this program directly from RStudio pursuant
* to the terms of a commercial license agreement with RStudio, then
* this program is licensed to you under the terms of version 3 of the
* GNU Affero General Public License. This program is distributed WITHOUT
* ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT,
* MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the
* AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details.
*
*/
#ifndef _WIN32
#include <atomic>
#include <boost/bind.hpp>
#include <boost/foreach.hpp>
#include <boost/thread.hpp>
#include <core/SafeConvert.hpp>
#include <core/system/PosixProcess.hpp>
#include <core/system/PosixChildProcess.hpp>
#include <core/system/PosixSystem.hpp>
#include <core/Thread.hpp>
#include <tests/TestThat.hpp>
namespace rstudio {
namespace core {
namespace system {
namespace tests {
void checkExitCode(int exitCode, int* outExitCode)
{
*outExitCode = exitCode;
}
void signalExit(int exitCode, int* outExitCode, boost::mutex* mutex, boost::condition_variable* signal)
{
*outExitCode = exitCode;
LOCK_MUTEX(*mutex)
{
signal->notify_all();
}
END_LOCK_MUTEX
}
void appendOutput(const std::string& output, std::string* pOutput)
{
pOutput->append(output);
}
struct IoServiceFixture
{
boost::asio::io_service ioService;
boost::asio::io_service::work work;
std::vector<boost::shared_ptr<boost::thread> > threads;
void runServiceThread()
{
ioService.run();
}
IoServiceFixture() :
ioService(), work(ioService)
{
for (int i = 0; i < 4; ++i)
{
boost::shared_ptr<boost::thread> pThread(
new boost::thread(boost::bind(&IoServiceFixture::runServiceThread, this)));
threads.push_back(pThread);
}
}
~IoServiceFixture()
{
ioService.stop();
for (const boost::shared_ptr<boost::thread>& thread : threads)
thread->join();
}
};
context("ProcessTests")
{
test_that("AsioProcessSupervisor can run program")
{
IoServiceFixture fixture;
// create new supervisor
AsioProcessSupervisor supervisor(fixture.ioService);
// create process options and callbacks
ProcessOptions options;
options.threadSafe = true;
ProcessCallbacks callbacks;
int exitCode = -1;
callbacks.onExit = boost::bind(&checkExitCode, _1, &exitCode);
// construct program arguments
std::vector<std::string> args;
args.push_back("Hello, world! This is a string to echo!");
// run program
supervisor.runProgram("/bin/echo", args, options, callbacks);
// wait for it to exit
bool success = supervisor.wait(boost::posix_time::seconds(5));
// verify process exited successfully
CHECK(success);
CHECK(exitCode == 0);
}
test_that("AsioProcessSupervisor returns correct output from stdout")
{
IoServiceFixture fixture;
// create new supervisor
AsioProcessSupervisor supervisor(fixture.ioService);
// create process options and callbacks
ProcessOptions options;
options.threadSafe = true;
ProcessCallbacks callbacks;
int exitCode = -1;
std::string output;
callbacks.onExit = boost::bind(&checkExitCode, _1, &exitCode);
callbacks.onStdout = boost::bind(&appendOutput, _2, &output);
// run command
std::string command = "bash -c \"python -c $'for i in range(10):\n print(i)'\"";
supervisor.runCommand(command, options, callbacks);
// wait for it to exit
bool success = supervisor.wait(boost::posix_time::seconds(5));
// verify process exited successfully and we got the expected output
std::string expectedOutput = "0\n1\n2\n3\n4\n5\n6\n7\n8\n9\n";
CHECK(success);
CHECK(exitCode == 0);
CHECK(output == expectedOutput);
}
/* test running child process as another user
* commented out due to users being different on every machine
test_that("AsioProcessSupervisor can run process as another user")
{
IoServiceFixture fixture;
// create new supervisor
AsioProcessSupervisor supervisor(fixture.ioService);
// create process options and callbacks
ProcessOptions options;
options.runAsUser = "jdoe1";
ProcessCallbacks callbacks;
int exitCode = -1;
std::string output;
callbacks.onExit = boost::bind(&checkExitCode, _1, &exitCode);
callbacks.onStdout = boost::bind(&appendOutput, _2, &output);
// run command
std::string command = "whoami";
supervisor.runCommand(command, options, callbacks);
// wait for it to exit
bool success = supervisor.wait(boost::posix_time::seconds(5));
// verify process exited successfully and we got the expected output
std::string expectedOutput = "jdoe1\n";
CHECK(success);
CHECK(exitCode == 0);
CHECK(output == expectedOutput);
}
*/
test_that("AsioProcessSupervisor returns correct error code for failure exit")
{
IoServiceFixture fixture;
// create new supervisor
AsioProcessSupervisor supervisor(fixture.ioService);
// create process options and callbacks
ProcessOptions options;
options.threadSafe = true;
ProcessCallbacks callbacks;
int exitCode = -1;
std::string output;
callbacks.onExit = boost::bind(&checkExitCode, _1, &exitCode);
// run command
std::string command = "this is not a valid command";
supervisor.runCommand(command, options, callbacks);
// wait for it to exit
bool success = supervisor.wait(boost::posix_time::seconds(5));
CHECK(success);
CHECK(exitCode == 127);
}
test_that("AsioAsyncChildProcess can write to std in")
{
IoServiceFixture fixture;
ProcessOptions options;
options.threadSafe = true;
options.threadSafe = true;
ProcessCallbacks callbacks;
int exitCode = -1;
std::string output;
boost::condition_variable signal;
boost::mutex mutex;
callbacks.onExit = boost::bind(&signalExit, _1, &exitCode, &mutex, &signal);
callbacks.onStdout = boost::bind(&appendOutput, _2, &output);
AsioAsyncChildProcess proc(fixture.ioService, "cat", options);
proc.run(callbacks);
proc.asyncWriteToStdin("Hello\n", false);
proc.asyncWriteToStdin("world!\n", true);
std::string expectedOutput = "Hello\nworld!\n";
boost::unique_lock<boost::mutex> lock(mutex);
bool timedOut = !signal.timed_wait<boost::posix_time::seconds>(lock, boost::posix_time::seconds(5),
[&](){return exitCode == 0;});
CHECK(!timedOut);
CHECK(exitCode == 0);
CHECK(output == expectedOutput);
}
test_that("Can spawn multiple sync processes and they all return correct results")
{
// create new supervisor
ProcessSupervisor supervisor;
int exitCodes[10];
std::string outputs[10];
for (int i = 0; i < 10; ++i)
{
// construct program arguments
std::vector<std::string> args;
args.push_back("Hello, " + safe_convert::numberToString(i));
// create process options and callbacks
ProcessOptions options;
options.threadSafe = true;
ProcessCallbacks callbacks;
callbacks.onExit = boost::bind(&checkExitCode, _1, exitCodes + i);
callbacks.onStdout = boost::bind(&appendOutput, _2, outputs + i);
// run program
supervisor.runProgram("/bin/echo", args, options, callbacks);
}
// wait for processes to exit
bool success = supervisor.wait();
// verify correct exit statuses and outputs
for (int i = 0; i < 10; ++i)
{
CHECK(exitCodes[i] == 0);
CHECK(outputs[i] == "Hello, " + safe_convert::numberToString(i) + "\n");
}
}
test_that("Can spawn multiple async processes and they all return correct results")
{
IoServiceFixture fixture;
std::string asioType;
#if defined(BOOST_ASIO_HAS_IOCP)
asioType = "iocp" ;
#elif defined(BOOST_ASIO_HAS_EPOLL)
asioType = "epoll" ;
#elif defined(BOOST_ASIO_HAS_KQUEUE)
asioType = "kqueue" ;
#elif defined(BOOST_ASIO_HAS_DEV_POLL)
asioType = "/dev/poll" ;
#else
asioType = "select" ;
#endif
std::cout << "Using asio type: " << asioType << std::endl;
// determine open files limit
RLimitType soft, hard;
Error error = core::system::getResourceLimit(core::system::FilesLimit, &soft, &hard);
REQUIRE_FALSE(error);
// ensure we set the hard limit
error = core::system::setResourceLimit(core::system::FilesLimit, ::fmin(10000, hard));
REQUIRE_FALSE(error);
// spawn amount of processes proportional to the hard limit
const int numProcs = ::fmin(hard / 6, 1000);
std::cout << "Spawning " << numProcs << " child procs" << std::endl;
// create new supervisor
AsioProcessSupervisor supervisor(fixture.ioService);
int exitCodes[1000];
std::string outputs[1000];
std::atomic<int> numExited(0);
int numError = 0;
Error lastError;
for (int i = 0; i < numProcs; ++i)
{
// set exit code to some initial bad value to ensure it is properly set when
// the process exits
exitCodes[i] = -1;
// construct program arguments
std::vector<std::string> args;
args.push_back("Hello, " + safe_convert::numberToString(i));
// create process options and callbacks
ProcessOptions options;
options.threadSafe = true;
ProcessCallbacks callbacks;
callbacks.onExit = [&exitCodes, &numExited, i](int exitCode) {
exitCodes[i] = exitCode;
numExited++;
};
callbacks.onStdout = boost::bind(&appendOutput, _2, outputs + i);
// run program
Error error = supervisor.runProgram("/bin/echo", args, options, callbacks);
if (error)
{
numError++;
lastError = error;
}
}
if (lastError)
std::cout << lastError.summary() << " " << lastError.location().asString() << std::endl;
CHECK(numError == 0);
// wait for processes to exit
bool success = supervisor.wait(boost::posix_time::seconds(60));
CHECK(success);
// check to make sure all processes really exited
CHECK(numExited == numProcs);
// verify correct exit statuses and outputs
for (int i = 0; i < numProcs; ++i)
{
CHECK(exitCodes[i] == 0);
CHECK(outputs[i] == "Hello, " + safe_convert::numberToString(i) + "\n");
}
}
}
} // end namespace tests
} // end namespace system
} // end namespace core
} // end namespace rstudio
#endif // !_WIN32
<|endoftext|> |
<commit_before>/*
* Copyright 2014 Matthew Harvey
*
* 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 "stint.hpp"
#include "config.hpp"
#include "interval.hpp"
#include "round.hpp"
#include "stream_flag_guard.hpp"
#include <cassert>
#include <iomanip>
#include <ios>
#include <iostream>
#include <ostream>
#include <map>
#include <string>
#include <vector>
using std::endl;
using std::fixed;
using std::ios_base;
using std::left;
using std::map;
using std::ostream;
using std::right;
using std::setprecision;
using std::setw;
using std::string;
using std::vector;
namespace swx
{
namespace
{
ostream& print_activity
( ostream& p_os,
string const& p_name,
unsigned int p_width
)
{
StreamFlagGuard guard(p_os);
p_os << left << setw(p_width) << p_name;
return p_os;
}
ostream& print_hours
( ostream& p_os,
double p_hours,
unsigned int p_rounding_num,
unsigned int p_rounding_den,
unsigned int p_precision,
unsigned int p_width
)
{
StreamFlagGuard guard(p_os);
p_os << fixed << setprecision(p_precision) << right
<< setw(p_width)
<< round(p_hours, p_rounding_num, p_rounding_den);
return p_os;
}
ostream& print_time_point(ostream& p_os, TimePoint const& p_time_point)
{
StreamFlagGuard guard(p_os);
p_os << time_point_to_stamp(p_time_point);
return p_os;
}
} // end anonymous namespace
Stint::Stint(string const& p_activity, Interval const& p_interval):
m_activity(p_activity),
m_interval(p_interval)
{
}
string const&
Stint::activity() const
{
return m_activity;
}
Interval
Stint::interval() const
{
return m_interval;
}
ostream&
operator<<(ostream& os, vector<Stint> const& container)
{
map<string, double> accum_map;
double accum_hours = 0.0;
string live_activity;
auto const gap = " ";
auto const rounding_num = Config::output_rounding_numerator();
auto const rounding_den = Config::output_rounding_denominator();
auto const w = Config::output_width();
auto const prec = Config::output_precision();
for (auto const& stint: container)
{
string const activity = stint.activity();
if (!activity.empty())
{
auto const interval = stint.interval();
double hours = interval.duration().count() / 60.0 / 60.0;
accum_hours += hours;
auto const it = accum_map.find(activity);
if (it == accum_map.end())
{
accum_map[activity] = hours;
}
else
{
it->second += hours;
}
print_time_point(os, interval.beginning()) << gap;
print_time_point(os, interval.ending()) << gap;
print_hours(os, hours, rounding_num, rounding_den, prec, w);
if (interval.is_live())
{
os << '*';
live_activity = activity;
}
else
{
os << ' ';
}
os << gap << activity << endl;
}
}
os << endl;
string::size_type max_name_width = 0;
for (auto const& pair: accum_map)
{
string const& activity = pair.first;
auto const length = activity.length();
if (length > max_name_width) max_name_width = length;
}
for (auto const& pair: accum_map)
{
string const& activity = pair.first;
double const hours = pair.second;
print_activity(os, activity, max_name_width);
print_hours(os, hours, rounding_num, rounding_den, prec, w);
if (live_activity == activity) os << '*';
os << endl;
}
os << endl;
print_activity(os, "TOTAL", max_name_width);
print_hours(os, accum_hours, rounding_num, rounding_den, prec, w);
os << endl;
if (!live_activity.empty()) os << "\n*ongoing" << endl;
return os;
}
} // namespace swx
<commit_msg>Improve output of reporting commands.<commit_after>/*
* Copyright 2014 Matthew Harvey
*
* 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 "stint.hpp"
#include "config.hpp"
#include "interval.hpp"
#include "round.hpp"
#include "stream_flag_guard.hpp"
#include <cassert>
#include <iomanip>
#include <ios>
#include <iostream>
#include <ostream>
#include <map>
#include <string>
#include <vector>
using std::endl;
using std::fixed;
using std::ios_base;
using std::left;
using std::map;
using std::ostream;
using std::right;
using std::setprecision;
using std::setw;
using std::string;
using std::vector;
namespace swx
{
namespace
{
ostream& print_activity
( ostream& p_os,
string const& p_name,
unsigned int p_width
)
{
StreamFlagGuard guard(p_os);
p_os << left << setw(p_width) << p_name;
return p_os;
}
ostream& print_hours
( ostream& p_os,
double p_hours,
unsigned int p_rounding_num,
unsigned int p_rounding_den,
unsigned int p_precision,
unsigned int p_width
)
{
StreamFlagGuard guard(p_os);
p_os << fixed << setprecision(p_precision) << right
<< setw(p_width)
<< round(p_hours, p_rounding_num, p_rounding_den);
return p_os;
}
ostream& print_time_point(ostream& p_os, TimePoint const& p_time_point)
{
StreamFlagGuard guard(p_os);
p_os << time_point_to_stamp(p_time_point);
return p_os;
}
} // end anonymous namespace
Stint::Stint(string const& p_activity, Interval const& p_interval):
m_activity(p_activity),
m_interval(p_interval)
{
}
string const&
Stint::activity() const
{
return m_activity;
}
Interval
Stint::interval() const
{
return m_interval;
}
ostream&
operator<<(ostream& os, vector<Stint> const& container)
{
map<string, double> accum_map;
double accum_hours = 0.0;
string live_activity;
auto const gap = " ";
auto const rounding_num = Config::output_rounding_numerator();
auto const rounding_den = Config::output_rounding_denominator();
auto const w = Config::output_width();
auto const prec = Config::output_precision();
bool last_activity_empty = true;
for
( vector<Stint>::const_iterator it = container.begin();
it != container.end();
++it
)
{
string const activity = it->activity();
if (activity.empty())
{
if (!last_activity_empty) os << endl;
last_activity_empty = true;
}
else
{
last_activity_empty = false;
auto const interval = it->interval();
double hours = interval.duration().count() / 60.0 / 60.0;
accum_hours += hours;
auto const it = accum_map.find(activity);
if (it == accum_map.end())
{
accum_map[activity] = hours;
}
else
{
it->second += hours;
}
print_time_point(os, interval.beginning()) << gap;
print_time_point(os, interval.ending()) << gap;
print_hours(os, hours, rounding_num, rounding_den, prec, w);
if (interval.is_live())
{
os << '*';
live_activity = activity;
}
else
{
os << ' ';
}
os << gap << activity << endl;
}
}
os << endl;
string::size_type max_name_width = 0;
for (auto const& pair: accum_map)
{
string const& activity = pair.first;
auto const length = activity.length();
if (length > max_name_width) max_name_width = length;
}
for (auto const& pair: accum_map)
{
string const& activity = pair.first;
double const hours = pair.second;
print_activity(os, activity, max_name_width);
print_hours(os, hours, rounding_num, rounding_den, prec, w);
if (live_activity == activity) os << '*';
os << endl;
}
os << endl;
print_activity(os, "TOTAL", max_name_width);
print_hours(os, accum_hours, rounding_num, rounding_den, prec, w);
os << endl;
if (!live_activity.empty()) os << "\n*ongoing" << endl;
return os;
}
} // namespace swx
<|endoftext|> |
<commit_before>////////////////////////////////////////
// test lcio::TrackerHit
////////////////////////////////////////
#include "tutil.h"
#include "lcio.h"
#include "EVENT/LCIO.h"
#include "IO/LCReader.h"
#include "IO/LCWriter.h"
#include "IMPL/LCEventImpl.h"
#include "IMPL/LCCollectionVec.h"
#include "IMPL/TrackerHitImpl.h"
#include "IMPL/LCFlagImpl.h"
//#include "UTIL/Operators.h"
#include "UTIL/CellIDEncoder.h"
#include "UTIL/CellIDDecoder.h"
#include "UTIL/ILDConf.h"
//#include <iostream>
using namespace std ;
using namespace lcio ;
//static const int NRUN = 10 ;
static const int NEVENT = 10 ; // events
static const int NHITS = 1000 ; // tracker hits per event
static string FILEN = "trackerhits.slcio" ;
// replace mytest with the name of your test
const static string testname="test_trackerhit";
//=============================================================================
int main(int argc, char** argv ){
// this should be the first line in your test
TEST MYTEST=TEST( testname, std::cout );
try{
MYTEST.LOG( " writing TrackerHits " );
// create sio writer
LCWriter* lcWrt = LCFactory::getInstance()->createLCWriter() ;
lcWrt->open( FILEN , LCIO::WRITE_NEW ) ;
// EventLoop - create some events and write them to the file
for(int i=0;i<NEVENT;i++){
// we need to use the implementation classes here
LCEventImpl* evt = new LCEventImpl() ;
evt->setRunNumber( 4711 ) ;
evt->setEventNumber( i ) ;
LCCollectionVec* trkHits = new LCCollectionVec( LCIO::TRACKERHIT ) ;
ILDCellIDEncoder<TrackerHitImpl> idEnc( "readoutUnit:8,daqChannel:16," , trkHits ) ;
// this is effectively the same as:
// CellIDEncoder<TrackerHitImpl> idEnc( ILDCellID0::encoder_string + ",readoutUnit:8,daqChannel:16" , trkHits ) ;
for(int j=0;j<NHITS;j++){
TrackerHitImpl* trkHit = new TrackerHitImpl ;
idEnc.reset() ;
idEnc[ ILDCellID0::subdet ] = ILDDetID::FTD ;
idEnc[ ILDCellID0::layer ] = j % 100 ;
idEnc[ ILDCellID0::side ] = ILDDetID::bwd ;
idEnc[ ILDCellID0::module ] = j / 100 + 1 ;
idEnc[ ILDCellID0::sensor ] = j % 4 ;
idEnc["daqChannel"] = j*8 ;
idEnc.setCellID( trkHit ) ;
trkHit->setEDep( i*j*117. ) ;
// trkHit->setdEdx( i*j*117. ) ;
trkHit->setEDepError( (i+j)*.3 ) ;
double pos[3] = { i, j, i*j } ;
trkHit->setPosition( pos ) ;
float cov[3] = { i, j, i+j } ;
trkHit->setCovMatrix( cov );
trkHits->addElement( trkHit ) ;
}
evt->addCollection( trkHits , "TrackerHits") ;
lcWrt->writeEvent(evt) ;
delete evt ;
}
lcWrt->close() ;
MYTEST.LOG(" reading back TrackerHits from file " ) ;
// create sio reader
LCReader* lcRdr = LCFactory::getInstance()->createLCReader() ;
lcRdr->open( FILEN ) ;
for(int i=0;i<NEVENT;i++){
//std::cout << " testing event " << i << std::endl ;
LCEvent* evt = lcRdr->readNextEvent() ;
MYTEST( evt->getRunNumber() , 4711 , " run number " ) ;
MYTEST( evt->getEventNumber() , i , " event number " ) ;
LCCollection* trkHits = evt->getCollection( "TrackerHits") ;
CellIDDecoder<TrackerHit> idDec( trkHits ) ;
for(int j=0;j<NHITS;j++) {
//std::cout << " testing hit " << j << std::endl ;
TrackerHit* trkHit = dynamic_cast<TrackerHit*>(trkHits->getElementAt(j)) ;
MYTEST( idDec(trkHit)[ ILDCellID0::subdet ] , ILDDetID::FTD , " cellID(trkHit) == ( ILDDetID::FTD ) " ) ;
MYTEST( idDec(trkHit)[ ILDCellID0::layer ] , j % 100 , " cellID(trkHit) == ( j % 100 ) " ) ;
MYTEST( idDec(trkHit)[ ILDCellID0::side ] , ILDDetID::bwd , " cellID(trkHit) == ( ILDDetID::bwd ) " ) ;
MYTEST( idDec(trkHit)[ ILDCellID0::module ] , j / 100 + 1 , " cellID(trkHit) == ( j / 100 + 1 ) " ) ;
MYTEST( idDec(trkHit)[ ILDCellID0::sensor ] , j % 4 , " cellID(trkHit) == ( j % 4 ) " ) ;
MYTEST( idDec(trkHit)["daqChannel"] , j*8 , " cellID(trkHit) == ( j*8 ) " ) ;
//std::cout << *trkHit << std::endl ;
MYTEST( trkHit->getEDep() , i*j*117. , "EDep" ) ;
// MYTEST( trkHit->getdEdx() , i*j*117. , "dEdx" ) ;
// remove float converstion and check what happens ;)
MYTEST( trkHit->getEDepError() , float((i+j)*.3) , "EDepError" ) ;
//MYTEST( trkHit->getEDepError() , (i+j)*.3 , "EDepError" ) ;
const double* pos = trkHit->getPosition() ;
MYTEST( pos[0] , i , " pos[0] " ) ;
MYTEST( pos[1] , j , " pos[1] " ) ;
MYTEST( pos[2] , i*j , " pos[2] " ) ;
const FloatVec& cov = trkHit->getCovMatrix() ;
MYTEST( cov[0] , i , " cov[0] " ) ;
MYTEST( cov[1] , j , " cov[1] " ) ;
MYTEST( cov[2] , i+j , " cov[2] " ) ;
}
}
lcRdr->close() ;
} catch( Exception &e ){
MYTEST.FAILED( e.what() );
}
return 0;
}
//=============================================================================
<commit_msg> - fixed array size [covid 38125]<commit_after>////////////////////////////////////////
// test lcio::TrackerHit
////////////////////////////////////////
#include "tutil.h"
#include "lcio.h"
#include "EVENT/LCIO.h"
#include "IO/LCReader.h"
#include "IO/LCWriter.h"
#include "IMPL/LCEventImpl.h"
#include "IMPL/LCCollectionVec.h"
#include "IMPL/TrackerHitImpl.h"
#include "IMPL/LCFlagImpl.h"
//#include "UTIL/Operators.h"
#include "UTIL/CellIDEncoder.h"
#include "UTIL/CellIDDecoder.h"
#include "UTIL/ILDConf.h"
//#include <iostream>
using namespace std ;
using namespace lcio ;
//static const int NRUN = 10 ;
static const int NEVENT = 10 ; // events
static const int NHITS = 1000 ; // tracker hits per event
static string FILEN = "trackerhits.slcio" ;
// replace mytest with the name of your test
const static string testname="test_trackerhit";
//=============================================================================
int main(int argc, char** argv ){
// this should be the first line in your test
TEST MYTEST=TEST( testname, std::cout );
try{
MYTEST.LOG( " writing TrackerHits " );
// create sio writer
LCWriter* lcWrt = LCFactory::getInstance()->createLCWriter() ;
lcWrt->open( FILEN , LCIO::WRITE_NEW ) ;
// EventLoop - create some events and write them to the file
for(int i=0;i<NEVENT;i++){
// we need to use the implementation classes here
LCEventImpl* evt = new LCEventImpl() ;
evt->setRunNumber( 4711 ) ;
evt->setEventNumber( i ) ;
LCCollectionVec* trkHits = new LCCollectionVec( LCIO::TRACKERHIT ) ;
ILDCellIDEncoder<TrackerHitImpl> idEnc( "readoutUnit:8,daqChannel:16," , trkHits ) ;
// this is effectively the same as:
// CellIDEncoder<TrackerHitImpl> idEnc( ILDCellID0::encoder_string + ",readoutUnit:8,daqChannel:16" , trkHits ) ;
for(int j=0;j<NHITS;j++){
TrackerHitImpl* trkHit = new TrackerHitImpl ;
idEnc.reset() ;
idEnc[ ILDCellID0::subdet ] = ILDDetID::FTD ;
idEnc[ ILDCellID0::layer ] = j % 100 ;
idEnc[ ILDCellID0::side ] = ILDDetID::bwd ;
idEnc[ ILDCellID0::module ] = j / 100 + 1 ;
idEnc[ ILDCellID0::sensor ] = j % 4 ;
idEnc["daqChannel"] = j*8 ;
idEnc.setCellID( trkHit ) ;
trkHit->setEDep( i*j*117. ) ;
// trkHit->setdEdx( i*j*117. ) ;
trkHit->setEDepError( (i+j)*.3 ) ;
double pos[3] = { i, j, i*j } ;
trkHit->setPosition( pos ) ;
float cov[TRKHITNCOVMATRIX] = { i, j, i+j , 2*i, 2*j, 2*(i+j) } ;
trkHit->setCovMatrix( cov );
trkHits->addElement( trkHit ) ;
}
evt->addCollection( trkHits , "TrackerHits") ;
lcWrt->writeEvent(evt) ;
delete evt ;
}
lcWrt->close() ;
MYTEST.LOG(" reading back TrackerHits from file " ) ;
// create sio reader
LCReader* lcRdr = LCFactory::getInstance()->createLCReader() ;
lcRdr->open( FILEN ) ;
for(int i=0;i<NEVENT;i++){
//std::cout << " testing event " << i << std::endl ;
LCEvent* evt = lcRdr->readNextEvent() ;
MYTEST( evt->getRunNumber() , 4711 , " run number " ) ;
MYTEST( evt->getEventNumber() , i , " event number " ) ;
LCCollection* trkHits = evt->getCollection( "TrackerHits") ;
CellIDDecoder<TrackerHit> idDec( trkHits ) ;
for(int j=0;j<NHITS;j++) {
//std::cout << " testing hit " << j << std::endl ;
TrackerHit* trkHit = dynamic_cast<TrackerHit*>(trkHits->getElementAt(j)) ;
MYTEST( idDec(trkHit)[ ILDCellID0::subdet ] , ILDDetID::FTD , " cellID(trkHit) == ( ILDDetID::FTD ) " ) ;
MYTEST( idDec(trkHit)[ ILDCellID0::layer ] , j % 100 , " cellID(trkHit) == ( j % 100 ) " ) ;
MYTEST( idDec(trkHit)[ ILDCellID0::side ] , ILDDetID::bwd , " cellID(trkHit) == ( ILDDetID::bwd ) " ) ;
MYTEST( idDec(trkHit)[ ILDCellID0::module ] , j / 100 + 1 , " cellID(trkHit) == ( j / 100 + 1 ) " ) ;
MYTEST( idDec(trkHit)[ ILDCellID0::sensor ] , j % 4 , " cellID(trkHit) == ( j % 4 ) " ) ;
MYTEST( idDec(trkHit)["daqChannel"] , j*8 , " cellID(trkHit) == ( j*8 ) " ) ;
//std::cout << *trkHit << std::endl ;
MYTEST( trkHit->getEDep() , i*j*117. , "EDep" ) ;
// MYTEST( trkHit->getdEdx() , i*j*117. , "dEdx" ) ;
// remove float converstion and check what happens ;)
MYTEST( trkHit->getEDepError() , float((i+j)*.3) , "EDepError" ) ;
//MYTEST( trkHit->getEDepError() , (i+j)*.3 , "EDepError" ) ;
const double* pos = trkHit->getPosition() ;
MYTEST( pos[0] , i , " pos[0] " ) ;
MYTEST( pos[1] , j , " pos[1] " ) ;
MYTEST( pos[2] , i*j , " pos[2] " ) ;
const FloatVec& cov = trkHit->getCovMatrix() ;
MYTEST( cov[0] , i , " cov[0] " ) ;
MYTEST( cov[1] , j , " cov[1] " ) ;
MYTEST( cov[2] , i+j , " cov[2] " ) ;
}
}
lcRdr->close() ;
} catch( Exception &e ){
MYTEST.FAILED( e.what() );
}
return 0;
}
//=============================================================================
<|endoftext|> |
<commit_before>/// HEADER
#include <csapex/model/node_facade.h>
/// PROJECT
#include <csapex/model/node_handle.h>
#include <csapex/model/node_worker.h>
#include <csapex/model/node_state.h>
#include <csapex/msg/input_transition.h>
#include <csapex/msg/output_transition.h>
#include <csapex/signal/event.h>
#include <csapex/model/graph/vertex.h>
#include <csapex/model/node.h>
/// SYSTEM
#include <iostream>
#include <sstream>
using namespace csapex;
NodeFacade::NodeFacade(NodeHandlePtr nh, NodeWorkerPtr nw)
: NodeFacade(nh)
{
nw_ = nw;
observe(nw->start_profiling, [this](NodeWorker*) {
start_profiling(this);
});
observe(nw->stop_profiling, [this](NodeWorker*) {
stop_profiling(this);
});
observe(nw->destroyed, destroyed);
observe(nw->notification, notification);
observe(nw->messages_processed, messages_processed);
observe(nw->interval_start, [this](NodeWorker*, ActivityType type, std::shared_ptr<const Interval> stamp) {
interval_start(this, type, stamp);
});
observe(nw->interval_end, [this](NodeWorker*, std::shared_ptr<const Interval> stamp) {
interval_end(this, stamp);
});
}
NodeFacade::NodeFacade(NodeHandlePtr nh)
: nh_(nh)
{
observe(nh->connector_created, connector_created);
observe(nh->connector_removed, connector_removed);
observe(nh->node_state_changed, node_state_changed);
observe(nh->connection_in_prograss, connection_in_prograss);
observe(nh->connection_done, connection_done);
observe(nh->connection_start, connection_start);
observe(nh->parameters_changed, parameters_changed);
}
NodeFacade::~NodeFacade()
{
}
std::string NodeFacade::getType() const
{
return nh_->getType();
}
UUID NodeFacade::getUUID() const
{
return nh_->getUUID();
}
bool NodeFacade::isActive() const
{
return nh_->isActive();
}
bool NodeFacade::isProcessingEnabled() const
{
if(nw_) {
return nw_->isProcessingEnabled();
} else {
return false;
}
}
bool NodeFacade::isGraph() const
{
return nh_->isGraph();
}
AUUID NodeFacade::getSubgraphAUUID() const
{
return nh_->getSubgraphAUUID();
}
bool NodeFacade::isSource() const
{
return nh_->isSource();
}
bool NodeFacade::isSink() const
{
return nh_->isSink();
}
bool NodeFacade::isVariadic() const
{
return nh_->isVariadic();
}
bool NodeFacade::hasVariadicInputs() const
{
return nh_->hasVariadicInputs();
}
bool NodeFacade::hasVariadicOutputs() const
{
return nh_->hasVariadicOutputs();
}
bool NodeFacade::hasVariadicEvents() const
{
return nh_->hasVariadicEvents();
}
bool NodeFacade::hasVariadicSlots() const
{
return nh_->hasVariadicSlots();
}
NodeCharacteristics NodeFacade::getNodeCharacteristics() const
{
return nh_->getVertex()->getNodeCharacteristics();
}
bool NodeFacade::isProfiling() const
{
if(nw_) {
return nw_->isProfiling();
} else {
return false;
}
}
void NodeFacade::setProfiling(bool profiling)
{
if(nw_) {
nw_->setProfiling(profiling);
}
}
bool NodeFacade::isError() const
{
if(nw_) {
return nw_->isError();
} else {
return false;
}
}
ErrorState::ErrorLevel NodeFacade::errorLevel() const
{
if(nw_) {
return nw_->errorLevel();
} else {
return ErrorState::ErrorLevel::NONE;
}
}
std::string NodeFacade::errorMessage() const
{
if(nw_) {
return nw_->errorMessage();
} else {
return {};
}
}
ExecutionState NodeFacade::getExecutionState() const
{
if(nw_) {
return nw_->getExecutionState();
} else {
return ExecutionState::UNKNOWN;
}
}
std::string NodeFacade::getLabel() const
{
return nh_->getNodeState()->getLabel();
}
double NodeFacade::getExecutionFrequency() const
{
return nh_->getRate().getEffectiveFrequency();
}
double NodeFacade::getMaximumFrequency() const
{
return nh_->getNodeState()->getMaximumFrequency();
}
NodeHandlePtr NodeFacade::getNodeHandle()
{
return nh_;
}
NodeStatePtr NodeFacade::getNodeState() const
{
return nh_->getNodeState();
}
NodeStatePtr NodeFacade::getNodeStateCopy() const
{
return nh_->getNodeStateCopy();
}
GenericStateConstPtr NodeFacade::getParameterState() const
{
return nh_->getNode().lock()->getParameterStateClone();
}
ProfilerPtr NodeFacade::getProfiler()
{
if(nw_) {
return nw_->getProfiler();
} else {
return {};
}
}
std::string NodeFacade::getDebugDescription() const
{
OutputTransition* ot = nh_->getOutputTransition();
InputTransition* it = nh_->getInputTransition();
std::stringstream ss;
ss << ", source: ";
ss << (nh_->isSource() ? "yes" : "no");
ss << ", sink: ";
ss << (nh_->isSink() ? "yes" : "no");
ss << ", it: ";
ss << (it->isEnabled() ? "enabled" : "disabled");
ss << ", ot: ";
ss << (ot->isEnabled() ? "enabled" : "disabled");
ss << ", events: ";
bool events_enabled = true;
for(EventPtr e : nh_->getExternalEvents()){
if(!e->canReceiveToken()) {
events_enabled = false;
break;
}
}
ss << (events_enabled ? "enabled" : "disabled");
return ss.str();
}
std::string NodeFacade::getLoggerOutput(ErrorState::ErrorLevel level) const
{
if(NodePtr node = nh_->getNode().lock()){
switch(level) {
case ErrorState::ErrorLevel::ERROR:
return node->aerr.history().str();
case ErrorState::ErrorLevel::WARNING:
return node->awarn.history().str();
case ErrorState::ErrorLevel::NONE:
return node->ainfo.history().str();
}
}
return {};
}
bool NodeFacade::hasParameter(const std::string &name) const
{
if(auto node = nh_->getNode().lock()){
return node->hasParameter(name);
}
throw std::runtime_error("tried to check a parameter from an invalid node");
}
template <typename T>
T NodeFacade::readParameter(const std::string& name) const
{
if(auto node = nh_->getNode().lock()){
return node->readParameter<T>(name);
}
throw std::runtime_error("tried to read a parameter from an invalid node");
}
template <typename T>
void NodeFacade::setParameter(const std::string& name, const T& value)
{
if(auto node = nh_->getNode().lock()){
node->setParameter<T>(name, value);
}
throw std::runtime_error("tried to set a parameter from an invalid node");
}
template CSAPEX_EXPORT bool NodeFacade::readParameter<bool>(const std::string& name) const;
template CSAPEX_EXPORT double NodeFacade::readParameter<double>(const std::string& name) const;
template CSAPEX_EXPORT int NodeFacade::readParameter<int>(const std::string& name) const;
template CSAPEX_EXPORT std::string NodeFacade::readParameter<std::string>(const std::string& name) const;
template CSAPEX_EXPORT std::pair<int,int> NodeFacade::readParameter<std::pair<int,int> >(const std::string& name) const;
template CSAPEX_EXPORT std::pair<double,double> NodeFacade::readParameter<std::pair<double,double> >(const std::string& name) const;
template CSAPEX_EXPORT std::pair<std::string, bool> NodeFacade::readParameter<std::pair<std::string, bool> >(const std::string& name) const;
template CSAPEX_EXPORT std::vector<double> NodeFacade::readParameter<std::vector<double> >(const std::string& name) const;
template CSAPEX_EXPORT std::vector<int> NodeFacade::readParameter<std::vector<int> >(const std::string& name) const;
template CSAPEX_EXPORT void NodeFacade::setParameter<bool>(const std::string& name, const bool& value);
template CSAPEX_EXPORT void NodeFacade::setParameter<double>(const std::string& name, const double& value);
template CSAPEX_EXPORT void NodeFacade::setParameter<int>(const std::string& name, const int& value);
template CSAPEX_EXPORT void NodeFacade::setParameter<std::string>(const std::string& name, const std::string& value);
template CSAPEX_EXPORT void NodeFacade::setParameter<std::pair<int,int> > (const std::string& name, const std::pair<int,int>& value);
template CSAPEX_EXPORT void NodeFacade::setParameter<std::pair<double,double> >(const std::string& name, const std::pair<double,double>& value);
template CSAPEX_EXPORT void NodeFacade::setParameter<std::pair<std::string, bool> >(const std::string& name, const std::pair<std::string, bool>& value);
template CSAPEX_EXPORT void NodeFacade::setParameter<std::vector<int> >(const std::string& name, const std::vector<int>& value);
template CSAPEX_EXPORT void NodeFacade::setParameter<std::vector<double> >(const std::string& name, const std::vector<double>& value);
<commit_msg>bugfix<commit_after>/// HEADER
#include <csapex/model/node_facade.h>
/// PROJECT
#include <csapex/model/node_handle.h>
#include <csapex/model/node_worker.h>
#include <csapex/model/node_state.h>
#include <csapex/msg/input_transition.h>
#include <csapex/msg/output_transition.h>
#include <csapex/signal/event.h>
#include <csapex/model/graph/vertex.h>
#include <csapex/model/node.h>
/// SYSTEM
#include <iostream>
#include <sstream>
using namespace csapex;
NodeFacade::NodeFacade(NodeHandlePtr nh, NodeWorkerPtr nw)
: NodeFacade(nh)
{
nw_ = nw;
observe(nw->start_profiling, [this](NodeWorker*) {
start_profiling(this);
});
observe(nw->stop_profiling, [this](NodeWorker*) {
stop_profiling(this);
});
observe(nw->destroyed, destroyed);
observe(nw->notification, notification);
observe(nw->messages_processed, messages_processed);
observe(nw->interval_start, [this](NodeWorker*, ActivityType type, std::shared_ptr<const Interval> stamp) {
interval_start(this, type, stamp);
});
observe(nw->interval_end, [this](NodeWorker*, std::shared_ptr<const Interval> stamp) {
interval_end(this, stamp);
});
}
NodeFacade::NodeFacade(NodeHandlePtr nh)
: nh_(nh)
{
observe(nh->connector_created, connector_created);
observe(nh->connector_removed, connector_removed);
observe(nh->node_state_changed, node_state_changed);
observe(nh->connection_in_prograss, connection_in_prograss);
observe(nh->connection_done, connection_done);
observe(nh->connection_start, connection_start);
observe(nh->parameters_changed, parameters_changed);
}
NodeFacade::~NodeFacade()
{
}
std::string NodeFacade::getType() const
{
return nh_->getType();
}
UUID NodeFacade::getUUID() const
{
return nh_->getUUID();
}
bool NodeFacade::isActive() const
{
return nh_->isActive();
}
bool NodeFacade::isProcessingEnabled() const
{
if(nw_) {
return nw_->isProcessingEnabled();
} else {
return false;
}
}
bool NodeFacade::isGraph() const
{
return nh_->isGraph();
}
AUUID NodeFacade::getSubgraphAUUID() const
{
return nh_->getSubgraphAUUID();
}
bool NodeFacade::isSource() const
{
return nh_->isSource();
}
bool NodeFacade::isSink() const
{
return nh_->isSink();
}
bool NodeFacade::isVariadic() const
{
return nh_->isVariadic();
}
bool NodeFacade::hasVariadicInputs() const
{
return nh_->hasVariadicInputs();
}
bool NodeFacade::hasVariadicOutputs() const
{
return nh_->hasVariadicOutputs();
}
bool NodeFacade::hasVariadicEvents() const
{
return nh_->hasVariadicEvents();
}
bool NodeFacade::hasVariadicSlots() const
{
return nh_->hasVariadicSlots();
}
NodeCharacteristics NodeFacade::getNodeCharacteristics() const
{
return nh_->getVertex()->getNodeCharacteristics();
}
bool NodeFacade::isProfiling() const
{
if(nw_) {
return nw_->isProfiling();
} else {
return false;
}
}
void NodeFacade::setProfiling(bool profiling)
{
if(nw_) {
nw_->setProfiling(profiling);
}
}
bool NodeFacade::isError() const
{
if(nw_) {
return nw_->isError();
} else {
return false;
}
}
ErrorState::ErrorLevel NodeFacade::errorLevel() const
{
if(nw_) {
return nw_->errorLevel();
} else {
return ErrorState::ErrorLevel::NONE;
}
}
std::string NodeFacade::errorMessage() const
{
if(nw_) {
return nw_->errorMessage();
} else {
return {};
}
}
ExecutionState NodeFacade::getExecutionState() const
{
if(nw_) {
return nw_->getExecutionState();
} else {
return ExecutionState::UNKNOWN;
}
}
std::string NodeFacade::getLabel() const
{
return nh_->getNodeState()->getLabel();
}
double NodeFacade::getExecutionFrequency() const
{
return nh_->getRate().getEffectiveFrequency();
}
double NodeFacade::getMaximumFrequency() const
{
return nh_->getNodeState()->getMaximumFrequency();
}
NodeHandlePtr NodeFacade::getNodeHandle()
{
return nh_;
}
NodeStatePtr NodeFacade::getNodeState() const
{
return nh_->getNodeState();
}
NodeStatePtr NodeFacade::getNodeStateCopy() const
{
return nh_->getNodeStateCopy();
}
GenericStateConstPtr NodeFacade::getParameterState() const
{
return nh_->getNode().lock()->getParameterStateClone();
}
ProfilerPtr NodeFacade::getProfiler()
{
if(nw_) {
return nw_->getProfiler();
} else {
return {};
}
}
std::string NodeFacade::getDebugDescription() const
{
OutputTransition* ot = nh_->getOutputTransition();
InputTransition* it = nh_->getInputTransition();
std::stringstream ss;
ss << ", source: ";
ss << (nh_->isSource() ? "yes" : "no");
ss << ", sink: ";
ss << (nh_->isSink() ? "yes" : "no");
ss << ", it: ";
ss << (it->isEnabled() ? "enabled" : "disabled");
ss << ", ot: ";
ss << (ot->isEnabled() ? "enabled" : "disabled");
ss << ", events: ";
bool events_enabled = true;
for(EventPtr e : nh_->getExternalEvents()){
if(!e->canReceiveToken()) {
events_enabled = false;
break;
}
}
ss << (events_enabled ? "enabled" : "disabled");
return ss.str();
}
std::string NodeFacade::getLoggerOutput(ErrorState::ErrorLevel level) const
{
if(NodePtr node = nh_->getNode().lock()){
switch(level) {
case ErrorState::ErrorLevel::ERROR:
return node->aerr.history().str();
case ErrorState::ErrorLevel::WARNING:
return node->awarn.history().str();
case ErrorState::ErrorLevel::NONE:
return node->ainfo.history().str();
}
}
return {};
}
bool NodeFacade::hasParameter(const std::string &name) const
{
if(auto node = nh_->getNode().lock()){
return node->hasParameter(name);
}
throw std::runtime_error("tried to check a parameter from an invalid node");
}
template <typename T>
T NodeFacade::readParameter(const std::string& name) const
{
if(auto node = nh_->getNode().lock()){
return node->readParameter<T>(name);
}
throw std::runtime_error("tried to read a parameter from an invalid node");
}
template <typename T>
void NodeFacade::setParameter(const std::string& name, const T& value)
{
if(auto node = nh_->getNode().lock()){
node->setParameter<T>(name, value);
} else {
throw std::runtime_error("tried to set a parameter from an invalid node");
}
}
template CSAPEX_EXPORT bool NodeFacade::readParameter<bool>(const std::string& name) const;
template CSAPEX_EXPORT double NodeFacade::readParameter<double>(const std::string& name) const;
template CSAPEX_EXPORT int NodeFacade::readParameter<int>(const std::string& name) const;
template CSAPEX_EXPORT std::string NodeFacade::readParameter<std::string>(const std::string& name) const;
template CSAPEX_EXPORT std::pair<int,int> NodeFacade::readParameter<std::pair<int,int> >(const std::string& name) const;
template CSAPEX_EXPORT std::pair<double,double> NodeFacade::readParameter<std::pair<double,double> >(const std::string& name) const;
template CSAPEX_EXPORT std::pair<std::string, bool> NodeFacade::readParameter<std::pair<std::string, bool> >(const std::string& name) const;
template CSAPEX_EXPORT std::vector<double> NodeFacade::readParameter<std::vector<double> >(const std::string& name) const;
template CSAPEX_EXPORT std::vector<int> NodeFacade::readParameter<std::vector<int> >(const std::string& name) const;
template CSAPEX_EXPORT void NodeFacade::setParameter<bool>(const std::string& name, const bool& value);
template CSAPEX_EXPORT void NodeFacade::setParameter<double>(const std::string& name, const double& value);
template CSAPEX_EXPORT void NodeFacade::setParameter<int>(const std::string& name, const int& value);
template CSAPEX_EXPORT void NodeFacade::setParameter<std::string>(const std::string& name, const std::string& value);
template CSAPEX_EXPORT void NodeFacade::setParameter<std::pair<int,int> > (const std::string& name, const std::pair<int,int>& value);
template CSAPEX_EXPORT void NodeFacade::setParameter<std::pair<double,double> >(const std::string& name, const std::pair<double,double>& value);
template CSAPEX_EXPORT void NodeFacade::setParameter<std::pair<std::string, bool> >(const std::string& name, const std::pair<std::string, bool>& value);
template CSAPEX_EXPORT void NodeFacade::setParameter<std::vector<int> >(const std::string& name, const std::vector<int>& value);
template CSAPEX_EXPORT void NodeFacade::setParameter<std::vector<double> >(const std::string& name, const std::vector<double>& value);
<|endoftext|> |
<commit_before>#include <algorithm>
#include <iostream>
#include "boost/asio.hpp"
#include "google/protobuf/service.h"
#include "google/protobuf/descriptor.h"
#include "vtrc-bind.h"
#include "vtrc-function.h"
#include "vtrc-chrono.h"
#include "vtrc-common/vtrc-data-queue.h"
#include "vtrc-common/vtrc-hash-iface.h"
#include "vtrc-common/vtrc-transformer-iface.h"
#include "vtrc-common/vtrc-call-context.h"
#include "vtrc-common/vtrc-rpc-controller.h"
#include "vtrc-common/vtrc-random-device.h"
#include "vtrc-common/vtrc-transport-iface.h"
#include "vtrc-common/vtrc-lowlevel-protocol-iface.h"
#include "vtrc-common/vtrc-protocol-accessor-iface.h"
#include "vtrc-protocol-layer-c.h"
#include "vtrc-client.h"
#include "vtrc-auth.pb.h"
#include "vtrc-rpc-lowlevel.pb.h"
namespace vtrc { namespace client {
namespace gpb = google::protobuf;
typedef vtrc::function<void (const rpc::errors::container &,
const char *)> init_error_cb;
typedef common::lowlevel_protocol_layer_iface lowlevel_protocol_layer_iface;
lowlevel_protocol_layer_iface *create_default_setup( vtrc_client *c );
namespace {
typedef common::lowlevel_protocol_layer_iface connection_setup_iface;
typedef connection_setup_iface *connection_setup_ptr;
typedef vtrc::shared_ptr<rpc::lowlevel_unit> lowlevel_unit_sptr;
typedef vtrc::shared_ptr<gpb::Service> service_str;
enum protocol_stage {
STAGE_HELLO = 1
,STAGE_SETUP = 2
,STAGE_READY = 3
,STAGE_RPC = 4
};
//namespace default_cypher = common::transformers::chacha;
}
struct protocol_layer_c::impl: common::protocol_accessor {
typedef impl this_type;
typedef protocol_layer_c parent_type;
typedef vtrc::function<void (void)> stage_funcion_type;
common::transport_iface *connection_;
protocol_layer_c *parent_;
stage_funcion_type stage_call_;
vtrc_client *client_;
protocol_signals *callbacks_;
protocol_stage stage_;
bool closed_;
connection_setup_ptr conn_setup_;
impl( common::transport_iface *c, vtrc_client *client,
protocol_signals *cb )
:connection_(c)
,client_(client)
,callbacks_(cb)
,stage_(STAGE_HELLO)
,closed_(false)
{ }
//// ================ accessor =================
void call_setup_function( )
{
conn_setup_->do_handshake( );
}
void set_client_id( const std::string &id )
{
;;;
}
void error( const rpc::errors::container &err, const char *mes )
{
callbacks_->on_init_error( err, mes );
}
void write( const std::string &data,
common::system_closure_type cb,
bool on_send_success )
{
connection_->write( data.c_str( ), data.size( ),
cb, on_send_success );
}
common::connection_iface *connection( )
{
return connection_;
}
void ready( bool /*value*/ )
{
stage_call_ = vtrc::bind( &this_type::on_rpc_process, this );
on_ready( true );
}
void close( )
{
closed_ = true;
connection_->close( );
}
void configure_session( const vtrc::rpc::session_options &opts )
{
parent_->configure_session( opts );
}
//// ================ accessor =================
static void closure_none( const boost::system::error_code & )
{ }
void init( )
{
conn_setup_ = create_default_setup( client_ );
parent_->set_lowlevel( conn_setup_ );
stage_call_ = vtrc::bind( &this_type::call_setup_function, this );
conn_setup_->init( this, &this_type::closure_none );
}
rpc::errors::container create_error( unsigned code,
const std::string &add )
{
rpc::errors::container cont;
cont.set_code( code );
cont.set_category( rpc::errors::CATEGORY_INTERNAL );
cont.set_additional( add );
return cont;
}
const std::string &client_id( ) const
{
return client_->get_session_id( );
}
typedef common::rpc_service_wrapper_sptr wrapper_sptr;
wrapper_sptr get_service_by_name( const std::string &name )
{
vtrc::shared_ptr<gpb::Service> res(client_->get_rpc_handler(name));
if( res ) {
return wrapper_sptr (new common::rpc_service_wrapper( res ));
} else {
return wrapper_sptr( );
}
}
void send_proto_message( const gpb::MessageLite &mess ) const
{
std::string s(mess.SerializeAsString( ));
connection_->write(s.c_str( ), s.size( ) );
}
void send_proto_message( const gpb::MessageLite &mess,
common::system_closure_type closure,
bool on_send ) const
{
std::string s(mess.SerializeAsString( ));
connection_->write(s.c_str( ), s.size( ), closure, on_send );
}
void process_event_impl( vtrc_client_wptr client,
lowlevel_unit_sptr llu)
{
vtrc_client_sptr c(client.lock( ));
if( !c ) {
return;
}
parent_->make_local_call( llu );
}
void process_event( lowlevel_unit_sptr &llu )
{
if ( llu->id( ) != 0 ) {
client_->get_rpc_service( ).post(
vtrc::bind( &this_type::process_event_impl, this,
client_->weak_from_this( ), llu));
} else {
parent_->push_rpc_message_all( llu );
}
}
void process_service( lowlevel_unit_sptr &llu )
{
}
void process_internal( lowlevel_unit_sptr &llu )
{
}
void process_call( lowlevel_unit_sptr &llu )
{
parent_->push_rpc_message( llu->id( ), llu );
}
void process_callback( lowlevel_unit_sptr &llu )
{
parent_->push_rpc_message( llu->target_id( ), llu );
}
void process_invalid( lowlevel_unit_sptr &llu )
{
}
void on_ready( bool ready )
{
parent_->set_ready( ready );
callbacks_->on_ready( );
}
void on_rpc_process( )
{
while( !parent_->message_queue_empty( ) ) {
lowlevel_unit_sptr llu(vtrc::make_shared<lowlevel_unit_type>());
bool check = parent_->parse_and_pop( *llu );
if( !check ) {
llu->Clear( );
rpc::errors::container *err = llu->mutable_error( );
err->set_code( rpc::errors::ERR_PROTOCOL);
err->set_additional("Bad message was received");
err->set_fatal( true );
parent_->push_rpc_message_all( llu );
connection_->close( );
return;
}
switch( llu->info( ).message_type( ) ) {
/// SERVER_CALL = request; do not use id
case rpc::message_info::MESSAGE_SERVER_CALL:
process_event( llu );
break;
/// SERVER_CALLBACK = request; use target_id
case rpc::message_info::MESSAGE_SERVER_CALLBACK:
process_callback( llu );
break;
/// internals; not implemented yet
case rpc::message_info::MESSAGE_SERVICE:
process_service( llu );
break;
case rpc::message_info::MESSAGE_INTERNAL:
process_internal( llu );
break;
/// answers; use id
case rpc::message_info::MESSAGE_CLIENT_CALL:
case rpc::message_info::MESSAGE_CLIENT_CALLBACK:
process_call( llu );
break;
default:
process_invalid( llu );
}
}
}
static bool server_has_transformer( rpc::auth::init_capsule const &cap,
unsigned transformer_type )
{
rpc::auth::init_protocol init;
init.ParseFromString( cap.body( ) );
return std::find( init.transform_supported( ).begin( ),
init.transform_supported( ).end( ),
transformer_type ) != init.transform_supported( ).end( );
}
void data_ready( )
{
stage_call_( );
}
void drop_service( const std::string &name )
{
client_->erase_rpc_handler( name );
}
void drop_all_services( )
{
client_->erase_all_rpc_handlers( );
}
};
protocol_layer_c::protocol_layer_c(common::transport_iface *connection,
vtrc::client::vtrc_client *client ,
protocol_signals *callbacks)
:common::protocol_layer(connection, true)
,impl_(new impl(connection, client, callbacks))
{
impl_->parent_ = this;
}
protocol_layer_c::~protocol_layer_c( )
{
delete impl_;
}
void protocol_layer_c::init( )
{
impl_->init( );
}
void protocol_layer_c::close( )
{
impl_->conn_setup_->close( );
cancel_all_slots( );
impl_->callbacks_->on_disconnect( );
}
const std::string &protocol_layer_c::client_id( ) const
{
return impl_->client_id( );
}
void protocol_layer_c::on_data_ready( )
{
impl_->data_ready( );
}
void protocol_layer_c::on_init_error( const rpc::errors::container &error,
const char *message )
{
impl_->callbacks_->on_init_error( error, message );
}
common::rpc_service_wrapper_sptr protocol_layer_c::get_service_by_name(
const std::string &name)
{
return impl_->get_service_by_name( name );
}
void protocol_layer_c::drop_service( const std::string &name )
{
impl_->drop_service( name );
}
void protocol_layer_c::drop_all_services( )
{
impl_->drop_all_services( );
}
}}
<commit_msg>lowlevel_processor interface<commit_after>#include <algorithm>
#include <iostream>
#include "boost/asio.hpp"
#include "google/protobuf/service.h"
#include "google/protobuf/descriptor.h"
#include "vtrc-bind.h"
#include "vtrc-function.h"
#include "vtrc-chrono.h"
#include "vtrc-common/vtrc-data-queue.h"
#include "vtrc-common/vtrc-hash-iface.h"
#include "vtrc-common/vtrc-transformer-iface.h"
#include "vtrc-common/vtrc-call-context.h"
#include "vtrc-common/vtrc-rpc-controller.h"
#include "vtrc-common/vtrc-random-device.h"
#include "vtrc-common/vtrc-transport-iface.h"
#include "vtrc-common/vtrc-lowlevel-protocol-iface.h"
#include "vtrc-common/vtrc-protocol-accessor-iface.h"
#include "vtrc-protocol-layer-c.h"
#include "vtrc-client.h"
#include "vtrc-auth.pb.h"
#include "vtrc-rpc-lowlevel.pb.h"
namespace vtrc { namespace client {
namespace gpb = google::protobuf;
typedef vtrc::function<void (const rpc::errors::container &,
const char *)> init_error_cb;
typedef common::lowlevel_protocol_layer_iface lowlevel_protocol_layer_iface;
lowlevel_protocol_layer_iface *create_default_setup( vtrc_client *c );
namespace {
typedef common::lowlevel_protocol_layer_iface connection_setup_iface;
typedef connection_setup_iface *connection_setup_ptr;
typedef vtrc::shared_ptr<rpc::lowlevel_unit> lowlevel_unit_sptr;
typedef vtrc::shared_ptr<gpb::Service> service_str;
enum protocol_stage {
STAGE_HELLO = 1
,STAGE_SETUP = 2
,STAGE_READY = 3
,STAGE_RPC = 4
};
//namespace default_cypher = common::transformers::chacha;
}
struct protocol_layer_c::impl: common::protocol_accessor {
typedef impl this_type;
typedef protocol_layer_c parent_type;
typedef vtrc::function<void (void)> stage_funcion_type;
common::transport_iface *connection_;
protocol_layer_c *parent_;
stage_funcion_type stage_call_;
vtrc_client *client_;
protocol_signals *callbacks_;
protocol_stage stage_;
bool closed_;
connection_setup_ptr conn_setup_;
impl( common::transport_iface *c, vtrc_client *client,
protocol_signals *cb )
:connection_(c)
,client_(client)
,callbacks_(cb)
,stage_(STAGE_HELLO)
,closed_(false)
{ }
//// ================ accessor =================
void call_setup_function( )
{
conn_setup_->do_handshake( );
}
void set_client_id( const std::string &id )
{
;;;
}
void error( const rpc::errors::container &err, const char *mes )
{
callbacks_->on_init_error( err, mes );
}
void write( const std::string &data,
common::system_closure_type cb,
bool on_send_success )
{
connection_->write( data.c_str( ), data.size( ),
cb, on_send_success );
}
common::connection_iface *connection( )
{
return connection_;
}
void ready( bool /*value*/ )
{
stage_call_ = vtrc::bind( &this_type::on_rpc_process, this );
on_ready( true );
}
void close( )
{
closed_ = true;
connection_->close( );
}
void configure_session( const vtrc::rpc::session_options &opts )
{
parent_->configure_session( opts );
}
//// ================ accessor =================
static void closure_none( const boost::system::error_code & )
{ }
void init( )
{
conn_setup_ = create_default_setup( client_ );
parent_->set_lowlevel( conn_setup_ );
stage_call_ = vtrc::bind( &this_type::call_setup_function, this );
conn_setup_->init( this, &this_type::closure_none );
}
rpc::errors::container create_error( unsigned code,
const std::string &add )
{
rpc::errors::container cont;
cont.set_code( code );
cont.set_category( rpc::errors::CATEGORY_INTERNAL );
cont.set_additional( add );
return cont;
}
const std::string &client_id( ) const
{
return client_->get_session_id( );
}
typedef common::rpc_service_wrapper_sptr wrapper_sptr;
wrapper_sptr get_service_by_name( const std::string &name )
{
vtrc::shared_ptr<gpb::Service> res(client_->get_rpc_handler(name));
if( res ) {
return wrapper_sptr (new common::rpc_service_wrapper( res ));
} else {
return wrapper_sptr( );
}
}
void send_proto_message( const gpb::MessageLite &mess ) const
{
std::string s(mess.SerializeAsString( ));
connection_->write(s.c_str( ), s.size( ) );
}
void send_proto_message( const gpb::MessageLite &mess,
common::system_closure_type closure,
bool on_send ) const
{
std::string s(mess.SerializeAsString( ));
connection_->write(s.c_str( ), s.size( ), closure, on_send );
}
void process_event_impl( vtrc_client_wptr client,
lowlevel_unit_sptr llu)
{
vtrc_client_sptr c(client.lock( ));
if( !c ) {
return;
}
parent_->make_local_call( llu );
}
void process_event( lowlevel_unit_sptr &llu )
{
if ( llu->id( ) != 0 ) {
client_->get_rpc_service( ).post(
vtrc::bind( &this_type::process_event_impl, this,
client_->weak_from_this( ), llu));
} else {
parent_->push_rpc_message_all( llu );
}
}
void process_service( lowlevel_unit_sptr &llu )
{
}
void process_internal( lowlevel_unit_sptr &llu )
{
}
void process_call( lowlevel_unit_sptr &llu )
{
parent_->push_rpc_message( llu->id( ), llu );
}
void process_callback( lowlevel_unit_sptr &llu )
{
parent_->push_rpc_message( llu->target_id( ), llu );
}
void process_invalid( lowlevel_unit_sptr &llu )
{
}
void on_ready( bool ready )
{
parent_->set_ready( ready );
callbacks_->on_ready( );
}
void on_rpc_process( )
{
while( !parent_->message_queue_empty( ) ) {
lowlevel_unit_sptr llu(vtrc::make_shared<lowlevel_unit_type>());
bool check = parent_->parse_and_pop( *llu );
if( !check ) {
llu->Clear( );
rpc::errors::container *err = llu->mutable_error( );
err->set_code( rpc::errors::ERR_PROTOCOL);
err->set_additional("Bad message was received");
err->set_fatal( true );
parent_->push_rpc_message_all( llu );
connection_->close( );
return;
}
switch( llu->info( ).message_type( ) ) {
/// SERVER_CALL = request; do not use id
case rpc::message_info::MESSAGE_SERVER_CALL:
process_event( llu );
break;
/// SERVER_CALLBACK = request; use target_id
case rpc::message_info::MESSAGE_SERVER_CALLBACK:
process_callback( llu );
break;
/// internals; not implemented yet
case rpc::message_info::MESSAGE_SERVICE:
process_service( llu );
break;
case rpc::message_info::MESSAGE_INTERNAL:
process_internal( llu );
break;
/// answers; use id
case rpc::message_info::MESSAGE_CLIENT_CALL:
case rpc::message_info::MESSAGE_CLIENT_CALLBACK:
process_call( llu );
break;
default:
process_invalid( llu );
}
}
}
static bool server_has_transformer( rpc::auth::init_capsule const &cap,
unsigned transformer_type )
{
rpc::auth::init_protocol init;
init.ParseFromString( cap.body( ) );
return std::find( init.transform_supported( ).begin( ),
init.transform_supported( ).end( ),
transformer_type ) != init.transform_supported( ).end( );
}
void data_ready( )
{
stage_call_( );
}
void drop_service( const std::string &name )
{
client_->erase_rpc_handler( name );
}
void drop_all_services( )
{
client_->erase_all_rpc_handlers( );
}
};
protocol_layer_c::protocol_layer_c(common::transport_iface *connection,
vtrc::client::vtrc_client *client ,
protocol_signals *callbacks)
:common::protocol_layer(connection, true)
,impl_(new impl(connection, client, callbacks))
{
impl_->parent_ = this;
}
protocol_layer_c::~protocol_layer_c( )
{
delete impl_;
}
void protocol_layer_c::init( )
{
impl_->init( );
}
void protocol_layer_c::close( )
{
impl_->conn_setup_->close( );
cancel_all_slots( );
impl_->callbacks_->on_disconnect( );
}
const std::string &protocol_layer_c::client_id( ) const
{
return impl_->client_id( );
}
void protocol_layer_c::on_data_ready( )
{
impl_->data_ready( );
}
void protocol_layer_c::on_init_error( const rpc::errors::container &error,
const char *message )
{
impl_->callbacks_->on_init_error( error, message );
}
common::rpc_service_wrapper_sptr protocol_layer_c::get_service_by_name(
const std::string &name)
{
return impl_->get_service_by_name( name );
}
void protocol_layer_c::drop_service( const std::string &name )
{
impl_->drop_service( name );
}
void protocol_layer_c::drop_all_services( )
{
impl_->drop_all_services( );
}
}}
<|endoftext|> |
<commit_before>//
// RemotePhotoTool - remote camera control software
// Copyright (C) 2008-2014 Michael Fink
//
/// \file BulbReleaseControl.hpp Canon control - Release control for Bulb mode
//
#pragma once
// includes
/// \brief bulb shutter release control
/// this object is created by RemoteReleaseControl::StartBulb; just destroy it to stop bulb mode
class BulbReleaseControl
{
public:
/// dtor
virtual ~BulbReleaseControl() throw() {}
/// returns elapsed time, in seconds, since bulb start
virtual double ElapsedTime() const throw() = 0;
/// stops bulb method; can be used when the shared_ptr<BulbReleaseControl>
/// cannot be destroyed, e.g. since it is held somewhere (e.g. Lua)
virtual void Stop() throw() = 0;
};
<commit_msg>fixed xml in doxygen comment<commit_after>//
// RemotePhotoTool - remote camera control software
// Copyright (C) 2008-2014 Michael Fink
//
/// \file BulbReleaseControl.hpp Canon control - Release control for Bulb mode
//
#pragma once
// includes
/// \brief bulb shutter release control
/// this object is created by RemoteReleaseControl::StartBulb; just destroy it to stop bulb mode
class BulbReleaseControl
{
public:
/// dtor
virtual ~BulbReleaseControl() throw() {}
/// returns elapsed time, in seconds, since bulb start
virtual double ElapsedTime() const throw() = 0;
/// stops bulb method; can be used when the shared_ptr of BulbReleaseControl
/// cannot be destroyed, e.g. since it is held somewhere (e.g. Lua)
virtual void Stop() throw() = 0;
};
<|endoftext|> |
<commit_before>////////////////////////////////////////////////////////////////////////////////
// Name: test-printing.cpp
// Purpose: Implementation for wxExtension cpp unit testing
// Author: Anton van Wezenbeek
// Copyright: (c) 2015 Anton van Wezenbeek
////////////////////////////////////////////////////////////////////////////////
#include <wx/wxprec.h>
#ifndef WX_PRECOMP
#include <wx/wx.h>
#endif
#include <wx/extension/printing.h>
#include <wx/extension/managedframe.h>
#include <wx/extension/stc.h>
#include "test.h"
void fixture::testPrinting()
{
CPPUNIT_ASSERT(wxExPrinting::Get() != NULL);
CPPUNIT_ASSERT(wxExPrinting::Get()->GetPrinter() != NULL);
CPPUNIT_ASSERT(wxExPrinting::Get()->GetHtmlPrinter() != NULL);
wxExPrinting* old = wxExPrinting::Get();
CPPUNIT_ASSERT(wxExPrinting::Get()->Set(NULL) == old);
CPPUNIT_ASSERT(wxExPrinting::Get(false) == NULL);
CPPUNIT_ASSERT(wxExPrinting::Get(true) != NULL);
wxExSTC* stc = new wxExSTC(m_Frame, "hello printing");
new wxExPrintout(stc);
stc->Print(false);
// stc->PrintPreview(wxPreviewFrame_NonModal);
}
<commit_msg>outcommented print as well<commit_after>////////////////////////////////////////////////////////////////////////////////
// Name: test-printing.cpp
// Purpose: Implementation for wxExtension cpp unit testing
// Author: Anton van Wezenbeek
// Copyright: (c) 2015 Anton van Wezenbeek
////////////////////////////////////////////////////////////////////////////////
#include <wx/wxprec.h>
#ifndef WX_PRECOMP
#include <wx/wx.h>
#endif
#include <wx/extension/printing.h>
#include <wx/extension/managedframe.h>
#include <wx/extension/stc.h>
#include "test.h"
void fixture::testPrinting()
{
CPPUNIT_ASSERT(wxExPrinting::Get() != NULL);
CPPUNIT_ASSERT(wxExPrinting::Get()->GetPrinter() != NULL);
CPPUNIT_ASSERT(wxExPrinting::Get()->GetHtmlPrinter() != NULL);
wxExPrinting* old = wxExPrinting::Get();
CPPUNIT_ASSERT(wxExPrinting::Get()->Set(NULL) == old);
CPPUNIT_ASSERT(wxExPrinting::Get(false) == NULL);
CPPUNIT_ASSERT(wxExPrinting::Get(true) != NULL);
wxExSTC* stc = new wxExSTC(m_Frame, "hello printing");
new wxExPrintout(stc);
// stc->Print(false);
// stc->PrintPreview(wxPreviewFrame_NonModal);
}
<|endoftext|> |
<commit_before>/* +---------------------------------------------------------------------------+
| The Mobile Robot Programming Toolkit (MRPT) |
| |
| http://www.mrpt.org/ |
| |
| Copyright (c) 2005-2013, Individual contributors, see AUTHORS file |
| Copyright (c) 2005-2013, MAPIR group, University of Malaga |
| Copyright (c) 2012-2013, University of Almeria |
| All rights reserved. |
| |
| Redistribution and use in source and binary forms, with or without |
| modification, are permitted provided that the following conditions are |
| met: |
| * Redistributions of source code must retain the above copyright |
| notice, this list of conditions and the following disclaimer. |
| * Redistributions in binary form must reproduce the above copyright |
| notice, this list of conditions and the following disclaimer in the |
| documentation and/or other materials provided with the distribution. |
| * Neither the name of the copyright holders nor the |
| names of its contributors may be used to endorse or promote products |
| derived from this software without specific prior written permission.|
| |
| THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS |
| 'AS IS' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED |
| TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR|
| PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS 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 <mrpt/srba.h>
#include <mrpt/gui.h> // For rendering results as a 3D scene
#include <mrpt/random.h>
#include <gtest/gtest.h>
using namespace mrpt::srba;
using namespace mrpt::random;
using namespace std;
using namespace mrpt::srba;
using namespace mrpt::random;
using namespace std;
// --------------------------------------------------------------------------------
// Declare a typedef "my_srba_t" for easily referring to my RBA problem type:
// --------------------------------------------------------------------------------
typedef RbaEngine<
kf2kf_poses::SE3, // Parameterization KF-to-KF poses
landmarks::Euclidean3D, // Parameterization of landmark positions
observations::Cartesian_3D // Type of observations
>
my_srba_t;
// --------------------------------------------------------------------------------
// A test dataset. Generated with http://code.google.com/p/recursive-world-toolkit/
// and the script: tutorials_dataset-cartesian.cfg
// --------------------------------------------------------------------------------
struct basic_euclidean_dataset_entry_t
{
unsigned int landmark_id;
double x,y,z;
};
basic_euclidean_dataset_entry_t dummy_obs[] = {
{ 0, 5 , 4 , 3 },
{ 1, 1 , 7 , 8 },
{ 2, -2 ,-3 , -1 },
{ 3, 4 , -2, 9 },
};
template <bool INVERSE_INCR>
void run_test(const mrpt::poses::CPose3D &incr)
{
my_srba_t rba; // Create an empty RBA problem
rba.get_time_profiler().disable();
// --------------------------------------------------------------------------------
// Set parameters
// --------------------------------------------------------------------------------
rba.setVerbosityLevel( 0 ); // 0: None; 1:Important only; 2:Verbose
rba.parameters.srba.use_robust_kernel = false;
// =========== Topology parameters ===========
rba.parameters.srba.edge_creation_policy = mrpt::srba::ecpICRA2013;
rba.parameters.srba.max_tree_depth = 3;
rba.parameters.srba.max_optimize_depth = 3;
// ===========================================
// --------------------------------------------------------------------------------
// Define observations of KF #0:
// --------------------------------------------------------------------------------
my_srba_t::new_kf_observations_t list_obs;
my_srba_t::new_kf_observation_t obs_field;
obs_field.is_fixed = false; // Landmarks have unknown relative positions (i.e. treat them as unknowns to be estimated)
obs_field.is_unknown_with_init_val = false; // We don't have any guess on the initial LM position (will invoke the inverse sensor model)
for (size_t i=0;i<sizeof(dummy_obs)/sizeof(dummy_obs[0]);i++)
{
obs_field.obs.feat_id = dummy_obs[i].landmark_id;
obs_field.obs.obs_data.pt.x = dummy_obs[i].x;
obs_field.obs.obs_data.pt.y = dummy_obs[i].y;
obs_field.obs.obs_data.pt.z = dummy_obs[i].z;
list_obs.push_back( obs_field );
}
// Here happens the main stuff: create Key-frames, build structures, run optimization, etc.
// ============================================================================================
my_srba_t::TNewKeyFrameInfo new_kf_info;
rba.define_new_keyframe(
list_obs, // Input observations for the new KF
new_kf_info, // Output info
true // Also run local optimization?
);
// --------------------------------------------------------------------------------
// Define observations of next KF:
// --------------------------------------------------------------------------------
list_obs.clear();
for (size_t i=0;i<sizeof(dummy_obs)/sizeof(dummy_obs[0]);i++)
{
obs_field.obs.feat_id = dummy_obs[i].landmark_id;
obs_field.obs.obs_data.pt.x = dummy_obs[i].x;
obs_field.obs.obs_data.pt.y = dummy_obs[i].y;
obs_field.obs.obs_data.pt.z = dummy_obs[i].z;
if (INVERSE_INCR)
incr.inverseComposePoint(
obs_field.obs.obs_data.pt.x, obs_field.obs.obs_data.pt.y, obs_field.obs.obs_data.pt.z,
obs_field.obs.obs_data.pt.x, obs_field.obs.obs_data.pt.y, obs_field.obs.obs_data.pt.z);
else
incr.composePoint(obs_field.obs.obs_data.pt, obs_field.obs.obs_data.pt);
list_obs.push_back( obs_field );
}
// Here happens the main stuff: create Key-frames, build structures, run optimization, etc.
// ============================================================================================
rba.define_new_keyframe(
list_obs, // Input observations for the new KF
new_kf_info, // Output info
true // Also run local optimization?
);
mrpt::poses::CPose3D estIncr = rba.get_k2k_edges()[0].inv_pose;
if (INVERSE_INCR)
estIncr.inverse();
EXPECT_NEAR( (incr.getHomogeneousMatrixVal()-estIncr.getHomogeneousMatrixVal()).array().abs().sum(),0, 1e-3)
<< "=> Ground truth: " << incr << " Inverse: " << (INVERSE_INCR ? "YES":"NO") << endl
<< "=> inv_pose of KF-to-KF edge #0 (relative pose of KF#0 wrt KF#1):\n" << estIncr << endl
<< "=> Optimization error: " << new_kf_info.optimize_results.total_sqr_error_init << " -> " << new_kf_info.optimize_results.total_sqr_error_final << endl;
}
const double test_fixed_transfs[][6] = {
{ 0, 0, 0, DEG2RAD(0), DEG2RAD(0), DEG2RAD(0) },
//
{ 1, 0, 0, DEG2RAD(0), DEG2RAD(0), DEG2RAD(0) },
{ 0, 1, 0, DEG2RAD(0), DEG2RAD(0), DEG2RAD(0) },
{ 0, 0, 1, DEG2RAD(0), DEG2RAD(0), DEG2RAD(0) },
//
{-1, 0, 0, DEG2RAD(0), DEG2RAD(0), DEG2RAD(0) },
{ 0, -1, 0, DEG2RAD(0), DEG2RAD(0), DEG2RAD(0) },
{ 0, 0, -1, DEG2RAD(0), DEG2RAD(0), DEG2RAD(0) },
// 45deg
{ 0, 0, 0, DEG2RAD(45), DEG2RAD(0), DEG2RAD(0) },
{ 0, 0, 0, DEG2RAD(0), DEG2RAD(45), DEG2RAD(0) },
{ 0, 0, 0, DEG2RAD(0), DEG2RAD(0), DEG2RAD(45) },
// -45deg
{ 0, 0, 0, DEG2RAD(-45), DEG2RAD(0), DEG2RAD(0) },
{ 0, 0, 0, DEG2RAD(0), DEG2RAD(-45), DEG2RAD(0) },
{ 0, 0, 0, DEG2RAD(0), DEG2RAD(0), DEG2RAD(-45) },
// 90 deg
{ 0, 0, 0, DEG2RAD(90), DEG2RAD(0), DEG2RAD(0) },
{ 0, 0, 0, DEG2RAD(0), DEG2RAD(90), DEG2RAD(0) },
{ 0, 0, 0, DEG2RAD(0), DEG2RAD(0), DEG2RAD(90) },
// -90deg
{ 0, 0, 0, DEG2RAD(-90), DEG2RAD(0), DEG2RAD(0) },
{ 0, 0, 0, DEG2RAD(0), DEG2RAD(-90), DEG2RAD(0) },
{ 0, 0, 0, DEG2RAD(0), DEG2RAD(0), DEG2RAD(-90) },
// 45deg+displ
{ 1, 2, 3, DEG2RAD(45), DEG2RAD(0), DEG2RAD(0) },
{ 1, 2, 3, DEG2RAD(0), DEG2RAD(45), DEG2RAD(0) },
{ 1, 2, 3, DEG2RAD(0), DEG2RAD(0), DEG2RAD(45) },
// full 6D
{ 1, 2, 3, DEG2RAD(10), DEG2RAD(20), DEG2RAD(30) },
};
TEST(MiniProblems,FixedTransformations)
{
for (size_t i=0;i<sizeof(test_fixed_transfs)/sizeof(test_fixed_transfs[0]);i++)
{
const double *p = test_fixed_transfs[i];
const mrpt::poses::CPose3D incr(p[0],p[1],p[2],p[3],p[4],p[5]);
run_test<false>(incr);
run_test<true>(incr);
}
}
<commit_msg>fixed srba unit test for msvc9+x32<commit_after>/* +---------------------------------------------------------------------------+
| The Mobile Robot Programming Toolkit (MRPT) |
| |
| http://www.mrpt.org/ |
| |
| Copyright (c) 2005-2013, Individual contributors, see AUTHORS file |
| Copyright (c) 2005-2013, MAPIR group, University of Malaga |
| Copyright (c) 2012-2013, University of Almeria |
| All rights reserved. |
| |
| Redistribution and use in source and binary forms, with or without |
| modification, are permitted provided that the following conditions are |
| met: |
| * Redistributions of source code must retain the above copyright |
| notice, this list of conditions and the following disclaimer. |
| * Redistributions in binary form must reproduce the above copyright |
| notice, this list of conditions and the following disclaimer in the |
| documentation and/or other materials provided with the distribution. |
| * Neither the name of the copyright holders nor the |
| names of its contributors may be used to endorse or promote products |
| derived from this software without specific prior written permission.|
| |
| THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS |
| 'AS IS' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED |
| TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR|
| PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS 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 <mrpt/srba.h>
#include <mrpt/gui.h> // For rendering results as a 3D scene
#include <mrpt/random.h>
#include <gtest/gtest.h>
using namespace mrpt::srba;
using namespace mrpt::random;
using namespace std;
using namespace mrpt::srba;
using namespace mrpt::random;
using namespace std;
// --------------------------------------------------------------------------------
// Declare a typedef "my_srba_t" for easily referring to my RBA problem type:
// --------------------------------------------------------------------------------
typedef RbaEngine<
kf2kf_poses::SE3, // Parameterization KF-to-KF poses
landmarks::Euclidean3D, // Parameterization of landmark positions
observations::Cartesian_3D // Type of observations
>
my_srba_t;
// --------------------------------------------------------------------------------
// A test dataset. Generated with http://code.google.com/p/recursive-world-toolkit/
// and the script: tutorials_dataset-cartesian.cfg
// --------------------------------------------------------------------------------
struct basic_euclidean_dataset_entry_t
{
unsigned int landmark_id;
double x,y,z;
};
basic_euclidean_dataset_entry_t dummy_obs[] = {
{ 0, 5 , 4 , 3 },
{ 1, 1 , 7 , 8 },
{ 2, -2 ,-3 , -1 },
{ 3, 4 , -2, 9 },
};
template <bool INVERSE_INCR>
void run_test(const mrpt::poses::CPose3D &incr)
{
my_srba_t rba; // Create an empty RBA problem
rba.get_time_profiler().disable();
// --------------------------------------------------------------------------------
// Set parameters
// --------------------------------------------------------------------------------
rba.setVerbosityLevel( 0 ); // 0: None; 1:Important only; 2:Verbose
rba.parameters.srba.use_robust_kernel = false;
// =========== Topology parameters ===========
rba.parameters.srba.edge_creation_policy = mrpt::srba::ecpICRA2013;
rba.parameters.srba.max_tree_depth = 3;
rba.parameters.srba.max_optimize_depth = 3;
// ===========================================
// --------------------------------------------------------------------------------
// Define observations of KF #0:
// --------------------------------------------------------------------------------
my_srba_t::new_kf_observations_t list_obs;
my_srba_t::new_kf_observation_t obs_field;
obs_field.is_fixed = false; // Landmarks have unknown relative positions (i.e. treat them as unknowns to be estimated)
obs_field.is_unknown_with_init_val = false; // We don't have any guess on the initial LM position (will invoke the inverse sensor model)
for (size_t i=0;i<sizeof(dummy_obs)/sizeof(dummy_obs[0]);i++)
{
obs_field.obs.feat_id = dummy_obs[i].landmark_id;
obs_field.obs.obs_data.pt.x = dummy_obs[i].x;
obs_field.obs.obs_data.pt.y = dummy_obs[i].y;
obs_field.obs.obs_data.pt.z = dummy_obs[i].z;
list_obs.push_back( obs_field );
}
// Here happens the main stuff: create Key-frames, build structures, run optimization, etc.
// ============================================================================================
my_srba_t::TNewKeyFrameInfo new_kf_info;
rba.define_new_keyframe(
list_obs, // Input observations for the new KF
new_kf_info, // Output info
true // Also run local optimization?
);
// --------------------------------------------------------------------------------
// Define observations of next KF:
// --------------------------------------------------------------------------------
list_obs.clear();
for (size_t i=0;i<sizeof(dummy_obs)/sizeof(dummy_obs[0]);i++)
{
obs_field.obs.feat_id = dummy_obs[i].landmark_id;
obs_field.obs.obs_data.pt.x = dummy_obs[i].x;
obs_field.obs.obs_data.pt.y = dummy_obs[i].y;
obs_field.obs.obs_data.pt.z = dummy_obs[i].z;
if (INVERSE_INCR)
incr.inverseComposePoint(
obs_field.obs.obs_data.pt.x, obs_field.obs.obs_data.pt.y, obs_field.obs.obs_data.pt.z,
obs_field.obs.obs_data.pt.x, obs_field.obs.obs_data.pt.y, obs_field.obs.obs_data.pt.z);
else
incr.composePoint(obs_field.obs.obs_data.pt, obs_field.obs.obs_data.pt);
list_obs.push_back( obs_field );
}
// Here happens the main stuff: create Key-frames, build structures, run optimization, etc.
// ============================================================================================
rba.define_new_keyframe(
list_obs, // Input observations for the new KF
new_kf_info, // Output info
true // Also run local optimization?
);
mrpt::poses::CPose3D estIncr = rba.get_k2k_edges()[0]
#ifdef SRBA_WORKAROUND_MSVC9_DEQUE_BUG
->
#else
.
#endif
inv_pose;
if (INVERSE_INCR)
estIncr.inverse();
EXPECT_NEAR( (incr.getHomogeneousMatrixVal()-estIncr.getHomogeneousMatrixVal()).array().abs().sum(),0, 1e-3)
<< "=> Ground truth: " << incr << " Inverse: " << (INVERSE_INCR ? "YES":"NO") << endl
<< "=> inv_pose of KF-to-KF edge #0 (relative pose of KF#0 wrt KF#1):\n" << estIncr << endl
<< "=> Optimization error: " << new_kf_info.optimize_results.total_sqr_error_init << " -> " << new_kf_info.optimize_results.total_sqr_error_final << endl;
}
const double test_fixed_transfs[][6] = {
{ 0, 0, 0, DEG2RAD(0), DEG2RAD(0), DEG2RAD(0) },
//
{ 1, 0, 0, DEG2RAD(0), DEG2RAD(0), DEG2RAD(0) },
{ 0, 1, 0, DEG2RAD(0), DEG2RAD(0), DEG2RAD(0) },
{ 0, 0, 1, DEG2RAD(0), DEG2RAD(0), DEG2RAD(0) },
//
{-1, 0, 0, DEG2RAD(0), DEG2RAD(0), DEG2RAD(0) },
{ 0, -1, 0, DEG2RAD(0), DEG2RAD(0), DEG2RAD(0) },
{ 0, 0, -1, DEG2RAD(0), DEG2RAD(0), DEG2RAD(0) },
// 45deg
{ 0, 0, 0, DEG2RAD(45), DEG2RAD(0), DEG2RAD(0) },
{ 0, 0, 0, DEG2RAD(0), DEG2RAD(45), DEG2RAD(0) },
{ 0, 0, 0, DEG2RAD(0), DEG2RAD(0), DEG2RAD(45) },
// -45deg
{ 0, 0, 0, DEG2RAD(-45), DEG2RAD(0), DEG2RAD(0) },
{ 0, 0, 0, DEG2RAD(0), DEG2RAD(-45), DEG2RAD(0) },
{ 0, 0, 0, DEG2RAD(0), DEG2RAD(0), DEG2RAD(-45) },
// 90 deg
{ 0, 0, 0, DEG2RAD(90), DEG2RAD(0), DEG2RAD(0) },
{ 0, 0, 0, DEG2RAD(0), DEG2RAD(90), DEG2RAD(0) },
{ 0, 0, 0, DEG2RAD(0), DEG2RAD(0), DEG2RAD(90) },
// -90deg
{ 0, 0, 0, DEG2RAD(-90), DEG2RAD(0), DEG2RAD(0) },
{ 0, 0, 0, DEG2RAD(0), DEG2RAD(-90), DEG2RAD(0) },
{ 0, 0, 0, DEG2RAD(0), DEG2RAD(0), DEG2RAD(-90) },
// 45deg+displ
{ 1, 2, 3, DEG2RAD(45), DEG2RAD(0), DEG2RAD(0) },
{ 1, 2, 3, DEG2RAD(0), DEG2RAD(45), DEG2RAD(0) },
{ 1, 2, 3, DEG2RAD(0), DEG2RAD(0), DEG2RAD(45) },
// full 6D
{ 1, 2, 3, DEG2RAD(10), DEG2RAD(20), DEG2RAD(30) },
};
TEST(MiniProblems,FixedTransformations)
{
for (size_t i=0;i<sizeof(test_fixed_transfs)/sizeof(test_fixed_transfs[0]);i++)
{
const double *p = test_fixed_transfs[i];
const mrpt::poses::CPose3D incr(p[0],p[1],p[2],p[3],p[4],p[5]);
run_test<false>(incr);
run_test<true>(incr);
}
}
<|endoftext|> |
<commit_before>////////////////////////////////////////////////////////////////////////////////
/// DISCLAIMER
///
/// Copyright 2014-2016 ArangoDB GmbH, Cologne, Germany
/// Copyright 2004-2014 triAGENS GmbH, Cologne, Germany
///
/// Licensed under the Apache License, Version 2.0 (the "License");
/// you may not use this file except in compliance with the License.
/// You may obtain a copy of the License at
///
/// http://www.apache.org/licenses/LICENSE-2.0
///
/// Unless required by applicable law or agreed to in writing, software
/// distributed under the License is distributed on an "AS IS" BASIS,
/// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
/// See the License for the specific language governing permissions and
/// limitations under the License.
///
/// Copyright holder is ArangoDB GmbH, Cologne, Germany
///
/// @author Dr. Frank Celler
////////////////////////////////////////////////////////////////////////////////
#include "Basics/Common.h"
#include "Basics/directories.h"
#include "Basics/tri-strings.h"
#include "Actions/ActionFeature.h"
#include "Agency/AgencyFeature.h"
#include "ApplicationFeatures/ConfigFeature.h"
#include "ApplicationFeatures/DaemonFeature.h"
#include "ApplicationFeatures/GreetingsFeature.h"
#include "ApplicationFeatures/LanguageFeature.h"
#include "ApplicationFeatures/NonceFeature.h"
#include "ApplicationFeatures/PageSizeFeature.h"
#include "Pregel/PregelFeature.h"
#include "ApplicationFeatures/PrivilegeFeature.h"
#include "ApplicationFeatures/ShutdownFeature.h"
#include "ApplicationFeatures/SupervisorFeature.h"
#include "ApplicationFeatures/TempFeature.h"
#include "ApplicationFeatures/V8PlatformFeature.h"
#include "ApplicationFeatures/VersionFeature.h"
#include "Aql/AqlFunctionFeature.h"
#include "Aql/OptimizerRulesFeature.h"
#include "Basics/ArangoGlobalContext.h"
#include "Cache/CacheManagerFeature.h"
#include "Cluster/ClusterFeature.h"
#include "GeneralServer/AuthenticationFeature.h"
#include "GeneralServer/GeneralServerFeature.h"
#include "Logger/LoggerBufferFeature.h"
#include "Logger/LoggerFeature.h"
#include "ProgramOptions/ProgramOptions.h"
#include "Random/RandomFeature.h"
#include "RestServer/AqlFeature.h"
#include "RestServer/BootstrapFeature.h"
#include "RestServer/CheckVersionFeature.h"
#include "RestServer/ConsoleFeature.h"
#include "RestServer/DatabaseFeature.h"
#include "RestServer/DatabasePathFeature.h"
#include "RestServer/EndpointFeature.h"
#include "RestServer/FeatureCacheFeature.h"
#include "RestServer/FileDescriptorsFeature.h"
#include "RestServer/FrontendFeature.h"
#include "RestServer/InitDatabaseFeature.h"
#include "RestServer/LockfileFeature.h"
#include "RestServer/QueryRegistryFeature.h"
#include "RestServer/ScriptFeature.h"
#include "RestServer/ServerFeature.h"
#include "RestServer/ServerIdFeature.h"
#include "RestServer/TransactionManagerFeature.h"
#include "RestServer/TraverserEngineRegistryFeature.h"
#include "RestServer/UnitTestsFeature.h"
#include "RestServer/UpgradeFeature.h"
#include "RestServer/ViewTypesFeature.h"
#include "RestServer/WorkMonitorFeature.h"
#include "Scheduler/SchedulerFeature.h"
#include "Ssl/SslFeature.h"
#include "Ssl/SslServerFeature.h"
#include "Statistics/StatisticsFeature.h"
#include "StorageEngine/EngineSelectorFeature.h"
// TODO - move the following MMFiles includes to the storage engine
#include "MMFiles/MMFilesLogfileManager.h"
#include "MMFiles/MMFilesPersistentIndexFeature.h"
#include "MMFiles/MMFilesWalRecoveryFeature.h"
#include "MMFiles/MMFilesEngine.h"
#include "V8Server/FoxxQueuesFeature.h"
#include "V8Server/V8DealerFeature.h"
#ifdef _WIN32
#include "ApplicationFeatures/WindowsServiceFeature.h"
#endif
#ifdef USE_ENTERPRISE
#include "Enterprise/RestServer/arangodEE.h"
#endif
using namespace arangodb;
static int runServer(int argc, char** argv) {
try {
ArangoGlobalContext context(argc, argv, SBIN_DIRECTORY);
context.installSegv();
context.runStartupChecks();
std::string name = context.binaryName();
auto options = std::make_shared<options::ProgramOptions>(
argv[0], "Usage: " + name + " [<options>]", "For more information use:",
SBIN_DIRECTORY);
application_features::ApplicationServer server(options, SBIN_DIRECTORY);
std::vector<std::string> nonServerFeatures = {
"Action", "Affinity",
"Agency", "Authentication",
"Cluster", "Daemon",
"Dispatcher", "FoxxQueues",
"GeneralServer", "LoggerBufferFeature",
"Server", "SslServer",
"Statistics", "Supervisor"};
int ret = EXIT_FAILURE;
server.addFeature(new ActionFeature(&server));
server.addFeature(new AgencyFeature(&server));
server.addFeature(new aql::AqlFunctionFeature(&server));
server.addFeature(new aql::OptimizerRulesFeature(&server));
server.addFeature(new AuthenticationFeature(&server));
server.addFeature(new AqlFeature(&server));
server.addFeature(new BootstrapFeature(&server));
server.addFeature(new CacheManagerFeature(&server));
server.addFeature(
new CheckVersionFeature(&server, &ret, nonServerFeatures));
server.addFeature(new ClusterFeature(&server));
server.addFeature(new ConfigFeature(&server, name));
server.addFeature(new ConsoleFeature(&server));
server.addFeature(new DatabaseFeature(&server));
server.addFeature(new DatabasePathFeature(&server));
server.addFeature(new EndpointFeature(&server));
server.addFeature(new EngineSelectorFeature(&server));
server.addFeature(new FeatureCacheFeature(&server));
server.addFeature(new FileDescriptorsFeature(&server));
server.addFeature(new FoxxQueuesFeature(&server));
server.addFeature(new FrontendFeature(&server));
server.addFeature(new GeneralServerFeature(&server));
server.addFeature(new GreetingsFeature(&server));
server.addFeature(new InitDatabaseFeature(&server, nonServerFeatures));
server.addFeature(new LanguageFeature(&server));
server.addFeature(new LockfileFeature(&server));
server.addFeature(new LoggerBufferFeature(&server));
server.addFeature(new LoggerFeature(&server, true));
server.addFeature(new NonceFeature(&server));
server.addFeature(new PageSizeFeature(&server));
server.addFeature(new pregel::PregelFeature(&server));
server.addFeature(new PrivilegeFeature(&server));
server.addFeature(new RandomFeature(&server));
server.addFeature(new QueryRegistryFeature(&server));
server.addFeature(new SchedulerFeature(&server));
server.addFeature(new ScriptFeature(&server, &ret));
server.addFeature(new ServerFeature(&server, &ret));
server.addFeature(new ServerIdFeature(&server));
server.addFeature(new ShutdownFeature(&server, {"UnitTests", "Script"}));
server.addFeature(new SslFeature(&server));
server.addFeature(new StatisticsFeature(&server));
server.addFeature(new TempFeature(&server, name));
server.addFeature(new TransactionManagerFeature(&server));
server.addFeature(new TraverserEngineRegistryFeature(&server));
server.addFeature(new UnitTestsFeature(&server, &ret));
server.addFeature(new UpgradeFeature(&server, &ret, nonServerFeatures));
server.addFeature(new V8DealerFeature(&server));
server.addFeature(new V8PlatformFeature(&server));
server.addFeature(new VersionFeature(&server));
server.addFeature(new ViewTypesFeature(&server));
server.addFeature(new WorkMonitorFeature(&server));
#ifdef ARANGODB_HAVE_FORK
server.addFeature(new DaemonFeature(&server));
server.addFeature(new SupervisorFeature(&server));
#endif
#ifdef _WIN32
server.addFeature(new WindowsServiceFeature(&server));
#endif
#ifdef USE_ENTERPRISE
setupServerEE(&server);
#else
server.addFeature(new SslServerFeature(&server));
#endif
// storage engines
server.addFeature(new MMFilesEngine(&server));
server.addFeature(new MMFilesWalRecoveryFeature(&server));
server.addFeature(new MMFilesLogfileManager(&server));
server.addFeature(new MMFilesPersistentIndexFeature(&server));
try {
server.run(argc, argv);
if (server.helpShown()) {
// --help was displayed
ret = EXIT_SUCCESS;
}
} catch (std::exception const& ex) {
LOG_TOPIC(ERR, arangodb::Logger::FIXME)
<< "arangod terminated because of an unhandled exception: "
<< ex.what();
ret = EXIT_FAILURE;
} catch (...) {
LOG_TOPIC(ERR, arangodb::Logger::FIXME)
<< "arangod terminated because of an unhandled exception of "
"unknown type";
ret = EXIT_FAILURE;
}
Logger::flush();
return context.exit(ret);
} catch (std::exception const& ex) {
LOG_TOPIC(ERR, arangodb::Logger::FIXME)
<< "arangod terminated because of an unhandled exception: "
<< ex.what();
} catch (...) {
LOG_TOPIC(ERR, arangodb::Logger::FIXME)
<< "arangod terminated because of an unhandled exception of "
"unknown type";
}
exit(EXIT_FAILURE);
}
#if _WIN32
static int ARGC;
static char** ARGV;
static void WINAPI ServiceMain(DWORD dwArgc, LPSTR* lpszArgv) {
if (!TRI_InitWindowsEventLog()) {
return;
}
// register the service ctrl handler, lpszArgv[0] contains service name
ServiceStatus =
RegisterServiceCtrlHandlerA(lpszArgv[0], (LPHANDLER_FUNCTION)ServiceCtrl);
// set start pending
SetServiceStatus(SERVICE_START_PENDING, 0, 1, 10000);
runServer(ARGC, ARGV);
// service has stopped
SetServiceStatus(SERVICE_STOPPED, NO_ERROR, 0, 0);
TRI_CloseWindowsEventlog();
}
#endif
#include "Basics/LdapUrlParser.h"
static void parseUrl(std::string const& url) {
auto result = LdapUrlParser::parse(url);
std::cout << "URL: " << url << "\n";
std::cout << "VALID: " << result.valid << "\n";
std::cout << "STRING: " << result.toString() << "\n";
std::cout << "HOST: " << result.host.value << "\n";
std::cout << "PORT: " << result.port.value << "\n";
std::cout << "BASEDN: " << result.basedn.value << "\n";
std::cout << "SEARCHATTR: " << result.searchAttribute.value << "\n";
std::cout << "DEEP: " << result.deep.value << "\n\n";
}
int main(int argc, char* argv[]) {
parseUrl("ldap://arangodb.com:389/o=einstein?uid?sub");
parseUrl("arangodb.com:389/o=einstein?uid?sub");
parseUrl("arangodb.com/o=einstein?uid?sub");
parseUrl("/o=einstein?uid?sub");
parseUrl("/o=einstein?uid");
parseUrl("/o=einstein");
parseUrl("o=einstein");
parseUrl("/o=einstein?cn=example,cn=com?name?date?one");
parseUrl("/o=einstein/cn=example,cn=com?name?one");
parseUrl("host:name:389");
#if _WIN32
if (argc > 1 && TRI_EqualString("--start-service", argv[1])) {
ARGC = argc;
ARGV = argv;
SERVICE_TABLE_ENTRY ste[] = {
{TEXT(""), (LPSERVICE_MAIN_FUNCTION)ServiceMain}, {nullptr, nullptr}};
if (!StartServiceCtrlDispatcher(ste)) {
std::cerr << "FATAL: StartServiceCtrlDispatcher has failed with "
<< GetLastError() << std::endl;
exit(EXIT_FAILURE);
}
} else
#endif
return runServer(argc, argv);
}
<commit_msg>fail @jsteemann<commit_after>////////////////////////////////////////////////////////////////////////////////
/// DISCLAIMER
///
/// Copyright 2014-2016 ArangoDB GmbH, Cologne, Germany
/// Copyright 2004-2014 triAGENS GmbH, Cologne, Germany
///
/// Licensed under the Apache License, Version 2.0 (the "License");
/// you may not use this file except in compliance with the License.
/// You may obtain a copy of the License at
///
/// http://www.apache.org/licenses/LICENSE-2.0
///
/// Unless required by applicable law or agreed to in writing, software
/// distributed under the License is distributed on an "AS IS" BASIS,
/// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
/// See the License for the specific language governing permissions and
/// limitations under the License.
///
/// Copyright holder is ArangoDB GmbH, Cologne, Germany
///
/// @author Dr. Frank Celler
////////////////////////////////////////////////////////////////////////////////
#include "Basics/Common.h"
#include "Basics/directories.h"
#include "Basics/tri-strings.h"
#include "Actions/ActionFeature.h"
#include "Agency/AgencyFeature.h"
#include "ApplicationFeatures/ConfigFeature.h"
#include "ApplicationFeatures/DaemonFeature.h"
#include "ApplicationFeatures/GreetingsFeature.h"
#include "ApplicationFeatures/LanguageFeature.h"
#include "ApplicationFeatures/NonceFeature.h"
#include "ApplicationFeatures/PageSizeFeature.h"
#include "Pregel/PregelFeature.h"
#include "ApplicationFeatures/PrivilegeFeature.h"
#include "ApplicationFeatures/ShutdownFeature.h"
#include "ApplicationFeatures/SupervisorFeature.h"
#include "ApplicationFeatures/TempFeature.h"
#include "ApplicationFeatures/V8PlatformFeature.h"
#include "ApplicationFeatures/VersionFeature.h"
#include "Aql/AqlFunctionFeature.h"
#include "Aql/OptimizerRulesFeature.h"
#include "Basics/ArangoGlobalContext.h"
#include "Cache/CacheManagerFeature.h"
#include "Cluster/ClusterFeature.h"
#include "GeneralServer/AuthenticationFeature.h"
#include "GeneralServer/GeneralServerFeature.h"
#include "Logger/LoggerBufferFeature.h"
#include "Logger/LoggerFeature.h"
#include "ProgramOptions/ProgramOptions.h"
#include "Random/RandomFeature.h"
#include "RestServer/AqlFeature.h"
#include "RestServer/BootstrapFeature.h"
#include "RestServer/CheckVersionFeature.h"
#include "RestServer/ConsoleFeature.h"
#include "RestServer/DatabaseFeature.h"
#include "RestServer/DatabasePathFeature.h"
#include "RestServer/EndpointFeature.h"
#include "RestServer/FeatureCacheFeature.h"
#include "RestServer/FileDescriptorsFeature.h"
#include "RestServer/FrontendFeature.h"
#include "RestServer/InitDatabaseFeature.h"
#include "RestServer/LockfileFeature.h"
#include "RestServer/QueryRegistryFeature.h"
#include "RestServer/ScriptFeature.h"
#include "RestServer/ServerFeature.h"
#include "RestServer/ServerIdFeature.h"
#include "RestServer/TransactionManagerFeature.h"
#include "RestServer/TraverserEngineRegistryFeature.h"
#include "RestServer/UnitTestsFeature.h"
#include "RestServer/UpgradeFeature.h"
#include "RestServer/ViewTypesFeature.h"
#include "RestServer/WorkMonitorFeature.h"
#include "Scheduler/SchedulerFeature.h"
#include "Ssl/SslFeature.h"
#include "Ssl/SslServerFeature.h"
#include "Statistics/StatisticsFeature.h"
#include "StorageEngine/EngineSelectorFeature.h"
// TODO - move the following MMFiles includes to the storage engine
#include "MMFiles/MMFilesLogfileManager.h"
#include "MMFiles/MMFilesPersistentIndexFeature.h"
#include "MMFiles/MMFilesWalRecoveryFeature.h"
#include "MMFiles/MMFilesEngine.h"
#include "V8Server/FoxxQueuesFeature.h"
#include "V8Server/V8DealerFeature.h"
#ifdef _WIN32
#include "ApplicationFeatures/WindowsServiceFeature.h"
#endif
#ifdef USE_ENTERPRISE
#include "Enterprise/RestServer/arangodEE.h"
#endif
using namespace arangodb;
static int runServer(int argc, char** argv) {
try {
ArangoGlobalContext context(argc, argv, SBIN_DIRECTORY);
context.installSegv();
context.runStartupChecks();
std::string name = context.binaryName();
auto options = std::make_shared<options::ProgramOptions>(
argv[0], "Usage: " + name + " [<options>]", "For more information use:",
SBIN_DIRECTORY);
application_features::ApplicationServer server(options, SBIN_DIRECTORY);
std::vector<std::string> nonServerFeatures = {
"Action", "Affinity",
"Agency", "Authentication",
"Cluster", "Daemon",
"Dispatcher", "FoxxQueues",
"GeneralServer", "LoggerBufferFeature",
"Server", "SslServer",
"Statistics", "Supervisor"};
int ret = EXIT_FAILURE;
server.addFeature(new ActionFeature(&server));
server.addFeature(new AgencyFeature(&server));
server.addFeature(new aql::AqlFunctionFeature(&server));
server.addFeature(new aql::OptimizerRulesFeature(&server));
server.addFeature(new AuthenticationFeature(&server));
server.addFeature(new AqlFeature(&server));
server.addFeature(new BootstrapFeature(&server));
server.addFeature(new CacheManagerFeature(&server));
server.addFeature(
new CheckVersionFeature(&server, &ret, nonServerFeatures));
server.addFeature(new ClusterFeature(&server));
server.addFeature(new ConfigFeature(&server, name));
server.addFeature(new ConsoleFeature(&server));
server.addFeature(new DatabaseFeature(&server));
server.addFeature(new DatabasePathFeature(&server));
server.addFeature(new EndpointFeature(&server));
server.addFeature(new EngineSelectorFeature(&server));
server.addFeature(new FeatureCacheFeature(&server));
server.addFeature(new FileDescriptorsFeature(&server));
server.addFeature(new FoxxQueuesFeature(&server));
server.addFeature(new FrontendFeature(&server));
server.addFeature(new GeneralServerFeature(&server));
server.addFeature(new GreetingsFeature(&server));
server.addFeature(new InitDatabaseFeature(&server, nonServerFeatures));
server.addFeature(new LanguageFeature(&server));
server.addFeature(new LockfileFeature(&server));
server.addFeature(new LoggerBufferFeature(&server));
server.addFeature(new LoggerFeature(&server, true));
server.addFeature(new NonceFeature(&server));
server.addFeature(new PageSizeFeature(&server));
server.addFeature(new pregel::PregelFeature(&server));
server.addFeature(new PrivilegeFeature(&server));
server.addFeature(new RandomFeature(&server));
server.addFeature(new QueryRegistryFeature(&server));
server.addFeature(new SchedulerFeature(&server));
server.addFeature(new ScriptFeature(&server, &ret));
server.addFeature(new ServerFeature(&server, &ret));
server.addFeature(new ServerIdFeature(&server));
server.addFeature(new ShutdownFeature(&server, {"UnitTests", "Script"}));
server.addFeature(new SslFeature(&server));
server.addFeature(new StatisticsFeature(&server));
server.addFeature(new TempFeature(&server, name));
server.addFeature(new TransactionManagerFeature(&server));
server.addFeature(new TraverserEngineRegistryFeature(&server));
server.addFeature(new UnitTestsFeature(&server, &ret));
server.addFeature(new UpgradeFeature(&server, &ret, nonServerFeatures));
server.addFeature(new V8DealerFeature(&server));
server.addFeature(new V8PlatformFeature(&server));
server.addFeature(new VersionFeature(&server));
server.addFeature(new ViewTypesFeature(&server));
server.addFeature(new WorkMonitorFeature(&server));
#ifdef ARANGODB_HAVE_FORK
server.addFeature(new DaemonFeature(&server));
server.addFeature(new SupervisorFeature(&server));
#endif
#ifdef _WIN32
server.addFeature(new WindowsServiceFeature(&server));
#endif
#ifdef USE_ENTERPRISE
setupServerEE(&server);
#else
server.addFeature(new SslServerFeature(&server));
#endif
// storage engines
server.addFeature(new MMFilesEngine(&server));
server.addFeature(new MMFilesWalRecoveryFeature(&server));
server.addFeature(new MMFilesLogfileManager(&server));
server.addFeature(new MMFilesPersistentIndexFeature(&server));
try {
server.run(argc, argv);
if (server.helpShown()) {
// --help was displayed
ret = EXIT_SUCCESS;
}
} catch (std::exception const& ex) {
LOG_TOPIC(ERR, arangodb::Logger::FIXME)
<< "arangod terminated because of an unhandled exception: "
<< ex.what();
ret = EXIT_FAILURE;
} catch (...) {
LOG_TOPIC(ERR, arangodb::Logger::FIXME)
<< "arangod terminated because of an unhandled exception of "
"unknown type";
ret = EXIT_FAILURE;
}
Logger::flush();
return context.exit(ret);
} catch (std::exception const& ex) {
LOG_TOPIC(ERR, arangodb::Logger::FIXME)
<< "arangod terminated because of an unhandled exception: "
<< ex.what();
} catch (...) {
LOG_TOPIC(ERR, arangodb::Logger::FIXME)
<< "arangod terminated because of an unhandled exception of "
"unknown type";
}
exit(EXIT_FAILURE);
}
#if _WIN32
static int ARGC;
static char** ARGV;
static void WINAPI ServiceMain(DWORD dwArgc, LPSTR* lpszArgv) {
if (!TRI_InitWindowsEventLog()) {
return;
}
// register the service ctrl handler, lpszArgv[0] contains service name
ServiceStatus =
RegisterServiceCtrlHandlerA(lpszArgv[0], (LPHANDLER_FUNCTION)ServiceCtrl);
// set start pending
SetServiceStatus(SERVICE_START_PENDING, 0, 1, 10000);
runServer(ARGC, ARGV);
// service has stopped
SetServiceStatus(SERVICE_STOPPED, NO_ERROR, 0, 0);
TRI_CloseWindowsEventlog();
}
#endif
int main(int argc, char* argv[]) {
#if _WIN32
if (argc > 1 && TRI_EqualString("--start-service", argv[1])) {
ARGC = argc;
ARGV = argv;
SERVICE_TABLE_ENTRY ste[] = {
{TEXT(""), (LPSERVICE_MAIN_FUNCTION)ServiceMain}, {nullptr, nullptr}};
if (!StartServiceCtrlDispatcher(ste)) {
std::cerr << "FATAL: StartServiceCtrlDispatcher has failed with "
<< GetLastError() << std::endl;
exit(EXIT_FAILURE);
}
} else
#endif
return runServer(argc, argv);
}
<|endoftext|> |
<commit_before>//////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2008-2011, Image Engine Design Inc. All rights reserved.
//
// Copyright 2010 Dr D Studios Pty Limited (ACN 127 184 954) (Dr. D Studios),
// its affiliates and/or its licensors.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
//
// * Neither the name of Image Engine Design nor the names of any
// other contributors to this software may be used to endorse or
// promote products derived from this software without specific prior
// written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
// IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
// LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
// NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
//////////////////////////////////////////////////////////////////////////
#include "IECoreMaya/FromMayaSkinClusterConverter.h"
#include "IECoreMaya/Convert.h"
#include "IECore/Exception.h"
#include "IECore/SmoothSkinningData.h"
#include "IECore/CompoundParameter.h"
#include "maya/MFnSkinCluster.h"
#include "maya/MFnDagNode.h"
#include "maya/MFnDependencyNode.h"
#include "maya/MFnMatrixData.h"
#include "maya/MDoubleArray.h"
#include "maya/MDagPath.h"
#include "maya/MDagPathArray.h"
#include "maya/MObjectArray.h"
#include "maya/MItGeometry.h"
#include "maya/MPlug.h"
using namespace IECoreMaya;
using namespace std;
IE_CORE_DEFINERUNTIMETYPED( FromMayaSkinClusterConverter );
FromMayaObjectConverter::FromMayaObjectConverterDescription<FromMayaSkinClusterConverter> FromMayaSkinClusterConverter::m_description( MFn::kSkinClusterFilter, IECore::SmoothSkinningData::staticTypeId(), true );
FromMayaSkinClusterConverter::FromMayaSkinClusterConverter( const MObject &object )
: FromMayaObjectConverter( "Converts data on skinCluster nodes.into SmoothSkinningData", object )
{
IECore::IntParameter::PresetsContainer influenceNamePresets;
influenceNamePresets.push_back( IECore::IntParameter::Preset( "Partial", Partial ) );
influenceNamePresets.push_back( IECore::IntParameter::Preset( "Full", Full ) );
m_influenceNameParameter = new IECore::IntParameter(
"influenceName",
"Will the influence names contain the partial or full dag path.",
Partial,
Partial,
Full,
influenceNamePresets,
true
);
parameters()->addParameter( m_influenceNameParameter );
}
IECore::IntParameterPtr FromMayaSkinClusterConverter::influenceNameParameter()
{
return m_influenceNameParameter;
}
IECore::ConstIntParameterPtr FromMayaSkinClusterConverter::influenceNameParameter() const
{
return m_influenceNameParameter;
}
IECore::ObjectPtr FromMayaSkinClusterConverter::doConversion( const MObject &object, IECore::ConstCompoundObjectPtr operands ) const
{
MStatus stat;
// our data storage objects
IECore::StringVectorDataPtr influenceNamesData = new IECore::StringVectorData();
IECore::M44fVectorDataPtr influencePoseData = new IECore::M44fVectorData();
IECore::IntVectorDataPtr pointIndexOffsetsData = new IECore::IntVectorData();
IECore::IntVectorDataPtr pointInfluenceCountsData = new IECore::IntVectorData();
IECore::IntVectorDataPtr pointInfluenceIndicesData = new IECore::IntVectorData();
IECore::FloatVectorDataPtr pointInfluenceWeightsData = new IECore::FloatVectorData();
// get a skin cluster fn
MFnSkinCluster skinClusterFn(object);
MDagPathArray influencePaths;
skinClusterFn.influenceObjects(influencePaths);
// get the influence names
int influencesCount = influencePaths.length();
influenceNamesData->writable().reserve( influencesCount );
InfluenceName in = (InfluenceName)m_influenceNameParameter->getNumericValue();
switch( in )
{
case Partial :
{
for (int i=0; i < influencesCount; i++)
{
influenceNamesData->writable().push_back( influencePaths[i].partialPathName(&stat).asChar() );
}
break;
}
case Full :
{
for (int i=0; i < influencesCount; i++)
{
influenceNamesData->writable().push_back( influencePaths[i].fullPathName(&stat).asChar() );
}
break;
}
}
// extract bind pose
MFnDependencyNode skinClusterNodeFn( object );
MPlug bindPreMatrixArrayPlug = skinClusterNodeFn.findPlug( "bindPreMatrix", true, &stat );
if ( int( bindPreMatrixArrayPlug .numElements() ) != influencesCount )
{
throw IECore::Exception( "FromMayaSkinClusterConverter: number of elements in the skinCluster.bindPreMatrix"
"array plug does not match the number of influences" );
}
for (int i=0; i < influencesCount; i++)
{
MPlug bindPreMatrixElementPlug = bindPreMatrixArrayPlug.elementByLogicalIndex(
skinClusterFn.indexForInfluenceObject( influencePaths[i], NULL ), &stat);
MObject matObj;
bindPreMatrixElementPlug.getValue( matObj );
MFnMatrixData matFn( matObj, &stat );
MMatrix mat = matFn.matrix();
Imath::M44f cmat = IECore::convert<Imath::M44f>( mat );
influencePoseData->writable().push_back( cmat );
}
// extract the skinning information
// get the first input geometry to the skin cluster
// TODO: if needed, extend this to retrieve more than one output geometry
MObjectArray outputGeoObjs;
stat = skinClusterFn.getOutputGeometry( outputGeoObjs );
if (! stat)
{
throw IECore::Exception( "FromMayaSkinClusterConverter: skinCluster node does not have any output geometry!" );
}
// get the dag path to the first object
MFnDagNode dagFn( outputGeoObjs[0] );
MDagPath geoPath;
dagFn.getPath( geoPath );
// generate a geo iterator for the components
MItGeometry geoIt( outputGeoObjs[0] );
int currentOffset = 0;
// loop through all the points of the geometry to extract their bind information
for ( ; !geoIt.isDone(); geoIt.next() )
{
MObject pointObj = geoIt.currentItem( &stat );
MDoubleArray weights;
unsigned int weightsCount;
skinClusterFn.getWeights( geoPath, pointObj, weights, weightsCount );
int pointInfluencesCount = 0;
for ( int influenceId = 0; influenceId < int( weightsCount ); influenceId++ )
{
// ignore zero weights, we are generating a compressed (non-sparse) representation of the weights
/// \todo: use a parameter to specify a threshold value rather than 0.0
if ( weights[influenceId] != 0.0 )
{
pointInfluencesCount++;
pointInfluenceWeightsData->writable().push_back( float( weights[influenceId] ) );
pointInfluenceIndicesData->writable().push_back( influenceId );
}
}
pointIndexOffsetsData->writable().push_back( currentOffset );
pointInfluenceCountsData->writable().push_back( pointInfluencesCount );
currentOffset += pointInfluencesCount;
}
// put all our results in a smooth skinning data object
return new IECore::SmoothSkinningData( influenceNamesData, influencePoseData, pointIndexOffsetsData,
pointInfluenceCountsData, pointInfluenceIndicesData, pointInfluenceWeightsData );
}
<commit_msg>removing exception as it was causing issues and doesnt seem necessary<commit_after>//////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2008-2012, Image Engine Design Inc. All rights reserved.
//
// Copyright 2010 Dr D Studios Pty Limited (ACN 127 184 954) (Dr. D Studios),
// its affiliates and/or its licensors.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
//
// * Neither the name of Image Engine Design nor the names of any
// other contributors to this software may be used to endorse or
// promote products derived from this software without specific prior
// written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
// IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
// LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
// NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
//////////////////////////////////////////////////////////////////////////
#include "IECoreMaya/FromMayaSkinClusterConverter.h"
#include "IECoreMaya/Convert.h"
#include "IECore/Exception.h"
#include "IECore/SmoothSkinningData.h"
#include "IECore/CompoundParameter.h"
#include "maya/MFnSkinCluster.h"
#include "maya/MFnDagNode.h"
#include "maya/MFnDependencyNode.h"
#include "maya/MFnMatrixData.h"
#include "maya/MDoubleArray.h"
#include "maya/MDagPath.h"
#include "maya/MDagPathArray.h"
#include "maya/MObjectArray.h"
#include "maya/MItGeometry.h"
#include "maya/MPlug.h"
using namespace IECoreMaya;
using namespace std;
IE_CORE_DEFINERUNTIMETYPED( FromMayaSkinClusterConverter );
FromMayaObjectConverter::FromMayaObjectConverterDescription<FromMayaSkinClusterConverter> FromMayaSkinClusterConverter::m_description( MFn::kSkinClusterFilter, IECore::SmoothSkinningData::staticTypeId(), true );
FromMayaSkinClusterConverter::FromMayaSkinClusterConverter( const MObject &object )
: FromMayaObjectConverter( "Converts data on skinCluster nodes.into SmoothSkinningData", object )
{
IECore::IntParameter::PresetsContainer influenceNamePresets;
influenceNamePresets.push_back( IECore::IntParameter::Preset( "Partial", Partial ) );
influenceNamePresets.push_back( IECore::IntParameter::Preset( "Full", Full ) );
m_influenceNameParameter = new IECore::IntParameter(
"influenceName",
"Will the influence names contain the partial or full dag path.",
Partial,
Partial,
Full,
influenceNamePresets,
true
);
parameters()->addParameter( m_influenceNameParameter );
}
IECore::IntParameterPtr FromMayaSkinClusterConverter::influenceNameParameter()
{
return m_influenceNameParameter;
}
IECore::ConstIntParameterPtr FromMayaSkinClusterConverter::influenceNameParameter() const
{
return m_influenceNameParameter;
}
IECore::ObjectPtr FromMayaSkinClusterConverter::doConversion( const MObject &object, IECore::ConstCompoundObjectPtr operands ) const
{
MStatus stat;
// our data storage objects
IECore::StringVectorDataPtr influenceNamesData = new IECore::StringVectorData();
IECore::M44fVectorDataPtr influencePoseData = new IECore::M44fVectorData();
IECore::IntVectorDataPtr pointIndexOffsetsData = new IECore::IntVectorData();
IECore::IntVectorDataPtr pointInfluenceCountsData = new IECore::IntVectorData();
IECore::IntVectorDataPtr pointInfluenceIndicesData = new IECore::IntVectorData();
IECore::FloatVectorDataPtr pointInfluenceWeightsData = new IECore::FloatVectorData();
// get a skin cluster fn
MFnSkinCluster skinClusterFn(object);
MDagPathArray influencePaths;
skinClusterFn.influenceObjects(influencePaths);
// get the influence names
int influencesCount = influencePaths.length();
influenceNamesData->writable().reserve( influencesCount );
InfluenceName in = (InfluenceName)m_influenceNameParameter->getNumericValue();
switch( in )
{
case Partial :
{
for (int i=0; i < influencesCount; i++)
{
influenceNamesData->writable().push_back( influencePaths[i].partialPathName(&stat).asChar() );
}
break;
}
case Full :
{
for (int i=0; i < influencesCount; i++)
{
influenceNamesData->writable().push_back( influencePaths[i].fullPathName(&stat).asChar() );
}
break;
}
}
// extract bind pose
MFnDependencyNode skinClusterNodeFn( object );
MPlug bindPreMatrixArrayPlug = skinClusterNodeFn.findPlug( "bindPreMatrix", true, &stat );
for (int i=0; i < influencesCount; i++)
{
MPlug bindPreMatrixElementPlug = bindPreMatrixArrayPlug.elementByLogicalIndex(
skinClusterFn.indexForInfluenceObject( influencePaths[i], NULL ), &stat);
MObject matObj;
bindPreMatrixElementPlug.getValue( matObj );
MFnMatrixData matFn( matObj, &stat );
MMatrix mat = matFn.matrix();
Imath::M44f cmat = IECore::convert<Imath::M44f>( mat );
influencePoseData->writable().push_back( cmat );
}
// extract the skinning information
// get the first input geometry to the skin cluster
// TODO: if needed, extend this to retrieve more than one output geometry
MObjectArray outputGeoObjs;
stat = skinClusterFn.getOutputGeometry( outputGeoObjs );
if (! stat)
{
throw IECore::Exception( "FromMayaSkinClusterConverter: skinCluster node does not have any output geometry!" );
}
// get the dag path to the first object
MFnDagNode dagFn( outputGeoObjs[0] );
MDagPath geoPath;
dagFn.getPath( geoPath );
// generate a geo iterator for the components
MItGeometry geoIt( outputGeoObjs[0] );
int currentOffset = 0;
// loop through all the points of the geometry to extract their bind information
for ( ; !geoIt.isDone(); geoIt.next() )
{
MObject pointObj = geoIt.currentItem( &stat );
MDoubleArray weights;
unsigned int weightsCount;
skinClusterFn.getWeights( geoPath, pointObj, weights, weightsCount );
int pointInfluencesCount = 0;
for ( int influenceId = 0; influenceId < int( weightsCount ); influenceId++ )
{
// ignore zero weights, we are generating a compressed (non-sparse) representation of the weights
/// \todo: use a parameter to specify a threshold value rather than 0.0
if ( weights[influenceId] != 0.0 )
{
pointInfluencesCount++;
pointInfluenceWeightsData->writable().push_back( float( weights[influenceId] ) );
pointInfluenceIndicesData->writable().push_back( influenceId );
}
}
pointIndexOffsetsData->writable().push_back( currentOffset );
pointInfluenceCountsData->writable().push_back( pointInfluencesCount );
currentOffset += pointInfluencesCount;
}
// put all our results in a smooth skinning data object
return new IECore::SmoothSkinningData( influenceNamesData, influencePoseData, pointIndexOffsetsData,
pointInfluenceCountsData, pointInfluenceIndicesData, pointInfluenceWeightsData );
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: cfgmerge.hxx,v $
*
* $Revision: 1.7 $
*
* last change: $Author: hr $ $Date: 2006-08-14 17:07:26 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#ifndef _CFG_MERGE_HXX
#define _CFG_MERGE_HXX
#include <tools/string.hxx>
#include <tools/list.hxx>
#include <hash_map>
typedef std::hash_map<ByteString , ByteString , hashByteString,equalByteString>
ByteStringHashMap;
//
// class CfgStackData
//
class CfgStackData
{
friend class CfgParser;
friend class CfgExport;
friend class CfgMerge;
private:
ByteString sTagType;
ByteString sIdentifier;
ByteString sResTyp;
ByteString sTextTag;
ByteString sEndTextTag;
ByteStringHashMap sText;
public:
CfgStackData( const ByteString &rTag, const ByteString &rId )
: sTagType( rTag ), sIdentifier( rId ) {};
ByteString &GetTagType() { return sTagType; }
ByteString &GetIdentifier() { return sIdentifier; }
};
//
// class CfgStack
//
DECLARE_LIST( CfgStackList, CfgStackData * )
class CfgStack : public CfgStackList
{
public:
CfgStack() : CfgStackList( 10, 10 ) {}
~CfgStack();
ULONG Push( CfgStackData *pStackData );
CfgStackData *Push( const ByteString &rTag, const ByteString &rId );
CfgStackData *Pop() { return Remove( Count() - 1 ); }
CfgStackData *GetStackData( ULONG nPos = LIST_APPEND );
ByteString GetAccessPath( ULONG nPos = LIST_APPEND );
};
//
// class CfgParser
//
class CfgParser
{
protected:
ByteString sCurrentResTyp;
ByteString sCurrentIsoLang;
ByteString sCurrentText;
ByteString sLastWhitespace;
CfgStack aStack;
CfgStackData *pStackData;
BOOL bLocalize;
virtual void WorkOnText(
ByteString &rText,
const ByteString &nLangIndex )=0;
virtual void WorkOnRessourceEnd()=0;
virtual void Output( const ByteString& rOutput )=0;
void Error( const ByteString &rError );
private:
int ExecuteAnalyzedToken( int nToken, char *pToken );
std::vector<ByteString> aLanguages;
void AddText(
ByteString &rText,
const ByteString &rIsoLang,
const ByteString &rResTyp );
BOOL IsTokenClosed( const ByteString &rToken );
public:
CfgParser();
virtual ~CfgParser();
int Execute( int nToken, char * pToken );
};
//
// class CfgOutputParser
//
class CfgOutputParser : public CfgParser
{
protected:
SvFileStream *pOutputStream;
public:
CfgOutputParser ( const ByteString &rOutputFile );
virtual ~CfgOutputParser();
};
//
// class CfgExport
//
class CfgExport : public CfgOutputParser
{
private:
ByteString sPrj;
ByteString sPath;
std::vector<ByteString> aLanguages;
protected:
void WorkOnText(
ByteString &rText,
const ByteString &rIsoLang
);
void WorkOnRessourceEnd();
void Output( const ByteString& rOutput );
public:
CfgExport(
const ByteString &rOutputFile,
const ByteString &rProject,
const ByteString &rFilePath
);
~CfgExport();
};
//
// class CfgMerge
//
class CfgMerge : public CfgOutputParser
{
private:
MergeDataFile *pMergeDataFile;
std::vector<ByteString> aLanguages;
ResData *pResData;
BOOL bGerman;
ByteString sFilename;
BOOL bEnglish;
protected:
void WorkOnText(
ByteString &rText,
const ByteString &nLangIndex );
void WorkOnRessourceEnd();
void Output( const ByteString& rOutput );
public:
CfgMerge(
const ByteString &rMergeSource,
const ByteString &rOutputFile,
ByteString &rFilename
);
~CfgMerge();
};
#endif
<commit_msg>INTEGRATION: CWS changefileheader (1.7.96); FILE MERGED 2008/03/28 15:41:57 rt 1.7.96.1: #i87441# Change license header to LPGL v3.<commit_after>/*************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright 2008 by Sun Microsystems, Inc.
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: cfgmerge.hxx,v $
* $Revision: 1.8 $
*
* This file is part of OpenOffice.org.
*
* OpenOffice.org is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* only, as published by the Free Software Foundation.
*
* OpenOffice.org is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License version 3 for more details
* (a copy is included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with OpenOffice.org. If not, see
* <http://www.openoffice.org/license.html>
* for a copy of the LGPLv3 License.
*
************************************************************************/
#ifndef _CFG_MERGE_HXX
#define _CFG_MERGE_HXX
#include <tools/string.hxx>
#include <tools/list.hxx>
#include <hash_map>
typedef std::hash_map<ByteString , ByteString , hashByteString,equalByteString>
ByteStringHashMap;
//
// class CfgStackData
//
class CfgStackData
{
friend class CfgParser;
friend class CfgExport;
friend class CfgMerge;
private:
ByteString sTagType;
ByteString sIdentifier;
ByteString sResTyp;
ByteString sTextTag;
ByteString sEndTextTag;
ByteStringHashMap sText;
public:
CfgStackData( const ByteString &rTag, const ByteString &rId )
: sTagType( rTag ), sIdentifier( rId ) {};
ByteString &GetTagType() { return sTagType; }
ByteString &GetIdentifier() { return sIdentifier; }
};
//
// class CfgStack
//
DECLARE_LIST( CfgStackList, CfgStackData * )
class CfgStack : public CfgStackList
{
public:
CfgStack() : CfgStackList( 10, 10 ) {}
~CfgStack();
ULONG Push( CfgStackData *pStackData );
CfgStackData *Push( const ByteString &rTag, const ByteString &rId );
CfgStackData *Pop() { return Remove( Count() - 1 ); }
CfgStackData *GetStackData( ULONG nPos = LIST_APPEND );
ByteString GetAccessPath( ULONG nPos = LIST_APPEND );
};
//
// class CfgParser
//
class CfgParser
{
protected:
ByteString sCurrentResTyp;
ByteString sCurrentIsoLang;
ByteString sCurrentText;
ByteString sLastWhitespace;
CfgStack aStack;
CfgStackData *pStackData;
BOOL bLocalize;
virtual void WorkOnText(
ByteString &rText,
const ByteString &nLangIndex )=0;
virtual void WorkOnRessourceEnd()=0;
virtual void Output( const ByteString& rOutput )=0;
void Error( const ByteString &rError );
private:
int ExecuteAnalyzedToken( int nToken, char *pToken );
std::vector<ByteString> aLanguages;
void AddText(
ByteString &rText,
const ByteString &rIsoLang,
const ByteString &rResTyp );
BOOL IsTokenClosed( const ByteString &rToken );
public:
CfgParser();
virtual ~CfgParser();
int Execute( int nToken, char * pToken );
};
//
// class CfgOutputParser
//
class CfgOutputParser : public CfgParser
{
protected:
SvFileStream *pOutputStream;
public:
CfgOutputParser ( const ByteString &rOutputFile );
virtual ~CfgOutputParser();
};
//
// class CfgExport
//
class CfgExport : public CfgOutputParser
{
private:
ByteString sPrj;
ByteString sPath;
std::vector<ByteString> aLanguages;
protected:
void WorkOnText(
ByteString &rText,
const ByteString &rIsoLang
);
void WorkOnRessourceEnd();
void Output( const ByteString& rOutput );
public:
CfgExport(
const ByteString &rOutputFile,
const ByteString &rProject,
const ByteString &rFilePath
);
~CfgExport();
};
//
// class CfgMerge
//
class CfgMerge : public CfgOutputParser
{
private:
MergeDataFile *pMergeDataFile;
std::vector<ByteString> aLanguages;
ResData *pResData;
BOOL bGerman;
ByteString sFilename;
BOOL bEnglish;
protected:
void WorkOnText(
ByteString &rText,
const ByteString &nLangIndex );
void WorkOnRessourceEnd();
void Output( const ByteString& rOutput );
public:
CfgMerge(
const ByteString &rMergeSource,
const ByteString &rOutputFile,
ByteString &rFilename
);
~CfgMerge();
};
#endif
<|endoftext|> |
<commit_before>// Copyright 2016 Google Inc. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include <algorithm>
#include <cstdint>
#include <cstdio>
#include <iostream>
#include <string>
#include <utility>
#include "firebase/auth.h"
#include "firebase/auth/user.h"
#include "firebase/firestore.h"
#include "firebase/util.h"
// Thin OS abstraction layer.
#include "main.h" // NOLINT
const int kTimeoutMs = 5000;
const int kSleepMs = 100;
// Waits for a Future to be completed and returns whether the future has
// completed successfully. If the Future returns an error, it will be logged.
bool Await(const firebase::FutureBase& future, const char* name) {
int remaining_timeout = kTimeoutMs;
while (future.status() == firebase::kFutureStatusPending &&
remaining_timeout > 0) {
remaining_timeout -= kSleepMs;
ProcessEvents(kSleepMs);
}
if (future.status() != firebase::kFutureStatusComplete) {
LogMessage("ERROR: %s returned an invalid result.", name);
return false;
} else if (future.error() != 0) {
LogMessage("ERROR: %s returned error %d: %s", name, future.error(),
future.error_message());
return false;
}
return true;
}
class Countable {
public:
int event_count() const { return event_count_; }
protected:
int event_count_ = 0;
};
template <typename T>
class TestEventListener : public Countable,
public firebase::firestore::EventListener<T> {
public:
explicit TestEventListener(std::string name) : name_(std::move(name)) {}
void OnEvent(const T& value, const firebase::firestore::Error error_code,
const std::string& error_message) override {
event_count_++;
if (error_code != firebase::firestore::kErrorOk) {
LogMessage("ERROR: EventListener %s got %d (%s).", name_.c_str(),
error_code, error_message.c_str());
}
}
// Hides the STLPort-related quirk that `AddSnapshotListener` has different
// signatures depending on whether `std::function` is available.
template <typename U>
firebase::firestore::ListenerRegistration AttachTo(U* ref) {
#if !defined(STLPORT)
return ref->AddSnapshotListener(
[this](const T& result, firebase::firestore::Error error_code,
const std::string& error_message) {
OnEvent(result, error_code, error_message);
});
#else
return ref->AddSnapshotListener(this);
#endif
}
private:
std::string name_;
};
void Await(const Countable& listener, const char* name) {
int remaining_timeout = kTimeoutMs;
while (listener.event_count() && remaining_timeout > 0) {
remaining_timeout -= kSleepMs;
ProcessEvents(kSleepMs);
}
if (remaining_timeout <= 0) {
LogMessage("ERROR: %s listener timed out.", name);
}
}
extern "C" int common_main(int argc, const char* argv[]) {
firebase::App* app;
#if defined(__ANDROID__)
app = firebase::App::Create(GetJniEnv(), GetActivity());
#else
app = firebase::App::Create();
#endif // defined(__ANDROID__)
LogMessage("Initialized Firebase App.");
LogMessage("Initializing Firebase Auth...");
firebase::InitResult result;
firebase::auth::Auth* auth = firebase::auth::Auth::GetAuth(app, &result);
if (result != firebase::kInitResultSuccess) {
LogMessage("Failed to initialize Firebase Auth, error: %d",
static_cast<int>(result));
return -1;
}
LogMessage("Initialized Firebase Auth.");
LogMessage("Signing in...");
// Auth caches the previously signed-in user, which can be annoying when
// trying to test for sign-in failures.
auth->SignOut();
auto login_future = auth->SignInAnonymously();
Await(login_future, "Auth sign-in");
auto* login_result = login_future.result();
if (login_result && *login_result) {
const firebase::auth::User* user = *login_result;
LogMessage("Signed in as %s user, uid: %s, email: %s.\n",
user->is_anonymous() ? "an anonymous" : "a non-anonymous",
user->uid().c_str(), user->email().c_str());
} else {
LogMessage("ERROR: could not sign in");
}
// Note: Auth cannot be deleted while any of the futures issued by it are
// still valid.
login_future.Release();
LogMessage("Initialize Firebase Firestore.");
// Use ModuleInitializer to initialize Database, ensuring no dependencies are
// missing.
firebase::firestore::Firestore* firestore = nullptr;
void* initialize_targets[] = {&firestore};
const firebase::ModuleInitializer::InitializerFn initializers[] = {
[](firebase::App* app, void* data) {
LogMessage("Attempt to initialize Firebase Firestore.");
void** targets = reinterpret_cast<void**>(data);
firebase::InitResult result;
*reinterpret_cast<firebase::firestore::Firestore**>(targets[0]) =
firebase::firestore::Firestore::GetInstance(app, &result);
return result;
}};
firebase::ModuleInitializer initializer;
initializer.Initialize(app, initialize_targets, initializers,
sizeof(initializers) / sizeof(initializers[0]));
Await(initializer.InitializeLastResult(), "Initialize");
if (initializer.InitializeLastResult().error() != 0) {
LogMessage("Failed to initialize Firebase libraries: %s",
initializer.InitializeLastResult().error_message());
return -1;
}
LogMessage("Successfully initialized Firebase Firestore.");
firestore->set_log_level(firebase::kLogLevelDebug);
if (firestore->app() != app) {
LogMessage("ERROR: failed to get App the Firestore was created with.");
}
firebase::firestore::Settings settings = firestore->settings();
firestore->set_settings(settings);
LogMessage("Successfully set Firestore settings.");
LogMessage("Testing non-wrapping types.");
const firebase::Timestamp timestamp{1, 2};
if (timestamp.seconds() != 1 || timestamp.nanoseconds() != 2) {
LogMessage("ERROR: Timestamp creation failed.");
}
const firebase::firestore::SnapshotMetadata metadata{
/*has_pending_writes*/ false, /*is_from_cache*/ true};
if (metadata.has_pending_writes() || !metadata.is_from_cache()) {
LogMessage("ERROR: SnapshotMetadata creation failed.");
}
const firebase::firestore::GeoPoint point{1.23, 4.56};
if (point.latitude() != 1.23 || point.longitude() != 4.56) {
LogMessage("ERROR: GeoPoint creation failed.");
}
LogMessage("Tested non-wrapping types.");
LogMessage("Testing collections.");
firebase::firestore::CollectionReference collection =
firestore->Collection("foo");
if (collection.id() != "foo") {
LogMessage("ERROR: failed to get collection id.");
}
if (collection.Document("bar").path() != "foo/bar") {
LogMessage("ERROR: failed to get path of a nested document.");
}
LogMessage("Tested collections.");
LogMessage("Testing documents.");
firebase::firestore::DocumentReference document =
firestore->Document("foo/bar");
if (document.firestore() != firestore) {
LogMessage("ERROR: failed to get Firestore from document.");
}
if (document.path() != "foo/bar") {
LogMessage("ERROR: failed to get path string from document.");
}
LogMessage("Testing Set().");
Await(document.Set(firebase::firestore::MapFieldValue{
{"str", firebase::firestore::FieldValue::String("foo")},
{"int", firebase::firestore::FieldValue::Integer(123)}}),
"document.Set");
LogMessage("Testing Update().");
Await(document.Update(firebase::firestore::MapFieldValue{
{"int", firebase::firestore::FieldValue::Integer(321)}}),
"document.Update");
LogMessage("Testing Get().");
auto doc_future = document.Get();
if (Await(doc_future, "document.Get")) {
const firebase::firestore::DocumentSnapshot* snapshot = doc_future.result();
if (snapshot == nullptr) {
LogMessage("ERROR: failed to read document.");
} else {
for (const auto& kv : snapshot->GetData()) {
if (kv.second.type() ==
firebase::firestore::FieldValue::Type::kString) {
LogMessage("key is %s, value is %s", kv.first.c_str(),
kv.second.string_value().c_str());
} else if (kv.second.type() ==
firebase::firestore::FieldValue::Type::kInteger) {
LogMessage("key is %s, value is %ld", kv.first.c_str(),
kv.second.integer_value());
} else {
// Log unexpected type for debugging.
LogMessage("key is %s, value is neither string nor integer",
kv.first.c_str());
}
}
}
}
LogMessage("Testing Delete().");
Await(document.Delete(), "document.Delete");
LogMessage("Tested document operations.");
TestEventListener<firebase::firestore::DocumentSnapshot>
document_event_listener{"for document"};
firebase::firestore::ListenerRegistration registration =
document_event_listener.AttachTo(&document);
Await(document_event_listener, "document.AddSnapshotListener");
registration.Remove();
LogMessage("Successfully added and removed document snapshot listener.");
LogMessage("Testing batch write.");
firebase::firestore::WriteBatch batch = firestore->batch();
batch.Set(collection.Document("one"),
firebase::firestore::MapFieldValue{
{"str", firebase::firestore::FieldValue::String("foo")}});
batch.Set(collection.Document("two"),
firebase::firestore::MapFieldValue{
{"int", firebase::firestore::FieldValue::Integer(123)}});
Await(batch.Commit(), "batch.Commit");
LogMessage("Tested batch write.");
LogMessage("Testing transaction.");
Await(
firestore->RunTransaction(
[collection](firebase::firestore::Transaction& transaction,
std::string&) -> firebase::firestore::Error {
transaction.Update(
collection.Document("one"),
firebase::firestore::MapFieldValue{
{"int", firebase::firestore::FieldValue::Integer(123)}});
transaction.Delete(collection.Document("two"));
transaction.Set(
collection.Document("three"),
firebase::firestore::MapFieldValue{
{"int", firebase::firestore::FieldValue::Integer(321)}});
return firebase::firestore::kErrorOk;
}),
"firestore.RunTransaction");
LogMessage("Tested transaction.");
LogMessage("Testing query.");
firebase::firestore::Query query =
collection
.WhereGreaterThan("int",
firebase::firestore::FieldValue::Boolean(true))
.Limit(3);
auto query_future = query.Get();
if (Await(query_future, "query.Get")) {
const firebase::firestore::QuerySnapshot* snapshot = query_future.result();
if (snapshot == nullptr) {
LogMessage("ERROR: failed to fetch query result.");
} else {
for (const auto& doc : snapshot->documents()) {
if (doc.id() == "one" || doc.id() == "three") {
LogMessage("doc %s is %ld", doc.id().c_str(),
doc.Get("int").integer_value());
} else {
LogMessage("ERROR: unexpected document %s.", doc.id().c_str());
}
}
}
} else {
LogMessage("ERROR: failed to fetch query result.");
}
LogMessage("Tested query.");
LogMessage("Shutdown the Firestore library.");
delete firestore;
firestore = nullptr;
LogMessage("Shutdown Auth.");
delete auth;
LogMessage("Shutdown Firebase App.");
delete app;
// Log this as the last line to ensure all test cases above goes through.
// The test harness will check this line appears.
LogMessage("Tests PASS.");
// Wait until the user wants to quit the app.
while (!ProcessEvents(1000)) {
}
return 0;
}
<commit_msg>Apply clang-format (updated).<commit_after>// Copyright 2016 Google Inc. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include <algorithm>
#include <cstdint>
#include <cstdio>
#include <iostream>
#include <string>
#include <utility>
#include "firebase/auth.h"
#include "firebase/auth/user.h"
#include "firebase/firestore.h"
#include "firebase/util.h"
// Thin OS abstraction layer.
#include "main.h" // NOLINT
const int kTimeoutMs = 5000;
const int kSleepMs = 100;
// Waits for a Future to be completed and returns whether the future has
// completed successfully. If the Future returns an error, it will be logged.
bool Await(const firebase::FutureBase& future, const char* name) {
int remaining_timeout = kTimeoutMs;
while (future.status() == firebase::kFutureStatusPending &&
remaining_timeout > 0) {
remaining_timeout -= kSleepMs;
ProcessEvents(kSleepMs);
}
if (future.status() != firebase::kFutureStatusComplete) {
LogMessage("ERROR: %s returned an invalid result.", name);
return false;
} else if (future.error() != 0) {
LogMessage("ERROR: %s returned error %d: %s", name, future.error(),
future.error_message());
return false;
}
return true;
}
class Countable {
public:
int event_count() const { return event_count_; }
protected:
int event_count_ = 0;
};
template <typename T>
class TestEventListener : public Countable,
public firebase::firestore::EventListener<T> {
public:
explicit TestEventListener(std::string name) : name_(std::move(name)) {}
void OnEvent(const T& value,
const firebase::firestore::Error error_code,
const std::string& error_message) override {
event_count_++;
if (error_code != firebase::firestore::kErrorOk) {
LogMessage("ERROR: EventListener %s got %d (%s).", name_.c_str(),
error_code, error_message.c_str());
}
}
// Hides the STLPort-related quirk that `AddSnapshotListener` has different
// signatures depending on whether `std::function` is available.
template <typename U>
firebase::firestore::ListenerRegistration AttachTo(U* ref) {
#if !defined(STLPORT)
return ref->AddSnapshotListener(
[this](const T& result, firebase::firestore::Error error_code,
const std::string& error_message) {
OnEvent(result, error_code, error_message);
});
#else
return ref->AddSnapshotListener(this);
#endif
}
private:
std::string name_;
};
void Await(const Countable& listener, const char* name) {
int remaining_timeout = kTimeoutMs;
while (listener.event_count() && remaining_timeout > 0) {
remaining_timeout -= kSleepMs;
ProcessEvents(kSleepMs);
}
if (remaining_timeout <= 0) {
LogMessage("ERROR: %s listener timed out.", name);
}
}
extern "C" int common_main(int argc, const char* argv[]) {
firebase::App* app;
#if defined(__ANDROID__)
app = firebase::App::Create(GetJniEnv(), GetActivity());
#else
app = firebase::App::Create();
#endif // defined(__ANDROID__)
LogMessage("Initialized Firebase App.");
LogMessage("Initializing Firebase Auth...");
firebase::InitResult result;
firebase::auth::Auth* auth = firebase::auth::Auth::GetAuth(app, &result);
if (result != firebase::kInitResultSuccess) {
LogMessage("Failed to initialize Firebase Auth, error: %d",
static_cast<int>(result));
return -1;
}
LogMessage("Initialized Firebase Auth.");
LogMessage("Signing in...");
// Auth caches the previously signed-in user, which can be annoying when
// trying to test for sign-in failures.
auth->SignOut();
auto login_future = auth->SignInAnonymously();
Await(login_future, "Auth sign-in");
auto* login_result = login_future.result();
if (login_result && *login_result) {
const firebase::auth::User* user = *login_result;
LogMessage("Signed in as %s user, uid: %s, email: %s.\n",
user->is_anonymous() ? "an anonymous" : "a non-anonymous",
user->uid().c_str(), user->email().c_str());
} else {
LogMessage("ERROR: could not sign in");
}
// Note: Auth cannot be deleted while any of the futures issued by it are
// still valid.
login_future.Release();
LogMessage("Initialize Firebase Firestore.");
// Use ModuleInitializer to initialize Database, ensuring no dependencies are
// missing.
firebase::firestore::Firestore* firestore = nullptr;
void* initialize_targets[] = {&firestore};
const firebase::ModuleInitializer::InitializerFn initializers[] = {
[](firebase::App* app, void* data) {
LogMessage("Attempt to initialize Firebase Firestore.");
void** targets = reinterpret_cast<void**>(data);
firebase::InitResult result;
*reinterpret_cast<firebase::firestore::Firestore**>(targets[0]) =
firebase::firestore::Firestore::GetInstance(app, &result);
return result;
}};
firebase::ModuleInitializer initializer;
initializer.Initialize(app, initialize_targets, initializers,
sizeof(initializers) / sizeof(initializers[0]));
Await(initializer.InitializeLastResult(), "Initialize");
if (initializer.InitializeLastResult().error() != 0) {
LogMessage("Failed to initialize Firebase libraries: %s",
initializer.InitializeLastResult().error_message());
return -1;
}
LogMessage("Successfully initialized Firebase Firestore.");
firestore->set_log_level(firebase::kLogLevelDebug);
if (firestore->app() != app) {
LogMessage("ERROR: failed to get App the Firestore was created with.");
}
firebase::firestore::Settings settings = firestore->settings();
firestore->set_settings(settings);
LogMessage("Successfully set Firestore settings.");
LogMessage("Testing non-wrapping types.");
const firebase::Timestamp timestamp{1, 2};
if (timestamp.seconds() != 1 || timestamp.nanoseconds() != 2) {
LogMessage("ERROR: Timestamp creation failed.");
}
const firebase::firestore::SnapshotMetadata metadata{
/*has_pending_writes*/ false, /*is_from_cache*/ true};
if (metadata.has_pending_writes() || !metadata.is_from_cache()) {
LogMessage("ERROR: SnapshotMetadata creation failed.");
}
const firebase::firestore::GeoPoint point{1.23, 4.56};
if (point.latitude() != 1.23 || point.longitude() != 4.56) {
LogMessage("ERROR: GeoPoint creation failed.");
}
LogMessage("Tested non-wrapping types.");
LogMessage("Testing collections.");
firebase::firestore::CollectionReference collection =
firestore->Collection("foo");
if (collection.id() != "foo") {
LogMessage("ERROR: failed to get collection id.");
}
if (collection.Document("bar").path() != "foo/bar") {
LogMessage("ERROR: failed to get path of a nested document.");
}
LogMessage("Tested collections.");
LogMessage("Testing documents.");
firebase::firestore::DocumentReference document =
firestore->Document("foo/bar");
if (document.firestore() != firestore) {
LogMessage("ERROR: failed to get Firestore from document.");
}
if (document.path() != "foo/bar") {
LogMessage("ERROR: failed to get path string from document.");
}
LogMessage("Testing Set().");
Await(document.Set(firebase::firestore::MapFieldValue{
{"str", firebase::firestore::FieldValue::String("foo")},
{"int", firebase::firestore::FieldValue::Integer(123)}}),
"document.Set");
LogMessage("Testing Update().");
Await(document.Update(firebase::firestore::MapFieldValue{
{"int", firebase::firestore::FieldValue::Integer(321)}}),
"document.Update");
LogMessage("Testing Get().");
auto doc_future = document.Get();
if (Await(doc_future, "document.Get")) {
const firebase::firestore::DocumentSnapshot* snapshot = doc_future.result();
if (snapshot == nullptr) {
LogMessage("ERROR: failed to read document.");
} else {
for (const auto& kv : snapshot->GetData()) {
if (kv.second.type() ==
firebase::firestore::FieldValue::Type::kString) {
LogMessage("key is %s, value is %s", kv.first.c_str(),
kv.second.string_value().c_str());
} else if (kv.second.type() ==
firebase::firestore::FieldValue::Type::kInteger) {
LogMessage("key is %s, value is %ld", kv.first.c_str(),
kv.second.integer_value());
} else {
// Log unexpected type for debugging.
LogMessage("key is %s, value is neither string nor integer",
kv.first.c_str());
}
}
}
}
LogMessage("Testing Delete().");
Await(document.Delete(), "document.Delete");
LogMessage("Tested document operations.");
TestEventListener<firebase::firestore::DocumentSnapshot>
document_event_listener{"for document"};
firebase::firestore::ListenerRegistration registration =
document_event_listener.AttachTo(&document);
Await(document_event_listener, "document.AddSnapshotListener");
registration.Remove();
LogMessage("Successfully added and removed document snapshot listener.");
LogMessage("Testing batch write.");
firebase::firestore::WriteBatch batch = firestore->batch();
batch.Set(collection.Document("one"),
firebase::firestore::MapFieldValue{
{"str", firebase::firestore::FieldValue::String("foo")}});
batch.Set(collection.Document("two"),
firebase::firestore::MapFieldValue{
{"int", firebase::firestore::FieldValue::Integer(123)}});
Await(batch.Commit(), "batch.Commit");
LogMessage("Tested batch write.");
LogMessage("Testing transaction.");
Await(firestore->RunTransaction(
[collection](firebase::firestore::Transaction& transaction,
std::string&) -> firebase::firestore::Error {
transaction.Update(
collection.Document("one"),
firebase::firestore::MapFieldValue{
{"int", firebase::firestore::FieldValue::Integer(123)}});
transaction.Delete(collection.Document("two"));
transaction.Set(
collection.Document("three"),
firebase::firestore::MapFieldValue{
{"int", firebase::firestore::FieldValue::Integer(321)}});
return firebase::firestore::kErrorOk;
}),
"firestore.RunTransaction");
LogMessage("Tested transaction.");
LogMessage("Testing query.");
firebase::firestore::Query query =
collection
.WhereGreaterThan("int",
firebase::firestore::FieldValue::Boolean(true))
.Limit(3);
auto query_future = query.Get();
if (Await(query_future, "query.Get")) {
const firebase::firestore::QuerySnapshot* snapshot = query_future.result();
if (snapshot == nullptr) {
LogMessage("ERROR: failed to fetch query result.");
} else {
for (const auto& doc : snapshot->documents()) {
if (doc.id() == "one" || doc.id() == "three") {
LogMessage("doc %s is %ld", doc.id().c_str(),
doc.Get("int").integer_value());
} else {
LogMessage("ERROR: unexpected document %s.", doc.id().c_str());
}
}
}
} else {
LogMessage("ERROR: failed to fetch query result.");
}
LogMessage("Tested query.");
LogMessage("Shutdown the Firestore library.");
delete firestore;
firestore = nullptr;
LogMessage("Shutdown Auth.");
delete auth;
LogMessage("Shutdown Firebase App.");
delete app;
// Log this as the last line to ensure all test cases above goes through.
// The test harness will check this line appears.
LogMessage("Tests PASS.");
// Wait until the user wants to quit the app.
while (!ProcessEvents(1000)) {
}
return 0;
}
<|endoftext|> |
<commit_before>#include "../../DataStructures/RangeTable.h"
#include <boost/test/unit_test.hpp>
#include <boost/test/test_case_template.hpp>
#include <numeric>
constexpr unsigned BLOCK_SIZE = 16;
typedef RangeTable<BLOCK_SIZE, false> TestRangeTable;
BOOST_AUTO_TEST_SUITE(range_table)
void ConstructionTest(std::vector<unsigned> lengths, std::vector<unsigned> offsets)
{
BOOST_ASSERT(lengths.size() == offsets.size() - 1);
TestRangeTable table(lengths);
for (unsigned i = 0; i < lengths.size(); i++)
{
auto range = table.GetRange(i);
BOOST_CHECK_EQUAL(range.front(), offsets[i]);
BOOST_CHECK_EQUAL(range.back()+1, offsets[i+1]);
}
}
void ComputeLengthsOffsets(std::vector<unsigned>& lengths, std::vector<unsigned>& offsets, unsigned num)
{
lengths.resize(num);
offsets.resize(num+1);
std::iota(lengths.begin(), lengths.end(), 1);
offsets[0] = 0;
std::partial_sum(lengths.begin(), lengths.end(), offsets.begin()+1);
std::stringstream l_ss;
l_ss << "Lengths: ";
for (auto l : lengths)
l_ss << l << ", ";
BOOST_TEST_MESSAGE(l_ss.str());
std::stringstream o_ss;
o_ss << "Offsets: ";
for (auto o : offsets)
o_ss << o << ", ";
BOOST_TEST_MESSAGE(o_ss.str());
}
BOOST_AUTO_TEST_CASE(serialization_test)
{
std::vector<unsigned> lengths;
std::vector<unsigned> offsets;
ComputeLengthsOffsets(lengths, offsets, (BLOCK_SIZE+1)*10);
TestRangeTable in_table(lengths);
TestRangeTable out_table;
std::stringstream ss;
ss << in_table;
ss >> out_table;
for (unsigned i = 0; i < lengths.size(); i++)
{
auto range = out_table.GetRange(i);
BOOST_CHECK_EQUAL(range.front(), offsets[i]);
BOOST_CHECK_EQUAL(range.back()+1, offsets[i+1]);
}
}
BOOST_AUTO_TEST_CASE(construction_test)
{
// only offset empty block
ConstructionTest({1}, {0, 1});
// first block almost full => sentinel is last element of block
// [0] {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, (16)}
std::vector<unsigned> almost_full_lengths;
std::vector<unsigned> almost_full_offsets;
ComputeLengthsOffsets(almost_full_lengths, almost_full_offsets, BLOCK_SIZE);
ConstructionTest(almost_full_lengths, almost_full_offsets);
// first block full => sentinel is offset of new block, next block empty
// [0] {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16}
// [(153)] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}
std::vector<unsigned> full_lengths;
std::vector<unsigned> full_offsets;
ComputeLengthsOffsets(full_lengths, full_offsets, BLOCK_SIZE+1);
ConstructionTest(full_lengths, full_offsets);
// first block full and offset of next block not sentinel, but the first differential value
// [0] {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16}
// [153] {(17), 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}
std::vector<unsigned> over_full_lengths;
std::vector<unsigned> over_full_offsets;
ComputeLengthsOffsets(over_full_lengths, over_full_offsets, BLOCK_SIZE+2);
ConstructionTest(over_full_lengths, over_full_offsets);
// test multiple blocks
std::vector<unsigned> multiple_lengths;
std::vector<unsigned> multiple_offsets;
ComputeLengthsOffsets(multiple_lengths, multiple_offsets, (BLOCK_SIZE+1)*10);
ConstructionTest(multiple_lengths, multiple_offsets);
}
BOOST_AUTO_TEST_SUITE_END()
<commit_msg>Try including typedefs<commit_after>#include "../../DataStructures/RangeTable.h"
#include "../../typedefs.h"
#include <boost/test/unit_test.hpp>
#include <boost/test/test_case_template.hpp>
#include <numeric>
constexpr unsigned BLOCK_SIZE = 16;
typedef RangeTable<BLOCK_SIZE, false> TestRangeTable;
BOOST_AUTO_TEST_SUITE(range_table)
void ConstructionTest(std::vector<unsigned> lengths, std::vector<unsigned> offsets)
{
BOOST_ASSERT(lengths.size() == offsets.size() - 1);
TestRangeTable table(lengths);
for (unsigned i = 0; i < lengths.size(); i++)
{
auto range = table.GetRange(i);
BOOST_CHECK_EQUAL(range.front(), offsets[i]);
BOOST_CHECK_EQUAL(range.back()+1, offsets[i+1]);
}
}
void ComputeLengthsOffsets(std::vector<unsigned>& lengths, std::vector<unsigned>& offsets, unsigned num)
{
lengths.resize(num);
offsets.resize(num+1);
std::iota(lengths.begin(), lengths.end(), 1);
offsets[0] = 0;
std::partial_sum(lengths.begin(), lengths.end(), offsets.begin()+1);
std::stringstream l_ss;
l_ss << "Lengths: ";
for (auto l : lengths)
l_ss << l << ", ";
BOOST_TEST_MESSAGE(l_ss.str());
std::stringstream o_ss;
o_ss << "Offsets: ";
for (auto o : offsets)
o_ss << o << ", ";
BOOST_TEST_MESSAGE(o_ss.str());
}
BOOST_AUTO_TEST_CASE(serialization_test)
{
std::vector<unsigned> lengths;
std::vector<unsigned> offsets;
ComputeLengthsOffsets(lengths, offsets, (BLOCK_SIZE+1)*10);
TestRangeTable in_table(lengths);
TestRangeTable out_table;
std::stringstream ss;
ss << in_table;
ss >> out_table;
for (unsigned i = 0; i < lengths.size(); i++)
{
auto range = out_table.GetRange(i);
BOOST_CHECK_EQUAL(range.front(), offsets[i]);
BOOST_CHECK_EQUAL(range.back()+1, offsets[i+1]);
}
}
BOOST_AUTO_TEST_CASE(construction_test)
{
// only offset empty block
ConstructionTest({1}, {0, 1});
// first block almost full => sentinel is last element of block
// [0] {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, (16)}
std::vector<unsigned> almost_full_lengths;
std::vector<unsigned> almost_full_offsets;
ComputeLengthsOffsets(almost_full_lengths, almost_full_offsets, BLOCK_SIZE);
ConstructionTest(almost_full_lengths, almost_full_offsets);
// first block full => sentinel is offset of new block, next block empty
// [0] {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16}
// [(153)] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}
std::vector<unsigned> full_lengths;
std::vector<unsigned> full_offsets;
ComputeLengthsOffsets(full_lengths, full_offsets, BLOCK_SIZE+1);
ConstructionTest(full_lengths, full_offsets);
// first block full and offset of next block not sentinel, but the first differential value
// [0] {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16}
// [153] {(17), 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}
std::vector<unsigned> over_full_lengths;
std::vector<unsigned> over_full_offsets;
ComputeLengthsOffsets(over_full_lengths, over_full_offsets, BLOCK_SIZE+2);
ConstructionTest(over_full_lengths, over_full_offsets);
// test multiple blocks
std::vector<unsigned> multiple_lengths;
std::vector<unsigned> multiple_offsets;
ComputeLengthsOffsets(multiple_lengths, multiple_offsets, (BLOCK_SIZE+1)*10);
ConstructionTest(multiple_lengths, multiple_offsets);
}
BOOST_AUTO_TEST_SUITE_END()
<|endoftext|> |
<commit_before>#pragma once
#include <cmath>
#include <string>
namespace principia {
namespace quantities {
template<int64_t LengthExponent, int64_t MassExponent, int64_t TimeExponent,
int64_t CurrentExponent, int64_t TemperatureExponent,
int64_t AmountExponent, int64_t LuminousIntensityExponent,
int64_t WindingExponent, int64_t AngleExponent,
int64_t SolidAngleExponent>
struct Dimensions {
enum {
Length = LengthExponent,
Mass = MassExponent,
Time = TimeExponent,
Current = CurrentExponent,
Temperature = TemperatureExponent,
Amount = AmountExponent,
LuminousIntensity = LuminousIntensityExponent,
Winding = WindingExponent,
Angle = AngleExponent,
SolidAngle = SolidAngleExponent
};
static int const kMinExponent = -16;
static int const kMaxExponent = 15;
static int const kExponentBits = 5;
static int const kExponentMask = 0x1F;
static_assert(LengthExponent >= kMinExponent &&
LengthExponent <= kMaxExponent,
"Invalid length exponent");
static_assert(MassExponent >= kMinExponent &&
MassExponent <= kMaxExponent,
"Invalid mass exponent");
static_assert(TimeExponent >= kMinExponent &&
TimeExponent <= kMaxExponent,
"Invalid time exponent");
static_assert(CurrentExponent >= kMinExponent &&
CurrentExponent <= kMaxExponent,
"Invalid current exponent");
static_assert(TemperatureExponent >= kMinExponent &&
TemperatureExponent <= kMaxExponent,
"Invalid temperature exponent");
static_assert(AmountExponent >= kMinExponent &&
AmountExponent <= kMaxExponent,
"Invalid amount exponent");
static_assert(LuminousIntensityExponent >= kMinExponent &&
LuminousIntensityExponent <= kMaxExponent,
"Invalid luminous intensity exponent");
static_assert(AngleExponent >= kMinExponent &&
AngleExponent <= kMaxExponent,
"Invalid angle exponent");
static_assert(SolidAngleExponent >= kMinExponent &&
SolidAngleExponent <= kMaxExponent,
"Invalid solid angle exponent");
static_assert(WindingExponent >= kMinExponent &&
WindingExponent <= kMaxExponent,
"Invalid winding exponent");
// The NOLINT are because glint is confused by the binary and. I kid you not.
static int64_t const representation =
(LengthExponent & kExponentMask) | // NOLINT
(MassExponent & kExponentMask) << 1 * kExponentBits | // NOLINT
(TimeExponent & kExponentMask) << 2 * kExponentBits | // NOLINT
(CurrentExponent & kExponentMask) << 3 * kExponentBits | // NOLINT
(TemperatureExponent & kExponentMask) << 4 * kExponentBits | // NOLINT
(AmountExponent & kExponentMask) << 5 * kExponentBits | // NOLINT
(LuminousIntensityExponent & kExponentMask) << 6 * kExponentBits | // NOLINT
(AngleExponent & kExponentMask) << 7 * kExponentBits | // NOLINT
(SolidAngleExponent & kExponentMask) << 8 * kExponentBits | // NOLINT
(WindingExponent & kExponentMask) << 9 * kExponentBits; // NOLINT
};
namespace internal {
template<typename Q>
struct Collapse { using Type = Q; };
template<>
struct Collapse<Quantity<NoDimensions>> { using Type = double; };
template<typename Left, typename Right>
struct ProductGenerator {
enum {
Length = Left::Dimensions::Length + Right::Dimensions::Length,
Mass = Left::Dimensions::Mass + Right::Dimensions::Mass,
Time = Left::Dimensions::Time + Right::Dimensions::Time,
Current = Left::Dimensions::Current + Right::Dimensions::Current,
Temperature = Left::Dimensions::Temperature +
Right::Dimensions::Temperature,
Amount = Left::Dimensions::Amount + Right::Dimensions::Amount,
LuminousIntensity = Left::Dimensions::LuminousIntensity +
Right:: Dimensions::LuminousIntensity,
Winding = Left::Dimensions::Winding + Right::Dimensions::Winding,
Angle = Left::Dimensions::Angle + Right::Dimensions::Angle,
SolidAngle = Left::Dimensions::SolidAngle +
Right::Dimensions::SolidAngle
};
using Type = typename Collapse<
Quantity<Dimensions<Length, Mass, Time, Current, Temperature, Amount,
LuminousIntensity, Winding, Angle,
SolidAngle>>>::Type;
};
template<typename Left>
struct ProductGenerator<Left, double> { using Type = Left; };
template<typename Right>
struct ProductGenerator<double, Right> { using Type = Right; };
template<>
struct ProductGenerator<double, double> {
using Type = double;
};
template<typename Left, typename Right>
struct QuotientGenerator {
enum {
Length = Left::Dimensions::Length - Right::Dimensions::Length,
Mass = Left::Dimensions::Mass - Right::Dimensions::Mass,
Time = Left::Dimensions::Time - Right::Dimensions::Time,
Current = Left::Dimensions::Current - Right::Dimensions::Current,
Temperature = Left::Dimensions::Temperature -
Right::Dimensions::Temperature,
Amount = Left::Dimensions::Amount - Right::Dimensions::Amount,
LuminousIntensity = Left::Dimensions::LuminousIntensity -
Right:: Dimensions::LuminousIntensity,
Winding = Left::Dimensions::Winding - Right::Dimensions::Winding,
Angle = Left::Dimensions::Angle - Right::Dimensions::Angle,
SolidAngle = Left::Dimensions::SolidAngle -
Right::Dimensions::SolidAngle
};
using Type = typename Collapse<
Quantity<Dimensions<Length, Mass, Time, Current, Temperature, Amount,
LuminousIntensity, Winding, Angle,
SolidAngle>>>::Type;
};
template<typename Left>
struct QuotientGenerator<Left, double> { using Type = Left; };
template<>
struct QuotientGenerator<double, double> {
using Type = double;
};
template<typename Right>
struct QuotientGenerator<double, Right> {
enum {
Length = -Right::Dimensions::Length,
Mass = -Right::Dimensions::Mass,
Time = -Right::Dimensions::Time,
Current = -Right::Dimensions::Current,
Temperature = -Right::Dimensions::Temperature,
Amount = -Right::Dimensions::Amount,
LuminousIntensity = -Right::Dimensions::LuminousIntensity,
Winding = -Right::Dimensions::Winding,
Angle = -Right::Dimensions::Angle,
SolidAngle = -Right::Dimensions::SolidAngle
};
using Type = Quantity<
Dimensions<Length, Mass, Time, Current, Temperature, Amount,
LuminousIntensity, Winding, Angle, SolidAngle>>;
};
template<typename T, int exponent>
struct ExponentiationGenerator<T, exponent, std::enable_if_t<(exponent > 1)>> {
using Type = Product<typename ExponentiationGenerator<T, exponent - 1>::Type,
T>;
};
template<typename T, int exponent>
struct ExponentiationGenerator<T, exponent, std::enable_if_t<(exponent < 1)>>{
using Type = Quotient<typename ExponentiationGenerator<T, exponent + 1>::Type,
T>;
};
template<typename T, int exponent>
struct ExponentiationGenerator<T, exponent, std::enable_if_t<(exponent == 1)>>{
using Type = T;
};
} // namespace internal
template<typename D>
inline Quantity<D>::Quantity() : magnitude_(0) {}
template<typename D>
inline Quantity<D>::Quantity(double const magnitude) : magnitude_(magnitude) {}
template<typename D>
inline Quantity<D>& Quantity<D>::operator+=(Quantity const& right) {
magnitude_ += right.magnitude_;
return *this;
}
template<typename D>
inline Quantity<D>& Quantity<D>::operator-=(Quantity const& right) {
magnitude_ -= right.magnitude_;
return *this;
}
template<typename D>
inline Quantity<D>& Quantity<D>::operator*=(double const right) {
magnitude_ *= right;
return *this;
}
template<typename D>
inline Quantity<D>& Quantity<D>::operator/=(double const right) {
magnitude_ /= right;
return *this;
}
// Additive group
template<typename D>
inline Quantity<D> Quantity<D>::operator+() const {
return *this;
}
template<typename D>
inline Quantity<D> Quantity<D>::operator-() const {
return Quantity(-magnitude_);
}
template<typename D>
inline Quantity<D> Quantity<D>::operator+(Quantity const& right) const {
return Quantity(magnitude_ + right.magnitude_);
}
template<typename D>
inline Quantity<D> Quantity<D>::operator-(Quantity const& right) const {
return Quantity(magnitude_ - right.magnitude_);
}
// Comparison operators
template<typename D>
inline bool Quantity<D>::operator>(Quantity const& right) const {
return magnitude_ > right.magnitude_;
}
template<typename D>
inline bool Quantity<D>::operator<(Quantity const& right) const {
return magnitude_ < right.magnitude_;
}
template<typename D>
inline bool Quantity<D>::operator>=(Quantity const& right) const {
return magnitude_ >= right.magnitude_;
}
template<typename D>
inline bool Quantity<D>::operator<=(Quantity const& right) const {
return magnitude_ <= right.magnitude_;
}
template<typename D>
inline bool Quantity<D>::operator==(Quantity const& right) const {
return magnitude_ == right.magnitude_;
}
template<typename D>
inline bool Quantity<D>::operator!=(Quantity const& right) const {
return magnitude_ != right.magnitude_;
}
template<typename D>
void Quantity<D>::WriteToMessage(
not_null<serialization::Quantity*> const message) const {
message->set_dimensions(D::representation);
message->set_magnitude(magnitude_);
}
template<typename D>
Quantity<D> Quantity<D>::ReadFromMessage(
serialization::Quantity const& message) {
CHECK_EQ(D::representation, message.dimensions());
return Quantity(message.magnitude());
}
// Multiplicative group
template<typename D>
inline Quantity<D> Quantity<D>::operator/(double const right) const {
return Quantity(magnitude_ / right);
}
template<typename D>
inline Quantity<D> Quantity<D>::operator*(double const right) const {
return Quantity(magnitude_ * right);
}
template<typename LDimensions, typename RDimensions>
inline internal::Product<Quantity<LDimensions>, Quantity<RDimensions>>
operator*(Quantity<LDimensions> const& left,
Quantity<RDimensions> const& right) {
return Product<Quantity<LDimensions>,
Quantity<RDimensions>>(left.magnitude_ * right.magnitude_);
}
template<typename LDimensions, typename RDimensions>
inline internal::Quotient<Quantity<LDimensions>, Quantity<RDimensions>>
operator/(Quantity<LDimensions> const& left,
Quantity<RDimensions> const& right) {
return Quotient<Quantity<LDimensions>,
Quantity<RDimensions>>(left.magnitude_ / right.magnitude_);
}
template<typename RDimensions>
inline Quantity<RDimensions> operator*(double const left,
Quantity<RDimensions> const& right) {
return Quantity<RDimensions>(left * right.magnitude_);
}
template<typename RDimensions>
inline typename Quantity<RDimensions>::Inverse operator/(
double const left,
Quantity<RDimensions> const& right) {
return typename Quantity<RDimensions>::Inverse(left / right.magnitude_);
}
template<int exponent>
inline double Pow(double x) {
return std::pow(x, exponent);
}
// Static specializations for frequently-used exponents, so that this gets
// turned into multiplications at compile time.
template<>
inline double Pow<-3>(double x) {
return 1 / (x * x * x);
}
template<>
inline double Pow<-2>(double x) {
return 1 / (x * x);
}
template<>
inline double Pow<-1>(double x) {
return 1 / x;
}
template<>
inline double Pow<0>(double x) {
return 1;
}
template<>
inline double Pow<1>(double x) {
return x;
}
template<>
inline double Pow<2>(double x) {
return x * x;
}
template<>
inline double Pow<3>(double x) {
return x * x * x;
}
template<int exponent, typename D>
Exponentiation<Quantity<D>, exponent> Pow(
Quantity<D> const& x) {
return Exponentiation<Quantity<D>, exponent>(
Pow<exponent>(x.magnitude_));
}
inline double Abs(double const x) {
return std::abs(x);
}
template<typename D>
Quantity<D> Abs(Quantity<D> const& quantity) {
return Quantity<D>(std::abs(quantity.magnitude_));
}
template<typename Q>
inline Q SIUnit() {
return Q(1);
}
template<>
inline double SIUnit<double>() {
return 1;
}
inline std::string FormatUnit(std::string const& name, int const exponent) {
switch (exponent) {
case 0:
return "";
break;
case 1:
return " " + name;
default:
return " " + name + "^" + std::to_string(exponent);
}
}
inline std::string DebugString(double const number, int const precision) {
char result[50];
#ifdef _MSC_VER
unsigned int old_exponent_format = _set_output_format(_TWO_DIGIT_EXPONENT);
sprintf_s(result, ("%+."+ std::to_string(precision) + "e").c_str(), number);
_set_output_format(old_exponent_format);
#else
snprintf(result, sizeof(result),
("%+."+ std::to_string(precision) + "e").c_str(), number);
#endif
return result;
}
template<typename D>
std::string DebugString(Quantity<D> const& quantity, int const precision) {
return DebugString(quantity.magnitude_, precision) +
FormatUnit("m", D::Length) + FormatUnit("kg", D::Mass) +
FormatUnit("s", D::Time) + FormatUnit("A", D::Current) +
FormatUnit("K", D::Temperature) + FormatUnit("mol", D::Amount) +
FormatUnit("cd", D::LuminousIntensity) + FormatUnit("cycle", D::Winding) +
FormatUnit("rad", D::Angle) + FormatUnit("sr", D::SolidAngle);
}
template<typename D>
std::ostream& operator<<(std::ostream& out, Quantity<D> const& quantity) {
return out << DebugString(quantity);
}
} // namespace quantities
} // namespace principia
<commit_msg>After egg's review.<commit_after>#pragma once
#include <cmath>
#include <string>
namespace principia {
namespace quantities {
template<int64_t LengthExponent, int64_t MassExponent, int64_t TimeExponent,
int64_t CurrentExponent, int64_t TemperatureExponent,
int64_t AmountExponent, int64_t LuminousIntensityExponent,
int64_t WindingExponent, int64_t AngleExponent,
int64_t SolidAngleExponent>
struct Dimensions {
enum {
Length = LengthExponent,
Mass = MassExponent,
Time = TimeExponent,
Current = CurrentExponent,
Temperature = TemperatureExponent,
Amount = AmountExponent,
LuminousIntensity = LuminousIntensityExponent,
Winding = WindingExponent,
Angle = AngleExponent,
SolidAngle = SolidAngleExponent
};
static int const kMinExponent = -16;
static int const kMaxExponent = 15;
static int const kExponentBits = 5;
static int const kExponentMask = 0x1F;
static_assert(LengthExponent >= kMinExponent &&
LengthExponent <= kMaxExponent,
"Invalid length exponent");
static_assert(MassExponent >= kMinExponent &&
MassExponent <= kMaxExponent,
"Invalid mass exponent");
static_assert(TimeExponent >= kMinExponent &&
TimeExponent <= kMaxExponent,
"Invalid time exponent");
static_assert(CurrentExponent >= kMinExponent &&
CurrentExponent <= kMaxExponent,
"Invalid current exponent");
static_assert(TemperatureExponent >= kMinExponent &&
TemperatureExponent <= kMaxExponent,
"Invalid temperature exponent");
static_assert(AmountExponent >= kMinExponent &&
AmountExponent <= kMaxExponent,
"Invalid amount exponent");
static_assert(LuminousIntensityExponent >= kMinExponent &&
LuminousIntensityExponent <= kMaxExponent,
"Invalid luminous intensity exponent");
static_assert(AngleExponent >= kMinExponent &&
AngleExponent <= kMaxExponent,
"Invalid angle exponent");
static_assert(SolidAngleExponent >= kMinExponent &&
SolidAngleExponent <= kMaxExponent,
"Invalid solid angle exponent");
static_assert(WindingExponent >= kMinExponent &&
WindingExponent <= kMaxExponent,
"Invalid winding exponent");
// The NOLINT are because glint is confused by the binary and. I kid you not.
static int64_t const representation =
(LengthExponent & kExponentMask) | // NOLINT
(MassExponent & kExponentMask) << 1 * kExponentBits | // NOLINT
(TimeExponent & kExponentMask) << 2 * kExponentBits | // NOLINT
(CurrentExponent & kExponentMask) << 3 * kExponentBits | // NOLINT
(TemperatureExponent & kExponentMask) << 4 * kExponentBits | // NOLINT
(AmountExponent & kExponentMask) << 5 * kExponentBits | // NOLINT
(LuminousIntensityExponent & kExponentMask) << 6 * kExponentBits | // NOLINT
(AngleExponent & kExponentMask) << 7 * kExponentBits | // NOLINT
(SolidAngleExponent & kExponentMask) << 8 * kExponentBits | // NOLINT
(WindingExponent & kExponentMask) << 9 * kExponentBits; // NOLINT
};
namespace internal {
template<typename Q>
struct Collapse { using Type = Q; };
template<>
struct Collapse<Quantity<NoDimensions>> { using Type = double; };
template<typename Left, typename Right>
struct ProductGenerator {
enum {
Length = Left::Dimensions::Length + Right::Dimensions::Length,
Mass = Left::Dimensions::Mass + Right::Dimensions::Mass,
Time = Left::Dimensions::Time + Right::Dimensions::Time,
Current = Left::Dimensions::Current + Right::Dimensions::Current,
Temperature = Left::Dimensions::Temperature +
Right::Dimensions::Temperature,
Amount = Left::Dimensions::Amount + Right::Dimensions::Amount,
LuminousIntensity = Left::Dimensions::LuminousIntensity +
Right:: Dimensions::LuminousIntensity,
Winding = Left::Dimensions::Winding + Right::Dimensions::Winding,
Angle = Left::Dimensions::Angle + Right::Dimensions::Angle,
SolidAngle = Left::Dimensions::SolidAngle +
Right::Dimensions::SolidAngle
};
using Type = typename Collapse<
Quantity<Dimensions<Length, Mass, Time, Current, Temperature, Amount,
LuminousIntensity, Winding, Angle,
SolidAngle>>>::Type;
};
template<typename Left>
struct ProductGenerator<Left, double> { using Type = Left; };
template<typename Right>
struct ProductGenerator<double, Right> { using Type = Right; };
template<>
struct ProductGenerator<double, double> {
using Type = double;
};
template<typename Left, typename Right>
struct QuotientGenerator {
enum {
Length = Left::Dimensions::Length - Right::Dimensions::Length,
Mass = Left::Dimensions::Mass - Right::Dimensions::Mass,
Time = Left::Dimensions::Time - Right::Dimensions::Time,
Current = Left::Dimensions::Current - Right::Dimensions::Current,
Temperature = Left::Dimensions::Temperature -
Right::Dimensions::Temperature,
Amount = Left::Dimensions::Amount - Right::Dimensions::Amount,
LuminousIntensity = Left::Dimensions::LuminousIntensity -
Right:: Dimensions::LuminousIntensity,
Winding = Left::Dimensions::Winding - Right::Dimensions::Winding,
Angle = Left::Dimensions::Angle - Right::Dimensions::Angle,
SolidAngle = Left::Dimensions::SolidAngle -
Right::Dimensions::SolidAngle
};
using Type = typename Collapse<
Quantity<Dimensions<Length, Mass, Time, Current, Temperature, Amount,
LuminousIntensity, Winding, Angle,
SolidAngle>>>::Type;
};
template<typename Left>
struct QuotientGenerator<Left, double> { using Type = Left; };
template<>
struct QuotientGenerator<double, double> {
using Type = double;
};
template<typename Right>
struct QuotientGenerator<double, Right> {
enum {
Length = -Right::Dimensions::Length,
Mass = -Right::Dimensions::Mass,
Time = -Right::Dimensions::Time,
Current = -Right::Dimensions::Current,
Temperature = -Right::Dimensions::Temperature,
Amount = -Right::Dimensions::Amount,
LuminousIntensity = -Right::Dimensions::LuminousIntensity,
Winding = -Right::Dimensions::Winding,
Angle = -Right::Dimensions::Angle,
SolidAngle = -Right::Dimensions::SolidAngle
};
using Type = Quantity<
Dimensions<Length, Mass, Time, Current, Temperature, Amount,
LuminousIntensity, Winding, Angle, SolidAngle>>;
};
template<typename T, int exponent>
struct ExponentiationGenerator<T, exponent, std::enable_if_t<(exponent > 1)>> {
using Type = Product<typename ExponentiationGenerator<T, exponent - 1>::Type,
T>;
};
template<typename T, int exponent>
struct ExponentiationGenerator<T, exponent, std::enable_if_t<(exponent < 1)>>{
using Type = Quotient<typename ExponentiationGenerator<T, exponent + 1>::Type,
T>;
};
template<typename T, int exponent>
struct ExponentiationGenerator<T, exponent, std::enable_if_t<(exponent == 1)>>{
using Type = T;
};
} // namespace internal
template<typename D>
inline Quantity<D>::Quantity() : magnitude_(0) {}
template<typename D>
inline Quantity<D>::Quantity(double const magnitude) : magnitude_(magnitude) {}
template<typename D>
inline Quantity<D>& Quantity<D>::operator+=(Quantity const& right) {
magnitude_ += right.magnitude_;
return *this;
}
template<typename D>
inline Quantity<D>& Quantity<D>::operator-=(Quantity const& right) {
magnitude_ -= right.magnitude_;
return *this;
}
template<typename D>
inline Quantity<D>& Quantity<D>::operator*=(double const right) {
magnitude_ *= right;
return *this;
}
template<typename D>
inline Quantity<D>& Quantity<D>::operator/=(double const right) {
magnitude_ /= right;
return *this;
}
// Additive group
template<typename D>
inline Quantity<D> Quantity<D>::operator+() const {
return *this;
}
template<typename D>
inline Quantity<D> Quantity<D>::operator-() const {
return Quantity(-magnitude_);
}
template<typename D>
inline Quantity<D> Quantity<D>::operator+(Quantity const& right) const {
return Quantity(magnitude_ + right.magnitude_);
}
template<typename D>
inline Quantity<D> Quantity<D>::operator-(Quantity const& right) const {
return Quantity(magnitude_ - right.magnitude_);
}
// Comparison operators
template<typename D>
inline bool Quantity<D>::operator>(Quantity const& right) const {
return magnitude_ > right.magnitude_;
}
template<typename D>
inline bool Quantity<D>::operator<(Quantity const& right) const {
return magnitude_ < right.magnitude_;
}
template<typename D>
inline bool Quantity<D>::operator>=(Quantity const& right) const {
return magnitude_ >= right.magnitude_;
}
template<typename D>
inline bool Quantity<D>::operator<=(Quantity const& right) const {
return magnitude_ <= right.magnitude_;
}
template<typename D>
inline bool Quantity<D>::operator==(Quantity const& right) const {
return magnitude_ == right.magnitude_;
}
template<typename D>
inline bool Quantity<D>::operator!=(Quantity const& right) const {
return magnitude_ != right.magnitude_;
}
template<typename D>
void Quantity<D>::WriteToMessage(
not_null<serialization::Quantity*> const message) const {
message->set_dimensions(D::representation);
message->set_magnitude(magnitude_);
}
template<typename D>
Quantity<D> Quantity<D>::ReadFromMessage(
serialization::Quantity const& message) {
CHECK_EQ(D::representation, message.dimensions());
return Quantity(message.magnitude());
}
// Multiplicative group
template<typename D>
inline Quantity<D> Quantity<D>::operator/(double const right) const {
return Quantity(magnitude_ / right);
}
template<typename D>
inline Quantity<D> Quantity<D>::operator*(double const right) const {
return Quantity(magnitude_ * right);
}
template<typename LDimensions, typename RDimensions>
inline internal::Product<Quantity<LDimensions>, Quantity<RDimensions>>
operator*(Quantity<LDimensions> const& left,
Quantity<RDimensions> const& right) {
return Product<Quantity<LDimensions>,
Quantity<RDimensions>>(left.magnitude_ * right.magnitude_);
}
template<typename LDimensions, typename RDimensions>
inline internal::Quotient<Quantity<LDimensions>, Quantity<RDimensions>>
operator/(Quantity<LDimensions> const& left,
Quantity<RDimensions> const& right) {
return Quotient<Quantity<LDimensions>,
Quantity<RDimensions>>(left.magnitude_ / right.magnitude_);
}
template<typename RDimensions>
inline Quantity<RDimensions> operator*(double const left,
Quantity<RDimensions> const& right) {
return Quantity<RDimensions>(left * right.magnitude_);
}
template<typename RDimensions>
inline typename Quantity<RDimensions>::Inverse operator/(
double const left,
Quantity<RDimensions> const& right) {
return typename Quantity<RDimensions>::Inverse(left / right.magnitude_);
}
template<int exponent>
inline double Pow(double x) {
return std::pow(x, exponent);
}
// Static specializations for frequently-used exponents, so that this gets
// turned into multiplications at compile time.
template<>
inline double Pow<-3>(double x) {
return 1 / (x * x * x);
}
template<>
inline double Pow<-2>(double x) {
return 1 / (x * x);
}
template<>
inline double Pow<-1>(double x) {
return 1 / x;
}
template<>
inline double Pow<0>(double x) {
return 1;
}
template<>
inline double Pow<1>(double x) {
return x;
}
template<>
inline double Pow<2>(double x) {
return x * x;
}
template<>
inline double Pow<3>(double x) {
return x * x * x;
}
template<int exponent, typename D>
Exponentiation<Quantity<D>, exponent> Pow(
Quantity<D> const& x) {
return Exponentiation<Quantity<D>, exponent>(
Pow<exponent>(x.magnitude_));
}
inline double Abs(double const x) {
return std::abs(x);
}
template<typename D>
Quantity<D> Abs(Quantity<D> const& quantity) {
return Quantity<D>(std::abs(quantity.magnitude_));
}
template<typename Q>
inline Q SIUnit() {
return Q(1);
}
template<>
inline double SIUnit<double>() {
return 1;
}
inline std::string FormatUnit(std::string const& name, int const exponent) {
switch (exponent) {
case 0:
return "";
break;
case 1:
return " " + name;
default:
return " " + name + "^" + std::to_string(exponent);
}
}
inline std::string DebugString(double const number, int const precision) {
char result[50];
#ifdef _MSC_VER
unsigned int old_exponent_format = _set_output_format(_TWO_DIGIT_EXPONENT);
sprintf_s(result, ("%+." + std::to_string(precision) + "e").c_str(), number);
_set_output_format(old_exponent_format);
#else
snprintf(result, sizeof(result),
("%+." + std::to_string(precision) + "e").c_str(), number);
#endif
return result;
}
template<typename D>
std::string DebugString(Quantity<D> const& quantity, int const precision) {
return DebugString(quantity.magnitude_, precision) +
FormatUnit("m", D::Length) + FormatUnit("kg", D::Mass) +
FormatUnit("s", D::Time) + FormatUnit("A", D::Current) +
FormatUnit("K", D::Temperature) + FormatUnit("mol", D::Amount) +
FormatUnit("cd", D::LuminousIntensity) + FormatUnit("cycle", D::Winding) +
FormatUnit("rad", D::Angle) + FormatUnit("sr", D::SolidAngle);
}
template<typename D>
std::ostream& operator<<(std::ostream& out, Quantity<D> const& quantity) {
return out << DebugString(quantity);
}
} // namespace quantities
} // namespace principia
<|endoftext|> |
<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
* Version: MPL 1.1 / GPLv3+ / LGPLv3+
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the License or as specified alternatively below. You may obtain a copy of
* the License at http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* Major Contributor(s):
* Copyright (C) 2012 Michael Meeks <michael.meeks@suse.com> (initial developer)
*
* All Rights Reserved.
*
* For minor contributions see the git repository.
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 3 or later (the "GPLv3+"), or
* the GNU Lesser General Public License Version 3 or later (the "LGPLv3+"),
* in which case the provisions of the GPLv3+ or the LGPLv3+ are applicable
* instead of those above.
*/
#include <sal/config.h>
#include "contacts.hrc"
#include <svtools/filter.hxx>
#include <svx/simptabl.hxx>
#include <tools/resid.hxx>
#include <tubes/conference.hxx>
#include <tubes/collaboration.hxx>
#include <tubes/contact-list.hxx>
#include <tubes/contacts.hxx>
#include <tubes/manager.hxx>
#include <unotools/confignode.hxx>
#include <vcl/fixed.hxx>
#include <vcl/dialog.hxx>
#include <vcl/unohelp.hxx>
#include <vector>
#include <boost/ptr_container/ptr_vector.hpp>
#include <telepathy-glib/telepathy-glib.h>
ResId TubesResId( sal_uInt32 nId )
{
static ResMgr* pResMgr = NULL;
if (!pResMgr)
{
pResMgr = ResMgr::CreateResMgr( "tubes" );
}
return ResId( nId, *pResMgr );
}
#define CONTACTS_DLG
#ifdef CONTACTS_DLG
namespace {
class TubeContacts : public ModelessDialog
{
FixedLine maLabel;
PushButton maBtnConnect;
PushButton maBtnGroup;
PushButton maBtnInvite;
PushButton maBtnListen;
SvxSimpleTableContainer maListContainer;
SvxSimpleTable maList;
TeleManager* mpManager;
Collaboration* mpCollaboration;
DECL_LINK( BtnConnectHdl, void * );
DECL_LINK( BtnGroupHdl, void * );
DECL_LINK( BtnInviteHdl, void * );
DECL_LINK( BtnListenHdl, void * );
struct AccountContact
{
TpAccount* mpAccount;
TpContact* mpContact;
AccountContact( TpAccount* pAccount, TpContact* pContact ):
mpAccount(pAccount), mpContact(pContact) {}
};
boost::ptr_vector<AccountContact> maACs;
void Invite()
{
AccountContact *pAC = NULL;
if (maList.FirstSelected())
pAC = static_cast<AccountContact*> (maList.FirstSelected()->GetUserData());
if (pAC)
{
if (mpCollaboration->GetConference())
{
TpContact* pContact = pAC->mpContact;
mpCollaboration->GetConference()->invite( pContact );
mpCollaboration->SendFile( pContact, OStringToOUString(
mpCollaboration->GetConference()->getUuid(), RTL_TEXTENCODING_UTF8 ) );
}
}
}
void Listen()
{
if (!mpManager->registerClients())
SAL_INFO( "sc.tubes", "Could not register client handlers." );
}
void StartBuddySession()
{
AccountContact *pAC = NULL;
if (maList.FirstSelected())
pAC = static_cast<AccountContact*> (maList.FirstSelected()->GetUserData());
if (pAC)
{
TpAccount* pAccount = pAC->mpAccount;
TpContact* pContact = pAC->mpContact;
fprintf( stderr, "picked %s\n", tp_contact_get_identifier( pContact ) );
TeleConference* pConference = mpManager->startBuddySession( pAccount, pContact );
if (!pConference)
fprintf( stderr, "could not start session with %s\n",
tp_contact_get_identifier( pContact ) );
else
{
mpCollaboration->SetCollaboration( pConference );
mpCollaboration->SendFile( pContact, OStringToOUString(
pConference->getUuid(), RTL_TEXTENCODING_UTF8 ) );
}
}
}
void StartGroupSession()
{
AccountContact *pAC = NULL;
if (maList.FirstSelected())
pAC = static_cast<AccountContact*> (maList.FirstSelected()->GetUserData());
if (pAC)
{
TpAccount* pAccount = pAC->mpAccount;
fprintf( stderr, "picked %s\n", tp_account_get_display_name( pAccount ) );
TeleConference* pConference = mpManager->startGroupSession( pAccount,
rtl::OUString("liboroom"), rtl::OUString("conference.jabber.org") );
if (!pConference)
fprintf( stderr, "could not start group session\n" );
else
{
mpCollaboration->SetCollaboration( pConference );
}
}
}
public:
TubeContacts( Collaboration* pCollaboration ) :
ModelessDialog( NULL, TubesResId( RID_TUBES_DLG_CONTACTS ) ),
maLabel( this, TubesResId( FL_LABEL ) ),
maBtnConnect( this, TubesResId( BTN_CONNECT ) ),
maBtnGroup( this, TubesResId( BTN_GROUP ) ),
maBtnInvite( this, TubesResId( BTN_INVITE ) ),
maBtnListen( this, TubesResId( BTN_LISTEN ) ),
maListContainer( this, TubesResId( CTL_LIST ) ),
maList( maListContainer ),
mpManager( new TeleManager() ),
mpCollaboration( pCollaboration )
{
Hide();
maBtnConnect.SetClickHdl( LINK( this, TubeContacts, BtnConnectHdl ) );
maBtnGroup.SetClickHdl( LINK( this, TubeContacts, BtnGroupHdl ) );
maBtnInvite.SetClickHdl( LINK( this, TubeContacts, BtnInviteHdl ) );
maBtnListen.SetClickHdl( LINK( this, TubeContacts, BtnListenHdl ) );
static long aStaticTabs[]=
{
3 /* count */, 0, 20, 100, 150, 200
};
maList.SvxSimpleTable::SetTabs( aStaticTabs );
String sHeader( '\t' );
sHeader += String( TubesResId( STR_HEADER_ALIAS ) );
sHeader += '\t';
sHeader += String( TubesResId( STR_HEADER_NAME ) );
sHeader += '\t';
maList.InsertHeaderEntry( sHeader, HEADERBAR_APPEND, HIB_LEFT );
mpManager->getContactList()->sigContactListChanged.connect(
boost::bind( &TubeContacts::Populate, this ) );
}
virtual ~TubeContacts()
{
delete mpCollaboration;
delete mpManager;
}
static rtl::OUString fromUTF8( const char *pStr )
{
return rtl::OStringToOUString( rtl::OString( pStr, strlen( pStr ) ),
RTL_TEXTENCODING_UTF8 );
}
void Populate()
{
SAL_INFO( "sc.tubes", "Populating contact list dialog" );
maList.Clear();
ContactList *pContacts = mpManager->getContactList();
if ( pContacts )
{
AccountContactPairV aPairs = pContacts->getContacts();
AccountContactPairV::iterator it;
for( it = aPairs.begin(); it != aPairs.end(); ++it )
{
Image aImage;
GFile *pAvatarFile = tp_contact_get_avatar_file( it->second );
if( pAvatarFile )
{
const rtl::OUString sAvatarFileUrl = fromUTF8( g_file_get_path ( pAvatarFile ) );
Graphic aGraphic;
if( GRFILTER_OK == GraphicFilter::LoadGraphic( sAvatarFileUrl, rtl::OUString(""), aGraphic ) )
{
BitmapEx aBitmap = aGraphic.GetBitmapEx();
double fScale = 30.0 / aBitmap.GetSizePixel().Height();
aBitmap.Scale( fScale, fScale );
aImage = Image( aBitmap );
}
}
rtl::OUStringBuffer aEntry( 128 );
aEntry.append( sal_Unicode( '\t' ) );
aEntry.append( fromUTF8 ( tp_contact_get_alias( it->second ) ) );
aEntry.append( sal_Unicode( '\t' ) );
aEntry.append( fromUTF8 ( tp_contact_get_identifier( it->second ) ) );
aEntry.append( sal_Unicode( '\t' ) );
SvLBoxEntry* pEntry = maList.InsertEntry( aEntry.makeStringAndClear(), aImage, aImage );
// FIXME: ref the TpAccount, TpContact ...
maACs.push_back( new AccountContact( it->first, it->second ) );
pEntry->SetUserData( &maACs.back() );
}
}
Show();
}
};
IMPL_LINK_NOARG( TubeContacts, BtnConnectHdl )
{
StartBuddySession();
return 0;
}
IMPL_LINK_NOARG( TubeContacts, BtnGroupHdl )
{
StartGroupSession();
return 0;
}
IMPL_LINK_NOARG( TubeContacts, BtnInviteHdl )
{
Invite();
return 0;
}
IMPL_LINK_NOARG( TubeContacts, BtnListenHdl )
{
Listen();
return 0;
}
} // anonymous namespace
#endif
namespace tubes {
void createContacts( Collaboration* pCollaboration )
{
#ifdef CONTACTS_DLG
static TubeContacts *pContacts = new TubeContacts( pCollaboration );
pContacts->Populate();
#endif
}
}
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<commit_msg>tubes: remove pointless define<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
* Version: MPL 1.1 / GPLv3+ / LGPLv3+
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the License or as specified alternatively below. You may obtain a copy of
* the License at http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* Major Contributor(s):
* Copyright (C) 2012 Michael Meeks <michael.meeks@suse.com> (initial developer)
*
* All Rights Reserved.
*
* For minor contributions see the git repository.
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 3 or later (the "GPLv3+"), or
* the GNU Lesser General Public License Version 3 or later (the "LGPLv3+"),
* in which case the provisions of the GPLv3+ or the LGPLv3+ are applicable
* instead of those above.
*/
#include <sal/config.h>
#include "contacts.hrc"
#include <svtools/filter.hxx>
#include <svx/simptabl.hxx>
#include <tools/resid.hxx>
#include <tubes/conference.hxx>
#include <tubes/collaboration.hxx>
#include <tubes/contact-list.hxx>
#include <tubes/contacts.hxx>
#include <tubes/manager.hxx>
#include <unotools/confignode.hxx>
#include <vcl/fixed.hxx>
#include <vcl/dialog.hxx>
#include <vcl/unohelp.hxx>
#include <vector>
#include <boost/ptr_container/ptr_vector.hpp>
#include <telepathy-glib/telepathy-glib.h>
ResId TubesResId( sal_uInt32 nId )
{
static ResMgr* pResMgr = NULL;
if (!pResMgr)
{
pResMgr = ResMgr::CreateResMgr( "tubes" );
}
return ResId( nId, *pResMgr );
}
namespace {
class TubeContacts : public ModelessDialog
{
FixedLine maLabel;
PushButton maBtnConnect;
PushButton maBtnGroup;
PushButton maBtnInvite;
PushButton maBtnListen;
SvxSimpleTableContainer maListContainer;
SvxSimpleTable maList;
TeleManager* mpManager;
Collaboration* mpCollaboration;
DECL_LINK( BtnConnectHdl, void * );
DECL_LINK( BtnGroupHdl, void * );
DECL_LINK( BtnInviteHdl, void * );
DECL_LINK( BtnListenHdl, void * );
struct AccountContact
{
TpAccount* mpAccount;
TpContact* mpContact;
AccountContact( TpAccount* pAccount, TpContact* pContact ):
mpAccount(pAccount), mpContact(pContact) {}
};
boost::ptr_vector<AccountContact> maACs;
void Invite()
{
AccountContact *pAC = NULL;
if (maList.FirstSelected())
pAC = static_cast<AccountContact*> (maList.FirstSelected()->GetUserData());
if (pAC)
{
if (mpCollaboration->GetConference())
{
TpContact* pContact = pAC->mpContact;
mpCollaboration->GetConference()->invite( pContact );
mpCollaboration->SendFile( pContact, OStringToOUString(
mpCollaboration->GetConference()->getUuid(), RTL_TEXTENCODING_UTF8 ) );
}
}
}
void Listen()
{
if (!mpManager->registerClients())
SAL_INFO( "sc.tubes", "Could not register client handlers." );
}
void StartBuddySession()
{
AccountContact *pAC = NULL;
if (maList.FirstSelected())
pAC = static_cast<AccountContact*> (maList.FirstSelected()->GetUserData());
if (pAC)
{
TpAccount* pAccount = pAC->mpAccount;
TpContact* pContact = pAC->mpContact;
fprintf( stderr, "picked %s\n", tp_contact_get_identifier( pContact ) );
TeleConference* pConference = mpManager->startBuddySession( pAccount, pContact );
if (!pConference)
fprintf( stderr, "could not start session with %s\n",
tp_contact_get_identifier( pContact ) );
else
{
mpCollaboration->SetCollaboration( pConference );
mpCollaboration->SendFile( pContact, OStringToOUString(
pConference->getUuid(), RTL_TEXTENCODING_UTF8 ) );
}
}
}
void StartGroupSession()
{
AccountContact *pAC = NULL;
if (maList.FirstSelected())
pAC = static_cast<AccountContact*> (maList.FirstSelected()->GetUserData());
if (pAC)
{
TpAccount* pAccount = pAC->mpAccount;
fprintf( stderr, "picked %s\n", tp_account_get_display_name( pAccount ) );
TeleConference* pConference = mpManager->startGroupSession( pAccount,
rtl::OUString("liboroom"), rtl::OUString("conference.jabber.org") );
if (!pConference)
fprintf( stderr, "could not start group session\n" );
else
{
mpCollaboration->SetCollaboration( pConference );
}
}
}
public:
TubeContacts( Collaboration* pCollaboration ) :
ModelessDialog( NULL, TubesResId( RID_TUBES_DLG_CONTACTS ) ),
maLabel( this, TubesResId( FL_LABEL ) ),
maBtnConnect( this, TubesResId( BTN_CONNECT ) ),
maBtnGroup( this, TubesResId( BTN_GROUP ) ),
maBtnInvite( this, TubesResId( BTN_INVITE ) ),
maBtnListen( this, TubesResId( BTN_LISTEN ) ),
maListContainer( this, TubesResId( CTL_LIST ) ),
maList( maListContainer ),
mpManager( new TeleManager() ),
mpCollaboration( pCollaboration )
{
Hide();
maBtnConnect.SetClickHdl( LINK( this, TubeContacts, BtnConnectHdl ) );
maBtnGroup.SetClickHdl( LINK( this, TubeContacts, BtnGroupHdl ) );
maBtnInvite.SetClickHdl( LINK( this, TubeContacts, BtnInviteHdl ) );
maBtnListen.SetClickHdl( LINK( this, TubeContacts, BtnListenHdl ) );
static long aStaticTabs[]=
{
3 /* count */, 0, 20, 100, 150, 200
};
maList.SvxSimpleTable::SetTabs( aStaticTabs );
String sHeader( '\t' );
sHeader += String( TubesResId( STR_HEADER_ALIAS ) );
sHeader += '\t';
sHeader += String( TubesResId( STR_HEADER_NAME ) );
sHeader += '\t';
maList.InsertHeaderEntry( sHeader, HEADERBAR_APPEND, HIB_LEFT );
mpManager->getContactList()->sigContactListChanged.connect(
boost::bind( &TubeContacts::Populate, this ) );
}
virtual ~TubeContacts()
{
delete mpCollaboration;
delete mpManager;
}
static rtl::OUString fromUTF8( const char *pStr )
{
return rtl::OStringToOUString( rtl::OString( pStr, strlen( pStr ) ),
RTL_TEXTENCODING_UTF8 );
}
void Populate()
{
SAL_INFO( "sc.tubes", "Populating contact list dialog" );
maList.Clear();
ContactList *pContacts = mpManager->getContactList();
if ( pContacts )
{
AccountContactPairV aPairs = pContacts->getContacts();
AccountContactPairV::iterator it;
for( it = aPairs.begin(); it != aPairs.end(); ++it )
{
Image aImage;
GFile *pAvatarFile = tp_contact_get_avatar_file( it->second );
if( pAvatarFile )
{
const rtl::OUString sAvatarFileUrl = fromUTF8( g_file_get_path ( pAvatarFile ) );
Graphic aGraphic;
if( GRFILTER_OK == GraphicFilter::LoadGraphic( sAvatarFileUrl, rtl::OUString(""), aGraphic ) )
{
BitmapEx aBitmap = aGraphic.GetBitmapEx();
double fScale = 30.0 / aBitmap.GetSizePixel().Height();
aBitmap.Scale( fScale, fScale );
aImage = Image( aBitmap );
}
}
rtl::OUStringBuffer aEntry( 128 );
aEntry.append( sal_Unicode( '\t' ) );
aEntry.append( fromUTF8 ( tp_contact_get_alias( it->second ) ) );
aEntry.append( sal_Unicode( '\t' ) );
aEntry.append( fromUTF8 ( tp_contact_get_identifier( it->second ) ) );
aEntry.append( sal_Unicode( '\t' ) );
SvLBoxEntry* pEntry = maList.InsertEntry( aEntry.makeStringAndClear(), aImage, aImage );
// FIXME: ref the TpAccount, TpContact ...
maACs.push_back( new AccountContact( it->first, it->second ) );
pEntry->SetUserData( &maACs.back() );
}
}
Show();
}
};
IMPL_LINK_NOARG( TubeContacts, BtnConnectHdl )
{
StartBuddySession();
return 0;
}
IMPL_LINK_NOARG( TubeContacts, BtnGroupHdl )
{
StartGroupSession();
return 0;
}
IMPL_LINK_NOARG( TubeContacts, BtnInviteHdl )
{
Invite();
return 0;
}
IMPL_LINK_NOARG( TubeContacts, BtnListenHdl )
{
Listen();
return 0;
}
} // anonymous namespace
namespace tubes {
void createContacts( Collaboration* pCollaboration )
{
static TubeContacts *pContacts = new TubeContacts( pCollaboration );
pContacts->Populate();
}
}
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<|endoftext|> |
<commit_before>/* Copyright © 2006-2007 Fredrik Höglund <fredrik@kde.org>
* (c)GPL2 (c)GPL3
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public
* License version 2 or at your option version 3 as published
* by the Free Software Foundation.
*
* 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; see the file COPYING. If not, write to
* the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301, USA.
*/
/*
* additional code: Ketmar // Vampire Avalon (psyc://ketmar.no-ip.org/~Ketmar)
*/
#include <QDebug>
#include "crtheme.h"
#include <QStyle>
#include <QX11Info>
#include "cfgfile.h"
#include <X11/Xlib.h>
#include <X11/Xcursor/Xcursor.h>
#include <X11/extensions/Xfixes.h>
// Static variable holding alternative names for some cursors
static QHash<QString, QString> alternatives;
///////////////////////////////////////////////////////////////////////////////
XCursorThemeData::XCursorThemeData (const QDir &aDir) {
mHidden = false;
// parse configs, etc
mPath = aDir.path();
setName(aDir.dirName());
if (aDir.exists("index.theme")) parseIndexFile();
if (mDescription.isEmpty()) mDescription = "no description";
if (mTitle.isEmpty()) mTitle = mName;
}
void XCursorThemeData::parseIndexFile () {
QMultiMap<QString, QString> cfg = loadCfgFile(mPath+"/index.theme", true);
if (cfg.contains("icon theme/name")) mTitle = cfg.values("icon theme/name").at(0).trimmed();
if (cfg.contains("icon theme/comment")) mDescription = cfg.values("icon theme/comment").at(0).trimmed();
if (cfg.contains("icon theme/example")) mSample = cfg.values("icon theme/example").at(0).trimmed();
if (cfg.contains("icon theme/hidden")) {
QString hiddenValue = cfg.values("icon theme/hidden").at(0).toLower();
mHidden = hiddenValue=="false" ? false : true;
}
if (cfg.contains("icon theme/inherits")) {
QStringList i = cfg.values("icon theme/inherits"), res;
for (int f = i.size()-1; f >= 0; f--) res << i.at(f).trimmed();
}
if (mDescription.startsWith("- Converted by")) mDescription.remove(0, 2);
}
QString XCursorThemeData::findAlternative (const QString &name) const {
if (alternatives.isEmpty()) {
alternatives.reserve(18);
// Qt uses non-standard names for some core cursors.
// If Xcursor fails to load the cursor, Qt creates it with the correct name using the
// core protcol instead (which in turn calls Xcursor). We emulate that process here.
// Note that there's a core cursor called cross, but it's not the one Qt expects.
alternatives.insert("cross", "crosshair");
alternatives.insert("up_arrow", "center_ptr");
alternatives.insert("wait", "watch");
alternatives.insert("ibeam", "xterm");
alternatives.insert("size_all", "fleur");
alternatives.insert("pointing_hand", "hand2");
// Precomputed MD5 hashes for the hardcoded bitmap cursors in Qt and KDE.
// Note that the MD5 hash for left_ptr_watch is for the KDE version of that cursor.
alternatives.insert("size_ver", "00008160000006810000408080010102");
alternatives.insert("size_hor", "028006030e0e7ebffc7f7070c0600140");
alternatives.insert("size_bdiag", "c7088f0f3e6c8088236ef8e1e3e70000");
alternatives.insert("size_fdiag", "fcf1c3c7cd4491d801f1e1c78f100000");
alternatives.insert("whats_this", "d9ce0ab605698f320427677b458ad60b");
alternatives.insert("split_h", "14fef782d02440884392942c11205230");
alternatives.insert("split_v", "2870a09082c103050810ffdffffe0204");
alternatives.insert("forbidden", "03b6e0fcb3499374a867c041f52298f0");
alternatives.insert("left_ptr_watch", "3ecb610c1bf2410f44200f48c40d3599");
alternatives.insert("hand2", "e29285e634086352946a0e7090d73106");
alternatives.insert("openhand", "9141b49c8149039304290b508d208c40");
alternatives.insert("closedhand", "05e88622050804100c20044008402080");
}
return alternatives.value(name, QString());
}
QPixmap XCursorThemeData::icon () const {
if (mIcon.isNull()) mIcon = createIcon();
return mIcon;
}
QImage XCursorThemeData::autoCropImage (const QImage &image) const {
// Compute an autocrop rectangle for the image
QRect r(image.rect().bottomRight(), image.rect().topLeft());
const quint32 *pixels = reinterpret_cast<const quint32*>(image.bits());
for (int y = 0; y < image.height(); y++) {
for (int x = 0; x < image.width(); x++) {
if (*(pixels++)) {
if (x < r.left()) r.setLeft(x);
if (x > r.right()) r.setRight(x);
if (y < r.top()) r.setTop(y);
if (y > r.bottom()) r.setBottom(y);
}
}
}
// Normalize the rectangle
return image.copy(r.normalized());
}
static int nominalCursorSize (int iconSize) {
for (int i = 512; i > 8; i /= 2) {
if (i < iconSize) return i;
if ((i*0.75) < iconSize) return int(i*0.75);
}
return 8;
}
QPixmap XCursorThemeData::createIcon () const {
int iconSize = QApplication::style()->pixelMetric(QStyle::PM_LargeIconSize);
int cursorSize = nominalCursorSize(iconSize);
QSize size = QSize(iconSize, iconSize);
QPixmap pixmap;
QImage image = loadImage(sample(), cursorSize);
if (image.isNull() && sample() != "left_ptr") image = loadImage("left_ptr", cursorSize);
if (!image.isNull()) {
// Scale the image if it's larger than the preferred icon size
if (image.width() > size.width() || image.height() > size.height())
image = image.scaled(size, Qt::KeepAspectRatio, Qt::SmoothTransformation);
pixmap = QPixmap::fromImage(image);
}
return pixmap;
}
XcursorImage *XCursorThemeData::xcLoadImage (const QString &image, int size) const {
QByteArray cursorName = QFile::encodeName(image);
QByteArray themeName = QFile::encodeName(name());
return XcursorLibraryLoadImage(cursorName, themeName, size);
}
XcursorImages *XCursorThemeData::xcLoadImages (const QString &image, int size) const {
QByteArray cursorName = QFile::encodeName(image);
QByteArray themeName = QFile::encodeName(name());
return XcursorLibraryLoadImages(cursorName, themeName, size);
}
QCursor XCursorThemeData::loadCursor (const QString &name, int size) const {
if (size == -1) size = XcursorGetDefaultSize(QX11Info::display());
// Load the cursor images
XcursorImages *images = xcLoadImages(name, size);
if (!images) images = xcLoadImages(findAlternative(name), size);
// Fall back to a legacy cursor
//if (!images) return LegacyTheme::loadCursor(name);
if (!images) return false;
// Create the cursor
Cursor handle = XcursorImagesLoadCursor(QX11Info::display(), images);
QCursor cursor = QCursor(Qt::HANDLE(handle)); // QCursor takes ownership of the handle
XcursorImagesDestroy(images);
//setCursorName(cursor, name);
return cursor;
}
QImage XCursorThemeData::loadImage (const QString &name, int size) const {
if (size == -1) size = XcursorGetDefaultSize(QX11Info::display());
// Load the image
XcursorImage *xcimage = xcLoadImage(name, size);
if (!xcimage) xcimage = xcLoadImage(findAlternative(name), size);
// Fall back to a legacy cursor
//if (!xcimage) return LegacyTheme::loadImage(name);
if (!xcimage) return QImage();
// Convert the XcursorImage to a QImage, and auto-crop it
QImage image((uchar *)xcimage->pixels, xcimage->width, xcimage->height, QImage::Format_ARGB32_Premultiplied);
image = autoCropImage(image);
XcursorImageDestroy(xcimage);
return image;
}
bool XCursorThemeData::isWritable () const {
QFileInfo fi(path());
return fi.isWritable();
}
///////////////////////////////////////////////////////////////////////////////
bool haveXfixes () {
bool result = false;
int event_base, error_base;
if (XFixesQueryExtension(QX11Info::display(), &event_base, &error_base)) {
int major, minor;
XFixesQueryVersion(QX11Info::display(), &major, &minor);
result = (major >= 2);
}
return result;
}
bool applyTheme (const XCursorThemeData &theme) {
// Require the Xcursor version that shipped with X11R6.9 or greater, since
// in previous versions the Xfixes code wasn't enabled due to a bug in the
// build system (freedesktop bug #975).
if (!haveXfixes()) return false;
QByteArray themeName = QFile::encodeName(theme.name());
// Set up the proper launch environment for newly started apps
//k8:!!!:KToolInvocation::klauncher()->setLaunchEnv("XCURSOR_THEME", themeName);
// Update the Xcursor X resources
//k8:!!!:runRdb(0);
// Reload the standard cursors
QStringList names;
// Qt cursors
names << "left_ptr" << "up_arrow" << "cross" << "wait"
<< "left_ptr_watch" << "ibeam" << "size_ver" << "size_hor"
<< "size_bdiag" << "size_fdiag" << "size_all" << "split_v"
<< "split_h" << "pointing_hand" << "openhand"
<< "closedhand" << "forbidden" << "whats_this";
// X core cursors
names << "X_cursor" << "right_ptr" << "hand1"
<< "hand2" << "watch" << "xterm"
<< "crosshair" << "left_ptr_watch" << "center_ptr"
<< "sb_h_double_arrow" << "sb_v_double_arrow" << "fleur"
<< "top_left_corner" << "top_side" << "top_right_corner"
<< "right_side" << "bottom_right_corner" << "bottom_side"
<< "bottom_left_corner" << "left_side" << "question_arrow"
<< "pirate";
//QX11Info x11Info;
foreach (const QString &name, names) {
QCursor cursor = theme.loadCursor(name);
XFixesChangeCursorByName(QX11Info::display(), cursor.handle(), QFile::encodeName(name));
}
return true;
}
QString getCurrentTheme () {
return XcursorGetTheme(QX11Info::display());
}
<commit_msg>fix coding style errors<commit_after>/* Copyright © 2006-2007 Fredrik Höglund <fredrik@kde.org>
* (c)GPL2 (c)GPL3
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public
* License version 2 or at your option version 3 as published
* by the Free Software Foundation.
*
* 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; see the file COPYING. If not, write to
* the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301, USA.
*/
/*
* additional code: Ketmar // Vampire Avalon (psyc://ketmar.no-ip.org/~Ketmar)
*/
#include <QtCore/QDebug>
#include "crtheme.h"
#include <QtGui/QStyle>
#include <QtGui/QX11Info>
#include "cfgfile.h"
#include <X11/Xlib.h>
#include <X11/Xcursor/Xcursor.h>
#include <X11/extensions/Xfixes.h>
// Static variable holding alternative names for some cursors
static QHash<QString, QString> alternatives;
///////////////////////////////////////////////////////////////////////////////
XCursorThemeData::XCursorThemeData(const QDir &aDir)
{
mHidden = false;
// parse configs, etc
mPath = aDir.path();
setName(aDir.dirName());
if (aDir.exists("index.theme")) parseIndexFile();
if (mDescription.isEmpty()) mDescription = "no description";
if (mTitle.isEmpty()) mTitle = mName;
}
void XCursorThemeData::parseIndexFile()
{
QMultiMap<QString, QString> cfg = loadCfgFile(mPath+"/index.theme", true);
if (cfg.contains("icon theme/name")) mTitle = cfg.values("icon theme/name").at(0).trimmed();
if (cfg.contains("icon theme/comment")) mDescription = cfg.values("icon theme/comment").at(0).trimmed();
if (cfg.contains("icon theme/example")) mSample = cfg.values("icon theme/example").at(0).trimmed();
if (cfg.contains("icon theme/hidden"))
{
QString hiddenValue = cfg.values("icon theme/hidden").at(0).toLower();
mHidden = hiddenValue=="false" ? false : true;
}
if (cfg.contains("icon theme/inherits"))
{
QStringList i = cfg.values("icon theme/inherits"), res;
for (int f = i.size()-1; f >= 0; f--) res << i.at(f).trimmed();
}
if (mDescription.startsWith("- Converted by")) mDescription.remove(0, 2);
}
QString XCursorThemeData::findAlternative(const QString &name) const
{
if (alternatives.isEmpty())
{
alternatives.reserve(18);
// Qt uses non-standard names for some core cursors.
// If Xcursor fails to load the cursor, Qt creates it with the correct name using the
// core protcol instead (which in turn calls Xcursor). We emulate that process here.
// Note that there's a core cursor called cross, but it's not the one Qt expects.
alternatives.insert("cross", "crosshair");
alternatives.insert("up_arrow", "center_ptr");
alternatives.insert("wait", "watch");
alternatives.insert("ibeam", "xterm");
alternatives.insert("size_all", "fleur");
alternatives.insert("pointing_hand", "hand2");
// Precomputed MD5 hashes for the hardcoded bitmap cursors in Qt and KDE.
// Note that the MD5 hash for left_ptr_watch is for the KDE version of that cursor.
alternatives.insert("size_ver", "00008160000006810000408080010102");
alternatives.insert("size_hor", "028006030e0e7ebffc7f7070c0600140");
alternatives.insert("size_bdiag", "c7088f0f3e6c8088236ef8e1e3e70000");
alternatives.insert("size_fdiag", "fcf1c3c7cd4491d801f1e1c78f100000");
alternatives.insert("whats_this", "d9ce0ab605698f320427677b458ad60b");
alternatives.insert("split_h", "14fef782d02440884392942c11205230");
alternatives.insert("split_v", "2870a09082c103050810ffdffffe0204");
alternatives.insert("forbidden", "03b6e0fcb3499374a867c041f52298f0");
alternatives.insert("left_ptr_watch", "3ecb610c1bf2410f44200f48c40d3599");
alternatives.insert("hand2", "e29285e634086352946a0e7090d73106");
alternatives.insert("openhand", "9141b49c8149039304290b508d208c40");
alternatives.insert("closedhand", "05e88622050804100c20044008402080");
}
return alternatives.value(name, QString());
}
QPixmap XCursorThemeData::icon() const
{
if (mIcon.isNull()) mIcon = createIcon();
return mIcon;
}
QImage XCursorThemeData::autoCropImage(const QImage &image) const
{
// Compute an autocrop rectangle for the image
QRect r(image.rect().bottomRight(), image.rect().topLeft());
const quint32 *pixels = reinterpret_cast<const quint32*>(image.bits());
for (int y = 0; y < image.height(); ++y)
{
for (int x = 0; x < image.width(); ++x)
{
if (*(pixels++))
{
if (x < r.left()) r.setLeft(x);
if (x > r.right()) r.setRight(x);
if (y < r.top()) r.setTop(y);
if (y > r.bottom()) r.setBottom(y);
}
}
}
// Normalize the rectangle
return image.copy(r.normalized());
}
static int nominalCursorSize(int iconSize)
{
for (int i = 512; i > 8; i /= 2)
{
if (i < iconSize) return i;
if ((i*0.75) < iconSize) return int(i*0.75);
}
return 8;
}
QPixmap XCursorThemeData::createIcon() const
{
int iconSize = QApplication::style()->pixelMetric(QStyle::PM_LargeIconSize);
int cursorSize = nominalCursorSize(iconSize);
QSize size = QSize(iconSize, iconSize);
QPixmap pixmap;
QImage image = loadImage(sample(), cursorSize);
if (image.isNull() && sample() != "left_ptr") image = loadImage("left_ptr", cursorSize);
if (!image.isNull())
{
// Scale the image if it's larger than the preferred icon size
if (image.width() > size.width() || image.height() > size.height())
{
image = image.scaled(size, Qt::KeepAspectRatio, Qt::SmoothTransformation);
pixmap = QPixmap::fromImage(image);
}
}
return pixmap;
}
XcursorImage *XCursorThemeData::xcLoadImage(const QString &image, int size) const
{
QByteArray cursorName = QFile::encodeName(image);
QByteArray themeName = QFile::encodeName(name());
return XcursorLibraryLoadImage(cursorName, themeName, size);
}
XcursorImages *XCursorThemeData::xcLoadImages(const QString &image, int size) const
{
QByteArray cursorName = QFile::encodeName(image);
QByteArray themeName = QFile::encodeName(name());
return XcursorLibraryLoadImages(cursorName, themeName, size);
}
QCursor XCursorThemeData::loadCursor(const QString &name, int size) const
{
if (size == -1) size = XcursorGetDefaultSize(QX11Info::display());
// Load the cursor images
XcursorImages *images = xcLoadImages(name, size);
if (!images) images = xcLoadImages(findAlternative(name), size);
// Fall back to a legacy cursor
//if (!images) return LegacyTheme::loadCursor(name);
if (!images) return false;
// Create the cursor
Cursor handle = XcursorImagesLoadCursor(QX11Info::display(), images);
QCursor cursor = QCursor(Qt::HANDLE(handle)); // QCursor takes ownership of the handle
XcursorImagesDestroy(images);
//setCursorName(cursor, name);
return cursor;
}
QImage XCursorThemeData::loadImage(const QString &name, int size) const
{
if (size == -1) size = XcursorGetDefaultSize(QX11Info::display());
// Load the image
XcursorImage *xcimage = xcLoadImage(name, size);
if (!xcimage) xcimage = xcLoadImage(findAlternative(name), size);
// Fall back to a legacy cursor
//if (!xcimage) return LegacyTheme::loadImage(name);
if (!xcimage) return QImage();
// Convert the XcursorImage to a QImage, and auto-crop it
QImage image((uchar *)xcimage->pixels, xcimage->width, xcimage->height, QImage::Format_ARGB32_Premultiplied);
image = autoCropImage(image);
XcursorImageDestroy(xcimage);
return image;
}
bool XCursorThemeData::isWritable() const
{
QFileInfo fi(path());
return fi.isWritable();
}
///////////////////////////////////////////////////////////////////////////////
bool haveXfixes()
{
bool result = false;
int event_base, error_base;
if (XFixesQueryExtension(QX11Info::display(), &event_base, &error_base))
{
int major, minor;
XFixesQueryVersion(QX11Info::display(), &major, &minor);
result = (major >= 2);
}
return result;
}
bool applyTheme(const XCursorThemeData &theme)
{
// Require the Xcursor version that shipped with X11R6.9 or greater, since
// in previous versions the Xfixes code wasn't enabled due to a bug in the
// build system (freedesktop bug #975).
if (!haveXfixes()) return false;
QByteArray themeName = QFile::encodeName(theme.name());
// Set up the proper launch environment for newly started apps
//k8:!!!:KToolInvocation::klauncher()->setLaunchEnv("XCURSOR_THEME", themeName);
// Update the Xcursor X resources
//k8:!!!:runRdb(0);
// Reload the standard cursors
QStringList names;
// Qt cursors
names << "left_ptr" << "up_arrow" << "cross" << "wait"
<< "left_ptr_watch" << "ibeam" << "size_ver" << "size_hor"
<< "size_bdiag" << "size_fdiag" << "size_all" << "split_v"
<< "split_h" << "pointing_hand" << "openhand"
<< "closedhand" << "forbidden" << "whats_this";
// X core cursors
names << "X_cursor" << "right_ptr" << "hand1"
<< "hand2" << "watch" << "xterm"
<< "crosshair" << "left_ptr_watch" << "center_ptr"
<< "sb_h_double_arrow" << "sb_v_double_arrow" << "fleur"
<< "top_left_corner" << "top_side" << "top_right_corner"
<< "right_side" << "bottom_right_corner" << "bottom_side"
<< "bottom_left_corner" << "left_side" << "question_arrow"
<< "pirate";
//QX11Info x11Info;
foreach (const QString &name, names)
{
QCursor cursor = theme.loadCursor(name);
XFixesChangeCursorByName(QX11Info::display(), cursor.handle(), QFile::encodeName(name));
}
return true;
}
QString getCurrentTheme()
{
return XcursorGetTheme(QX11Info::display());
}
<|endoftext|> |
<commit_before>// Copyright 2017 Open Source Robotics Foundation, 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.
#ifndef RCLCPP__TIME_HPP_
#define RCLCPP__TIME_HPP_
#include <utility>
#include "builtin_interfaces/msg/time.hpp"
#include "rcl/time.h"
#include "rcutils/time.h"
#include "rclcpp/exceptions.hpp"
namespace rclcpp
{
class Time
{
public:
template<rcl_time_source_type_t ClockT = RCL_SYSTEM_TIME>
static Time
now()
{
rcutils_time_point_value_t rcutils_now = 0;
rcutils_ret_t ret = RCUTILS_RET_ERROR;
if (ClockT == RCL_ROS_TIME) {
throw std::runtime_error("RCL_ROS_TIME is currently not implemented.");
ret = false;
} else if (ClockT == RCL_SYSTEM_TIME) {
ret = rcutils_system_time_now(&rcutils_now);
} else if (ClockT == RCL_STEADY_TIME) {
ret = rcutils_steady_time_now(&rcutils_now);
}
if (ret != RCUTILS_RET_OK) {
rclcpp::exceptions::throw_from_rcl_error(
ret, "Could not get current time: ");
}
return Time(std::move(rcutils_now));
}
operator builtin_interfaces::msg::Time() const
{
builtin_interfaces::msg::Time msg_time;
msg_time.sec = static_cast<std::int32_t>(RCL_NS_TO_S(rcl_time_));
msg_time.nanosec = static_cast<std::uint32_t>(rcl_time_ % (1000 * 1000 * 1000));
return msg_time;
}
private:
rcl_time_point_value_t rcl_time_;
explicit Time(rcl_time_point_value_t && rcl_time)
: rcl_time_(std::forward<decltype(rcl_time)>(rcl_time))
{}
};
} // namespace rclcpp
#endif // RCLCPP__TIME_HPP_
<commit_msg>use rcl api for rclcpp time (#348)<commit_after>// Copyright 2017 Open Source Robotics Foundation, 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.
#ifndef RCLCPP__TIME_HPP_
#define RCLCPP__TIME_HPP_
#include <utility>
#include "builtin_interfaces/msg/time.hpp"
#include "rcl/time.h"
#include "rclcpp/exceptions.hpp"
#include "rcutils/logging_macros.h"
namespace rclcpp
{
class Time
{
public:
template<rcl_time_source_type_t ClockT = RCL_SYSTEM_TIME>
static Time
now()
{
// TODO(karsten1987): This impl throws explicitely on RCL_ROS_TIME
// we have to do this, because rcl_time_source_init returns RCL_RET_OK
// for RCL_ROS_TIME, however defaults to system time under the hood.
// ref: https://github.com/ros2/rcl/blob/master/rcl/src/rcl/time.c#L66-L77
// This section can be removed when rcl supports ROS_TIME correctly.
if (ClockT == RCL_ROS_TIME) {
throw std::runtime_error("RCL_ROS_TIME is currently not implemented.");
}
rcl_ret_t ret = RCL_RET_ERROR;
rcl_time_source_t time_source;
ret = rcl_time_source_init(ClockT, &time_source);
if (ret != RCL_RET_OK) {
rclcpp::exceptions::throw_from_rcl_error(
ret, "could not initialize time source: ");
}
rcl_time_point_t time_point;
ret = rcl_time_point_init(&time_point, &time_source);
if (ret != RCL_RET_OK) {
rclcpp::exceptions::throw_from_rcl_error(
ret, "could not initialize time point: ");
}
ret = rcl_time_point_get_now(&time_point);
if (ret != RCL_RET_OK) {
rclcpp::exceptions::throw_from_rcl_error(
ret, "could not get current time stamp: ");
}
return Time(std::move(time_point));
}
operator builtin_interfaces::msg::Time() const
{
builtin_interfaces::msg::Time msg_time;
msg_time.sec = static_cast<std::int32_t>(RCL_NS_TO_S(rcl_time_.nanoseconds));
msg_time.nanosec = static_cast<std::uint32_t>(rcl_time_.nanoseconds % (1000 * 1000 * 1000));
return msg_time;
}
private:
rcl_time_point_t rcl_time_;
explicit Time(rcl_time_point_t && rcl_time)
: rcl_time_(std::forward<decltype(rcl_time)>(rcl_time))
{}
public:
virtual ~Time()
{
if (rcl_time_point_fini(&rcl_time_) != RCL_RET_OK) {
RCUTILS_LOG_FATAL("failed to reclaim rcl_time_point_t in destructor of rclcpp::Time")
}
}
};
} // namespace rclcpp
#endif // RCLCPP__TIME_HPP_
<|endoftext|> |
<commit_before>/*
qgpgmekeylistjob.cpp
This file is part of libkleopatra, the KDE keymanagement library
Copyright (c) 2004,2008 Klarälvdalens Datakonsult AB
Libkleopatra 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.
Libkleopatra 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 "qgpgmekeylistjob.h"
#include <gpgme++/key.h>
#include <gpgme++/context.h>
#include <gpgme++/keylistresult.h>
#include <gpg-error.h>
#include <kmessagebox.h>
#include <klocale.h>
#include <kdebug.h>
#include <QStringList>
#include <algorithm>
#include <cstdlib>
#include <cstring>
#include <cassert>
using namespace Kleo;
using namespace GpgME;
using namespace boost;
QGpgMEKeyListJob::QGpgMEKeyListJob( Context * context )
: mixin_type( context ),
mResult(), mSecretOnly( false )
{
lateInitialization();
}
QGpgMEKeyListJob::~QGpgMEKeyListJob() {}
static KeyListResult do_list_keys( Context * ctx, const QStringList & pats, std::vector<Key> & keys, bool secretOnly ) {
const _detail::PatternConverter pc( pats );
if ( const Error err = ctx->startKeyListing( pc.patterns(), secretOnly ) )
return KeyListResult( 0, err );
Error err;
do
keys.push_back( ctx->nextKey( err ) );
while ( !err );
keys.pop_back();
return ctx->endKeyListing();
}
static QGpgMEKeyListJob::result_type list_keys( Context * ctx, QStringList pats, bool secretOnly ) {
if ( pats.size() < 2 ) {
std::vector<Key> keys;
const KeyListResult r = do_list_keys( ctx, pats, keys, secretOnly );
return make_tuple( r, keys, QString() );
}
// The communication channel between gpgme and gpgsm is limited in
// the number of patterns that can be transported, but they won't
// say to how much, so we need to find out ourselves if we get a
// LINE_TOO_LONG error back...
// We could of course just feed them single patterns, and that would
// probably be easier, but the performance penalty would currently
// be noticeable.
unsigned int chunkSize = pats.size();
retry:
std::vector<Key> keys;
keys.reserve( pats.size() );
KeyListResult result;
do {
const KeyListResult this_result = do_list_keys( ctx, pats.mid( 0, chunkSize ), keys, secretOnly );
if ( this_result.error().code() == GPG_ERR_LINE_TOO_LONG ) {
// got LINE_TOO_LONG, try a smaller chunksize:
chunkSize /= 2;
if ( chunkSize < 1 )
// chunks smaller than one can't be -> return the error.
return make_tuple( this_result, keys, QString() );
else
goto retry;
}
// ok, that seemed to work...
result.mergeWith( this_result );
if ( result.error().code() )
break;
pats = pats.mid( chunkSize );
} while ( !pats.empty() );
return make_tuple( result, keys, QString() );
}
Error QGpgMEKeyListJob::start( const QStringList & patterns, bool secretOnly ) {
mSecretOnly = secretOnly;
run( bind( &list_keys, _1, patterns, secretOnly ) );
return Error();
}
KeyListResult QGpgMEKeyListJob::exec( const QStringList & patterns, bool secretOnly, std::vector<Key> & keys ) {
mSecretOnly = secretOnly;
const result_type r = list_keys( context(), patterns, secretOnly );
resultHook( r );
keys = get<1>( r );
return get<0>( r );
}
void QGpgMEKeyListJob::resultHook( const result_type & tuple ) {
mResult = get<0>( tuple );
Q_FOREACH( const Key & key, get<1>( tuple ) )
emit nextKey( key );
}
void QGpgMEKeyListJob::showErrorDialog( QWidget * parent, const QString & caption ) const {
if ( !mResult.error() || mResult.error().isCanceled() )
return;
const QString msg = i18n( "<qt><p>An error occurred while fetching "
"the keys from the backend:</p>"
"<p><b>%1</b></p></qt>" ,
QString::fromLocal8Bit( mResult.error().asString() ) );
KMessageBox::error( parent, msg, caption );
}
#include "qgpgmekeylistjob.moc"
<commit_msg>Cancel the completed operation to avoid the hang in the other operations<commit_after>/*
qgpgmekeylistjob.cpp
This file is part of libkleopatra, the KDE keymanagement library
Copyright (c) 2004,2008 Klarälvdalens Datakonsult AB
Libkleopatra 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.
Libkleopatra 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 "qgpgmekeylistjob.h"
#include <gpgme++/key.h>
#include <gpgme++/context.h>
#include <gpgme++/keylistresult.h>
#include <gpg-error.h>
#include <kmessagebox.h>
#include <klocale.h>
#include <kdebug.h>
#include <QStringList>
#include <algorithm>
#include <cstdlib>
#include <cstring>
#include <cassert>
using namespace Kleo;
using namespace GpgME;
using namespace boost;
QGpgMEKeyListJob::QGpgMEKeyListJob( Context * context )
: mixin_type( context ),
mResult(), mSecretOnly( false )
{
lateInitialization();
}
QGpgMEKeyListJob::~QGpgMEKeyListJob() {}
static KeyListResult do_list_keys( Context * ctx, const QStringList & pats, std::vector<Key> & keys, bool secretOnly ) {
const _detail::PatternConverter pc( pats );
if ( const Error err = ctx->startKeyListing( pc.patterns(), secretOnly ) )
return KeyListResult( 0, err );
Error err;
do
keys.push_back( ctx->nextKey( err ) );
while ( !err );
keys.pop_back();
const KeyListResult result = ctx->endKeyListing();
ctx->cancelPendingOperation();
return result;
}
static QGpgMEKeyListJob::result_type list_keys( Context * ctx, QStringList pats, bool secretOnly ) {
if ( pats.size() < 2 ) {
std::vector<Key> keys;
const KeyListResult r = do_list_keys( ctx, pats, keys, secretOnly );
return make_tuple( r, keys, QString() );
}
// The communication channel between gpgme and gpgsm is limited in
// the number of patterns that can be transported, but they won't
// say to how much, so we need to find out ourselves if we get a
// LINE_TOO_LONG error back...
// We could of course just feed them single patterns, and that would
// probably be easier, but the performance penalty would currently
// be noticeable.
unsigned int chunkSize = pats.size();
retry:
std::vector<Key> keys;
keys.reserve( pats.size() );
KeyListResult result;
do {
const KeyListResult this_result = do_list_keys( ctx, pats.mid( 0, chunkSize ), keys, secretOnly );
if ( this_result.error().code() == GPG_ERR_LINE_TOO_LONG ) {
// got LINE_TOO_LONG, try a smaller chunksize:
chunkSize /= 2;
if ( chunkSize < 1 )
// chunks smaller than one can't be -> return the error.
return make_tuple( this_result, keys, QString() );
else
goto retry;
}
// ok, that seemed to work...
result.mergeWith( this_result );
if ( result.error().code() )
break;
pats = pats.mid( chunkSize );
} while ( !pats.empty() );
return make_tuple( result, keys, QString() );
}
Error QGpgMEKeyListJob::start( const QStringList & patterns, bool secretOnly ) {
mSecretOnly = secretOnly;
run( bind( &list_keys, _1, patterns, secretOnly ) );
return Error();
}
KeyListResult QGpgMEKeyListJob::exec( const QStringList & patterns, bool secretOnly, std::vector<Key> & keys ) {
mSecretOnly = secretOnly;
const result_type r = list_keys( context(), patterns, secretOnly );
resultHook( r );
keys = get<1>( r );
return get<0>( r );
}
void QGpgMEKeyListJob::resultHook( const result_type & tuple ) {
mResult = get<0>( tuple );
Q_FOREACH( const Key & key, get<1>( tuple ) )
emit nextKey( key );
}
void QGpgMEKeyListJob::showErrorDialog( QWidget * parent, const QString & caption ) const {
if ( !mResult.error() || mResult.error().isCanceled() )
return;
const QString msg = i18n( "<qt><p>An error occurred while fetching "
"the keys from the backend:</p>"
"<p><b>%1</b></p></qt>" ,
QString::fromLocal8Bit( mResult.error().asString() ) );
KMessageBox::error( parent, msg, caption );
}
#include "qgpgmekeylistjob.moc"
<|endoftext|> |
<commit_before>#ifndef __NODE_MAPNIK_UTILS_H__
#define __NODE_MAPNIK_UTILS_H__
// core types
#ifdef MAPNIK_METRICS
#include <mapnik/metrics.hpp>
#endif
#include <mapnik/params.hpp>
#include <mapnik/unicode.hpp>
#include <mapnik/value_types.hpp>
#include <mapnik/value.hpp>
#include <mapnik/version.hpp>
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wunused-parameter"
#pragma GCC diagnostic ignored "-Wshadow"
#include <nan.h>
#pragma GCC diagnostic pop
// stl
#include <string>
#include <memory>
#define TOSTR(obj) (*v8::String::Utf8Value((obj)->ToString()))
#define FUNCTION_ARG(I, VAR) \
if (info.Length() <= (I) || !info[I]->IsFunction()) { \
Nan::ThrowTypeError("Argument " #I " must be a function"); \
return; \
} \
v8::Local<v8::Function> VAR = info[I].As<v8::Function>();
#define ATTR(t, name, get, set) \
Nan::SetAccessor(t->InstanceTemplate(), Nan::New<v8::String>(name).ToLocalChecked(), get, set);
#define NODE_MAPNIK_DEFINE_CONSTANT(target, name, constant) \
(target)->Set(Nan::New<v8::String>(name).ToLocalChecked(), \
Nan::New<v8::Integer>(constant)); \
#define NODE_MAPNIK_DEFINE_64_BIT_CONSTANT(target, name, constant) \
(target)->Set(Nan::New<v8::String>(name).ToLocalChecked(), \
Nan::New<v8::Number>(constant)); \
namespace node_mapnik {
typedef mapnik::value_integer value_integer;
// adapted to work for both mapnik features and mapnik parameters
struct value_converter
{
v8::Local<v8::Value> operator () ( value_integer val ) const
{
return Nan::New<v8::Number>(val);
}
v8::Local<v8::Value> operator () (mapnik::value_bool val ) const
{
return Nan::New<v8::Boolean>(val);
}
v8::Local<v8::Value> operator () ( double val ) const
{
return Nan::New<v8::Number>(val);
}
v8::Local<v8::Value> operator () ( std::string const& val ) const
{
return Nan::New<v8::String>(val.c_str()).ToLocalChecked();
}
v8::Local<v8::Value> operator () ( mapnik::value_unicode_string const& val) const
{
std::string buffer;
mapnik::to_utf8(val,buffer);
return Nan::New<v8::String>(buffer.c_str()).ToLocalChecked();
}
v8::Local<v8::Value> operator () ( mapnik::value_null const& ) const
{
return Nan::Null();
}
};
inline void params_to_object(v8::Local<v8::Object>& ds, std::string const& key, mapnik::value_holder const& val)
{
ds->Set(Nan::New<v8::String>(key.c_str()).ToLocalChecked(), mapnik::util::apply_visitor(value_converter(), val));
}
#ifdef MAPNIK_METRICS
inline Nan::MaybeLocal<v8::Value> metrics_to_object(mapnik::metrics &metrics)
{
v8::Local<v8::String> json_string = Nan::New(metrics.to_string()).ToLocalChecked();
Nan::JSON NanJSON;
return NanJSON.Parse(json_string);
}
#endif
} // end ns
#endif
<commit_msg>Use Nan::Utf8String instead of v8::String::Utf8Value<commit_after>#ifndef __NODE_MAPNIK_UTILS_H__
#define __NODE_MAPNIK_UTILS_H__
// core types
#ifdef MAPNIK_METRICS
#include <mapnik/metrics.hpp>
#endif
#include <mapnik/params.hpp>
#include <mapnik/unicode.hpp>
#include <mapnik/value_types.hpp>
#include <mapnik/value.hpp>
#include <mapnik/version.hpp>
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wunused-parameter"
#pragma GCC diagnostic ignored "-Wshadow"
#include <nan.h>
#pragma GCC diagnostic pop
// stl
#include <string>
#include <memory>
#define TOSTR(obj) (*Nan::Utf8String(obj))
#define FUNCTION_ARG(I, VAR) \
if (info.Length() <= (I) || !info[I]->IsFunction()) { \
Nan::ThrowTypeError("Argument " #I " must be a function"); \
return; \
} \
v8::Local<v8::Function> VAR = info[I].As<v8::Function>();
#define ATTR(t, name, get, set) \
Nan::SetAccessor(t->InstanceTemplate(), Nan::New<v8::String>(name).ToLocalChecked(), get, set);
#define NODE_MAPNIK_DEFINE_CONSTANT(target, name, constant) \
(target)->Set(Nan::New<v8::String>(name).ToLocalChecked(), \
Nan::New<v8::Integer>(constant)); \
#define NODE_MAPNIK_DEFINE_64_BIT_CONSTANT(target, name, constant) \
(target)->Set(Nan::New<v8::String>(name).ToLocalChecked(), \
Nan::New<v8::Number>(constant)); \
namespace node_mapnik {
typedef mapnik::value_integer value_integer;
// adapted to work for both mapnik features and mapnik parameters
struct value_converter
{
v8::Local<v8::Value> operator () ( value_integer val ) const
{
return Nan::New<v8::Number>(val);
}
v8::Local<v8::Value> operator () (mapnik::value_bool val ) const
{
return Nan::New<v8::Boolean>(val);
}
v8::Local<v8::Value> operator () ( double val ) const
{
return Nan::New<v8::Number>(val);
}
v8::Local<v8::Value> operator () ( std::string const& val ) const
{
return Nan::New<v8::String>(val.c_str()).ToLocalChecked();
}
v8::Local<v8::Value> operator () ( mapnik::value_unicode_string const& val) const
{
std::string buffer;
mapnik::to_utf8(val,buffer);
return Nan::New<v8::String>(buffer.c_str()).ToLocalChecked();
}
v8::Local<v8::Value> operator () ( mapnik::value_null const& ) const
{
return Nan::Null();
}
};
inline void params_to_object(v8::Local<v8::Object>& ds, std::string const& key, mapnik::value_holder const& val)
{
ds->Set(Nan::New<v8::String>(key.c_str()).ToLocalChecked(), mapnik::util::apply_visitor(value_converter(), val));
}
#ifdef MAPNIK_METRICS
inline Nan::MaybeLocal<v8::Value> metrics_to_object(mapnik::metrics &metrics)
{
v8::Local<v8::String> json_string = Nan::New(metrics.to_string()).ToLocalChecked();
Nan::JSON NanJSON;
return NanJSON.Parse(json_string);
}
#endif
} // end ns
#endif
<|endoftext|> |
<commit_before>/*
** Author(s):
** - Cedric GESTES <cgestes@aldebaran-robotics.com>
**
** Copyright (C) 2010, 2012 Aldebaran Robotics
*/
#include <vector>
#include <iostream>
#include <string>
#include <gtest/gtest.h>
#include <qimessaging/session.hpp>
#include <qitype/genericobject.hpp>
#include <qitype/genericobjectbuilder.hpp>
#include <qimessaging/servicedirectory.hpp>
#include <qimessaging/gateway.hpp>
#include <qi/os.hpp>
#include <qi/application.hpp>
#include <boost/thread.hpp>
#include <testsession/testsessionpair.hpp>
static std::string reply(const std::string &msg)
{
return msg;
}
qi::ObjectPtr newObject() {
qi::GenericObjectBuilder ob;
ob.advertiseMethod("reply", &reply);
return ob.object();
}
void alternateModule(qi::Session *session) {
unsigned int id;
while (!boost::this_thread::interruption_requested())
{
boost::this_thread::interruption_point();
//a--;
qi::ObjectPtr obj = newObject();
qi::Future<unsigned int> fut = session->registerService("TestToto", obj);
if (fut.hasError()) {
std::cout << "Error registering service: " << fut.error() << std::endl;
continue;
}
std::cout << "Service TestToto registered" << std::endl;
qi::Future<void> futun = session->unregisterService(fut.value());
if (futun.hasError()) {
std::cout << "Error unregistering service: " << futun.error() << std::endl;
continue;
}
std::cout << "Service TestToto unregistered" << std::endl;
qi::os::msleep(50);
}
}
TEST(QiSession, RegisterUnregisterTwoSession)
{
int a = 1000;
TestSessionPair p;
EXPECT_TRUE(p.client()->isConnected());
boost::thread worker(boost::bind(&alternateModule, p.server()));
while (a) {
a--;
qi::Future<qi::ObjectPtr> fut = p.client()->service("TestToto");
if (fut.hasError()) {
std::cout << "Call error:" << fut.error();
continue;
}
std::string ret = fut.value()->call<std::string>("reply", "plif");
std::cout << "ret:" << ret << std::endl;
}
worker.interrupt();
worker.join();
}
TEST(QiSession, RegisterUnregisterSameSession)
{
int a = 1000;
TestSessionPair p;
EXPECT_TRUE(p.client()->isConnected());
boost::thread worker(boost::bind(&alternateModule, p.server()));
while (a) {
a--;
qi::Future<qi::ObjectPtr> fut = p.server()->service("TestToto");
if (fut.hasError()) {
std::cout << "Call error:" << fut.error() << std::endl;
continue;
}
std::string ret = fut.value()->call<std::string>("reply", "plif");
std::cout << "ret:" << ret << std::endl;
}
worker.interrupt();
worker.join();
}
int main(int argc, char **argv)
{
qi::Application app(argc, argv);
#if defined(__APPLE__) || defined(__linux__)
setsid();
#endif
::testing::InitGoogleTest(&argc, argv);
TestMode::initTestMode(argc, argv);
return RUN_ALL_TESTS();
}
<commit_msg>Fix a warning in tests<commit_after>/*
** Author(s):
** - Cedric GESTES <cgestes@aldebaran-robotics.com>
**
** Copyright (C) 2010, 2012 Aldebaran Robotics
*/
#include <vector>
#include <iostream>
#include <string>
#include <gtest/gtest.h>
#include <qimessaging/session.hpp>
#include <qitype/genericobject.hpp>
#include <qitype/genericobjectbuilder.hpp>
#include <qimessaging/servicedirectory.hpp>
#include <qimessaging/gateway.hpp>
#include <qi/os.hpp>
#include <qi/application.hpp>
#include <boost/thread.hpp>
#include <testsession/testsessionpair.hpp>
static std::string reply(const std::string &msg)
{
return msg;
}
qi::ObjectPtr newObject() {
qi::GenericObjectBuilder ob;
ob.advertiseMethod("reply", &reply);
return ob.object();
}
void alternateModule(qi::Session *session) {
while (!boost::this_thread::interruption_requested())
{
boost::this_thread::interruption_point();
//a--;
qi::ObjectPtr obj = newObject();
qi::Future<unsigned int> fut = session->registerService("TestToto", obj);
if (fut.hasError()) {
std::cout << "Error registering service: " << fut.error() << std::endl;
continue;
}
std::cout << "Service TestToto registered" << std::endl;
qi::Future<void> futun = session->unregisterService(fut.value());
if (futun.hasError()) {
std::cout << "Error unregistering service: " << futun.error() << std::endl;
continue;
}
std::cout << "Service TestToto unregistered" << std::endl;
qi::os::msleep(50);
}
}
TEST(QiSession, RegisterUnregisterTwoSession)
{
int a = 1000;
TestSessionPair p;
EXPECT_TRUE(p.client()->isConnected());
boost::thread worker(boost::bind(&alternateModule, p.server()));
while (a) {
a--;
qi::Future<qi::ObjectPtr> fut = p.client()->service("TestToto");
if (fut.hasError()) {
std::cout << "Call error:" << fut.error();
continue;
}
std::string ret = fut.value()->call<std::string>("reply", "plif");
std::cout << "ret:" << ret << std::endl;
}
worker.interrupt();
worker.join();
}
TEST(QiSession, RegisterUnregisterSameSession)
{
int a = 1000;
TestSessionPair p;
EXPECT_TRUE(p.client()->isConnected());
boost::thread worker(boost::bind(&alternateModule, p.server()));
while (a) {
a--;
qi::Future<qi::ObjectPtr> fut = p.server()->service("TestToto");
if (fut.hasError()) {
std::cout << "Call error:" << fut.error() << std::endl;
continue;
}
std::string ret = fut.value()->call<std::string>("reply", "plif");
std::cout << "ret:" << ret << std::endl;
}
worker.interrupt();
worker.join();
}
int main(int argc, char **argv)
{
qi::Application app(argc, argv);
#if defined(__APPLE__) || defined(__linux__)
setsid();
#endif
::testing::InitGoogleTest(&argc, argv);
TestMode::initTestMode(argc, argv);
return RUN_ALL_TESTS();
}
<|endoftext|> |
<commit_before>#ifndef DICE_VALUE_HPP_
#define DICE_VALUE_HPP_
#include <memory>
#include <string>
#include <typeinfo>
#include "random_variable.hpp"
namespace dice
{
// Type of the type identifier of a value in a dice expression
using type_id = std::string;
// Parent of all value types that are used in a dice expressions
class base_value
{
public:
virtual ~base_value() {}
/** Get type of this value.
* It has to be unique for each type.
* It has to be the same for the same type
* (i.e. multiple values of the same type will return the same type id)
*/
virtual type_id type() const = 0;
};
// Value with data
template<typename T>
class typed_value : public base_value
{
public:
using value_type = T;
static type_id id()
{
return typeid(typed_value<value_type>).name();
}
typed_value() {}
explicit typed_value(value_type&& value) : value_(std::move(value)) {}
// get type id
type_id type() const override { return id(); }
// value getter setter
value_type& data() { return value_; }
const value_type& data() const { return value_; }
private:
value_type value_;
};
// used data types
using type_int = typed_value<int>;
using type_double = typed_value<double>;
using type_rand_var = typed_value<random_variable<int, double>>;
template<typename T, typename... Value>
std::unique_ptr<T> make(Value&&... data)
{
static_assert(std::is_base_of<base_value, T>::value,
"Dice value has to be derived from dice::base_value.");
using value_type = typename T::value_type;
return std::make_unique<T>(value_type{ std::forward<Value>(data)... });
}
}
#endif // DICE_VALUE_HPP_<commit_msg>Use decomposition instead of random variable<commit_after>#ifndef DICE_VALUE_HPP_
#define DICE_VALUE_HPP_
#include <memory>
#include <string>
#include <typeinfo>
#include "random_variable.hpp"
#include "random_variable_decomposition.hpp"
namespace dice
{
// Type of the type identifier of a value in a dice expression
using type_id = std::string;
// Parent of all value types that are used in a dice expressions
class base_value
{
public:
virtual ~base_value() {}
/** Get type of this value.
* It has to be unique for each type.
* It has to be the same for the same type
* (i.e. multiple values of the same type will return the same type id)
*/
virtual type_id type() const = 0;
};
// Value with data
template<typename T>
class typed_value : public base_value
{
public:
using value_type = T;
static type_id id()
{
return typeid(typed_value<value_type>).name();
}
typed_value() {}
explicit typed_value(value_type&& value) : value_(std::move(value)) {}
// get type id
type_id type() const override { return id(); }
// value getter setter
value_type& data() { return value_; }
const value_type& data() const { return value_; }
private:
value_type value_;
};
// used data types
using type_int = typed_value<int>;
using type_double = typed_value<double>;
using type_rand_var = typed_value<
random_variable_decomposition<int, double>>;
template<typename T, typename... Value>
std::unique_ptr<T> make(Value&&... data)
{
static_assert(std::is_base_of<base_value, T>::value,
"Dice value has to be derived from dice::base_value.");
using value_type = typename T::value_type;
return std::make_unique<T>(value_type{ std::forward<Value>(data)... });
}
}
#endif // DICE_VALUE_HPP_<|endoftext|> |
<commit_before>/**
* @file
* @copyright defined in eos/LICENSE.txt
*/
#pragma once
#include <eos/types/types.hpp>
namespace eosio { namespace config {
using types::uint16;
using types::uint32;
using types::uint64;
using types::uint128;
using types::share_type;
using types::asset;
using types::account_name;
using types::permission_name;
const static char key_prefix[] = "EOS";
const static account_name eos_contract_name = N(eos);
const static account_name nobody_account_name = N(nobody);
const static account_name anybody_account_name = N(anybody);
const static account_name producers_account_name = N(producers);
const static permission_name active_name = N(active);
const static permission_name owner_name = N(owner);
const static share_type initial_token_supply = asset::from_string("90000000.0000 EOS").amount;
const static int block_interval_seconds = 3;
/** Percentages are fixed point with a denominator of 10,000 */
const static int percent100 = 10000;
const static int percent1 = 100;
const static int default_per_auth_account_time_frame_seconds = 18;
const static int default_per_auth_account = 1800;
const static int default_per_code_account_time_frame_seconds = 18;
const static int default_per_code_account = 18000;
const static uint32 required_producer_participation = 33 * config::percent1;
const static uint32 default_max_block_size = 5 * 1024 * 1024;
const static uint32 default_target_block_size = 128 * 1024;
const static uint64 default_max_storage_size = 10 * 1024;
const static share_type default_elected_pay = asset(100).amount;
const static share_type default_runner_up_pay = asset(75).amount;
const static share_type default_min_eos_balance = asset(100).amount;
const static uint32 default_max_trx_lifetime = 60*60;
const static uint16 default_auth_depth_limit = 6;
const static uint32 default_max_trx_runtime = 10*1000;
const static uint16 default_inline_depth_limit = 4;
const static uint32 default_max_inline_msg_size = 4 * 1024;
const static uint32 default_max_gen_trx_size = 64 * 1024;
const static uint32 producers_authority_threshold = 14;
const static int blocks_per_round = 21;
const static int voted_producers_per_round = 20;
const static int irreversible_threshold_percent = 70 * percent1;
const static int max_producer_votes = 30;
const static uint128 producer_race_lap_length = std::numeric_limits<uint128>::max();
const static auto staked_balance_cooldown_seconds = fc::days(3).to_seconds();
} } // namespace eosio::config
template<typename Number>
Number eos_percent(Number value, int percentage) {
return value * percentage / eosio::config::percent100;
}
<commit_msg>Change to 1 billion initial supply of EOS. #716<commit_after>/**
* @file
* @copyright defined in eos/LICENSE.txt
*/
#pragma once
#include <eos/types/types.hpp>
namespace eosio { namespace config {
using types::uint16;
using types::uint32;
using types::uint64;
using types::uint128;
using types::share_type;
using types::asset;
using types::account_name;
using types::permission_name;
const static char key_prefix[] = "EOS";
const static account_name eos_contract_name = N(eos);
const static account_name nobody_account_name = N(nobody);
const static account_name anybody_account_name = N(anybody);
const static account_name producers_account_name = N(producers);
const static permission_name active_name = N(active);
const static permission_name owner_name = N(owner);
const static share_type initial_token_supply = asset::from_string("1000000000.0000 EOS").amount;
const static int block_interval_seconds = 3;
/** Percentages are fixed point with a denominator of 10,000 */
const static int percent100 = 10000;
const static int percent1 = 100;
const static int default_per_auth_account_time_frame_seconds = 18;
const static int default_per_auth_account = 1800;
const static int default_per_code_account_time_frame_seconds = 18;
const static int default_per_code_account = 18000;
const static uint32 required_producer_participation = 33 * config::percent1;
const static uint32 default_max_block_size = 5 * 1024 * 1024;
const static uint32 default_target_block_size = 128 * 1024;
const static uint64 default_max_storage_size = 10 * 1024;
const static share_type default_elected_pay = asset(100).amount;
const static share_type default_runner_up_pay = asset(75).amount;
const static share_type default_min_eos_balance = asset(100).amount;
const static uint32 default_max_trx_lifetime = 60*60;
const static uint16 default_auth_depth_limit = 6;
const static uint32 default_max_trx_runtime = 10*1000;
const static uint16 default_inline_depth_limit = 4;
const static uint32 default_max_inline_msg_size = 4 * 1024;
const static uint32 default_max_gen_trx_size = 64 * 1024;
const static uint32 producers_authority_threshold = 14;
const static int blocks_per_round = 21;
const static int voted_producers_per_round = 20;
const static int irreversible_threshold_percent = 70 * percent1;
const static int max_producer_votes = 30;
const static uint128 producer_race_lap_length = std::numeric_limits<uint128>::max();
const static auto staked_balance_cooldown_seconds = fc::days(3).to_seconds();
} } // namespace eosio::config
template<typename Number>
Number eos_percent(Number value, int percentage) {
return value * percentage / eosio::config::percent100;
}
<|endoftext|> |
<commit_before>#include "Base.h"
#include "AnimationController.h"
#include "Game.h"
#include "Curve.h"
namespace gameplay
{
AnimationController::AnimationController()
: _state(IDLE), _animations(NULL)
{
}
AnimationController::~AnimationController()
{
destroyAllAnimations();
}
Animation* AnimationController::createAnimation(const char* id, AnimationTarget* target, int propertyId, unsigned int keyCount, unsigned long* keyTimes, float* keyValues, Curve::InterpolationType type)
{
assert(type != Curve::BEZIER && type != Curve::HERMITE);
assert(keyCount >= 2 && keyTimes && keyValues && target);
Animation* animation = new Animation(id, target, propertyId, keyCount, keyTimes, keyValues, type);
addAnimation(animation);
return animation;
}
Animation* AnimationController::createAnimation(const char* id, AnimationTarget* target, int propertyId, unsigned int keyCount, unsigned long* keyTimes, float* keyValues, float* keyInValue, float* keyOutValue, Curve::InterpolationType type)
{
assert(target && keyCount >= 2 && keyTimes && keyValues && keyInValue && keyOutValue);
Animation* animation = new Animation(id, target, propertyId, keyCount, keyTimes, keyValues, keyInValue, keyOutValue, type);
addAnimation(animation);
return animation;
}
Animation* AnimationController::createAnimation(const char* id, AnimationTarget* target, const char* animationFile)
{
assert(target && animationFile);
Properties* p = Properties::create(animationFile);
assert(p);
Animation* animation = createAnimation(id, target, p->getNextNamespace());
SAFE_DELETE(p);
return animation;
}
Animation* AnimationController::createAnimationFromTo(const char* id, AnimationTarget* target, int propertyId, float* from, float* to, Curve::InterpolationType type, unsigned long duration)
{
const unsigned int propertyComponentCount = target->getAnimationPropertyComponentCount(propertyId);
float* keyValues = new float[2 * propertyComponentCount];
memcpy(keyValues, from, sizeof(float) * propertyComponentCount);
memcpy(keyValues + propertyComponentCount, to, sizeof(float) * propertyComponentCount);
unsigned long* keyTimes = new unsigned long[2];
keyTimes[0] = 0;
keyTimes[1] = duration;
Animation* animation = createAnimation(id, target, propertyId, 2, keyTimes, keyValues, type);
SAFE_DELETE_ARRAY(keyTimes);
return animation;
}
Animation* AnimationController::createAnimationFromBy(const char* id, AnimationTarget* target, int propertyId, float* from, float* by, Curve::InterpolationType type, unsigned long duration)
{
const unsigned int propertyComponentCount = target->getAnimationPropertyComponentCount(propertyId);
float* keyValues = new float[2 * propertyComponentCount];
memcpy(keyValues, from, sizeof(float) * propertyComponentCount);
memcpy(keyValues + propertyComponentCount, by, sizeof(float) * propertyComponentCount);
unsigned long* keyTimes = new unsigned long[2];
keyTimes[0] = 0;
keyTimes[1] = duration;
Animation* animation = createAnimation(id, target, propertyId, 2, keyTimes, keyValues, type);
SAFE_DELETE_ARRAY(keyTimes);
return animation;
}
Animation* AnimationController::getAnimation(const char* id) const
{
unsigned int animationCount = _animations.size();
for (unsigned int i = 0; i < animationCount; i++)
{
if (_animations.at(i)->_id.compare(id) == 0)
{
return _animations.at(i);
}
}
return NULL;
}
void AnimationController::stopAllAnimations()
{
std::list<AnimationClip*>::iterator clipIter = _runningClips.begin();
while (clipIter != _runningClips.end())
{
AnimationClip* clip = *clipIter;
clip->_isPlaying = false;
clip->onEnd();
SAFE_RELEASE(clip);
}
_runningClips.clear();
_state = IDLE;
}
Animation* AnimationController::createAnimation(const char* id, AnimationTarget* target, Properties* animationProperties)
{
assert(target && animationProperties);
assert(std::strcmp(animationProperties->getNamespace(), "animation") == 0);
const char* propertyIdStr = animationProperties->getString("property");
assert(propertyIdStr);
// Get animation target property id
int propertyId = AnimationTarget::getPropertyId(target->_targetType, propertyIdStr);
assert(propertyId != -1);
unsigned int keyCount = animationProperties->getInt("keyCount");
assert(keyCount > 0);
const char* keyTimesStr = animationProperties->getString("keyTimes");
assert(keyTimesStr);
const char* keyValuesStr = animationProperties->getString("keyValues");
assert(keyValuesStr);
const char* curveStr = animationProperties->getString("curve");
assert(curveStr);
char delimeter = ' ';
unsigned int startOffset = 0;
unsigned int endOffset = std::string::npos;
unsigned long* keyTimes = new unsigned long[keyCount];
for (unsigned int i = 0; i < keyCount; i++)
{
endOffset = static_cast<std::string>(keyTimesStr).find_first_of(delimeter, startOffset);
if (endOffset != std::string::npos)
{
keyTimes[i] = std::strtoul(static_cast<std::string>(keyTimesStr).substr(startOffset, endOffset - startOffset).c_str(), NULL, 0);
}
else
{
keyTimes[i] = std::strtoul(static_cast<std::string>(keyTimesStr).substr(startOffset, static_cast<std::string>(keyTimesStr).length()).c_str(), NULL, 0);
}
startOffset = endOffset + 1;
}
startOffset = 0;
endOffset = std::string::npos;
int componentCount = target->getAnimationPropertyComponentCount(propertyId);
assert(componentCount > 0);
unsigned int components = keyCount * componentCount;
float* keyValues = new float[components];
for (unsigned int i = 0; i < components; i++)
{
endOffset = static_cast<std::string>(keyValuesStr).find_first_of(delimeter, startOffset);
if (endOffset != std::string::npos)
{
keyValues[i] = std::atof(static_cast<std::string>(keyValuesStr).substr(startOffset, endOffset - startOffset).c_str());
}
else
{
keyValues[i] = std::atof(static_cast<std::string>(keyValuesStr).substr(startOffset, static_cast<std::string>(keyValuesStr).length()).c_str());
}
startOffset = endOffset + 1;
}
const char* keyInStr = animationProperties->getString("keyIn");
float* keyIn = NULL;
if (keyInStr)
{
keyIn = new float[components];
startOffset = 0;
endOffset = std::string::npos;
for (unsigned int i = 0; i < components; i++)
{
endOffset = static_cast<std::string>(keyInStr).find_first_of(delimeter, startOffset);
if (endOffset != std::string::npos)
{
keyIn[i] = std::atof(static_cast<std::string>(keyInStr).substr(startOffset, endOffset - startOffset).c_str());
}
else
{
keyIn[i] = std::atof(static_cast<std::string>(keyInStr).substr(startOffset, static_cast<std::string>(keyInStr).length()).c_str());
}
startOffset = endOffset + 1;
}
}
const char* keyOutStr = animationProperties->getString("keyOut");
float* keyOut = NULL;
if(keyOutStr)
{
keyOut = new float[components];
startOffset = 0;
endOffset = std::string::npos;
for (unsigned int i = 0; i < components; i++)
{
endOffset = static_cast<std::string>(keyOutStr).find_first_of(delimeter, startOffset);
if (endOffset != std::string::npos)
{
keyOut[i] = std::atof(static_cast<std::string>(keyOutStr).substr(startOffset, endOffset - startOffset).c_str());
}
else
{
keyOut[i] = std::atof(static_cast<std::string>(keyOutStr).substr(startOffset, static_cast<std::string>(keyOutStr).length()).c_str());
}
startOffset = endOffset + 1;
}
}
int curve = Curve::getInterpolationType(curveStr);
Animation* animation = NULL;
if (keyIn && keyOut)
{
animation = createAnimation(id, target, propertyId, keyCount, keyTimes, keyValues, keyIn, keyOut, (Curve::InterpolationType)curve);
}
else
{
animation = createAnimation(id, target, propertyId, keyCount, keyTimes, keyValues, (Curve::InterpolationType) curve);
}
SAFE_DELETE(keyOut);
SAFE_DELETE(keyIn);
SAFE_DELETE(keyValues);
SAFE_DELETE(keyTimes);
Properties* pClip = animationProperties->getNextNamespace();
if (pClip && std::strcmp(pClip->getNamespace(), "clip") == 0)
{
int frameCount = animationProperties->getInt("frameCount");
assert(frameCount > 0);
animation->createClips(animationProperties, (unsigned int) frameCount);
}
return animation;
}
AnimationController::State AnimationController::getState() const
{
return _state;
}
void AnimationController::initialize()
{
_state = IDLE;
}
void AnimationController::finalize()
{
stopAllAnimations();
_state = PAUSED;
}
void AnimationController::resume()
{
if (_runningClips.empty())
_state = IDLE;
else
_state = RUNNING;
}
void AnimationController::pause()
{
_state = PAUSED;
}
void AnimationController::schedule(AnimationClip* clip)
{
if (_runningClips.empty())
{
_state = RUNNING;
}
if (clip->_isPlaying)
{
_runningClips.remove(clip);
clip->_isPlaying = false;
clip->onEnd();
}
else
{
clip->addRef();
}
_runningClips.push_back(clip);
}
void AnimationController::unschedule(AnimationClip* clip)
{
if (clip->_isPlaying)
{
_runningClips.remove(clip);
SAFE_RELEASE(clip);
}
if (_runningClips.empty())
_state = IDLE;
}
void AnimationController::update(long elapsedTime)
{
if (_state != RUNNING)
return;
std::list<AnimationClip*>::iterator clipIter = _runningClips.begin();
while (clipIter != _runningClips.end())
{
AnimationClip* clip = (*clipIter);
if (clip->update(elapsedTime))
{
SAFE_RELEASE(clip);
clipIter = _runningClips.erase(clipIter);
}
else
{
clipIter++;
}
}
if (_runningClips.empty())
_state = IDLE;
}
void AnimationController::addAnimation(Animation* animation)
{
_animations.push_back(animation);
}
void AnimationController::destroyAnimation(Animation* animation)
{
std::vector<Animation*>::iterator itr = _animations.begin();
while (itr != _animations.end())
{
if (animation == *itr)
{
Animation* animation = *itr;
_animations.erase(itr);
SAFE_RELEASE(animation);
return;
}
itr++;
}
}
void AnimationController::destroyAllAnimations()
{
std::vector<Animation*>::iterator itr = _animations.begin();
while (itr != _animations.end())
{
Animation* animation = *itr;
SAFE_RELEASE(animation);
itr++;
}
_animations.clear();
}
}
<commit_msg>Fixes crash when clip is playing and you exit your game.<commit_after>#include "Base.h"
#include "AnimationController.h"
#include "Game.h"
#include "Curve.h"
namespace gameplay
{
AnimationController::AnimationController()
: _state(IDLE), _animations(NULL)
{
}
AnimationController::~AnimationController()
{
destroyAllAnimations();
}
Animation* AnimationController::createAnimation(const char* id, AnimationTarget* target, int propertyId, unsigned int keyCount, unsigned long* keyTimes, float* keyValues, Curve::InterpolationType type)
{
assert(type != Curve::BEZIER && type != Curve::HERMITE);
assert(keyCount >= 2 && keyTimes && keyValues && target);
Animation* animation = new Animation(id, target, propertyId, keyCount, keyTimes, keyValues, type);
addAnimation(animation);
return animation;
}
Animation* AnimationController::createAnimation(const char* id, AnimationTarget* target, int propertyId, unsigned int keyCount, unsigned long* keyTimes, float* keyValues, float* keyInValue, float* keyOutValue, Curve::InterpolationType type)
{
assert(target && keyCount >= 2 && keyTimes && keyValues && keyInValue && keyOutValue);
Animation* animation = new Animation(id, target, propertyId, keyCount, keyTimes, keyValues, keyInValue, keyOutValue, type);
addAnimation(animation);
return animation;
}
Animation* AnimationController::createAnimation(const char* id, AnimationTarget* target, const char* animationFile)
{
assert(target && animationFile);
Properties* p = Properties::create(animationFile);
assert(p);
Animation* animation = createAnimation(id, target, p->getNextNamespace());
SAFE_DELETE(p);
return animation;
}
Animation* AnimationController::createAnimationFromTo(const char* id, AnimationTarget* target, int propertyId, float* from, float* to, Curve::InterpolationType type, unsigned long duration)
{
const unsigned int propertyComponentCount = target->getAnimationPropertyComponentCount(propertyId);
float* keyValues = new float[2 * propertyComponentCount];
memcpy(keyValues, from, sizeof(float) * propertyComponentCount);
memcpy(keyValues + propertyComponentCount, to, sizeof(float) * propertyComponentCount);
unsigned long* keyTimes = new unsigned long[2];
keyTimes[0] = 0;
keyTimes[1] = duration;
Animation* animation = createAnimation(id, target, propertyId, 2, keyTimes, keyValues, type);
SAFE_DELETE_ARRAY(keyTimes);
return animation;
}
Animation* AnimationController::createAnimationFromBy(const char* id, AnimationTarget* target, int propertyId, float* from, float* by, Curve::InterpolationType type, unsigned long duration)
{
const unsigned int propertyComponentCount = target->getAnimationPropertyComponentCount(propertyId);
float* keyValues = new float[2 * propertyComponentCount];
memcpy(keyValues, from, sizeof(float) * propertyComponentCount);
memcpy(keyValues + propertyComponentCount, by, sizeof(float) * propertyComponentCount);
unsigned long* keyTimes = new unsigned long[2];
keyTimes[0] = 0;
keyTimes[1] = duration;
Animation* animation = createAnimation(id, target, propertyId, 2, keyTimes, keyValues, type);
SAFE_DELETE_ARRAY(keyTimes);
return animation;
}
Animation* AnimationController::getAnimation(const char* id) const
{
unsigned int animationCount = _animations.size();
for (unsigned int i = 0; i < animationCount; i++)
{
if (_animations.at(i)->_id.compare(id) == 0)
{
return _animations.at(i);
}
}
return NULL;
}
void AnimationController::stopAllAnimations()
{
std::list<AnimationClip*>::iterator clipIter = _runningClips.begin();
while (clipIter != _runningClips.end())
{
AnimationClip* clip = *clipIter;
clip->_isPlaying = false;
clip->onEnd();
SAFE_RELEASE(clip);
}
_runningClips.clear();
_state = IDLE;
}
Animation* AnimationController::createAnimation(const char* id, AnimationTarget* target, Properties* animationProperties)
{
assert(target && animationProperties);
assert(std::strcmp(animationProperties->getNamespace(), "animation") == 0);
const char* propertyIdStr = animationProperties->getString("property");
assert(propertyIdStr);
// Get animation target property id
int propertyId = AnimationTarget::getPropertyId(target->_targetType, propertyIdStr);
assert(propertyId != -1);
unsigned int keyCount = animationProperties->getInt("keyCount");
assert(keyCount > 0);
const char* keyTimesStr = animationProperties->getString("keyTimes");
assert(keyTimesStr);
const char* keyValuesStr = animationProperties->getString("keyValues");
assert(keyValuesStr);
const char* curveStr = animationProperties->getString("curve");
assert(curveStr);
char delimeter = ' ';
unsigned int startOffset = 0;
unsigned int endOffset = std::string::npos;
unsigned long* keyTimes = new unsigned long[keyCount];
for (unsigned int i = 0; i < keyCount; i++)
{
endOffset = static_cast<std::string>(keyTimesStr).find_first_of(delimeter, startOffset);
if (endOffset != std::string::npos)
{
keyTimes[i] = std::strtoul(static_cast<std::string>(keyTimesStr).substr(startOffset, endOffset - startOffset).c_str(), NULL, 0);
}
else
{
keyTimes[i] = std::strtoul(static_cast<std::string>(keyTimesStr).substr(startOffset, static_cast<std::string>(keyTimesStr).length()).c_str(), NULL, 0);
}
startOffset = endOffset + 1;
}
startOffset = 0;
endOffset = std::string::npos;
int componentCount = target->getAnimationPropertyComponentCount(propertyId);
assert(componentCount > 0);
unsigned int components = keyCount * componentCount;
float* keyValues = new float[components];
for (unsigned int i = 0; i < components; i++)
{
endOffset = static_cast<std::string>(keyValuesStr).find_first_of(delimeter, startOffset);
if (endOffset != std::string::npos)
{
keyValues[i] = std::atof(static_cast<std::string>(keyValuesStr).substr(startOffset, endOffset - startOffset).c_str());
}
else
{
keyValues[i] = std::atof(static_cast<std::string>(keyValuesStr).substr(startOffset, static_cast<std::string>(keyValuesStr).length()).c_str());
}
startOffset = endOffset + 1;
}
const char* keyInStr = animationProperties->getString("keyIn");
float* keyIn = NULL;
if (keyInStr)
{
keyIn = new float[components];
startOffset = 0;
endOffset = std::string::npos;
for (unsigned int i = 0; i < components; i++)
{
endOffset = static_cast<std::string>(keyInStr).find_first_of(delimeter, startOffset);
if (endOffset != std::string::npos)
{
keyIn[i] = std::atof(static_cast<std::string>(keyInStr).substr(startOffset, endOffset - startOffset).c_str());
}
else
{
keyIn[i] = std::atof(static_cast<std::string>(keyInStr).substr(startOffset, static_cast<std::string>(keyInStr).length()).c_str());
}
startOffset = endOffset + 1;
}
}
const char* keyOutStr = animationProperties->getString("keyOut");
float* keyOut = NULL;
if(keyOutStr)
{
keyOut = new float[components];
startOffset = 0;
endOffset = std::string::npos;
for (unsigned int i = 0; i < components; i++)
{
endOffset = static_cast<std::string>(keyOutStr).find_first_of(delimeter, startOffset);
if (endOffset != std::string::npos)
{
keyOut[i] = std::atof(static_cast<std::string>(keyOutStr).substr(startOffset, endOffset - startOffset).c_str());
}
else
{
keyOut[i] = std::atof(static_cast<std::string>(keyOutStr).substr(startOffset, static_cast<std::string>(keyOutStr).length()).c_str());
}
startOffset = endOffset + 1;
}
}
int curve = Curve::getInterpolationType(curveStr);
Animation* animation = NULL;
if (keyIn && keyOut)
{
animation = createAnimation(id, target, propertyId, keyCount, keyTimes, keyValues, keyIn, keyOut, (Curve::InterpolationType)curve);
}
else
{
animation = createAnimation(id, target, propertyId, keyCount, keyTimes, keyValues, (Curve::InterpolationType) curve);
}
SAFE_DELETE(keyOut);
SAFE_DELETE(keyIn);
SAFE_DELETE(keyValues);
SAFE_DELETE(keyTimes);
Properties* pClip = animationProperties->getNextNamespace();
if (pClip && std::strcmp(pClip->getNamespace(), "clip") == 0)
{
int frameCount = animationProperties->getInt("frameCount");
assert(frameCount > 0);
animation->createClips(animationProperties, (unsigned int) frameCount);
}
return animation;
}
AnimationController::State AnimationController::getState() const
{
return _state;
}
void AnimationController::initialize()
{
_state = IDLE;
}
void AnimationController::finalize()
{
//stopAllAnimations();
_state = PAUSED;
}
void AnimationController::resume()
{
if (_runningClips.empty())
_state = IDLE;
else
_state = RUNNING;
}
void AnimationController::pause()
{
_state = PAUSED;
}
void AnimationController::schedule(AnimationClip* clip)
{
if (_runningClips.empty())
{
_state = RUNNING;
}
if (clip->_isPlaying)
{
_runningClips.remove(clip);
clip->_isPlaying = false;
clip->onEnd();
}
else
{
clip->addRef();
}
_runningClips.push_back(clip);
}
void AnimationController::unschedule(AnimationClip* clip)
{
if (clip->_isPlaying)
{
_runningClips.remove(clip);
SAFE_RELEASE(clip);
}
if (_runningClips.empty())
_state = IDLE;
}
void AnimationController::update(long elapsedTime)
{
if (_state != RUNNING)
return;
std::list<AnimationClip*>::iterator clipIter = _runningClips.begin();
while (clipIter != _runningClips.end())
{
AnimationClip* clip = (*clipIter);
if (clip->update(elapsedTime))
{
SAFE_RELEASE(clip);
clipIter = _runningClips.erase(clipIter);
}
else
{
clipIter++;
}
}
if (_runningClips.empty())
_state = IDLE;
}
void AnimationController::addAnimation(Animation* animation)
{
_animations.push_back(animation);
}
void AnimationController::destroyAnimation(Animation* animation)
{
std::vector<Animation*>::iterator itr = _animations.begin();
while (itr != _animations.end())
{
if (animation == *itr)
{
Animation* animation = *itr;
_animations.erase(itr);
SAFE_RELEASE(animation);
return;
}
itr++;
}
}
void AnimationController::destroyAllAnimations()
{
std::vector<Animation*>::iterator itr = _animations.begin();
while (itr != _animations.end())
{
Animation* animation = *itr;
SAFE_RELEASE(animation);
itr++;
}
_animations.clear();
}
}
<|endoftext|> |
<commit_before>/*
* Copyright (c) 2003 The Regents of The University of Michigan
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met: redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer;
* redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution;
* neither the name of the copyright holders nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#define USE_CPP
// #define CPP_PIPE
#ifdef USE_CPP
#include <sys/signal.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#endif
#include <fstream>
#include <iostream>
#if __GNUC__ >= 3
#include <ext/stdio_filebuf.h>
#endif
#include <vector>
#include <string>
#include "base/inifile.hh"
#include "base/str.hh"
using namespace std;
IniFile::IniFile()
{}
IniFile::~IniFile()
{
SectionTable::iterator i = table.begin();
SectionTable::iterator end = table.end();
while (i != end) {
delete (*i).second;
++i;
}
}
#ifdef USE_CPP
bool
IniFile::loadCPP(const string &file, vector<char *> &cppArgs)
{
int fd[2];
// Open the file just to verify that we can. Otherwise if the
// file doesn't exist or has bad permissions the user will get
// confusing errors from cpp/g++.
ifstream tmpf(file.c_str());
if (!tmpf.is_open())
return false;
tmpf.close();
#ifdef CPP_PIPE
if (pipe(fd) == -1)
return false;
#else
char tempfile[] = "/tmp/configXXXXXX";
fd[0] = fd[1] = mkstemp(tempfile);
#endif
int pid = fork();
if (pid == -1)
return 1;
if (pid == 0) {
char filename[FILENAME_MAX];
string::size_type i = file.copy(filename, sizeof(filename) - 1);
filename[i] = '\0';
int arg_count = cppArgs.size();
char **args = new char *[arg_count + 20];
int nextArg = 0;
args[nextArg++] = "g++";
args[nextArg++] = "-E";
args[nextArg++] = "-P";
args[nextArg++] = "-nostdinc";
args[nextArg++] = "-nostdinc++";
args[nextArg++] = "-x";
args[nextArg++] = "c++";
args[nextArg++] = "-undef";
for (int i = 0; i < arg_count; i++)
args[nextArg++] = cppArgs[i];
args[nextArg++] = filename;
args[nextArg++] = NULL;
close(STDOUT_FILENO);
if (dup2(fd[1], STDOUT_FILENO) == -1)
return 1;
execvp("g++", args);
exit(1);
}
int retval;
waitpid(pid, &retval, 0);
// check for normal completion of CPP
if (!WIFEXITED(retval) || WEXITSTATUS(retval) != 0)
return false;
#ifdef CPP_PIPE
close(fd[1]);
#else
lseek(fd[0], 0, SEEK_SET);
#endif
bool status = false;
#if __GNUC__ >= 3
using namespace __gnu_cxx;
stdio_filebuf<char> fbuf(fd[0], ios_base::in, true,
static_cast<stdio_filebuf<char>::int_type>(BUFSIZ));
if (fbuf.is_open()) {
istream f(&fbuf);
status = load(f);
}
#else
ifstream f(fd[0]);
if (f.is_open())
status = load(f);
#endif
#ifndef CPP_PIPE
unlink(tempfile);
#endif
return status;
}
#endif
bool
IniFile::load(const string &file)
{
ifstream f(file.c_str());
if (!f.is_open())
return false;
return load(f);
}
const string &
IniFile::Entry::getValue() const
{
referenced = true;
return value;
}
void
IniFile::Section::addEntry(const std::string &entryName,
const std::string &value,
bool append)
{
EntryTable::iterator ei = table.find(entryName);
if (ei == table.end()) {
// new entry
table[entryName] = new Entry(value);
}
else if (append) {
// append new reult to old entry
ei->second->appendValue(value);
}
else {
// override old entry
ei->second->setValue(value);
}
}
bool
IniFile::Section::add(const std::string &assignment)
{
string::size_type offset = assignment.find('=');
if (offset == string::npos) {
// no '=' found
cerr << "Can't parse .ini line " << assignment << endl;
return false;
}
// if "+=" rather than just "=" then append value
bool append = (assignment[offset-1] == '+');
string entryName = assignment.substr(0, append ? offset-1 : offset);
string value = assignment.substr(offset + 1);
eat_white(entryName);
eat_white(value);
addEntry(entryName, value, append);
return true;
}
IniFile::Entry *
IniFile::Section::findEntry(const std::string &entryName) const
{
referenced = true;
EntryTable::const_iterator ei = table.find(entryName);
return (ei == table.end()) ? NULL : ei->second;
}
IniFile::Section *
IniFile::addSection(const string §ionName)
{
SectionTable::iterator i = table.find(sectionName);
if (i != table.end()) {
return i->second;
}
else {
// new entry
Section *sec = new Section();
table[sectionName] = sec;
return sec;
}
}
IniFile::Section *
IniFile::findSection(const string §ionName) const
{
SectionTable::const_iterator i = table.find(sectionName);
return (i == table.end()) ? NULL : i->second;
}
// Take string of the form "<section>:<parameter>=<value>" and add to
// database. Return true if successful, false if parse error.
bool
IniFile::add(const string &str)
{
// find ':'
string::size_type offset = str.find(':');
if (offset == string::npos) // no ':' found
return false;
string sectionName = str.substr(0, offset);
string rest = str.substr(offset + 1);
eat_white(sectionName);
Section *s = addSection(sectionName);
return s->add(rest);
}
bool
IniFile::load(istream &f)
{
Section *section = NULL;
while (!f.eof()) {
f >> ws; // Eat whitespace
if (f.eof()) {
break;
}
string line;
getline(f, line);
if (line.size() == 0)
continue;
eat_end_white(line);
int last = line.size() - 1;
if (line[0] == '[' && line[last] == ']') {
string sectionName = line.substr(1, last - 1);
eat_white(sectionName);
section = addSection(sectionName);
continue;
}
if (section == NULL)
continue;
if (!section->add(line))
return false;
}
return true;
}
bool
IniFile::find(const string §ionName, const string &entryName,
string &value) const
{
Section *section = findSection(sectionName);
if (section == NULL)
return false;
Entry *entry = section->findEntry(entryName);
if (entry == NULL)
return false;
value = entry->getValue();
return true;
}
bool
IniFile::findDefault(const string &_section, const string &entry,
string &value) const
{
string section = _section;
while (!find(section, entry, value)) {
if (!find(section, "default", section))
return false;
}
return true;
}
bool
IniFile::Section::printUnreferenced(const string §ionName)
{
bool unref = false;
bool search_unref_entries = false;
vector<string> unref_ok_entries;
Entry *entry = findEntry("unref_entries_ok");
if (entry != NULL) {
tokenize(unref_ok_entries, entry->getValue(), ' ');
if (unref_ok_entries.size()) {
search_unref_entries = true;
}
}
for (EntryTable::iterator ei = table.begin();
ei != table.end(); ++ei) {
const string &entryName = ei->first;
Entry *entry = ei->second;
if (entryName == "unref_section_ok" ||
entryName == "unref_entries_ok")
{
continue;
}
if (!entry->isReferenced()) {
if (search_unref_entries &&
(std::find(unref_ok_entries.begin(), unref_ok_entries.end(),
entryName) != unref_ok_entries.end()))
{
continue;
}
cerr << "Parameter " << sectionName << ":" << entryName
<< " not referenced." << endl;
unref = true;
}
}
return unref;
}
bool
IniFile::printUnreferenced()
{
bool unref = false;
for (SectionTable::iterator i = table.begin();
i != table.end(); ++i) {
const string §ionName = i->first;
Section *section = i->second;
if (!section->isReferenced()) {
if (section->findEntry("unref_section_ok") == NULL) {
cerr << "Section " << sectionName << " not referenced."
<< endl;
unref = true;
}
}
else {
if (section->printUnreferenced(sectionName)) {
unref = true;
}
}
}
return unref;
}
void
IniFile::Section::dump(const string §ionName)
{
for (EntryTable::iterator ei = table.begin();
ei != table.end(); ++ei) {
cout << sectionName << ": " << (*ei).first << " => "
<< (*ei).second->getValue() << "\n";
}
}
void
IniFile::dump()
{
for (SectionTable::iterator i = table.begin();
i != table.end(); ++i) {
i->second->dump(i->first);
}
}
<commit_msg>Add the directory where the ini file was found into the #include search path<commit_after>/*
* Copyright (c) 2003 The Regents of The University of Michigan
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met: redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer;
* redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution;
* neither the name of the copyright holders nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#define USE_CPP
// #define CPP_PIPE
#ifdef USE_CPP
#include <sys/signal.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#endif
#include <fstream>
#include <iostream>
#if __GNUC__ >= 3
#include <ext/stdio_filebuf.h>
#endif
#include <vector>
#include <string>
#include "base/inifile.hh"
#include "base/str.hh"
using namespace std;
IniFile::IniFile()
{}
IniFile::~IniFile()
{
SectionTable::iterator i = table.begin();
SectionTable::iterator end = table.end();
while (i != end) {
delete (*i).second;
++i;
}
}
#ifdef USE_CPP
bool
IniFile::loadCPP(const string &file, vector<char *> &cppArgs)
{
int fd[2];
// Open the file just to verify that we can. Otherwise if the
// file doesn't exist or has bad permissions the user will get
// confusing errors from cpp/g++.
ifstream tmpf(file.c_str());
if (!tmpf.is_open())
return false;
tmpf.close();
const char *cfile = file.c_str();
char *dir = basename(cfile);
char *dir_arg = NULL;
if (*dir != '.' && dir != cfile) {
string arg = "-I";
arg += dir;
dir_arg = new char[arg.size() + 1];
strcpy(dir_arg, arg.c_str());
}
#ifdef CPP_PIPE
if (pipe(fd) == -1)
return false;
#else
char tempfile[] = "/tmp/configXXXXXX";
fd[0] = fd[1] = mkstemp(tempfile);
#endif
int pid = fork();
if (pid == -1)
return 1;
if (pid == 0) {
char filename[FILENAME_MAX];
string::size_type i = file.copy(filename, sizeof(filename) - 1);
filename[i] = '\0';
int arg_count = cppArgs.size();
char **args = new char *[arg_count + 20];
int nextArg = 0;
args[nextArg++] = "g++";
args[nextArg++] = "-E";
args[nextArg++] = "-P";
args[nextArg++] = "-nostdinc";
args[nextArg++] = "-nostdinc++";
args[nextArg++] = "-x";
args[nextArg++] = "c++";
args[nextArg++] = "-undef";
for (int i = 0; i < arg_count; i++)
args[nextArg++] = cppArgs[i];
if (dir_arg)
args[nextArg++] = dir_arg;
args[nextArg++] = filename;
args[nextArg++] = NULL;
close(STDOUT_FILENO);
if (dup2(fd[1], STDOUT_FILENO) == -1)
return 1;
execvp("g++", args);
exit(1);
}
int retval;
waitpid(pid, &retval, 0);
delete [] dir_arg;
// check for normal completion of CPP
if (!WIFEXITED(retval) || WEXITSTATUS(retval) != 0)
return false;
#ifdef CPP_PIPE
close(fd[1]);
#else
lseek(fd[0], 0, SEEK_SET);
#endif
bool status = false;
#if __GNUC__ >= 3
using namespace __gnu_cxx;
stdio_filebuf<char> fbuf(fd[0], ios_base::in, true,
static_cast<stdio_filebuf<char>::int_type>(BUFSIZ));
if (fbuf.is_open()) {
istream f(&fbuf);
status = load(f);
}
#else
ifstream f(fd[0]);
if (f.is_open())
status = load(f);
#endif
#ifndef CPP_PIPE
unlink(tempfile);
#endif
return status;
}
#endif
bool
IniFile::load(const string &file)
{
ifstream f(file.c_str());
if (!f.is_open())
return false;
return load(f);
}
const string &
IniFile::Entry::getValue() const
{
referenced = true;
return value;
}
void
IniFile::Section::addEntry(const std::string &entryName,
const std::string &value,
bool append)
{
EntryTable::iterator ei = table.find(entryName);
if (ei == table.end()) {
// new entry
table[entryName] = new Entry(value);
}
else if (append) {
// append new reult to old entry
ei->second->appendValue(value);
}
else {
// override old entry
ei->second->setValue(value);
}
}
bool
IniFile::Section::add(const std::string &assignment)
{
string::size_type offset = assignment.find('=');
if (offset == string::npos) {
// no '=' found
cerr << "Can't parse .ini line " << assignment << endl;
return false;
}
// if "+=" rather than just "=" then append value
bool append = (assignment[offset-1] == '+');
string entryName = assignment.substr(0, append ? offset-1 : offset);
string value = assignment.substr(offset + 1);
eat_white(entryName);
eat_white(value);
addEntry(entryName, value, append);
return true;
}
IniFile::Entry *
IniFile::Section::findEntry(const std::string &entryName) const
{
referenced = true;
EntryTable::const_iterator ei = table.find(entryName);
return (ei == table.end()) ? NULL : ei->second;
}
IniFile::Section *
IniFile::addSection(const string §ionName)
{
SectionTable::iterator i = table.find(sectionName);
if (i != table.end()) {
return i->second;
}
else {
// new entry
Section *sec = new Section();
table[sectionName] = sec;
return sec;
}
}
IniFile::Section *
IniFile::findSection(const string §ionName) const
{
SectionTable::const_iterator i = table.find(sectionName);
return (i == table.end()) ? NULL : i->second;
}
// Take string of the form "<section>:<parameter>=<value>" and add to
// database. Return true if successful, false if parse error.
bool
IniFile::add(const string &str)
{
// find ':'
string::size_type offset = str.find(':');
if (offset == string::npos) // no ':' found
return false;
string sectionName = str.substr(0, offset);
string rest = str.substr(offset + 1);
eat_white(sectionName);
Section *s = addSection(sectionName);
return s->add(rest);
}
bool
IniFile::load(istream &f)
{
Section *section = NULL;
while (!f.eof()) {
f >> ws; // Eat whitespace
if (f.eof()) {
break;
}
string line;
getline(f, line);
if (line.size() == 0)
continue;
eat_end_white(line);
int last = line.size() - 1;
if (line[0] == '[' && line[last] == ']') {
string sectionName = line.substr(1, last - 1);
eat_white(sectionName);
section = addSection(sectionName);
continue;
}
if (section == NULL)
continue;
if (!section->add(line))
return false;
}
return true;
}
bool
IniFile::find(const string §ionName, const string &entryName,
string &value) const
{
Section *section = findSection(sectionName);
if (section == NULL)
return false;
Entry *entry = section->findEntry(entryName);
if (entry == NULL)
return false;
value = entry->getValue();
return true;
}
bool
IniFile::findDefault(const string &_section, const string &entry,
string &value) const
{
string section = _section;
while (!find(section, entry, value)) {
if (!find(section, "default", section))
return false;
}
return true;
}
bool
IniFile::Section::printUnreferenced(const string §ionName)
{
bool unref = false;
bool search_unref_entries = false;
vector<string> unref_ok_entries;
Entry *entry = findEntry("unref_entries_ok");
if (entry != NULL) {
tokenize(unref_ok_entries, entry->getValue(), ' ');
if (unref_ok_entries.size()) {
search_unref_entries = true;
}
}
for (EntryTable::iterator ei = table.begin();
ei != table.end(); ++ei) {
const string &entryName = ei->first;
Entry *entry = ei->second;
if (entryName == "unref_section_ok" ||
entryName == "unref_entries_ok")
{
continue;
}
if (!entry->isReferenced()) {
if (search_unref_entries &&
(std::find(unref_ok_entries.begin(), unref_ok_entries.end(),
entryName) != unref_ok_entries.end()))
{
continue;
}
cerr << "Parameter " << sectionName << ":" << entryName
<< " not referenced." << endl;
unref = true;
}
}
return unref;
}
bool
IniFile::printUnreferenced()
{
bool unref = false;
for (SectionTable::iterator i = table.begin();
i != table.end(); ++i) {
const string §ionName = i->first;
Section *section = i->second;
if (!section->isReferenced()) {
if (section->findEntry("unref_section_ok") == NULL) {
cerr << "Section " << sectionName << " not referenced."
<< endl;
unref = true;
}
}
else {
if (section->printUnreferenced(sectionName)) {
unref = true;
}
}
}
return unref;
}
void
IniFile::Section::dump(const string §ionName)
{
for (EntryTable::iterator ei = table.begin();
ei != table.end(); ++ei) {
cout << sectionName << ": " << (*ei).first << " => "
<< (*ei).second->getValue() << "\n";
}
}
void
IniFile::dump()
{
for (SectionTable::iterator i = table.begin();
i != table.end(); ++i) {
i->second->dump(i->first);
}
}
<|endoftext|> |
<commit_before>/*****************************************************************************
* MindTheGap: Integrated detection and assembly of insertion variants
* A tool from the GATB (Genome Assembly Tool Box)
* Copyright (C) 2014 INRIA
* Authors: C.Lemaitre, G.Rizk, P.Marijon
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*****************************************************************************/
#ifndef _TOOL_FindDeletion_HPP_
#define _TOOL_FindDeletion_HPP_
/*****************************************************************************/
#include <IFindObserver.hpp>
#include <FindBreakpoints.hpp>
template<size_t span>
class FindDeletion : public IFindObserver<span>
{
public :
typedef typename gatb::core::kmer::impl::Kmer<span> Kmer;
typedef typename Kmer::ModelCanonical KmerModel;
typedef typename KmerModel::Iterator KmerIterator;
public :
/** \copydoc IFindObserver<span>
*/
FindDeletion(FindBreakpoints<span> * find);
/** \copydoc IFindObserver::IFindObserver
*/
bool update();
};
template<size_t span>
FindDeletion<span>::FindDeletion(FindBreakpoints<span> * find) : IFindObserver<span>(find){}
template<size_t span>
bool FindDeletion<span>::update()
{
if((this->_find->kmer_begin().isValid() && this->_find->kmer_end().isValid()) == false)
{
return false;
}
// Test if deletion is a fuzzy deletion
std::string begin = this->_find->model().toString(this->_find->kmer_begin().forward());
std::string end = this->_find->model().toString(this->_find->kmer_end().forward());
unsigned int repeat_size = 0;
for(repeat_size = 0; begin.substr(begin.length() - 1 - repeat_size, 1) == end.substr(repeat_size, 1); repeat_size++);
// Compute del_size
unsigned int del_size = this->_find->gap_stretch_size() - this->_find->kmer_size() + repeat_size + 1;
if(repeat_size != 0)
{
begin = begin.substr(0, begin.length() - repeat_size)
}
// Check gap is a deletion
std::string seq = begin + end;
KmerModel local_m(this->_find->kmer_size());
KmerIterator local_it(local_m);
Data local_d(const_cast<char*>(seq.c_str()));
local_d.setRef(const_cast<char*>(seq.c_str()), (size_t)seq.length());
local_it.setData(local_d);
for(local_it.first(); !local_it.isDone(); local_it.next())
{
if(!this->contains(local_it->forward()))
{
return false;
}
}
// Write the breakpoint
this->_find->writeBreakpoint(this->_find->breakpoint_id(), this->_find->chrom_name(), this->_find->position() - del_size - 1, begin, end, repeat_size, STR_DEL_TYPE);
this->_find->breakpoint_id_iterate();
if(repeat_size != 0)
this->_find->fuzzy_deletion_iterate();
else
this->_find->clean_deletion_iterate();
return true;
}
#endif /* _TOOL_FindDeletion_HPP_ */
<commit_msg>MTG: repetion in fuzzy deletion can't be greater than max_repeat<commit_after>/*****************************************************************************
* MindTheGap: Integrated detection and assembly of insertion variants
* A tool from the GATB (Genome Assembly Tool Box)
* Copyright (C) 2014 INRIA
* Authors: C.Lemaitre, G.Rizk, P.Marijon
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*****************************************************************************/
#ifndef _TOOL_FindDeletion_HPP_
#define _TOOL_FindDeletion_HPP_
/*****************************************************************************/
#include <IFindObserver.hpp>
#include <FindBreakpoints.hpp>
template<size_t span>
class FindDeletion : public IFindObserver<span>
{
public :
typedef typename gatb::core::kmer::impl::Kmer<span> Kmer;
typedef typename Kmer::ModelCanonical KmerModel;
typedef typename KmerModel::Iterator KmerIterator;
public :
/** \copydoc IFindObserver<span>
*/
FindDeletion(FindBreakpoints<span> * find);
/** \copydoc IFindObserver::IFindObserver
*/
bool update();
};
template<size_t span>
FindDeletion<span>::FindDeletion(FindBreakpoints<span> * find) : IFindObserver<span>(find){}
template<size_t span>
bool FindDeletion<span>::update()
{
if((this->_find->kmer_begin().isValid() && this->_find->kmer_end().isValid()) == false)
{
return false;
}
// Test if deletion is a fuzzy deletion
std::string begin = this->_find->model().toString(this->_find->kmer_begin().forward());
std::string end = this->_find->model().toString(this->_find->kmer_end().forward());
unsigned int repeat_size = 0;
for(repeat_size = 0; begin.substr(begin.length() - 1 - repeat_size, 1) == end.substr(repeat_size, 1); repeat_size++);
if(repeat_size > this->_find->max_repeat())
{
return false;
}
// Compute del_size
unsigned int del_size = this->_find->gap_stretch_size() - this->_find->kmer_size() + repeat_size + 1;
if(repeat_size != 0)
{
begin = begin.substr(0, begin.length() - repeat_size)
}
// Check gap is a deletion
std::string seq = begin + end;
KmerModel local_m(this->_find->kmer_size());
KmerIterator local_it(local_m);
Data local_d(const_cast<char*>(seq.c_str()));
local_d.setRef(const_cast<char*>(seq.c_str()), (size_t)seq.length());
local_it.setData(local_d);
for(local_it.first(); !local_it.isDone(); local_it.next())
{
if(!this->contains(local_it->forward()))
{
return false;
}
}
// Write the breakpoint
this->_find->writeBreakpoint(this->_find->breakpoint_id(), this->_find->chrom_name(), this->_find->position() - del_size - 1, begin, end, repeat_size, STR_DEL_TYPE);
this->_find->breakpoint_id_iterate();
if(repeat_size != 0)
this->_find->fuzzy_deletion_iterate();
else
this->_find->clean_deletion_iterate();
return true;
}
#endif /* _TOOL_FindDeletion_HPP_ */
<|endoftext|> |
<commit_before>#ifndef __AMUSE_COMMON_HPP__
#define __AMUSE_COMMON_HPP__
#include <algorithm>
#include <limits>
#include <stdio.h>
#include <stdint.h>
#include <stdarg.h>
#include <string>
#include <string_view>
#include <cstring>
#ifndef _WIN32
#include <strings.h>
#include <sys/stat.h>
#include <unistd.h>
#else
#ifndef WIN32_LEAN_AND_MEAN
#define WIN32_LEAN_AND_MEAN 1
#endif
#include <Windows.h>
#endif
#undef min
#undef max
constexpr float NativeSampleRate = 32000.0f;
namespace amuse
{
#ifndef PRISize
#ifdef _MSC_VER
#define PRISize "Iu"
#else
#define PRISize "zu"
#endif
#endif
#ifdef _WIN32
using SystemString = std::wstring;
using SystemStringView = std::wstring_view;
using SystemChar = wchar_t;
#ifndef _S
#define _S(val) L##val
#endif
typedef struct _stat Sstat;
static inline int Mkdir(const wchar_t* path, int) { return _wmkdir(path); }
static inline int Stat(const wchar_t* path, Sstat* statout) { return _wstat(path, statout); }
#else
using SystemString = std::string;
using SystemStringView = std::string_view;
using SystemChar = char;
#ifndef _S
#define _S(val) val
#endif
typedef struct stat Sstat;
static inline int Mkdir(const char* path, mode_t mode) { return mkdir(path, mode); }
static inline int Stat(const char* path, Sstat* statout) { return stat(path, statout); }
#endif
#if _WIN32
static inline int CompareCaseInsensitive(const char* a, const char* b) { return _stricmp(a, b); }
#endif
static inline int CompareCaseInsensitive(const SystemChar* a, const SystemChar* b)
{
#if _WIN32
return _wcsicmp(a, b);
#else
return strcasecmp(a, b);
#endif
}
template <typename T>
static inline T clamp(T a, T val, T b)
{
return std::max<T>(a, std::min<T>(b, val));
}
template <typename T>
inline T ClampFull(float in)
{
if(std::is_floating_point<T>())
{
return std::min<T>(std::max<T>(in, -1.0), 1.0);
}
else
{
constexpr T MAX = std::numeric_limits<T>::max();
constexpr T MIN = std::numeric_limits<T>::min();
if(in < MIN)
return MIN;
else if(in > MAX)
return MAX;
else
return in;
}
}
#ifndef M_PIF
#define M_PIF 3.14159265358979323846f /* pi */
#endif
#if __GNUC__
__attribute__((__format__(__printf__, 1, 2)))
#endif
static inline void
Printf(const SystemChar* fmt, ...)
{
va_list args;
va_start(args, fmt);
#if _WIN32
vwprintf(fmt, args);
#else
vprintf(fmt, args);
#endif
va_end(args);
}
#if __GNUC__
__attribute__((__format__(__printf__, 3, 4)))
#endif
static inline void
SNPrintf(SystemChar* str, size_t maxlen, const SystemChar* format, ...)
{
va_list va;
va_start(va, format);
#if _WIN32
_vsnwprintf(str, maxlen, format, va);
#else
vsnprintf(str, maxlen, format, va);
#endif
va_end(va);
}
static inline const SystemChar* StrRChr(const SystemChar* str, SystemChar ch)
{
#if _WIN32
return wcsrchr(str, ch);
#else
return strrchr(str, ch);
#endif
}
static inline SystemChar* StrRChr(SystemChar* str, SystemChar ch)
{
#if _WIN32
return wcsrchr(str, ch);
#else
return strrchr(str, ch);
#endif
}
static inline int FSeek(FILE* fp, int64_t offset, int whence)
{
#if _WIN32
return _fseeki64(fp, offset, whence);
#elif __APPLE__ || __FreeBSD__
return fseeko(fp, offset, whence);
#else
return fseeko64(fp, offset, whence);
#endif
}
static inline int64_t FTell(FILE* fp)
{
#if _WIN32
return _ftelli64(fp);
#elif __APPLE__ || __FreeBSD__
return ftello(fp);
#else
return ftello64(fp);
#endif
}
static inline FILE* FOpen(const SystemChar* path, const SystemChar* mode)
{
#if _WIN32
FILE* fp = _wfopen(path, mode);
if (!fp)
return nullptr;
#else
FILE* fp = fopen(path, mode);
if (!fp)
return nullptr;
#endif
return fp;
}
static inline void Unlink(const SystemChar* file)
{
#if _WIN32
_wunlink(file);
#else
unlink(file);
#endif
}
#undef bswap16
#undef bswap32
#undef bswap64
/* Type-sensitive byte swappers */
template <typename T>
static inline T bswap16(T val)
{
#if __GNUC__
return __builtin_bswap16(val);
#elif _WIN32
return _byteswap_ushort(val);
#else
return (val = (val << 8) | ((val >> 8) & 0xFF));
#endif
}
template <typename T>
static inline T bswap32(T val)
{
#if __GNUC__
return __builtin_bswap32(val);
#elif _WIN32
return _byteswap_ulong(val);
#else
val = (val & 0x0000FFFF) << 16 | (val & 0xFFFF0000) >> 16;
val = (val & 0x00FF00FF) << 8 | (val & 0xFF00FF00) >> 8;
return val;
#endif
}
template <typename T>
static inline T bswap64(T val)
{
#if __GNUC__
return __builtin_bswap64(val);
#elif _WIN32
return _byteswap_uint64(val);
#else
return ((val & 0xFF00000000000000ULL) >> 56) | ((val & 0x00FF000000000000ULL) >> 40) |
((val & 0x0000FF0000000000ULL) >> 24) | ((val & 0x000000FF00000000ULL) >> 8) |
((val & 0x00000000FF000000ULL) << 8) | ((val & 0x0000000000FF0000ULL) << 24) |
((val & 0x000000000000FF00ULL) << 40) | ((val & 0x00000000000000FFULL) << 56);
#endif
}
#if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
static inline int16_t SBig(int16_t val) { return bswap16(val); }
static inline uint16_t SBig(uint16_t val) { return bswap16(val); }
static inline int32_t SBig(int32_t val) { return bswap32(val); }
static inline uint32_t SBig(uint32_t val) { return bswap32(val); }
static inline int64_t SBig(int64_t val) { return bswap64(val); }
static inline uint64_t SBig(uint64_t val) { return bswap64(val); }
static inline float SBig(float val)
{
int32_t ival = bswap32(*((int32_t*)(&val)));
return *((float*)(&ival));
}
static inline double SBig(double val)
{
int64_t ival = bswap64(*((int64_t*)(&val)));
return *((double*)(&ival));
}
#ifndef SBIG
#define SBIG(q) (((q)&0x000000FF) << 24 | ((q)&0x0000FF00) << 8 | ((q)&0x00FF0000) >> 8 | ((q)&0xFF000000) >> 24)
#endif
static inline int16_t SLittle(int16_t val) { return val; }
static inline uint16_t SLittle(uint16_t val) { return val; }
static inline int32_t SLittle(int32_t val) { return val; }
static inline uint32_t SLittle(uint32_t val) { return val; }
static inline int64_t SLittle(int64_t val) { return val; }
static inline uint64_t SLittle(uint64_t val) { return val; }
static inline float SLittle(float val) { return val; }
static inline double SLittle(double val) { return val; }
#ifndef SLITTLE
#define SLITTLE(q) (q)
#endif
#else
static inline int16_t SLittle(int16_t val) { return bswap16(val); }
static inline uint16_t SLittle(uint16_t val) { return bswap16(val); }
static inline int32_t SLittle(int32_t val) { return bswap32(val); }
static inline uint32_t SLittle(uint32_t val) { return bswap32(val); }
static inline int64_t SLittle(int64_t val) { return bswap64(val); }
static inline uint64_t SLittle(uint64_t val) { return bswap64(val); }
static inline float SLittle(float val)
{
int32_t ival = bswap32(*((int32_t*)(&val)));
return *((float*)(&ival));
}
static inline double SLittle(double val)
{
int64_t ival = bswap64(*((int64_t*)(&val)));
return *((double*)(&ival));
}
#ifndef SLITTLE
#define SLITTLE(q) (((q)&0x000000FF) << 24 | ((q)&0x0000FF00) << 8 | ((q)&0x00FF0000) >> 8 | ((q)&0xFF000000) >> 24)
#endif
static inline int16_t SBig(int16_t val) { return val; }
static inline uint16_t SBig(uint16_t val) { return val; }
static inline int32_t SBig(int32_t val) { return val; }
static inline uint32_t SBig(uint32_t val) { return val; }
static inline int64_t SBig(int64_t val) { return val; }
static inline uint64_t SBig(uint64_t val) { return val; }
static inline float SBig(float val) { return val; }
static inline double SBig(double val) { return val; }
#ifndef SBIG
#define SBIG(q) (q)
#endif
#endif
/** Versioned data format to interpret */
enum class DataFormat
{
GCN,
N64,
PC
};
/** Meta-type for selecting GameCube (MusyX 2.0) data formats */
struct GCNDataTag
{
};
/** Meta-type for selecting N64 (MusyX 1.0) data formats */
struct N64DataTag
{
};
/** Meta-type for selecting PC (MusyX 1.0) data formats */
struct PCDataTag
{
};
}
#endif // __AMUSE_COMMON_HPP__
<commit_msg>Minor code formatting adjustments<commit_after>#ifndef __AMUSE_COMMON_HPP__
#define __AMUSE_COMMON_HPP__
#include <algorithm>
#include <limits>
#include <stdio.h>
#include <stdint.h>
#include <stdarg.h>
#include <string>
#include <string_view>
#include <cstring>
#ifndef _WIN32
#include <strings.h>
#include <sys/stat.h>
#include <unistd.h>
#else
#ifndef WIN32_LEAN_AND_MEAN
#define WIN32_LEAN_AND_MEAN 1
#endif
#include <Windows.h>
#endif
#undef min
#undef max
constexpr float NativeSampleRate = 32000.0f;
namespace amuse
{
#ifndef PRISize
#ifdef _MSC_VER
#define PRISize "Iu"
#else
#define PRISize "zu"
#endif
#endif
#ifdef _WIN32
using SystemString = std::wstring;
using SystemStringView = std::wstring_view;
using SystemChar = wchar_t;
#ifndef _S
#define _S(val) L##val
#endif
typedef struct _stat Sstat;
static inline int Mkdir(const wchar_t* path, int) { return _wmkdir(path); }
static inline int Stat(const wchar_t* path, Sstat* statout) { return _wstat(path, statout); }
#else
using SystemString = std::string;
using SystemStringView = std::string_view;
using SystemChar = char;
#ifndef _S
#define _S(val) val
#endif
typedef struct stat Sstat;
static inline int Mkdir(const char* path, mode_t mode) { return mkdir(path, mode); }
static inline int Stat(const char* path, Sstat* statout) { return stat(path, statout); }
#endif
#if _WIN32
static inline int CompareCaseInsensitive(const char* a, const char* b) { return _stricmp(a, b); }
#endif
static inline int CompareCaseInsensitive(const SystemChar* a, const SystemChar* b)
{
#if _WIN32
return _wcsicmp(a, b);
#else
return strcasecmp(a, b);
#endif
}
template <typename T>
static inline T clamp(T a, T val, T b)
{
return std::max<T>(a, std::min<T>(b, val));
}
template <typename T>
inline T ClampFull(float in)
{
if (std::is_floating_point<T>())
{
return std::min<T>(std::max<T>(in, -1.f), 1.f);
}
else
{
constexpr T MAX = std::numeric_limits<T>::max();
constexpr T MIN = std::numeric_limits<T>::min();
if (in < MIN)
return MIN;
else if (in > MAX)
return MAX;
else
return in;
}
}
#ifndef M_PIF
#define M_PIF 3.14159265358979323846f /* pi */
#endif
#if __GNUC__
__attribute__((__format__(__printf__, 1, 2)))
#endif
static inline void
Printf(const SystemChar* fmt, ...)
{
va_list args;
va_start(args, fmt);
#if _WIN32
vwprintf(fmt, args);
#else
vprintf(fmt, args);
#endif
va_end(args);
}
#if __GNUC__
__attribute__((__format__(__printf__, 3, 4)))
#endif
static inline void
SNPrintf(SystemChar* str, size_t maxlen, const SystemChar* format, ...)
{
va_list va;
va_start(va, format);
#if _WIN32
_vsnwprintf(str, maxlen, format, va);
#else
vsnprintf(str, maxlen, format, va);
#endif
va_end(va);
}
static inline const SystemChar* StrRChr(const SystemChar* str, SystemChar ch)
{
#if _WIN32
return wcsrchr(str, ch);
#else
return strrchr(str, ch);
#endif
}
static inline SystemChar* StrRChr(SystemChar* str, SystemChar ch)
{
#if _WIN32
return wcsrchr(str, ch);
#else
return strrchr(str, ch);
#endif
}
static inline int FSeek(FILE* fp, int64_t offset, int whence)
{
#if _WIN32
return _fseeki64(fp, offset, whence);
#elif __APPLE__ || __FreeBSD__
return fseeko(fp, offset, whence);
#else
return fseeko64(fp, offset, whence);
#endif
}
static inline int64_t FTell(FILE* fp)
{
#if _WIN32
return _ftelli64(fp);
#elif __APPLE__ || __FreeBSD__
return ftello(fp);
#else
return ftello64(fp);
#endif
}
static inline FILE* FOpen(const SystemChar* path, const SystemChar* mode)
{
#if _WIN32
FILE* fp = _wfopen(path, mode);
if (!fp)
return nullptr;
#else
FILE* fp = fopen(path, mode);
if (!fp)
return nullptr;
#endif
return fp;
}
static inline void Unlink(const SystemChar* file)
{
#if _WIN32
_wunlink(file);
#else
unlink(file);
#endif
}
#undef bswap16
#undef bswap32
#undef bswap64
/* Type-sensitive byte swappers */
template <typename T>
static inline T bswap16(T val)
{
#if __GNUC__
return __builtin_bswap16(val);
#elif _WIN32
return _byteswap_ushort(val);
#else
return (val = (val << 8) | ((val >> 8) & 0xFF));
#endif
}
template <typename T>
static inline T bswap32(T val)
{
#if __GNUC__
return __builtin_bswap32(val);
#elif _WIN32
return _byteswap_ulong(val);
#else
val = (val & 0x0000FFFF) << 16 | (val & 0xFFFF0000) >> 16;
val = (val & 0x00FF00FF) << 8 | (val & 0xFF00FF00) >> 8;
return val;
#endif
}
template <typename T>
static inline T bswap64(T val)
{
#if __GNUC__
return __builtin_bswap64(val);
#elif _WIN32
return _byteswap_uint64(val);
#else
return ((val & 0xFF00000000000000ULL) >> 56) | ((val & 0x00FF000000000000ULL) >> 40) |
((val & 0x0000FF0000000000ULL) >> 24) | ((val & 0x000000FF00000000ULL) >> 8) |
((val & 0x00000000FF000000ULL) << 8) | ((val & 0x0000000000FF0000ULL) << 24) |
((val & 0x000000000000FF00ULL) << 40) | ((val & 0x00000000000000FFULL) << 56);
#endif
}
#if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
static inline int16_t SBig(int16_t val) { return bswap16(val); }
static inline uint16_t SBig(uint16_t val) { return bswap16(val); }
static inline int32_t SBig(int32_t val) { return bswap32(val); }
static inline uint32_t SBig(uint32_t val) { return bswap32(val); }
static inline int64_t SBig(int64_t val) { return bswap64(val); }
static inline uint64_t SBig(uint64_t val) { return bswap64(val); }
static inline float SBig(float val)
{
int32_t ival = bswap32(*((int32_t*)(&val)));
return *((float*)(&ival));
}
static inline double SBig(double val)
{
int64_t ival = bswap64(*((int64_t*)(&val)));
return *((double*)(&ival));
}
#ifndef SBIG
#define SBIG(q) (((q)&0x000000FF) << 24 | ((q)&0x0000FF00) << 8 | ((q)&0x00FF0000) >> 8 | ((q)&0xFF000000) >> 24)
#endif
static inline int16_t SLittle(int16_t val) { return val; }
static inline uint16_t SLittle(uint16_t val) { return val; }
static inline int32_t SLittle(int32_t val) { return val; }
static inline uint32_t SLittle(uint32_t val) { return val; }
static inline int64_t SLittle(int64_t val) { return val; }
static inline uint64_t SLittle(uint64_t val) { return val; }
static inline float SLittle(float val) { return val; }
static inline double SLittle(double val) { return val; }
#ifndef SLITTLE
#define SLITTLE(q) (q)
#endif
#else
static inline int16_t SLittle(int16_t val) { return bswap16(val); }
static inline uint16_t SLittle(uint16_t val) { return bswap16(val); }
static inline int32_t SLittle(int32_t val) { return bswap32(val); }
static inline uint32_t SLittle(uint32_t val) { return bswap32(val); }
static inline int64_t SLittle(int64_t val) { return bswap64(val); }
static inline uint64_t SLittle(uint64_t val) { return bswap64(val); }
static inline float SLittle(float val)
{
int32_t ival = bswap32(*((int32_t*)(&val)));
return *((float*)(&ival));
}
static inline double SLittle(double val)
{
int64_t ival = bswap64(*((int64_t*)(&val)));
return *((double*)(&ival));
}
#ifndef SLITTLE
#define SLITTLE(q) (((q)&0x000000FF) << 24 | ((q)&0x0000FF00) << 8 | ((q)&0x00FF0000) >> 8 | ((q)&0xFF000000) >> 24)
#endif
static inline int16_t SBig(int16_t val) { return val; }
static inline uint16_t SBig(uint16_t val) { return val; }
static inline int32_t SBig(int32_t val) { return val; }
static inline uint32_t SBig(uint32_t val) { return val; }
static inline int64_t SBig(int64_t val) { return val; }
static inline uint64_t SBig(uint64_t val) { return val; }
static inline float SBig(float val) { return val; }
static inline double SBig(double val) { return val; }
#ifndef SBIG
#define SBIG(q) (q)
#endif
#endif
/** Versioned data format to interpret */
enum class DataFormat
{
GCN,
N64,
PC
};
/** Meta-type for selecting GameCube (MusyX 2.0) data formats */
struct GCNDataTag
{
};
/** Meta-type for selecting N64 (MusyX 1.0) data formats */
struct N64DataTag
{
};
/** Meta-type for selecting PC (MusyX 1.0) data formats */
struct PCDataTag
{
};
}
#endif // __AMUSE_COMMON_HPP__
<|endoftext|> |
<commit_before>//=======================================================================
// Copyright Baptiste Wicht 2011-2012.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
//=======================================================================
#ifndef AST_OPERATOR_H
#define AST_OPERATOR_H
#include <string>
namespace eddic {
namespace ast {
enum class Operator : unsigned int {
ASSIGN,
ADD,
SUB,
DIV,
MUL,
MOD,
AND,
OR,
NOT,
DEC,
INC,
EQUALS,
NOT_EQUALS,
LESS,
LESS_EQUALS,
GREATER,
GREATER_EQUALS
};
std::string toString(Operator op);
std::ostream& operator<< (std::ostream& stream, Operator);
} //end of ast
} //end of eddic
#endif
<commit_msg>Add star operator to the list of operators<commit_after>//=======================================================================
// Copyright Baptiste Wicht 2011-2012.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
//=======================================================================
#ifndef AST_OPERATOR_H
#define AST_OPERATOR_H
#include <string>
namespace eddic {
namespace ast {
/*!
* \enum Operator
* \brief Define an operator in the AST for generic node.
*/
enum class Operator : unsigned int {
ASSIGN,
ADD,
SUB,
DIV,
MUL,
MOD,
AND,
OR,
NOT,
DEC,
INC,
EQUALS,
NOT_EQUALS,
LESS,
LESS_EQUALS,
GREATER,
GREATER_EQUALS,
STAR /**< Star operator, to dereference pointers. */
};
std::string toString(Operator op);
std::ostream& operator<< (std::ostream& stream, Operator);
} //end of ast
} //end of eddic
#endif
<|endoftext|> |
<commit_before>#ifndef TYPES_HPP
#define TYPES_HPP
#include <stdint.h>
#include <inttypes.h>
using atInt8 = int8_t;
using atUint8 = uint8_t;
using atInt16 = int16_t;
using atUint16 = uint16_t;
using atInt32 = int32_t;
using atUint32 = uint32_t;
using atInt64 = int64_t;
using atUint64 = uint64_t;
// Vector types
#if __SSE__
#include <xmmintrin.h>
#include <emmintrin.h>
#ifndef _WIN32
#include <mm_malloc.h>
#endif
#endif
#include <new>
#define AT_ALIGNED_ALLOCATOR \
void* operator new(size_t bytes) noexcept \
{return _mm_malloc(bytes, 16);} \
void* operator new[](size_t bytes) noexcept \
{return _mm_malloc(bytes, 16);} \
void operator delete(void* buf) noexcept \
{_mm_free(buf);} \
void operator delete[](void* buf) noexcept \
{_mm_free(buf);}
typedef union alignas(16)
{
#if __clang__
float clangVec __attribute__((__vector_size__(8)));
#endif
#if __SSE__
__m128 mVec128;
AT_ALIGNED_ALLOCATOR
#endif
float vec[2];
} atVec2f;
typedef union alignas(16)
{
#if __clang__
float clangVec __attribute__((__vector_size__(12)));
#endif
#if __SSE__
__m128 mVec128;
AT_ALIGNED_ALLOCATOR
#endif
float vec[3];
} atVec3f;
typedef union alignas(16)
{
#if __clang__
float clangVec __attribute__((__vector_size__(16)));
#endif
#if __SSE__
__m128 mVec128;
AT_ALIGNED_ALLOCATOR
#endif
float vec[4];
} atVec4f;
typedef union alignas(16)
{
#if __SSE__
__m128d mVec128;
AT_ALIGNED_ALLOCATOR
#endif
double vec[2];
} atVec2d;
typedef union alignas(16)
{
#if __SSE__
__m128d mVec128[2];
AT_ALIGNED_ALLOCATOR
#endif
double vec[3];
} atVec3d;
typedef union alignas(16)
{
#if __SSE__
__m128d mVec128[2];
AT_ALIGNED_ALLOCATOR
#endif
double vec[4];
} atVec4d;
#ifndef UNUSED
#define UNUSED(x) ((void)x)
#endif // UNUSED
#ifdef __GNUC__
#define DEPRECATED(func) func __attribute__ ((deprecated))
#elif defined(_MSC_VER)
#define DEPRECATED(func) __declspec(deprecated) func
#else
#pragma message("WARNING: You need to implement DEPRECATED for this compiler")
#define DEPRECATED(func) func
#endif
#endif // TYPES_HPP
<commit_msg>Make atVec3d 32-byte aligned<commit_after>#ifndef TYPES_HPP
#define TYPES_HPP
#include <stdint.h>
#include <inttypes.h>
using atInt8 = int8_t;
using atUint8 = uint8_t;
using atInt16 = int16_t;
using atUint16 = uint16_t;
using atInt32 = int32_t;
using atUint32 = uint32_t;
using atInt64 = int64_t;
using atUint64 = uint64_t;
// Vector types
#if __SSE__
#include <immintrin.h>
#ifndef _WIN32
#include <mm_malloc.h>
#endif
#endif
#include <new>
#define AT_ALIGNED_ALLOCATOR \
void* operator new(size_t bytes) noexcept \
{return _mm_malloc(bytes, 16);} \
void* operator new[](size_t bytes) noexcept \
{return _mm_malloc(bytes, 16);} \
void operator delete(void* buf) noexcept \
{_mm_free(buf);} \
void operator delete[](void* buf) noexcept \
{_mm_free(buf);}
#define AT_ALIGNED_ALLOCATOR32 \
void* operator new(size_t bytes) noexcept \
{return _mm_malloc(bytes, 32);} \
void* operator new[](size_t bytes) noexcept \
{return _mm_malloc(bytes, 32);} \
void operator delete(void* buf) noexcept \
{_mm_free(buf);} \
void operator delete[](void* buf) noexcept \
{_mm_free(buf);}
typedef union alignas(16)
{
#if __clang__
float clangVec __attribute__((__vector_size__(8)));
#endif
#if __SSE__
__m128 mVec128;
AT_ALIGNED_ALLOCATOR
#endif
float vec[2];
} atVec2f;
typedef union alignas(16)
{
#if __clang__
float clangVec __attribute__((__vector_size__(12)));
#endif
#if __SSE__
__m128 mVec128;
AT_ALIGNED_ALLOCATOR
#endif
float vec[3];
} atVec3f;
typedef union alignas(16)
{
#if __clang__
float clangVec __attribute__((__vector_size__(16)));
#endif
#if __SSE__
__m128 mVec128;
AT_ALIGNED_ALLOCATOR
#endif
float vec[4];
} atVec4f;
typedef union alignas(16)
{
#if __SSE__
__m128d mVec128;
AT_ALIGNED_ALLOCATOR
#endif
double vec[2];
} atVec2d;
typedef union alignas(32)
{
#if __AVX__
__m256d mVec256;
AT_ALIGNED_ALLOCATOR32
#elif __SSE__
AT_ALIGNED_ALLOCATOR
#endif
#if __SSE__
__m128d mVec128[2];
#endif
double vec[3];
} atVec3d;
typedef union alignas(32)
{
#if __AVX__
__m256d mVec256;
AT_ALIGNED_ALLOCATOR32
#elif __SSE__
AT_ALIGNED_ALLOCATOR
#endif
#if __SSE__
__m128d mVec128[2];
#endif
double vec[4];
} atVec4d;
#ifndef UNUSED
#define UNUSED(x) ((void)x)
#endif // UNUSED
#ifdef __GNUC__
#define DEPRECATED(func) func __attribute__ ((deprecated))
#elif defined(_MSC_VER)
#define DEPRECATED(func) __declspec(deprecated) func
#else
#pragma message("WARNING: You need to implement DEPRECATED for this compiler")
#define DEPRECATED(func) func
#endif
#endif // TYPES_HPP
<|endoftext|> |
<commit_before>//=======================================================================
// Copyright (c) 2014 Baptiste Wicht
// Distributed under the terms of the MIT License.
// (See accompanying file LICENSE or copy at
// http://opensource.org/licenses/MIT)
//=======================================================================
#ifndef DLL_CONV_DBN_INL
#define DLL_CONV_DBN_INL
#include <tuple>
#include "cpp_utils/tuple_utils.hpp"
#include "etl/etl.hpp"
#include "io.hpp"
#include "dbn_trainer.hpp"
#include "dbn_common.hpp"
#include "svm_common.hpp"
namespace dll {
/*!
* \brief A Deep Belief Network implementation
*/
template<typename Desc>
struct conv_dbn {
using desc = Desc;
using this_type = conv_dbn<desc>;
using tuple_type = typename desc::layers::tuple_type;
tuple_type tuples;
static constexpr const std::size_t layers = desc::layers::layers;
template <std::size_t N>
using rbm_type = typename std::tuple_element<N, tuple_type>::type;
using weight = typename rbm_type<0>::weight;
#ifdef DLL_SVM_SUPPORT
svm::model svm_model; ///< The learned model
svm::problem problem; ///< libsvm is stupid, therefore, you cannot destroy the problem if you want to use the model...
bool svm_loaded = false; ///< Indicates if a SVM model has been loaded (and therefore must be saved)
#endif //DLL_SVM_SUPPORT
//No arguments by default
conv_dbn(){};
//No copying
conv_dbn(const conv_dbn& dbn) = delete;
conv_dbn& operator=(const conv_dbn& dbn) = delete;
//No moving
conv_dbn(conv_dbn&& dbn) = delete;
conv_dbn& operator=(conv_dbn&& dbn) = delete;
void display() const {
std::size_t parameters = 0;
cpp::for_each(tuples, [¶meters](auto& rbm){
typedef typename std::remove_reference<decltype(rbm)>::type rbm_t;
constexpr const auto NV = rbm_t::NV;
constexpr const auto NH = rbm_t::NH;
constexpr const auto K = rbm_t::K;
printf("RBM: %lux%lu -> %lux%lu (%lu)\n", NV, NV, NH, NH, K);
});
}
void store(std::ostream& os) const {
cpp::for_each(tuples, [&os](auto& rbm){
rbm.store(os);
});
#ifdef DLL_SVM_SUPPORT
svm_store(*this, os);
#endif //DLL_SVM_SUPPORT
}
void load(std::istream& is){
cpp::for_each(tuples, [&is](auto& rbm){
rbm.load(is);
});
#ifdef DLL_SVM_SUPPORT
svm_load(*this, is);
#endif //DLL_SVM_SUPPORT
}
template<std::size_t N>
auto layer() -> typename std::add_lvalue_reference<rbm_type<N>>::type {
return std::get<N>(tuples);
}
template<std::size_t N>
constexpr auto layer() const -> typename std::add_lvalue_reference<typename std::add_const<rbm_type<N>>::type>::type {
return std::get<N>(tuples);
}
template<std::size_t N>
static constexpr std::size_t rbm_nv(){
return rbm_type<N>::NV;
}
template<std::size_t N>
static constexpr std::size_t rbm_k(){
return rbm_type<N>::K;
}
template<std::size_t N>
static constexpr std::size_t rbm_nh(){
return rbm_type<N>::NH;
}
template<typename RBM, cpp::enable_if_u<rbm_traits<RBM>::has_probabilistic_max_pooling()> = cpp::detail::dummy>
static constexpr std::size_t rbm_t_no(){
return RBM::NP;
}
template<typename RBM, cpp::disable_if_u<rbm_traits<RBM>::has_probabilistic_max_pooling()> = cpp::detail::dummy>
static constexpr std::size_t rbm_t_no(){
return RBM::NH;
}
template<std::size_t N>
static constexpr std::size_t rbm_no(){
return rbm_t_no<rbm_type<N>>();
}
template<std::size_t N>
static constexpr std::size_t rbm_input(){
return rbm_traits<rbm_type<N>>::input_size();
}
template<std::size_t N>
static constexpr std::size_t rbm_output(){
return rbm_traits<rbm_type<N>>::output_size();
}
static constexpr std::size_t input_size(){
return rbm_input<0>();
}
static constexpr std::size_t output_size(){
return rbm_output<layers - 1>();
}
static std::size_t full_output_size(){
std::size_t output = 0;
for_each_type<tuple_type>([&output](auto* rbm){
output += std::decay_t<std::remove_pointer_t<decltype(rbm)>>::output_size();
});
return output;
}
/*{{{ Pretrain */
template<typename RBM, typename Input, typename Next, cpp::enable_if_u<rbm_traits<RBM>::has_probabilistic_max_pooling()> = cpp::detail::dummy>
static void propagate(RBM& rbm, Input& input, Next& next_a, Next& next_s){
rbm.v1 = input;
rbm.activate_pooling(next_a, next_s, rbm.v1, rbm.v1);
}
template<typename RBM, typename Input, typename Next, cpp::disable_if_u<rbm_traits<RBM>::has_probabilistic_max_pooling()> = cpp::detail::dummy>
static void propagate(RBM& rbm, Input& input, Next& next_a, Next& next_s){
rbm.v1 = input;
rbm.activate_hidden(next_a, next_s, rbm.v1, rbm.v1);
}
/*!
* \brief Pretrain the network by training all layers in an unsupervised
* manner.
*/
template<typename Samples>
void pretrain(Samples& training_data, std::size_t max_epochs){
using visible_t = std::vector<etl::dyn_matrix<weight, 3>>;
using hidden_t = std::vector<etl::dyn_matrix<weight, 3>>;
using watcher_t = typename desc::template watcher_t<this_type>;
watcher_t watcher;
watcher.pretraining_begin(*this);
//I don't know why it is necesary to copy them here
constexpr const auto NC = rbm_type<0>::NC;
constexpr const auto NV = rbm_type<0>::NV;
//Convert data to an useful form
visible_t data;
data.reserve(training_data.size());
for(auto& sample : training_data){
data.emplace_back(NC, NV, NV);
data.back() = sample;
}
hidden_t next_a;
hidden_t next_s;
auto input = std::ref(data);
cpp::for_each_i(tuples, [&watcher, this, &input, &next_a, &next_s, max_epochs](std::size_t I, auto& rbm){
typedef typename std::remove_reference<decltype(rbm)>::type rbm_t;
constexpr const auto K = rbm_t::K;
constexpr const auto NO = rbm_t_no<rbm_t>();
auto input_size = static_cast<visible_t&>(input).size();
watcher.template pretrain_layer<rbm_t>(*this, I, input_size);
rbm.template train<
visible_t,
!watcher_t::ignore_sub, //Enable the RBM Watcher or not
typename dbn_detail::rbm_watcher_t<watcher_t>::type> //Replace the RBM watcher if not void
(static_cast<visible_t&>(input), max_epochs);
//Get the activation probabilities for the next level
if(I < layers - 1){
next_a.clear();
next_a.reserve(input_size);
next_s.clear();
next_s.reserve(input_size);
for(std::size_t i = 0; i < input_size; ++i){
next_a.emplace_back(K, NO, NO);
next_s.emplace_back(K, NO, NO);
}
for(std::size_t i = 0; i < input_size; ++i){
propagate(rbm, static_cast<visible_t&>(input)[i], next_a[i], next_s[i]);
}
input = std::ref(next_a);
}
});
watcher.pretraining_end(*this);
}
/*}}}*/
/*{{{ Predict */
template<typename Sample, typename Output>
void activation_probabilities(const Sample& item_data, Output& result){
using visible_t = etl::dyn_matrix<weight, 3>;
using hidden_t = etl::dyn_matrix<weight, 3>;
visible_t item(rbm_type<0>::NC, rbm_type<0>::NV, rbm_type<0>::NV);
item = item_data;
auto input = std::cref(item);
cpp::for_each_i(tuples, [&input](std::size_t I, auto& rbm){
if(I != layers - 1){
typedef typename std::remove_reference<decltype(rbm)>::type rbm_t;
constexpr const auto K = rbm_t::K;
constexpr const auto NO = rbm_t_no<rbm_t>();
static hidden_t next_a(K, NO, NO);
static hidden_t next_s(K, NO, NO);
propagate(rbm, static_cast<const visible_t&>(input), next_a, next_s);
input = std::cref(next_a);
}
});
constexpr const auto K = rbm_k<layers - 1>();
constexpr const auto NO = rbm_no<layers - 1>();
static hidden_t next_a(K, NO, NO);
static hidden_t next_s(K, NO, NO);
auto& last_rbm = layer<layers - 1>();
propagate(last_rbm, static_cast<const visible_t&>(input), next_a, next_s);
result = next_a;
}
template<typename Sample>
etl::dyn_vector<weight> activation_probabilities(const Sample& item_data){
etl::dyn_vector<weight> result(output_size());
activation_probabilities(item_data, result);
return result;
}
template<typename Sample, typename Output>
void full_activation_probabilities(const Sample& item_data, Output& result){
using visible_t = etl::dyn_matrix<weight, 3>;
using hidden_t = etl::dyn_matrix<weight, 3>;
visible_t item(rbm_type<0>::NC, rbm_type<0>::NV, rbm_type<0>::NV);
std::size_t i = 0;
item = item_data;
auto input = std::cref(item);
cpp::for_each_i(tuples, [&i, &input, &result](std::size_t I, auto& rbm){
if(I != layers - 1){
typedef typename std::remove_reference<decltype(rbm)>::type rbm_t;
constexpr const auto K = rbm_t::K;
constexpr const auto NO = rbm_t_no<rbm_t>();
static hidden_t next_a(K, NO, NO);
static hidden_t next_s(K, NO, NO);
propagate(rbm, static_cast<const visible_t&>(input), next_a, next_s);
for(auto& value : next_a){
result[i++] = value;
}
input = std::cref(next_a);
}
});
constexpr const auto K = rbm_k<layers - 1>();
constexpr const auto NO = rbm_no<layers - 1>();
static hidden_t next_a(K, NO, NO);
static hidden_t next_s(K, NO, NO);
auto& last_rbm = layer<layers - 1>();
propagate(last_rbm, static_cast<const visible_t&>(input), next_a, next_s);
for(auto& value : next_a){
result[i++] = value;
}
}
template<typename Sample>
etl::dyn_vector<weight> full_activation_probabilities(const Sample& item_data){
etl::dyn_vector<weight> result(full_output_size());
full_activation_probabilities(item_data, result);
return result;
}
template<typename Weights>
size_t predict_label(const Weights& result){
size_t label = 0;
weight max = 0;
for(size_t l = 0; l < result.size(); ++l){
auto value = result[l];
if(value > max){
max = value;
label = l;
}
}
return label;
}
template<typename Sample>
size_t predict(const Sample& item){
auto result = activation_probabilities(item);
return predict_label(result);;
}
/*}}}*/
#ifdef DLL_SVM_SUPPORT
/*{{{ SVM Training and prediction */
template<typename Samples, typename Labels>
bool svm_train(const Samples& training_data, const Labels& labels, const svm_parameter& parameters = default_svm_parameters()){
return dll::svm_train(*this, training_data, labels, parameters);
}
template<typename Iterator, typename LIterator>
bool svm_train(Iterator&& first, Iterator&& last, LIterator&& lfirst, LIterator&& llast, const svm_parameter& parameters = default_svm_parameters()){
return dll::svm_train(*this,
std::forward<Iterator>(first), std::forward<Iterator>(last),
std::forward<LIterator>(lfirst), std::forward<LIterator>(llast),
parameters);
}
template<typename Samples, typename Labels>
bool svm_grid_search(const Samples& training_data, const Labels& labels, std::size_t n_fold = 5, const svm::rbf_grid& g = svm::rbf_grid()){
return dll::svm_grid_search(*this, training_data, labels, n_fold, g);
}
template<typename Iterator, typename LIterator>
bool svm_grid_search(Iterator&& first, Iterator&& last, LIterator&& lfirst, LIterator&& llast, std::size_t n_fold = 5, const svm::rbf_grid& g = svm::rbf_grid()){
return dll::svm_grid_search(*this,
std::forward<Iterator>(first), std::forward<Iterator>(last),
std::forward<LIterator>(lfirst), std::forward<LIterator>(llast),
n_fold, g);
}
template<typename Sample>
double svm_predict(const Sample& sample){
return dll::svm_predict(*this, sample);
}
/*}}}*/
#endif //DLL_SVM_SUPPORT
};
} //end of namespace dll
#endif
<commit_msg>Support more containers<commit_after>//=======================================================================
// Copyright (c) 2014 Baptiste Wicht
// Distributed under the terms of the MIT License.
// (See accompanying file LICENSE or copy at
// http://opensource.org/licenses/MIT)
//=======================================================================
#ifndef DLL_CONV_DBN_INL
#define DLL_CONV_DBN_INL
#include <tuple>
#include "cpp_utils/tuple_utils.hpp"
#include "etl/etl.hpp"
#include "io.hpp"
#include "dbn_trainer.hpp"
#include "dbn_common.hpp"
#include "svm_common.hpp"
namespace dll {
/*!
* \brief A Deep Belief Network implementation
*/
template<typename Desc>
struct conv_dbn {
using desc = Desc;
using this_type = conv_dbn<desc>;
using tuple_type = typename desc::layers::tuple_type;
tuple_type tuples;
static constexpr const std::size_t layers = desc::layers::layers;
template <std::size_t N>
using rbm_type = typename std::tuple_element<N, tuple_type>::type;
using weight = typename rbm_type<0>::weight;
#ifdef DLL_SVM_SUPPORT
svm::model svm_model; ///< The learned model
svm::problem problem; ///< libsvm is stupid, therefore, you cannot destroy the problem if you want to use the model...
bool svm_loaded = false; ///< Indicates if a SVM model has been loaded (and therefore must be saved)
#endif //DLL_SVM_SUPPORT
//No arguments by default
conv_dbn(){};
//No copying
conv_dbn(const conv_dbn& dbn) = delete;
conv_dbn& operator=(const conv_dbn& dbn) = delete;
//No moving
conv_dbn(conv_dbn&& dbn) = delete;
conv_dbn& operator=(conv_dbn&& dbn) = delete;
void display() const {
std::size_t parameters = 0;
cpp::for_each(tuples, [¶meters](auto& rbm){
typedef typename std::remove_reference<decltype(rbm)>::type rbm_t;
constexpr const auto NV = rbm_t::NV;
constexpr const auto NH = rbm_t::NH;
constexpr const auto K = rbm_t::K;
printf("RBM: %lux%lu -> %lux%lu (%lu)\n", NV, NV, NH, NH, K);
});
}
void store(std::ostream& os) const {
cpp::for_each(tuples, [&os](auto& rbm){
rbm.store(os);
});
#ifdef DLL_SVM_SUPPORT
svm_store(*this, os);
#endif //DLL_SVM_SUPPORT
}
void load(std::istream& is){
cpp::for_each(tuples, [&is](auto& rbm){
rbm.load(is);
});
#ifdef DLL_SVM_SUPPORT
svm_load(*this, is);
#endif //DLL_SVM_SUPPORT
}
template<std::size_t N>
auto layer() -> typename std::add_lvalue_reference<rbm_type<N>>::type {
return std::get<N>(tuples);
}
template<std::size_t N>
constexpr auto layer() const -> typename std::add_lvalue_reference<typename std::add_const<rbm_type<N>>::type>::type {
return std::get<N>(tuples);
}
template<std::size_t N>
static constexpr std::size_t rbm_nv(){
return rbm_type<N>::NV;
}
template<std::size_t N>
static constexpr std::size_t rbm_k(){
return rbm_type<N>::K;
}
template<std::size_t N>
static constexpr std::size_t rbm_nh(){
return rbm_type<N>::NH;
}
template<typename RBM, cpp::enable_if_u<rbm_traits<RBM>::has_probabilistic_max_pooling()> = cpp::detail::dummy>
static constexpr std::size_t rbm_t_no(){
return RBM::NP;
}
template<typename RBM, cpp::disable_if_u<rbm_traits<RBM>::has_probabilistic_max_pooling()> = cpp::detail::dummy>
static constexpr std::size_t rbm_t_no(){
return RBM::NH;
}
template<std::size_t N>
static constexpr std::size_t rbm_no(){
return rbm_t_no<rbm_type<N>>();
}
template<std::size_t N>
static constexpr std::size_t rbm_input(){
return rbm_traits<rbm_type<N>>::input_size();
}
template<std::size_t N>
static constexpr std::size_t rbm_output(){
return rbm_traits<rbm_type<N>>::output_size();
}
static constexpr std::size_t input_size(){
return rbm_input<0>();
}
static constexpr std::size_t output_size(){
return rbm_output<layers - 1>();
}
static std::size_t full_output_size(){
std::size_t output = 0;
for_each_type<tuple_type>([&output](auto* rbm){
output += std::decay_t<std::remove_pointer_t<decltype(rbm)>>::output_size();
});
return output;
}
/*{{{ Pretrain */
template<typename RBM, typename Input, typename Next, cpp::enable_if_u<rbm_traits<RBM>::has_probabilistic_max_pooling()> = cpp::detail::dummy>
static void propagate(RBM& rbm, Input& input, Next& next_a, Next& next_s){
rbm.v1 = input;
rbm.activate_pooling(next_a, next_s, rbm.v1, rbm.v1);
}
template<typename RBM, typename Input, typename Next, cpp::disable_if_u<rbm_traits<RBM>::has_probabilistic_max_pooling()> = cpp::detail::dummy>
static void propagate(RBM& rbm, Input& input, Next& next_a, Next& next_s){
rbm.v1 = input;
rbm.activate_hidden(next_a, next_s, rbm.v1, rbm.v1);
}
/*!
* \brief Pretrain the network by training all layers in an unsupervised
* manner.
*/
template<typename Samples>
void pretrain(Samples& training_data, std::size_t max_epochs){
using visible_t = std::vector<etl::dyn_matrix<weight, 3>>;
using hidden_t = std::vector<etl::dyn_matrix<weight, 3>>;
using watcher_t = typename desc::template watcher_t<this_type>;
watcher_t watcher;
watcher.pretraining_begin(*this);
//I don't know why it is necesary to copy them here
constexpr const auto NC = rbm_type<0>::NC;
constexpr const auto NV = rbm_type<0>::NV;
//Convert data to an useful form
visible_t data;
data.reserve(training_data.size());
for(auto& sample : training_data){
data.emplace_back(NC, NV, NV);
data.back() = sample;
}
hidden_t next_a;
hidden_t next_s;
auto input = std::ref(data);
cpp::for_each_i(tuples, [&watcher, this, &input, &next_a, &next_s, max_epochs](std::size_t I, auto& rbm){
typedef typename std::remove_reference<decltype(rbm)>::type rbm_t;
constexpr const auto K = rbm_t::K;
constexpr const auto NO = rbm_t_no<rbm_t>();
auto input_size = static_cast<visible_t&>(input).size();
watcher.template pretrain_layer<rbm_t>(*this, I, input_size);
rbm.template train<
visible_t,
!watcher_t::ignore_sub, //Enable the RBM Watcher or not
typename dbn_detail::rbm_watcher_t<watcher_t>::type> //Replace the RBM watcher if not void
(static_cast<visible_t&>(input), max_epochs);
//Get the activation probabilities for the next level
if(I < layers - 1){
next_a.clear();
next_a.reserve(input_size);
next_s.clear();
next_s.reserve(input_size);
for(std::size_t i = 0; i < input_size; ++i){
next_a.emplace_back(K, NO, NO);
next_s.emplace_back(K, NO, NO);
}
for(std::size_t i = 0; i < input_size; ++i){
propagate(rbm, static_cast<visible_t&>(input)[i], next_a[i], next_s[i]);
}
input = std::ref(next_a);
}
});
watcher.pretraining_end(*this);
}
/*}}}*/
/*{{{ Predict */
template<typename Sample, typename Output>
void activation_probabilities(const Sample& item_data, Output& result){
using visible_t = etl::dyn_matrix<weight, 3>;
using hidden_t = etl::dyn_matrix<weight, 3>;
visible_t item(rbm_type<0>::NC, rbm_type<0>::NV, rbm_type<0>::NV);
item = item_data;
auto input = std::cref(item);
cpp::for_each_i(tuples, [&input](std::size_t I, auto& rbm){
if(I != layers - 1){
typedef typename std::remove_reference<decltype(rbm)>::type rbm_t;
constexpr const auto K = rbm_t::K;
constexpr const auto NO = rbm_t_no<rbm_t>();
static hidden_t next_a(K, NO, NO);
static hidden_t next_s(K, NO, NO);
propagate(rbm, static_cast<const visible_t&>(input), next_a, next_s);
input = std::cref(next_a);
}
});
constexpr const auto K = rbm_k<layers - 1>();
constexpr const auto NO = rbm_no<layers - 1>();
static hidden_t next_a(K, NO, NO);
static hidden_t next_s(K, NO, NO);
auto& last_rbm = layer<layers - 1>();
propagate(last_rbm, static_cast<const visible_t&>(input), next_a, next_s);
for(std::size_t i = 0; i < output_size(); ++i){
result[i] = next_a[i];
}
}
template<typename Sample>
etl::dyn_vector<weight> activation_probabilities(const Sample& item_data){
etl::dyn_vector<weight> result(output_size());
activation_probabilities(item_data, result);
return result;
}
template<typename Sample, typename Output>
void full_activation_probabilities(const Sample& item_data, Output& result){
using visible_t = etl::dyn_matrix<weight, 3>;
using hidden_t = etl::dyn_matrix<weight, 3>;
visible_t item(rbm_type<0>::NC, rbm_type<0>::NV, rbm_type<0>::NV);
std::size_t i = 0;
item = item_data;
auto input = std::cref(item);
cpp::for_each_i(tuples, [&i, &input, &result](std::size_t I, auto& rbm){
if(I != layers - 1){
typedef typename std::remove_reference<decltype(rbm)>::type rbm_t;
constexpr const auto K = rbm_t::K;
constexpr const auto NO = rbm_t_no<rbm_t>();
static hidden_t next_a(K, NO, NO);
static hidden_t next_s(K, NO, NO);
propagate(rbm, static_cast<const visible_t&>(input), next_a, next_s);
for(auto& value : next_a){
result[i++] = value;
}
input = std::cref(next_a);
}
});
constexpr const auto K = rbm_k<layers - 1>();
constexpr const auto NO = rbm_no<layers - 1>();
static hidden_t next_a(K, NO, NO);
static hidden_t next_s(K, NO, NO);
auto& last_rbm = layer<layers - 1>();
propagate(last_rbm, static_cast<const visible_t&>(input), next_a, next_s);
for(auto& value : next_a){
result[i++] = value;
}
}
template<typename Sample>
etl::dyn_vector<weight> full_activation_probabilities(const Sample& item_data){
etl::dyn_vector<weight> result(full_output_size());
full_activation_probabilities(item_data, result);
return result;
}
template<typename Weights>
size_t predict_label(const Weights& result){
size_t label = 0;
weight max = 0;
for(size_t l = 0; l < result.size(); ++l){
auto value = result[l];
if(value > max){
max = value;
label = l;
}
}
return label;
}
template<typename Sample>
size_t predict(const Sample& item){
auto result = activation_probabilities(item);
return predict_label(result);;
}
/*}}}*/
#ifdef DLL_SVM_SUPPORT
/*{{{ SVM Training and prediction */
template<typename Samples, typename Labels>
bool svm_train(const Samples& training_data, const Labels& labels, const svm_parameter& parameters = default_svm_parameters()){
return dll::svm_train(*this, training_data, labels, parameters);
}
template<typename Iterator, typename LIterator>
bool svm_train(Iterator&& first, Iterator&& last, LIterator&& lfirst, LIterator&& llast, const svm_parameter& parameters = default_svm_parameters()){
return dll::svm_train(*this,
std::forward<Iterator>(first), std::forward<Iterator>(last),
std::forward<LIterator>(lfirst), std::forward<LIterator>(llast),
parameters);
}
template<typename Samples, typename Labels>
bool svm_grid_search(const Samples& training_data, const Labels& labels, std::size_t n_fold = 5, const svm::rbf_grid& g = svm::rbf_grid()){
return dll::svm_grid_search(*this, training_data, labels, n_fold, g);
}
template<typename Iterator, typename LIterator>
bool svm_grid_search(Iterator&& first, Iterator&& last, LIterator&& lfirst, LIterator&& llast, std::size_t n_fold = 5, const svm::rbf_grid& g = svm::rbf_grid()){
return dll::svm_grid_search(*this,
std::forward<Iterator>(first), std::forward<Iterator>(last),
std::forward<LIterator>(lfirst), std::forward<LIterator>(llast),
n_fold, g);
}
template<typename Sample>
double svm_predict(const Sample& sample){
return dll::svm_predict(*this, sample);
}
/*}}}*/
#endif //DLL_SVM_SUPPORT
};
} //end of namespace dll
#endif
<|endoftext|> |
<commit_before>namespace hfsm {
////////////////////////////////////////////////////////////////////////////////
#pragma region Utility
template <typename TC, unsigned TMS>
M<TC, TMS>::Fork::Fork(const Index index,
const TypeInfo HSFM_DEBUG_ONLY(type_))
: self(index)
#ifdef _DEBUG
, type(type_)
#endif
{}
//------------------------------------------------------------------------------
template <typename TC, unsigned TMS>
template <unsigned TCapacity>
unsigned
M<TC, TMS>::StateRegistryT<TCapacity>::add(const TypeInfo stateType) {
const unsigned index = _typeToIndex.count();
HSFM_CHECKED(_typeToIndex.insert(*stateType, index));
return index;
}
#pragma endregion
////////////////////////////////////////////////////////////////////////////////
#pragma region Injections
template <typename TC, unsigned TMS>
template <typename TI, typename... TR>
void
M<TC, TMS>::_B<TI, TR...>::widePreSubstitute(Context& context) {
TI::preSubstitute(context);
_B<TR...>::widePreSubstitute(context);
}
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
template <typename TC, unsigned TMS>
template <typename TI, typename... TR>
void
M<TC, TMS>::_B<TI, TR...>::widePreEnter(Context& context) {
TI::preEnter(context);
_B<TR...>::widePreEnter(context);
}
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
template <typename TC, unsigned TMS>
template <typename TI, typename... TR>
void
M<TC, TMS>::_B<TI, TR...>::widePreUpdate(Context& context) {
TI::preUpdate(context);
_B<TR...>::widePreUpdate(context);
}
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
template <typename TC, unsigned TMS>
template <typename TI, typename... TR>
void
M<TC, TMS>::_B<TI, TR...>::widePreTransition(Context& context) {
TI::preTransition(context);
_B<TR...>::widePreTransition(context);
}
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
template <typename TC, unsigned TMS>
template <typename TI, typename... TR>
template <typename TEvent>
void
M<TC, TMS>::_B<TI, TR...>::widePreReact(const TEvent& event,
Context& context)
{
TI::preReact(event, context);
_B<TR...>::widePreReact(event, context);
}
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
template <typename TC, unsigned TMS>
template <typename TI, typename... TR>
void
M<TC, TMS>::_B<TI, TR...>::widePostLeave(Context& context) {
TI::postLeave(context);
_B<TR...>::widePostLeave(context);
}
//------------------------------------------------------------------------------
template <typename TC, unsigned TMS>
template <typename TI>
void
M<TC, TMS>::_B<TI>::widePreSubstitute(Context& context) {
TI::preSubstitute(context);
}
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
template <typename TC, unsigned TMS>
template <typename TI>
void
M<TC, TMS>::_B<TI>::widePreEnter(Context& context) {
TI::preEnter(context);
}
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
template <typename TC, unsigned TMS>
template <typename TI>
void
M<TC, TMS>::_B<TI>::widePreUpdate(Context& context) {
TI::preUpdate(context);
}
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
template <typename TC, unsigned TMS>
template <typename TI>
void
M<TC, TMS>::_B<TI>::widePreTransition(Context& context) {
TI::preTransition(context);
}
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
template <typename TC, unsigned TMS>
template <typename TI>
template <typename TEvent>
void
M<TC, TMS>::_B<TI>::widePreReact(const TEvent& event,
Context& context)
{
TI::preReact(event, context);
}
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
template <typename TC, unsigned TMS>
template <typename TI>
void
M<TC, TMS>::_B<TI>::widePostLeave(Context& context) {
TI::postLeave(context);
}
#pragma endregion
////////////////////////////////////////////////////////////////////////////////
#pragma region Root
template <typename TC, unsigned TMS>
template <typename TA>
M<TC, TMS>::_R<TA>::_R(Context& context)
: _context(context)
, _apex(_stateRegistry, Parent(), _stateParents, _forkParents, _forkPointers)
{
HFSM_IF_STRUCTURE_REPORT(getStateNames());
_apex.deepEnterInitial(_context);
HFSM_IF_STRUCTURE_REPORT(udpateActivity());
}
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
template <typename TC, unsigned TMS>
template <typename TA>
M<TC, TMS>::_R<TA>::~_R() {
_apex.deepLeave(_context);
}
//------------------------------------------------------------------------------
template <typename TC, unsigned TMS>
template <typename TA>
void
M<TC, TMS>::_R<TA>::update() {
Control control(_requests);
_apex.deepUpdateAndTransition(control, _context);
if (_requests.count())
processTransitions();
}
//------------------------------------------------------------------------------
template <typename TC, unsigned TMS>
template <typename TA>
template <typename TEvent>
void
M<TC, TMS>::_R<TA>::react(const TEvent& event) {
Control control(_requests);
_apex.deepReact(event, control, _context);
if (_requests.count())
processTransitions();
}
//------------------------------------------------------------------------------
template <typename TC, unsigned TMS>
template <typename TA>
template <typename T>
bool
M<TC, TMS>::_R<TA>::isActive() {
using Type = T;
const auto stateType = TypeInfo::get<Type>();
const auto state = _stateRegistry[*stateType];
for (auto parent = _stateParents[state]; parent; parent = _forkParents[parent.fork]) {
const auto& fork = *_forkPointers[parent.fork];
if (fork.active != INVALID_INDEX)
return parent.prong == fork.active;
}
return false;
}
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
template <typename TC, unsigned TMS>
template <typename TA>
template <typename T>
bool
M<TC, TMS>::_R<TA>::isResumable() {
using Type = T;
const auto stateType = TypeInfo::get<Type>();
const auto state = _stateRegistry[*stateType];
for (auto parent = _stateParents[state]; parent; parent = _forkParents[parent.fork]) {
const auto& fork = *_forkPointers[parent.fork];
if (fork.active != INVALID_INDEX)
return parent.prong == fork.resumable;
}
return false;
}
//------------------------------------------------------------------------------
template <typename TC, unsigned TMS>
template <typename TA>
void
M<TC, TMS>::_R<TA>::processTransitions() {
HFSM_IF_STRUCTURE_REPORT(_lastTransitions.clear());
for (unsigned i = 0;
i < MaxSubstitutions && _requests.count();
++i)
{
unsigned changeCount = 0;
for (const auto& request : _requests) {
HFSM_IF_STRUCTURE_REPORT(_lastTransitions << DebugTransitionInfo(request, DebugTransitionInfo::Update));
switch (request.type) {
case Transition::Restart:
case Transition::Resume:
requestImmediate(request);
++changeCount;
break;
case Transition::Schedule:
requestScheduled(request);
break;
default:
assert(false);
}
}
_requests.clear();
if (changeCount > 0) {
Control substitutionControl(_requests);
_apex.deepForwardSubstitute(substitutionControl, _context);
#ifdef HFSM_MACHINE_ENABLE_STRUCTURE_REPORT
for (const auto& request : _requests)
_lastTransitions << DebugTransitionInfo(request, DebugTransitionInfo::Substitute);
#endif
}
}
_apex.deepChangeToRequested(_context);
HFSM_IF_STRUCTURE_REPORT(udpateActivity());
}
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
template <typename TC, unsigned TMS>
template <typename TA>
void
M<TC, TMS>::_R<TA>::requestImmediate(const Transition request) {
const unsigned state = id(request);
for (auto parent = _stateParents[state]; parent; parent = _forkParents[parent.fork]) {
auto& fork = *_forkPointers[parent.fork];
HSFM_DEBUG_ONLY(fork.requestedType = parent.prongType);
fork.requested = parent.prong;
}
_apex.deepForwardRequest(request.type);
}
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
template <typename TC, unsigned TMS>
template <typename TA>
void
M<TC, TMS>::_R<TA>::requestScheduled(const Transition request) {
const unsigned state = id(request);
const auto parent = _stateParents[state];
auto& fork = *_forkPointers[parent.fork];
HSFM_ASSERT_ONLY(const auto forksParent = _stateParents[fork.self]);
HSFM_ASSERT_ONLY(const auto& forksFork = *_forkPointers[forksParent.fork]);
assert(forksFork.active == INVALID_INDEX);
HSFM_DEBUG_ONLY(fork.resumableType = parent.prongType);
fork.resumable = parent.prong;
}
//------------------------------------------------------------------------------
#ifdef HFSM_MACHINE_ENABLE_STRUCTURE_REPORT
template <typename TC, unsigned TMS>
template <typename TA>
void
M<TC, TMS>::_R<TA>::getStateNames() {
_stateInfos.clear();
_apex.deepGetNames((unsigned) -1, StateInfo::Composite, 0, _stateInfos);
for (unsigned s = 0; s < _stateInfos.count(); ++s) {
const auto& state = _stateInfos[s];
auto& prefix = _prefixes[s];
if (state.depth == 0)
prefix[0] = L'\0';
else {
const auto mark = state.depth * 2 - 1;
prefix[mark + 2] = L'\0';
prefix[mark + 1] = state.name[0] != '\0' ? L' ' : L'─';
prefix[mark + 0] = state.region == StateInfo::Composite ? L'└' : L'╙';
for (unsigned d = mark; d > 0; --d)
prefix[d - 1] = L' ';
for (unsigned r = s; r > state.parent; --r) {
auto& prefixAbove = _prefixes[r - 1];
switch (prefixAbove[mark]) {
case L' ':
prefixAbove[mark] = state.region == StateInfo::Composite ? L'│' : L'║';
break;
case L'└':
prefixAbove[mark] = L'├';
break;
case L'╙':
prefixAbove[mark] = L'╟';
break;
}
}
}
}
_structure.clear();
for (unsigned s = 0; s < _stateInfos.count(); ++s) {
const auto& state = _stateInfos[s];
auto& prefix = _prefixes[s];
const auto space = state.depth * 2;
if (state.name[0] != L'\0') {
_structure << StructureEntry { false, &prefix[0], state.name };
_activityHistory << (char) 0;
} else if (s + 1 < _stateInfos.count()) {
auto& nextPrefix = _prefixes[s + 1];
if (s > 0)
for (unsigned c = 0; c <= space; ++c)
nextPrefix[c] = prefix[c];
const auto mark = space + 1;
switch (nextPrefix[mark]) {
case L'├':
nextPrefix[mark] = s == 0 ? L'┌' : L'┬';
break;
case L'╟':
nextPrefix[mark] = s == 0 ? L'╓' : L'╥';
break;
}
}
}
}
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
template <typename TC, unsigned TMS>
template <typename TA>
void
M<TC, TMS>::_R<TA>::udpateActivity() {
for (auto& item : _structure)
item.isActive = false;
unsigned index = 0;
_apex.deepIsActive(true, index, _structure);
for (unsigned i = 0; i < _structure.count(); ++i) {
auto& activity = _activityHistory[i];
if (_structure[i].isActive) {
if (activity > 0)
activity = activity < std::numeric_limits<char>::max() ? activity + 1 : activity;
else
activity = +1;
} else {
if (activity > 0)
activity = -1;
else
activity = activity > std::numeric_limits<char>::min() ? activity - 1 : activity;
}
}
}
#endif
#pragma endregion
////////////////////////////////////////////////////////////////////////////////
}
#include "detail/machine_state.inl"
#include "detail/machine_composite.inl"
#include "detail/machine_orthogonal.inl"
<commit_msg>* fixed structure report formatting<commit_after>namespace hfsm {
////////////////////////////////////////////////////////////////////////////////
#pragma region Utility
template <typename TC, unsigned TMS>
M<TC, TMS>::Fork::Fork(const Index index,
const TypeInfo HSFM_DEBUG_ONLY(type_))
: self(index)
#ifdef _DEBUG
, type(type_)
#endif
{}
//------------------------------------------------------------------------------
template <typename TC, unsigned TMS>
template <unsigned TCapacity>
unsigned
M<TC, TMS>::StateRegistryT<TCapacity>::add(const TypeInfo stateType) {
const unsigned index = _typeToIndex.count();
HSFM_CHECKED(_typeToIndex.insert(*stateType, index));
return index;
}
#pragma endregion
////////////////////////////////////////////////////////////////////////////////
#pragma region Injections
template <typename TC, unsigned TMS>
template <typename TI, typename... TR>
void
M<TC, TMS>::_B<TI, TR...>::widePreSubstitute(Context& context) {
TI::preSubstitute(context);
_B<TR...>::widePreSubstitute(context);
}
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
template <typename TC, unsigned TMS>
template <typename TI, typename... TR>
void
M<TC, TMS>::_B<TI, TR...>::widePreEnter(Context& context) {
TI::preEnter(context);
_B<TR...>::widePreEnter(context);
}
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
template <typename TC, unsigned TMS>
template <typename TI, typename... TR>
void
M<TC, TMS>::_B<TI, TR...>::widePreUpdate(Context& context) {
TI::preUpdate(context);
_B<TR...>::widePreUpdate(context);
}
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
template <typename TC, unsigned TMS>
template <typename TI, typename... TR>
void
M<TC, TMS>::_B<TI, TR...>::widePreTransition(Context& context) {
TI::preTransition(context);
_B<TR...>::widePreTransition(context);
}
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
template <typename TC, unsigned TMS>
template <typename TI, typename... TR>
template <typename TEvent>
void
M<TC, TMS>::_B<TI, TR...>::widePreReact(const TEvent& event,
Context& context)
{
TI::preReact(event, context);
_B<TR...>::widePreReact(event, context);
}
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
template <typename TC, unsigned TMS>
template <typename TI, typename... TR>
void
M<TC, TMS>::_B<TI, TR...>::widePostLeave(Context& context) {
TI::postLeave(context);
_B<TR...>::widePostLeave(context);
}
//------------------------------------------------------------------------------
template <typename TC, unsigned TMS>
template <typename TI>
void
M<TC, TMS>::_B<TI>::widePreSubstitute(Context& context) {
TI::preSubstitute(context);
}
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
template <typename TC, unsigned TMS>
template <typename TI>
void
M<TC, TMS>::_B<TI>::widePreEnter(Context& context) {
TI::preEnter(context);
}
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
template <typename TC, unsigned TMS>
template <typename TI>
void
M<TC, TMS>::_B<TI>::widePreUpdate(Context& context) {
TI::preUpdate(context);
}
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
template <typename TC, unsigned TMS>
template <typename TI>
void
M<TC, TMS>::_B<TI>::widePreTransition(Context& context) {
TI::preTransition(context);
}
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
template <typename TC, unsigned TMS>
template <typename TI>
template <typename TEvent>
void
M<TC, TMS>::_B<TI>::widePreReact(const TEvent& event,
Context& context)
{
TI::preReact(event, context);
}
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
template <typename TC, unsigned TMS>
template <typename TI>
void
M<TC, TMS>::_B<TI>::widePostLeave(Context& context) {
TI::postLeave(context);
}
#pragma endregion
////////////////////////////////////////////////////////////////////////////////
#pragma region Root
template <typename TC, unsigned TMS>
template <typename TA>
M<TC, TMS>::_R<TA>::_R(Context& context)
: _context(context)
, _apex(_stateRegistry, Parent(), _stateParents, _forkParents, _forkPointers)
{
HFSM_IF_STRUCTURE_REPORT(getStateNames());
_apex.deepEnterInitial(_context);
HFSM_IF_STRUCTURE_REPORT(udpateActivity());
}
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
template <typename TC, unsigned TMS>
template <typename TA>
M<TC, TMS>::_R<TA>::~_R() {
_apex.deepLeave(_context);
}
//------------------------------------------------------------------------------
template <typename TC, unsigned TMS>
template <typename TA>
void
M<TC, TMS>::_R<TA>::update() {
Control control(_requests);
_apex.deepUpdateAndTransition(control, _context);
if (_requests.count())
processTransitions();
}
//------------------------------------------------------------------------------
template <typename TC, unsigned TMS>
template <typename TA>
template <typename TEvent>
void
M<TC, TMS>::_R<TA>::react(const TEvent& event) {
Control control(_requests);
_apex.deepReact(event, control, _context);
if (_requests.count())
processTransitions();
}
//------------------------------------------------------------------------------
template <typename TC, unsigned TMS>
template <typename TA>
template <typename T>
bool
M<TC, TMS>::_R<TA>::isActive() {
using Type = T;
const auto stateType = TypeInfo::get<Type>();
const auto state = _stateRegistry[*stateType];
for (auto parent = _stateParents[state]; parent; parent = _forkParents[parent.fork]) {
const auto& fork = *_forkPointers[parent.fork];
if (fork.active != INVALID_INDEX)
return parent.prong == fork.active;
}
return false;
}
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
template <typename TC, unsigned TMS>
template <typename TA>
template <typename T>
bool
M<TC, TMS>::_R<TA>::isResumable() {
using Type = T;
const auto stateType = TypeInfo::get<Type>();
const auto state = _stateRegistry[*stateType];
for (auto parent = _stateParents[state]; parent; parent = _forkParents[parent.fork]) {
const auto& fork = *_forkPointers[parent.fork];
if (fork.active != INVALID_INDEX)
return parent.prong == fork.resumable;
}
return false;
}
//------------------------------------------------------------------------------
template <typename TC, unsigned TMS>
template <typename TA>
void
M<TC, TMS>::_R<TA>::processTransitions() {
HFSM_IF_STRUCTURE_REPORT(_lastTransitions.clear());
for (unsigned i = 0;
i < MaxSubstitutions && _requests.count();
++i)
{
unsigned changeCount = 0;
for (const auto& request : _requests) {
HFSM_IF_STRUCTURE_REPORT(_lastTransitions << DebugTransitionInfo(request, DebugTransitionInfo::Update));
switch (request.type) {
case Transition::Restart:
case Transition::Resume:
requestImmediate(request);
++changeCount;
break;
case Transition::Schedule:
requestScheduled(request);
break;
default:
assert(false);
}
}
_requests.clear();
if (changeCount > 0) {
Control substitutionControl(_requests);
_apex.deepForwardSubstitute(substitutionControl, _context);
#ifdef HFSM_MACHINE_ENABLE_STRUCTURE_REPORT
for (const auto& request : _requests)
_lastTransitions << DebugTransitionInfo(request, DebugTransitionInfo::Substitute);
#endif
}
}
_apex.deepChangeToRequested(_context);
HFSM_IF_STRUCTURE_REPORT(udpateActivity());
}
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
template <typename TC, unsigned TMS>
template <typename TA>
void
M<TC, TMS>::_R<TA>::requestImmediate(const Transition request) {
const unsigned state = id(request);
for (auto parent = _stateParents[state]; parent; parent = _forkParents[parent.fork]) {
auto& fork = *_forkPointers[parent.fork];
HSFM_DEBUG_ONLY(fork.requestedType = parent.prongType);
fork.requested = parent.prong;
}
_apex.deepForwardRequest(request.type);
}
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
template <typename TC, unsigned TMS>
template <typename TA>
void
M<TC, TMS>::_R<TA>::requestScheduled(const Transition request) {
const unsigned state = id(request);
const auto parent = _stateParents[state];
auto& fork = *_forkPointers[parent.fork];
HSFM_ASSERT_ONLY(const auto forksParent = _stateParents[fork.self]);
HSFM_ASSERT_ONLY(const auto& forksFork = *_forkPointers[forksParent.fork]);
assert(forksFork.active == INVALID_INDEX);
HSFM_DEBUG_ONLY(fork.resumableType = parent.prongType);
fork.resumable = parent.prong;
}
//------------------------------------------------------------------------------
#ifdef HFSM_MACHINE_ENABLE_STRUCTURE_REPORT
template <typename TC, unsigned TMS>
template <typename TA>
void
M<TC, TMS>::_R<TA>::getStateNames() {
_stateInfos.clear();
_apex.deepGetNames((unsigned) -1, StateInfo::Composite, 0, _stateInfos);
unsigned margin = (unsigned) -1;
for (unsigned s = 0; s < _stateInfos.count(); ++s) {
const auto& state = _stateInfos[s];
auto& prefix = _prefixes[s];
if (margin > state.depth && state.name[0] != '\0')
margin = state.depth;
if (state.depth == 0)
prefix[0] = L'\0';
else {
const auto mark = state.depth * 2 - 1;
prefix[mark + 0] = state.region == StateInfo::Composite ? L'└' : L'╙';
prefix[mark + 1] = L' ';
prefix[mark + 2] = L'\0';
for (unsigned d = mark; d > 0; --d)
prefix[d - 1] = L' ';
for (unsigned r = s; r > state.parent; --r) {
auto& prefixAbove = _prefixes[r - 1];
switch (prefixAbove[mark]) {
case L' ':
prefixAbove[mark] = state.region == StateInfo::Composite ? L'│' : L'║';
break;
case L'└':
prefixAbove[mark] = L'├';
break;
case L'╙':
prefixAbove[mark] = L'╟';
break;
}
}
}
}
if (margin > 0)
margin -= 1;
_structure.clear();
for (unsigned s = 0; s < _stateInfos.count(); ++s) {
const auto& state = _stateInfos[s];
auto& prefix = _prefixes[s];
const auto space = state.depth * 2;
if (state.name[0] != L'\0') {
_structure << StructureEntry { false, &prefix[margin * 2], state.name };
_activityHistory << (char) 0;
} else if (s + 1 < _stateInfos.count()) {
auto& nextPrefix = _prefixes[s + 1];
if (s > 0)
for (unsigned c = 0; c <= space; ++c)
nextPrefix[c] = prefix[c];
const auto mark = space + 1;
switch (nextPrefix[mark]) {
case L'├':
nextPrefix[mark] = state.depth == margin ? L'┌' : L'┬';
break;
case L'╟':
nextPrefix[mark] = state.depth == margin ? L'╓' : L'╥';
break;
}
}
}
}
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
template <typename TC, unsigned TMS>
template <typename TA>
void
M<TC, TMS>::_R<TA>::udpateActivity() {
for (auto& item : _structure)
item.isActive = false;
unsigned index = 0;
_apex.deepIsActive(true, index, _structure);
for (unsigned i = 0; i < _structure.count(); ++i) {
auto& activity = _activityHistory[i];
if (_structure[i].isActive) {
if (activity > 0)
activity = activity < std::numeric_limits<char>::max() ? activity + 1 : activity;
else
activity = +1;
} else {
if (activity > 0)
activity = -1;
else
activity = activity > std::numeric_limits<char>::min() ? activity - 1 : activity;
}
}
}
#endif
#pragma endregion
////////////////////////////////////////////////////////////////////////////////
}
#include "detail/machine_state.inl"
#include "detail/machine_composite.inl"
#include "detail/machine_orthogonal.inl"
<|endoftext|> |
<commit_before>/*************************************************************************
*
* $RCSfile: basdoc.hxx,v $
*
* $Revision: 1.3 $
*
* last change: $Author: mba $ $Date: 2001-07-20 10:49:36 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#ifndef _BASDOC_HXX
#define _BASDOC_HXX
#include <svx/ifaceids.hxx>
#include <iderid.hxx>
#ifndef _SFX_OBJSH_HXX //autogen
#include <sfx2/objsh.hxx>
#endif
class SfxPrinter;
class BasicDocShell: public SfxObjectShell
{
SfxPrinter* pPrinter;
protected:
virtual void FillStatusBar( StatusBar& rBar);
public:
TYPEINFO();
SFX_DECL_SIMPLE_OBJECTFACTORY_DLL( BasicDocShell );
SFX_DECL_INTERFACE( SVX_INTERFACE_BASIDE_DOCSH );
BasicDocShell( SfxObjectCreateMode eMode = SFX_CREATE_MODE_STANDARD );
~BasicDocShell();
void Execute( SfxRequest& rReq );
void GetState( SfxItemSet& rSet );
SfxPrinter* GetPrinter( BOOL bCreate );
void SetPrinter( SfxPrinter* pPrinter );
};
#endif // _BASDOC_HXX
<commit_msg>INTEGRATION: CWS fwkq1 (1.3.104); FILE MERGED 2003/08/29 13:33:33 mba 1.3.104.1: #110843#: removed unnecessary macros<commit_after>/*************************************************************************
*
* $RCSfile: basdoc.hxx,v $
*
* $Revision: 1.4 $
*
* last change: $Author: rt $ $Date: 2003-09-19 08:29:18 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#ifndef _BASDOC_HXX
#define _BASDOC_HXX
#include <svx/ifaceids.hxx>
#include <iderid.hxx>
#ifndef _SFX_OBJSH_HXX //autogen
#include <sfx2/objsh.hxx>
#endif
class SfxPrinter;
class BasicDocShell: public SfxObjectShell
{
SfxPrinter* pPrinter;
protected:
virtual void FillStatusBar( StatusBar& rBar);
public:
TYPEINFO();
SFX_DECL_SIMPLE_OBJECTFACTORY( BasicDocShell );
SFX_DECL_INTERFACE( SVX_INTERFACE_BASIDE_DOCSH );
BasicDocShell( SfxObjectCreateMode eMode = SFX_CREATE_MODE_STANDARD );
~BasicDocShell();
void Execute( SfxRequest& rReq );
void GetState( SfxItemSet& rSet );
SfxPrinter* GetPrinter( BOOL bCreate );
void SetPrinter( SfxPrinter* pPrinter );
};
#endif // _BASDOC_HXX
<|endoftext|> |
<commit_before>#include "chainerx/routines/linalg.h"
#include <algorithm>
#include <cassert>
#include <cstdint>
#include <utility>
#include <vector>
#include <nonstd/optional.hpp>
#include "chainerx/array.h"
#include "chainerx/axes.h"
#include "chainerx/backend.h"
#include "chainerx/backprop_mode.h"
#include "chainerx/backward_builder.h"
#include "chainerx/backward_context.h"
#include "chainerx/dtype.h"
#include "chainerx/error.h"
#include "chainerx/graph.h"
#include "chainerx/kernels/linalg.h"
#include "chainerx/routines/creation.h"
#include "chainerx/routines/type_util.h"
#include "chainerx/shape.h"
namespace chainerx {
Array Dot(const Array& a, const Array& b, nonstd::optional<Dtype> out_dtype) {
Dtype real_out_dtype = out_dtype.has_value() ? *out_dtype : ResultType(a, b);
if (a.ndim() == 0 || b.ndim() == 0) {
return a * b;
}
Array modified_b{};
Shape out_shape{};
std::copy(a.shape().begin(), a.shape().end() - 1, std::back_inserter(out_shape));
if (b.ndim() > 2) {
std::vector<int> b_transpose_axes{};
b_transpose_axes.reserve(b.ndim());
std::vector<int> axes_index(b.ndim());
std::iota(axes_index.begin(), axes_index.end(), 0);
std::copy(axes_index.begin(), axes_index.end() - 2, std::back_inserter(b_transpose_axes));
std::reverse_copy(axes_index.end() - 2, axes_index.end(), std::back_inserter(b_transpose_axes));
Axes axes(b_transpose_axes.begin(), b_transpose_axes.end());
modified_b = b.Transpose(axes);
std::copy(modified_b.shape().begin(), modified_b.shape().end() - 1, std::back_inserter(out_shape));
modified_b = modified_b.Reshape({-1, modified_b.shape().back()});
modified_b = modified_b.Transpose();
} else {
std::copy(b.shape().begin() + 1, b.shape().end(), std::back_inserter(out_shape));
modified_b = b;
}
int64_t k = a.shape()[a.ndim() - 1];
if (modified_b.shape()[0] != k) {
throw DimensionError{"Axis dimension mismatch"};
}
if (k == 0) {
return Zeros(out_shape, real_out_dtype, a.device());
}
// Make each operand a matrix
int64_t m = a.GetTotalSize() / k;
int64_t n = b.GetTotalSize() / k;
Array a_matrix = a.Reshape({m, k});
Array b_matrix = modified_b.Reshape({k, n});
// Matrix-matrix product
Array out_matrix = Empty({m, n}, real_out_dtype, a.device());
{
NoBackpropModeScope scope{};
a.device().backend().CallKernel<DotKernel>(a_matrix, b_matrix, out_matrix);
}
{
BackwardBuilder bb{"dot", {a_matrix, b_matrix}, out_matrix};
if (BackwardBuilder::Target bt = bb.CreateTarget(0)) {
bt.Define([b_matrix_tok = bb.RetainInput(1), a_dtype = a.dtype()](BackwardContext& bctx) {
const Array& b_matrix = bctx.GetRetainedInput(b_matrix_tok);
const Array& gout = *bctx.output_grad();
bctx.input_grad() = Dot(gout, b_matrix.Transpose(), a_dtype);
});
}
if (BackwardBuilder::Target bt = bb.CreateTarget(1)) {
bt.Define([a_matrix_tok = bb.RetainInput(0), b_dtype = b.dtype()](BackwardContext& bctx) {
const Array& a_matrix = bctx.GetRetainedInput(a_matrix_tok);
const Array& gout = *bctx.output_grad();
bctx.input_grad() = Dot(a_matrix.Transpose(), gout, b_dtype);
});
}
bb.Finalize();
}
return out_matrix.Reshape(out_shape);
}
Array Solve(const Array& a, const Array& b) {
if (a.ndim() != 2) {
throw DimensionError{"ChainerX solve supports only 2-dimensional arrays."};
}
if (a.shape()[0] != a.shape()[1]) {
throw DimensionError{"Matrix is not square."};
}
CheckEqual(a.device(), b.device());
CheckEqual(a.dtype(), b.dtype());
Dtype dtype = internal::GetMathResultDtype(b.dtype());
Array out = Empty(b.shape(), dtype, b.device());
{
NoBackpropModeScope scope{};
a.device().backend().CallKernel<SolveKernel>(a, b, out);
}
// Reference:
// https://people.maths.ox.ac.uk/gilesm/files/NA-08-01.pdf
// Sec. 2.3.1 Matrix inverse product
{
BackwardBuilder bb{"solve", {a, b}, out};
if (BackwardBuilder::Target bt = bb.CreateTarget(0)) {
bt.Define([out_tok = bb.RetainOutput(0), a_tok = bb.RetainInput(0), a_dtype = a.dtype()](BackwardContext& bctx) {
const Array& a = bctx.GetRetainedInput(a_tok);
const Array& out = bctx.GetRetainedOutput(out_tok);
const Array& gout = *bctx.output_grad();
bctx.input_grad() =
-Dot(Solve(a.Transpose(), gout).At(std::vector<ArrayIndex>{Slice{}, NewAxis{}}),
out.At(std::vector<ArrayIndex>{Slice{}, NewAxis{}}).Transpose(),
a_dtype);
});
}
if (BackwardBuilder::Target bt = bb.CreateTarget(1)) {
bt.Define([a_tok = bb.RetainInput(0)](BackwardContext& bctx) {
const Array& a = bctx.GetRetainedInput(a_tok);
const Array& gout = *bctx.output_grad();
bctx.input_grad() = Solve(a.Transpose(), gout);
});
}
bb.Finalize();
}
return out;
}
Array Inverse(const Array& a) {
if (a.ndim() != 2) {
throw DimensionError{"ChainerX inverse supports only 2-dimensional arrays."};
}
if (a.shape()[0] != a.shape()[1]) {
throw DimensionError{"Matrix is not square."};
}
Dtype dtype = internal::GetMathResultDtype(a.dtype());
Array out = Empty(a.shape(), dtype, a.device());
{
NoBackpropModeScope scope{};
a.device().backend().CallKernel<InverseKernel>(a, out);
}
// Reference:
// https://people.maths.ox.ac.uk/gilesm/files/NA-08-01.pdf
// Sec. 2.2.3 Inverse
{
BackwardBuilder bb{"inv", a, out};
if (BackwardBuilder::Target bt = bb.CreateTarget(0)) {
bt.Define([out_tok = bb.RetainOutput(0), a_dtype = a.dtype()](BackwardContext& bctx) {
const Array& out = bctx.GetRetainedOutput(out_tok);
const Array& gout = *bctx.output_grad();
bctx.input_grad() = -Dot(Dot(out.Transpose(), gout, a_dtype), out.Transpose(), a_dtype);
});
}
bb.Finalize();
}
return out;
}
} // namespace chainerx
<commit_msg>Use ExpandDims instead of Array.At+NewAxis<commit_after>#include "chainerx/routines/linalg.h"
#include <algorithm>
#include <cassert>
#include <cstdint>
#include <utility>
#include <vector>
#include <nonstd/optional.hpp>
#include "chainerx/array.h"
#include "chainerx/axes.h"
#include "chainerx/backend.h"
#include "chainerx/backprop_mode.h"
#include "chainerx/backward_builder.h"
#include "chainerx/backward_context.h"
#include "chainerx/dtype.h"
#include "chainerx/error.h"
#include "chainerx/graph.h"
#include "chainerx/kernels/linalg.h"
#include "chainerx/routines/creation.h"
#include "chainerx/routines/manipulation.h"
#include "chainerx/routines/type_util.h"
#include "chainerx/shape.h"
namespace chainerx {
Array Dot(const Array& a, const Array& b, nonstd::optional<Dtype> out_dtype) {
Dtype real_out_dtype = out_dtype.has_value() ? *out_dtype : ResultType(a, b);
if (a.ndim() == 0 || b.ndim() == 0) {
return a * b;
}
Array modified_b{};
Shape out_shape{};
std::copy(a.shape().begin(), a.shape().end() - 1, std::back_inserter(out_shape));
if (b.ndim() > 2) {
std::vector<int> b_transpose_axes{};
b_transpose_axes.reserve(b.ndim());
std::vector<int> axes_index(b.ndim());
std::iota(axes_index.begin(), axes_index.end(), 0);
std::copy(axes_index.begin(), axes_index.end() - 2, std::back_inserter(b_transpose_axes));
std::reverse_copy(axes_index.end() - 2, axes_index.end(), std::back_inserter(b_transpose_axes));
Axes axes(b_transpose_axes.begin(), b_transpose_axes.end());
modified_b = b.Transpose(axes);
std::copy(modified_b.shape().begin(), modified_b.shape().end() - 1, std::back_inserter(out_shape));
modified_b = modified_b.Reshape({-1, modified_b.shape().back()});
modified_b = modified_b.Transpose();
} else {
std::copy(b.shape().begin() + 1, b.shape().end(), std::back_inserter(out_shape));
modified_b = b;
}
int64_t k = a.shape()[a.ndim() - 1];
if (modified_b.shape()[0] != k) {
throw DimensionError{"Axis dimension mismatch"};
}
if (k == 0) {
return Zeros(out_shape, real_out_dtype, a.device());
}
// Make each operand a matrix
int64_t m = a.GetTotalSize() / k;
int64_t n = b.GetTotalSize() / k;
Array a_matrix = a.Reshape({m, k});
Array b_matrix = modified_b.Reshape({k, n});
// Matrix-matrix product
Array out_matrix = Empty({m, n}, real_out_dtype, a.device());
{
NoBackpropModeScope scope{};
a.device().backend().CallKernel<DotKernel>(a_matrix, b_matrix, out_matrix);
}
{
BackwardBuilder bb{"dot", {a_matrix, b_matrix}, out_matrix};
if (BackwardBuilder::Target bt = bb.CreateTarget(0)) {
bt.Define([b_matrix_tok = bb.RetainInput(1), a_dtype = a.dtype()](BackwardContext& bctx) {
const Array& b_matrix = bctx.GetRetainedInput(b_matrix_tok);
const Array& gout = *bctx.output_grad();
bctx.input_grad() = Dot(gout, b_matrix.Transpose(), a_dtype);
});
}
if (BackwardBuilder::Target bt = bb.CreateTarget(1)) {
bt.Define([a_matrix_tok = bb.RetainInput(0), b_dtype = b.dtype()](BackwardContext& bctx) {
const Array& a_matrix = bctx.GetRetainedInput(a_matrix_tok);
const Array& gout = *bctx.output_grad();
bctx.input_grad() = Dot(a_matrix.Transpose(), gout, b_dtype);
});
}
bb.Finalize();
}
return out_matrix.Reshape(out_shape);
}
Array Solve(const Array& a, const Array& b) {
if (a.ndim() != 2) {
throw DimensionError{"ChainerX solve supports only 2-dimensional arrays."};
}
if (a.shape()[0] != a.shape()[1]) {
throw DimensionError{"Matrix is not square."};
}
CheckEqual(a.device(), b.device());
CheckEqual(a.dtype(), b.dtype());
Dtype dtype = internal::GetMathResultDtype(b.dtype());
Array out = Empty(b.shape(), dtype, b.device());
{
NoBackpropModeScope scope{};
a.device().backend().CallKernel<SolveKernel>(a, b, out);
}
// Reference:
// https://people.maths.ox.ac.uk/gilesm/files/NA-08-01.pdf
// Sec. 2.3.1 Matrix inverse product
{
BackwardBuilder bb{"solve", {a, b}, out};
if (BackwardBuilder::Target bt = bb.CreateTarget(0)) {
bt.Define([out_tok = bb.RetainOutput(0), a_tok = bb.RetainInput(0), a_dtype = a.dtype()](BackwardContext& bctx) {
const Array& a = bctx.GetRetainedInput(a_tok);
const Array& out = bctx.GetRetainedOutput(out_tok);
const Array& gout = *bctx.output_grad();
bctx.input_grad() = -Dot(ExpandDims(Solve(a.Transpose(), gout), 1), ExpandDims(out, 0), a_dtype);
});
}
if (BackwardBuilder::Target bt = bb.CreateTarget(1)) {
bt.Define([a_tok = bb.RetainInput(0)](BackwardContext& bctx) {
const Array& a = bctx.GetRetainedInput(a_tok);
const Array& gout = *bctx.output_grad();
bctx.input_grad() = Solve(a.Transpose(), gout);
});
}
bb.Finalize();
}
return out;
}
Array Inverse(const Array& a) {
if (a.ndim() != 2) {
throw DimensionError{"ChainerX inverse supports only 2-dimensional arrays."};
}
if (a.shape()[0] != a.shape()[1]) {
throw DimensionError{"Matrix is not square."};
}
Dtype dtype = internal::GetMathResultDtype(a.dtype());
Array out = Empty(a.shape(), dtype, a.device());
{
NoBackpropModeScope scope{};
a.device().backend().CallKernel<InverseKernel>(a, out);
}
// Reference:
// https://people.maths.ox.ac.uk/gilesm/files/NA-08-01.pdf
// Sec. 2.2.3 Inverse
{
BackwardBuilder bb{"inv", a, out};
if (BackwardBuilder::Target bt = bb.CreateTarget(0)) {
bt.Define([out_tok = bb.RetainOutput(0), a_dtype = a.dtype()](BackwardContext& bctx) {
const Array& out = bctx.GetRetainedOutput(out_tok);
const Array& gout = *bctx.output_grad();
bctx.input_grad() = -Dot(Dot(out.Transpose(), gout, a_dtype), out.Transpose(), a_dtype);
});
}
bb.Finalize();
}
return out;
}
} // namespace chainerx
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: b2drange.cxx,v $
*
* $Revision: 1.9 $
*
* last change: $Author: ihi $ $Date: 2006-11-14 14:09:48 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_basegfx.hxx"
#ifndef _BGFX_RANGE_B2DRANGE_HXX
#include <basegfx/range/b2drange.hxx>
#endif
#ifndef _BGFX_RANGE_B2IRANGE_HXX
#include <basegfx/range/b2irange.hxx>
#endif
#ifndef _BGFX_NUMERIC_FTOOLS_HXX
#include <basegfx/numeric/ftools.hxx>
#endif
#ifndef _BGFX_MATRIX_B2DHOMMATRIX_HXX
#include <basegfx/matrix/b2dhommatrix.hxx>
#endif
namespace basegfx
{
B2DRange::B2DRange( const B2IRange& rRange ) :
maRangeX(),
maRangeY()
{
if( !rRange.isEmpty() )
{
maRangeX = rRange.getMinX();
maRangeY = rRange.getMinY();
maRangeX.expand(rRange.getMaxX());
maRangeY.expand(rRange.getMaxY());
}
}
void B2DRange::transform(const B2DHomMatrix& rMatrix)
{
if(!isEmpty() && !rMatrix.isIdentity())
{
const B2DRange aSource(*this);
reset();
expand(rMatrix * B2DPoint(aSource.getMinX(), aSource.getMinY()));
expand(rMatrix * B2DPoint(aSource.getMaxX(), aSource.getMinY()));
expand(rMatrix * B2DPoint(aSource.getMinX(), aSource.getMaxY()));
expand(rMatrix * B2DPoint(aSource.getMaxX(), aSource.getMaxY()));
}
}
B2IRange fround(const B2DRange& rRange)
{
return rRange.isEmpty() ?
B2IRange() :
B2IRange(fround(rRange.getMinimum()),
fround(rRange.getMaximum()));
}
} // end of namespace basegfx
// eof
<commit_msg>INTEGRATION: CWS changefileheader (1.9.48); FILE MERGED 2008/04/01 10:48:15 thb 1.9.48.2: #i85898# Stripping all external header guards 2008/03/28 16:05:55 rt 1.9.48.1: #i87441# Change license header to LPGL v3.<commit_after>/*************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright 2008 by Sun Microsystems, Inc.
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: b2drange.cxx,v $
* $Revision: 1.10 $
*
* This file is part of OpenOffice.org.
*
* OpenOffice.org is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* only, as published by the Free Software Foundation.
*
* OpenOffice.org is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License version 3 for more details
* (a copy is included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with OpenOffice.org. If not, see
* <http://www.openoffice.org/license.html>
* for a copy of the LGPLv3 License.
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_basegfx.hxx"
#include <basegfx/range/b2drange.hxx>
#include <basegfx/range/b2irange.hxx>
#include <basegfx/numeric/ftools.hxx>
#include <basegfx/matrix/b2dhommatrix.hxx>
namespace basegfx
{
B2DRange::B2DRange( const B2IRange& rRange ) :
maRangeX(),
maRangeY()
{
if( !rRange.isEmpty() )
{
maRangeX = rRange.getMinX();
maRangeY = rRange.getMinY();
maRangeX.expand(rRange.getMaxX());
maRangeY.expand(rRange.getMaxY());
}
}
void B2DRange::transform(const B2DHomMatrix& rMatrix)
{
if(!isEmpty() && !rMatrix.isIdentity())
{
const B2DRange aSource(*this);
reset();
expand(rMatrix * B2DPoint(aSource.getMinX(), aSource.getMinY()));
expand(rMatrix * B2DPoint(aSource.getMaxX(), aSource.getMinY()));
expand(rMatrix * B2DPoint(aSource.getMinX(), aSource.getMaxY()));
expand(rMatrix * B2DPoint(aSource.getMaxX(), aSource.getMaxY()));
}
}
B2IRange fround(const B2DRange& rRange)
{
return rRange.isEmpty() ?
B2IRange() :
B2IRange(fround(rRange.getMinimum()),
fround(rRange.getMaximum()));
}
} // end of namespace basegfx
// eof
<|endoftext|> |
<commit_before>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/media/media_internals.h"
#include "base/memory/scoped_ptr.h"
#include "base/string16.h"
#include "base/stringprintf.h"
#include "chrome/browser/media/media_internals_observer.h"
#include "content/browser/browser_thread.h"
#include "content/browser/webui/web_ui.h"
#include "media/base/media_log_event.h"
// The names of the javascript functions to call with updates.
static const char kDeleteItemFunction[] = "media.onItemDeleted";
static const char kAudioUpdateFunction[] = "media.addAudioStream";
static const char kSendEverythingFunction[] = "media.onReceiveEverything";
MediaInternals::~MediaInternals() {}
void MediaInternals::OnDeleteAudioStream(void* host, int stream_id) {
DCHECK(CalledOnValidThread());
std::string stream = base::StringPrintf("audio_streams.%p:%d",
host, stream_id);
DeleteItem(stream);
}
void MediaInternals::OnSetAudioStreamPlaying(
void* host, int stream_id, bool playing) {
DCHECK(CalledOnValidThread());
UpdateAudioStream(host, stream_id,
"playing", Value::CreateBooleanValue(playing));
}
void MediaInternals::OnSetAudioStreamStatus(
void* host, int stream_id, const std::string& status) {
DCHECK(CalledOnValidThread());
UpdateAudioStream(host, stream_id,
"status", Value::CreateStringValue(status));
}
void MediaInternals::OnSetAudioStreamVolume(
void* host, int stream_id, double volume) {
DCHECK(CalledOnValidThread());
UpdateAudioStream(host, stream_id,
"volume", Value::CreateDoubleValue(volume));
}
void MediaInternals::OnMediaEvent(
int render_process_id, const media::MediaLogEvent& event) {
DCHECK(CalledOnValidThread());
// TODO(scottfr): Handle |event|. Record status information in data_ and pass
// |event| along to observers.
}
void MediaInternals::AddObserver(MediaInternalsObserver* observer) {
DCHECK(CalledOnValidThread());
observers_.AddObserver(observer);
}
void MediaInternals::RemoveObserver(MediaInternalsObserver* observer) {
DCHECK(CalledOnValidThread());
observers_.RemoveObserver(observer);
}
void MediaInternals::SendEverything() {
DCHECK(CalledOnValidThread());
SendUpdate(kSendEverythingFunction, &data_);
}
MediaInternals::MediaInternals() {}
void MediaInternals::UpdateAudioStream(
void* host, int stream_id, const std::string& property, Value* value) {
std::string stream = base::StringPrintf("audio_streams.%p:%d",
host, stream_id);
UpdateItem(kAudioUpdateFunction, stream, property, value);
}
void MediaInternals::DeleteItem(const std::string& item) {
data_.Remove(item, NULL);
scoped_ptr<Value> value(Value::CreateStringValue(item));
SendUpdate(kDeleteItemFunction, value.get());
}
void MediaInternals::UpdateItem(
const std::string& update_fn, const std::string& id,
const std::string& property, Value* value) {
DictionaryValue* item_properties;
if (!data_.GetDictionary(id, &item_properties)) {
item_properties = new DictionaryValue();
data_.Set(id, item_properties);
item_properties->SetString("id", id);
}
item_properties->Set(property, value);
SendUpdate(update_fn, item_properties);
}
void MediaInternals::SendUpdate(const std::string& function, Value* value) {
// Only bother serializing the update to JSON if someone is watching.
if (observers_.size()) {
std::vector<const Value*> args;
args.push_back(value);
string16 update = WebUI::GetJavascriptCall(function, args);
FOR_EACH_OBSERVER(MediaInternalsObserver, observers_, OnUpdate(update));
}
}
<commit_msg>Make MediaInternals handle MediaLogEvents.<commit_after>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/media/media_internals.h"
#include "base/memory/scoped_ptr.h"
#include "base/string16.h"
#include "base/stringprintf.h"
#include "chrome/browser/media/media_internals_observer.h"
#include "content/browser/browser_thread.h"
#include "content/browser/webui/web_ui.h"
#include "media/base/media_log.h"
#include "media/base/media_log_event.h"
// The names of the javascript functions to call with updates.
static const char kAudioUpdateFunction[] = "media.addAudioStream";
static const char kDeleteItemFunction[] = "media.onItemDeleted";
static const char kMediaEventFunction[] = "media.onMediaEvent";
static const char kSendEverythingFunction[] = "media.onReceiveEverything";
MediaInternals::~MediaInternals() {}
void MediaInternals::OnDeleteAudioStream(void* host, int stream_id) {
DCHECK(CalledOnValidThread());
std::string stream = base::StringPrintf("audio_streams.%p:%d",
host, stream_id);
DeleteItem(stream);
}
void MediaInternals::OnSetAudioStreamPlaying(
void* host, int stream_id, bool playing) {
DCHECK(CalledOnValidThread());
UpdateAudioStream(host, stream_id,
"playing", Value::CreateBooleanValue(playing));
}
void MediaInternals::OnSetAudioStreamStatus(
void* host, int stream_id, const std::string& status) {
DCHECK(CalledOnValidThread());
UpdateAudioStream(host, stream_id,
"status", Value::CreateStringValue(status));
}
void MediaInternals::OnSetAudioStreamVolume(
void* host, int stream_id, double volume) {
DCHECK(CalledOnValidThread());
UpdateAudioStream(host, stream_id,
"volume", Value::CreateDoubleValue(volume));
}
void MediaInternals::OnMediaEvent(
int render_process_id, const media::MediaLogEvent& event) {
DCHECK(CalledOnValidThread());
// Notify observers that |event| has occured.
DictionaryValue dict;
dict.SetInteger("renderer", render_process_id);
dict.SetInteger("player", event.id);
dict.SetString("type", media::MediaLog::EventTypeToString(event.type));
dict.SetDouble("time", event.time.ToDoubleT());
dict.Set("params", event.params.DeepCopy());
SendUpdate(kMediaEventFunction, &dict);
}
void MediaInternals::AddObserver(MediaInternalsObserver* observer) {
DCHECK(CalledOnValidThread());
observers_.AddObserver(observer);
}
void MediaInternals::RemoveObserver(MediaInternalsObserver* observer) {
DCHECK(CalledOnValidThread());
observers_.RemoveObserver(observer);
}
void MediaInternals::SendEverything() {
DCHECK(CalledOnValidThread());
SendUpdate(kSendEverythingFunction, &data_);
}
MediaInternals::MediaInternals() {}
void MediaInternals::UpdateAudioStream(
void* host, int stream_id, const std::string& property, Value* value) {
std::string stream = base::StringPrintf("audio_streams.%p:%d",
host, stream_id);
UpdateItem(kAudioUpdateFunction, stream, property, value);
}
void MediaInternals::DeleteItem(const std::string& item) {
data_.Remove(item, NULL);
scoped_ptr<Value> value(Value::CreateStringValue(item));
SendUpdate(kDeleteItemFunction, value.get());
}
void MediaInternals::UpdateItem(
const std::string& update_fn, const std::string& id,
const std::string& property, Value* value) {
DictionaryValue* item_properties;
if (!data_.GetDictionary(id, &item_properties)) {
item_properties = new DictionaryValue();
data_.Set(id, item_properties);
item_properties->SetString("id", id);
}
item_properties->Set(property, value);
SendUpdate(update_fn, item_properties);
}
void MediaInternals::SendUpdate(const std::string& function, Value* value) {
// Only bother serializing the update to JSON if someone is watching.
if (observers_.size()) {
std::vector<const Value*> args;
args.push_back(value);
string16 update = WebUI::GetJavascriptCall(function, args);
FOR_EACH_OBSERVER(MediaInternalsObserver, observers_, OnUpdate(update));
}
}
<|endoftext|> |
<commit_before>/******************************************************************************
* Copyright 2017 The Apollo Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*****************************************************************************/
/**
* @file
**/
#include "modules/planning/common/change_lane_decider.h"
#include "modules/common/time/time.h"
#include "modules/planning/common/planning_gflags.h"
namespace apollo {
namespace planning {
using common::util::Dropbox;
using planning_internal::ChangeLaneState;
using common::time::Clock;
ChangeLaneDecider::ChangeLaneDecider() : state_key_("kChangeLaneStatus") {
dropbox_ = Dropbox<ChangeLaneState>::Open();
}
void ChangeLaneDecider::UpdateState(ChangeLaneState::State state_code,
const std::string& path_id) {
UpdateState(Clock::NowInSeconds(), state_code, path_id);
}
void ChangeLaneDecider::UpdateState(double timestamp,
ChangeLaneState::State state_code,
const std::string& path_id) {
ChangeLaneState state;
state.set_timestamp(timestamp);
state.set_path_id(path_id);
state.set_state(state_code);
dropbox_->Set(state_key_, state);
}
void ChangeLaneDecider::PrioritizeChangeLane(
std::list<ReferenceLineInfo>* reference_line_info) const {
if (reference_line_info->empty()) {
AERROR << "Reference line info empty";
return;
}
auto iter = reference_line_info->begin();
while (iter != reference_line_info->end()) {
if (!iter->IsChangeLanePath()) {
reference_line_info->splice(reference_line_info->begin(),
*reference_line_info, iter);
break;
}
++iter;
}
}
void ChangeLaneDecider::RemoveChangeLane(
std::list<ReferenceLineInfo>* reference_line_info) const {
auto iter = reference_line_info->begin();
while (iter != reference_line_info->end()) {
if (iter->IsChangeLanePath()) {
iter = reference_line_info->erase(iter);
} else {
++iter;
}
}
}
std::string GetCurrentPathId(
const std::list<ReferenceLineInfo>& reference_line_info) {
for (const auto& info : reference_line_info) {
if (!info.IsChangeLanePath()) {
return info.Lanes().Id();
}
}
return "";
}
bool ChangeLaneDecider::Apply(
std::list<ReferenceLineInfo>* reference_line_info) {
if (reference_line_info->empty()) {
AERROR << "Reference lines empty";
return false;
}
if (FLAGS_reckless_change_lane) {
PrioritizeChangeLane(reference_line_info);
return true;
}
auto* prev_state = dropbox_->Get(state_key_);
double now = Clock::NowInSeconds();
if (!prev_state) {
UpdateState(now, ChangeLaneState::CHANGE_LANE_SUCCESS,
GetCurrentPathId(*reference_line_info));
return true;
}
bool has_change_lane = reference_line_info->size() > 1;
if (!has_change_lane) {
const auto& path_id = reference_line_info->front().Lanes().Id();
if (prev_state->state() == ChangeLaneState::CHANGE_LANE_SUCCESS) {
} else if (prev_state->state() == ChangeLaneState::IN_CHANGE_LANE) {
UpdateState(now, ChangeLaneState::CHANGE_LANE_SUCCESS, path_id);
} else if (prev_state->state() == ChangeLaneState::CHANGE_LANE_FAILED) {
} else {
AERROR << "Unknown state: " << prev_state->ShortDebugString();
return false;
}
return true;
} else { // has change lane in reference lines.
auto current_path_id = GetCurrentPathId(*reference_line_info);
if (current_path_id.empty()) {
AERROR << "The vehicle is not on any reference line";
return false;
}
if (prev_state->state() == ChangeLaneState::IN_CHANGE_LANE) {
if (prev_state->path_id() == current_path_id) {
PrioritizeChangeLane(reference_line_info);
} else {
RemoveChangeLane(reference_line_info);
UpdateState(now, ChangeLaneState::CHANGE_LANE_SUCCESS, current_path_id);
}
return true;
} else if (prev_state->state() == ChangeLaneState::CHANGE_LANE_FAILED) {
if (now - prev_state->timestamp() < FLAGS_change_lane_fail_freeze_time) {
RemoveChangeLane(reference_line_info);
} else {
UpdateState(now, ChangeLaneState::IN_CHANGE_LANE, current_path_id);
}
return true;
} else if (prev_state->state() == ChangeLaneState::CHANGE_LANE_SUCCESS) {
if (now - prev_state->timestamp() <
FLAGS_change_lane_success_freeze_time) {
RemoveChangeLane(reference_line_info);
} else {
PrioritizeChangeLane(reference_line_info);
UpdateState(now, ChangeLaneState::IN_CHANGE_LANE, current_path_id);
}
} else {
AERROR << "Unknown state: " << prev_state->ShortDebugString();
return false;
}
}
return true;
}
} // namespace planning
} // namespace apollo
<commit_msg>planning: bug fix for PrioritizeChangeLane() for wrong condition.<commit_after>/******************************************************************************
* Copyright 2017 The Apollo Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*****************************************************************************/
/**
* @file
**/
#include "modules/planning/common/change_lane_decider.h"
#include "modules/common/time/time.h"
#include "modules/planning/common/planning_gflags.h"
namespace apollo {
namespace planning {
using common::util::Dropbox;
using planning_internal::ChangeLaneState;
using common::time::Clock;
ChangeLaneDecider::ChangeLaneDecider() : state_key_("kChangeLaneStatus") {
dropbox_ = Dropbox<ChangeLaneState>::Open();
}
void ChangeLaneDecider::UpdateState(ChangeLaneState::State state_code,
const std::string& path_id) {
UpdateState(Clock::NowInSeconds(), state_code, path_id);
}
void ChangeLaneDecider::UpdateState(double timestamp,
ChangeLaneState::State state_code,
const std::string& path_id) {
ChangeLaneState state;
state.set_timestamp(timestamp);
state.set_path_id(path_id);
state.set_state(state_code);
dropbox_->Set(state_key_, state);
}
void ChangeLaneDecider::PrioritizeChangeLane(
std::list<ReferenceLineInfo>* reference_line_info) const {
if (reference_line_info->empty()) {
AERROR << "Reference line info empty";
return;
}
auto iter = reference_line_info->begin();
while (iter != reference_line_info->end()) {
if (iter->IsChangeLanePath()) {
reference_line_info->splice(reference_line_info->begin(),
*reference_line_info, iter);
break;
}
++iter;
}
}
void ChangeLaneDecider::RemoveChangeLane(
std::list<ReferenceLineInfo>* reference_line_info) const {
auto iter = reference_line_info->begin();
while (iter != reference_line_info->end()) {
if (iter->IsChangeLanePath()) {
iter = reference_line_info->erase(iter);
} else {
++iter;
}
}
}
std::string GetCurrentPathId(
const std::list<ReferenceLineInfo>& reference_line_info) {
for (const auto& info : reference_line_info) {
if (!info.IsChangeLanePath()) {
return info.Lanes().Id();
}
}
return "";
}
bool ChangeLaneDecider::Apply(
std::list<ReferenceLineInfo>* reference_line_info) {
if (reference_line_info->empty()) {
AERROR << "Reference lines empty";
return false;
}
if (FLAGS_reckless_change_lane) {
PrioritizeChangeLane(reference_line_info);
return true;
}
auto* prev_state = dropbox_->Get(state_key_);
double now = Clock::NowInSeconds();
if (!prev_state) {
UpdateState(now, ChangeLaneState::CHANGE_LANE_SUCCESS,
GetCurrentPathId(*reference_line_info));
return true;
}
bool has_change_lane = reference_line_info->size() > 1;
if (!has_change_lane) {
const auto& path_id = reference_line_info->front().Lanes().Id();
if (prev_state->state() == ChangeLaneState::CHANGE_LANE_SUCCESS) {
} else if (prev_state->state() == ChangeLaneState::IN_CHANGE_LANE) {
UpdateState(now, ChangeLaneState::CHANGE_LANE_SUCCESS, path_id);
} else if (prev_state->state() == ChangeLaneState::CHANGE_LANE_FAILED) {
} else {
AERROR << "Unknown state: " << prev_state->ShortDebugString();
return false;
}
return true;
} else { // has change lane in reference lines.
auto current_path_id = GetCurrentPathId(*reference_line_info);
if (current_path_id.empty()) {
AERROR << "The vehicle is not on any reference line";
return false;
}
if (prev_state->state() == ChangeLaneState::IN_CHANGE_LANE) {
if (prev_state->path_id() == current_path_id) {
PrioritizeChangeLane(reference_line_info);
} else {
RemoveChangeLane(reference_line_info);
UpdateState(now, ChangeLaneState::CHANGE_LANE_SUCCESS, current_path_id);
}
return true;
} else if (prev_state->state() == ChangeLaneState::CHANGE_LANE_FAILED) {
if (now - prev_state->timestamp() < FLAGS_change_lane_fail_freeze_time) {
RemoveChangeLane(reference_line_info);
} else {
UpdateState(now, ChangeLaneState::IN_CHANGE_LANE, current_path_id);
}
return true;
} else if (prev_state->state() == ChangeLaneState::CHANGE_LANE_SUCCESS) {
if (now - prev_state->timestamp() <
FLAGS_change_lane_success_freeze_time) {
RemoveChangeLane(reference_line_info);
} else {
PrioritizeChangeLane(reference_line_info);
UpdateState(now, ChangeLaneState::IN_CHANGE_LANE, current_path_id);
}
} else {
AERROR << "Unknown state: " << prev_state->ShortDebugString();
return false;
}
}
return true;
}
} // namespace planning
} // namespace apollo
<|endoftext|> |
<commit_before><commit_msg>planning: add PARK_AND_GO to scenario matrix<commit_after><|endoftext|> |
<commit_before>//===-- AppleObjCRuntimeV2.cpp --------------------------------------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "AppleObjCRuntimeV2.h"
#include "AppleObjCTrampolineHandler.h"
#include "clang/AST/Type.h"
#include "lldb/Core/ConstString.h"
#include "lldb/Core/Error.h"
#include "lldb/Core/Log.h"
#include "lldb/Core/Module.h"
#include "lldb/Core/PluginManager.h"
#include "lldb/Core/Scalar.h"
#include "lldb/Core/StreamString.h"
#include "lldb/Expression/ClangFunction.h"
#include "lldb/Symbol/ClangASTContext.h"
#include "lldb/Target/ExecutionContext.h"
#include "lldb/Target/Process.h"
#include "lldb/Target/RegisterContext.h"
#include "lldb/Target/Target.h"
#include "lldb/Target/Thread.h"
#include <vector>
using namespace lldb;
using namespace lldb_private;
static const char *pluginName = "AppleObjCRuntimeV2";
static const char *pluginDesc = "Apple Objective C Language Runtime - Version 2";
static const char *pluginShort = "language.apple.objc.v2";
bool
AppleObjCRuntimeV2::GetObjectDescription (Stream &str, ValueObject &object, ExecutionContextScope *exe_scope)
{
// ObjC objects can only be pointers:
if (!ClangASTContext::IsPointerType (object.GetClangType()))
return NULL;
// Make the argument list: we pass one arg, the address of our pointer, to the print function.
Scalar scalar;
if (!ClangASTType::GetValueAsScalar (object.GetClangAST(),
object.GetClangType(),
object.GetDataExtractor(),
0,
object.GetByteSize(),
scalar))
return NULL;
Value val(scalar);
return GetObjectDescription(str, val, exe_scope);
}
bool
AppleObjCRuntimeV2::GetObjectDescription (Stream &str, Value &value, ExecutionContextScope *exe_scope)
{
if (!m_read_objc_library)
return false;
ExecutionContext exe_ctx;
exe_scope->CalculateExecutionContext(exe_ctx);
if (!exe_ctx.process)
return false;
// We need other parts of the exe_ctx, but the processes have to match.
assert (m_process == exe_ctx.process);
// Get the function address for the print function.
const Address *function_address = GetPrintForDebuggerAddr();
if (!function_address)
return false;
if (value.GetClangType())
{
clang::QualType value_type = clang::QualType::getFromOpaquePtr (value.GetClangType());
if (!value_type->isObjCObjectPointerType())
{
str.Printf ("Value doesn't point to an ObjC object.\n");
return false;
}
// FIXME: If we use the real types here then we end up crashing in the expression parser.
// For now, forcing this to be a generic pointer makes it work...
#if 1
ClangASTContext *ast_context = exe_ctx.target->GetScratchClangASTContext();
if (value.GetContextType() == Value::eContextTypeOpaqueClangQualType)
{
value.SetContext(Value::eContextTypeOpaqueClangQualType, ast_context->GetVoidPtrType(false));
}
#endif
}
else
{
// If it is not a pointer, see if we can make it into a pointer.
ClangASTContext *ast_context = exe_ctx.target->GetScratchClangASTContext();
void *opaque_type_ptr = ast_context->GetBuiltInType_objc_id();
if (opaque_type_ptr == NULL)
opaque_type_ptr = ast_context->GetVoidPtrType(false);
value.SetContext(Value::eContextTypeOpaqueClangQualType, opaque_type_ptr);
}
ValueList arg_value_list;
arg_value_list.PushValue(value);
// This is the return value:
const char *target_triple = exe_ctx.process->GetTargetTriple().GetCString();
ClangASTContext *ast_context = exe_ctx.target->GetScratchClangASTContext();
void *return_qualtype = ast_context->GetCStringType(true);
Value ret;
ret.SetContext(Value::eContextTypeOpaqueClangQualType, return_qualtype);
// Now we're ready to call the function:
ClangFunction func(target_triple, ast_context, return_qualtype, *function_address, arg_value_list);
StreamString error_stream;
lldb::addr_t wrapper_struct_addr = LLDB_INVALID_ADDRESS;
func.InsertFunction(exe_ctx, wrapper_struct_addr, error_stream);
ClangFunction::ExecutionResults results
= func.ExecuteFunction(exe_ctx, &wrapper_struct_addr, error_stream, true, 1000, true, ret);
if (results != ClangFunction::eExecutionCompleted)
{
str.Printf("Error evaluating Print Object function: %d.\n", results);
return false;
}
addr_t result_ptr = ret.GetScalar().ULongLong(LLDB_INVALID_ADDRESS);
// FIXME: poor man's strcpy - we should have a "read memory as string interface...
Error error;
std::vector<char> desc;
while (1)
{
char byte = '\0';
if (exe_ctx.process->ReadMemory(result_ptr + desc.size(), &byte, 1, error) != 1)
break;
desc.push_back(byte);
if (byte == '\0')
break;
}
if (!desc.empty())
{
str.PutCString(&desc.front());
return true;
}
return false;
}
Address *
AppleObjCRuntimeV2::GetPrintForDebuggerAddr()
{
if (!m_PrintForDebugger_addr.get())
{
ModuleList &modules = m_process->GetTarget().GetImages();
SymbolContextList contexts;
SymbolContext context;
if((!modules.FindSymbolsWithNameAndType(ConstString ("_NSPrintForDebugger"), eSymbolTypeCode, contexts)) &&
(!modules.FindSymbolsWithNameAndType(ConstString ("_CFPrintForDebugger"), eSymbolTypeCode, contexts)))
return NULL;
contexts.GetContextAtIndex(0, context);
m_PrintForDebugger_addr.reset(new Address(context.symbol->GetValue()));
}
return m_PrintForDebugger_addr.get();
}
lldb::ValueObjectSP
AppleObjCRuntimeV2::GetDynamicValue (lldb::ValueObjectSP in_value, ExecutionContextScope *exe_scope)
{
lldb::ValueObjectSP ret_sp;
return ret_sp;
}
bool
AppleObjCRuntimeV2::IsModuleObjCLibrary (const ModuleSP &module_sp)
{
const FileSpec &module_file_spec = module_sp->GetFileSpec();
static ConstString ObjCName ("libobjc.A.dylib");
if (module_file_spec)
{
if (module_file_spec.GetFilename() == ObjCName)
return true;
}
return false;
}
bool
AppleObjCRuntimeV2::ReadObjCLibrary (const ModuleSP &module_sp)
{
// Maybe check here and if we have a handler already, and the UUID of this module is the same as the one in the
// current module, then we don't have to reread it?
m_objc_trampoline_handler_ap.reset(new AppleObjCTrampolineHandler (m_process->GetSP(), module_sp));
if (m_objc_trampoline_handler_ap.get() != NULL)
{
m_read_objc_library = true;
return true;
}
else
return false;
}
ThreadPlanSP
AppleObjCRuntimeV2::GetStepThroughTrampolinePlan (Thread &thread, bool stop_others)
{
ThreadPlanSP thread_plan_sp;
if (m_objc_trampoline_handler_ap.get())
thread_plan_sp = m_objc_trampoline_handler_ap->GetStepThroughDispatchPlan (thread, stop_others);
return thread_plan_sp;
}
//------------------------------------------------------------------
// Static Functions
//------------------------------------------------------------------
lldb_private::LanguageRuntime *
AppleObjCRuntimeV2::CreateInstance (Process *process, lldb::LanguageType language)
{
// FIXME: This should be a MacOS or iOS process, and we need to look for the OBJC section to make
// sure we aren't using the V1 runtime.
if (language == eLanguageTypeObjC)
return new AppleObjCRuntimeV2 (process);
else
return NULL;
}
void
AppleObjCRuntimeV2::Initialize()
{
PluginManager::RegisterPlugin (pluginName,
pluginDesc,
CreateInstance);
}
void
AppleObjCRuntimeV2::Terminate()
{
PluginManager::UnregisterPlugin (CreateInstance);
}
//------------------------------------------------------------------
// PluginInterface protocol
//------------------------------------------------------------------
const char *
AppleObjCRuntimeV2::GetPluginName()
{
return pluginName;
}
const char *
AppleObjCRuntimeV2::GetShortPluginName()
{
return pluginShort;
}
uint32_t
AppleObjCRuntimeV2::GetPluginVersion()
{
return 1;
}
void
AppleObjCRuntimeV2::GetPluginCommandHelp (const char *command, Stream *strm)
{
}
Error
AppleObjCRuntimeV2::ExecutePluginCommand (Args &command, Stream *strm)
{
Error error;
error.SetErrorString("No plug-in command are currently supported.");
return error;
}
Log *
AppleObjCRuntimeV2::EnablePluginLogging (Stream *strm, Args &command)
{
return NULL;
}
<commit_msg>Use the ValueObject directly where possible.<commit_after>//===-- AppleObjCRuntimeV2.cpp --------------------------------------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "AppleObjCRuntimeV2.h"
#include "AppleObjCTrampolineHandler.h"
#include "clang/AST/Type.h"
#include "lldb/Core/ConstString.h"
#include "lldb/Core/Error.h"
#include "lldb/Core/Log.h"
#include "lldb/Core/Module.h"
#include "lldb/Core/PluginManager.h"
#include "lldb/Core/Scalar.h"
#include "lldb/Core/StreamString.h"
#include "lldb/Expression/ClangFunction.h"
#include "lldb/Symbol/ClangASTContext.h"
#include "lldb/Target/ExecutionContext.h"
#include "lldb/Target/Process.h"
#include "lldb/Target/RegisterContext.h"
#include "lldb/Target/Target.h"
#include "lldb/Target/Thread.h"
#include <vector>
using namespace lldb;
using namespace lldb_private;
static const char *pluginName = "AppleObjCRuntimeV2";
static const char *pluginDesc = "Apple Objective C Language Runtime - Version 2";
static const char *pluginShort = "language.apple.objc.v2";
bool
AppleObjCRuntimeV2::GetObjectDescription (Stream &str, ValueObject &object, ExecutionContextScope *exe_scope)
{
// ObjC objects can only be pointers:
if (!object.IsPointerType())
return NULL;
// Make the argument list: we pass one arg, the address of our pointer, to the print function.
Scalar scalar;
if (!ClangASTType::GetValueAsScalar (object.GetClangAST(),
object.GetClangType(),
object.GetDataExtractor(),
0,
object.GetByteSize(),
scalar))
return NULL;
Value val(scalar);
return GetObjectDescription(str, val, exe_scope);
}
bool
AppleObjCRuntimeV2::GetObjectDescription (Stream &str, Value &value, ExecutionContextScope *exe_scope)
{
if (!m_read_objc_library)
return false;
ExecutionContext exe_ctx;
exe_scope->CalculateExecutionContext(exe_ctx);
if (!exe_ctx.process)
return false;
// We need other parts of the exe_ctx, but the processes have to match.
assert (m_process == exe_ctx.process);
// Get the function address for the print function.
const Address *function_address = GetPrintForDebuggerAddr();
if (!function_address)
return false;
if (value.GetClangType())
{
clang::QualType value_type = clang::QualType::getFromOpaquePtr (value.GetClangType());
if (!value_type->isObjCObjectPointerType())
{
str.Printf ("Value doesn't point to an ObjC object.\n");
return false;
}
// FIXME: If we use the real types here then we end up crashing in the expression parser.
// For now, forcing this to be a generic pointer makes it work...
#if 1
ClangASTContext *ast_context = exe_ctx.target->GetScratchClangASTContext();
if (value.GetContextType() == Value::eContextTypeOpaqueClangQualType)
{
value.SetContext(Value::eContextTypeOpaqueClangQualType, ast_context->GetVoidPtrType(false));
}
#endif
}
else
{
// If it is not a pointer, see if we can make it into a pointer.
ClangASTContext *ast_context = exe_ctx.target->GetScratchClangASTContext();
void *opaque_type_ptr = ast_context->GetBuiltInType_objc_id();
if (opaque_type_ptr == NULL)
opaque_type_ptr = ast_context->GetVoidPtrType(false);
value.SetContext(Value::eContextTypeOpaqueClangQualType, opaque_type_ptr);
}
ValueList arg_value_list;
arg_value_list.PushValue(value);
// This is the return value:
const char *target_triple = exe_ctx.process->GetTargetTriple().GetCString();
ClangASTContext *ast_context = exe_ctx.target->GetScratchClangASTContext();
void *return_qualtype = ast_context->GetCStringType(true);
Value ret;
ret.SetContext(Value::eContextTypeOpaqueClangQualType, return_qualtype);
// Now we're ready to call the function:
ClangFunction func(target_triple, ast_context, return_qualtype, *function_address, arg_value_list);
StreamString error_stream;
lldb::addr_t wrapper_struct_addr = LLDB_INVALID_ADDRESS;
func.InsertFunction(exe_ctx, wrapper_struct_addr, error_stream);
ClangFunction::ExecutionResults results
= func.ExecuteFunction(exe_ctx, &wrapper_struct_addr, error_stream, true, 1000, true, ret);
if (results != ClangFunction::eExecutionCompleted)
{
str.Printf("Error evaluating Print Object function: %d.\n", results);
return false;
}
addr_t result_ptr = ret.GetScalar().ULongLong(LLDB_INVALID_ADDRESS);
// FIXME: poor man's strcpy - we should have a "read memory as string interface...
Error error;
std::vector<char> desc;
while (1)
{
char byte = '\0';
if (exe_ctx.process->ReadMemory(result_ptr + desc.size(), &byte, 1, error) != 1)
break;
desc.push_back(byte);
if (byte == '\0')
break;
}
if (!desc.empty())
{
str.PutCString(&desc.front());
return true;
}
return false;
}
Address *
AppleObjCRuntimeV2::GetPrintForDebuggerAddr()
{
if (!m_PrintForDebugger_addr.get())
{
ModuleList &modules = m_process->GetTarget().GetImages();
SymbolContextList contexts;
SymbolContext context;
if((!modules.FindSymbolsWithNameAndType(ConstString ("_NSPrintForDebugger"), eSymbolTypeCode, contexts)) &&
(!modules.FindSymbolsWithNameAndType(ConstString ("_CFPrintForDebugger"), eSymbolTypeCode, contexts)))
return NULL;
contexts.GetContextAtIndex(0, context);
m_PrintForDebugger_addr.reset(new Address(context.symbol->GetValue()));
}
return m_PrintForDebugger_addr.get();
}
lldb::ValueObjectSP
AppleObjCRuntimeV2::GetDynamicValue (lldb::ValueObjectSP in_value, ExecutionContextScope *exe_scope)
{
lldb::ValueObjectSP ret_sp;
return ret_sp;
}
bool
AppleObjCRuntimeV2::IsModuleObjCLibrary (const ModuleSP &module_sp)
{
const FileSpec &module_file_spec = module_sp->GetFileSpec();
static ConstString ObjCName ("libobjc.A.dylib");
if (module_file_spec)
{
if (module_file_spec.GetFilename() == ObjCName)
return true;
}
return false;
}
bool
AppleObjCRuntimeV2::ReadObjCLibrary (const ModuleSP &module_sp)
{
// Maybe check here and if we have a handler already, and the UUID of this module is the same as the one in the
// current module, then we don't have to reread it?
m_objc_trampoline_handler_ap.reset(new AppleObjCTrampolineHandler (m_process->GetSP(), module_sp));
if (m_objc_trampoline_handler_ap.get() != NULL)
{
m_read_objc_library = true;
return true;
}
else
return false;
}
ThreadPlanSP
AppleObjCRuntimeV2::GetStepThroughTrampolinePlan (Thread &thread, bool stop_others)
{
ThreadPlanSP thread_plan_sp;
if (m_objc_trampoline_handler_ap.get())
thread_plan_sp = m_objc_trampoline_handler_ap->GetStepThroughDispatchPlan (thread, stop_others);
return thread_plan_sp;
}
//------------------------------------------------------------------
// Static Functions
//------------------------------------------------------------------
lldb_private::LanguageRuntime *
AppleObjCRuntimeV2::CreateInstance (Process *process, lldb::LanguageType language)
{
// FIXME: This should be a MacOS or iOS process, and we need to look for the OBJC section to make
// sure we aren't using the V1 runtime.
if (language == eLanguageTypeObjC)
return new AppleObjCRuntimeV2 (process);
else
return NULL;
}
void
AppleObjCRuntimeV2::Initialize()
{
PluginManager::RegisterPlugin (pluginName,
pluginDesc,
CreateInstance);
}
void
AppleObjCRuntimeV2::Terminate()
{
PluginManager::UnregisterPlugin (CreateInstance);
}
//------------------------------------------------------------------
// PluginInterface protocol
//------------------------------------------------------------------
const char *
AppleObjCRuntimeV2::GetPluginName()
{
return pluginName;
}
const char *
AppleObjCRuntimeV2::GetShortPluginName()
{
return pluginShort;
}
uint32_t
AppleObjCRuntimeV2::GetPluginVersion()
{
return 1;
}
void
AppleObjCRuntimeV2::GetPluginCommandHelp (const char *command, Stream *strm)
{
}
Error
AppleObjCRuntimeV2::ExecutePluginCommand (Args &command, Stream *strm)
{
Error error;
error.SetErrorString("No plug-in command are currently supported.");
return error;
}
Log *
AppleObjCRuntimeV2::EnablePluginLogging (Stream *strm, Args &command)
{
return NULL;
}
<|endoftext|> |
<commit_before>// Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "temp_scaffolding_stubs.h"
#include "base/file_util.h"
#include "base/thread.h"
#include "base/path_service.h"
#include "base/singleton.h"
#include "chrome/browser/browser.h"
#include "chrome/browser/browser_shutdown.h"
#include "chrome/browser/history/in_memory_history_backend.h"
#include "chrome/browser/plugin_service.h"
#include "chrome/browser/profile_manager.h"
#include "chrome/browser/rlz/rlz.h"
#include "chrome/browser/shell_integration.h"
#include "chrome/common/chrome_constants.h"
#include "chrome/common/chrome_paths.h"
#include "chrome/common/pref_service.h"
BrowserProcessImpl::BrowserProcessImpl(const CommandLine& command_line)
: main_notification_service_(new NotificationService),
memory_model_(HIGH_MEMORY_MODEL),
created_local_state_(), created_metrics_service_(),
created_profile_manager_() {
g_browser_process = this;
}
BrowserProcessImpl::~BrowserProcessImpl() {
g_browser_process = NULL;
}
void BrowserProcessImpl::CreateLocalState() {
DCHECK(!created_local_state_ && local_state_.get() == NULL);
created_local_state_ = true;
std::wstring local_state_path;
PathService::Get(chrome::FILE_LOCAL_STATE, &local_state_path);
local_state_.reset(new PrefService(local_state_path));
}
void BrowserProcessImpl::CreateMetricsService() {
DCHECK(!created_metrics_service_ && metrics_service_.get() == NULL);
created_metrics_service_ = true;
metrics_service_.reset(new MetricsService);
}
void BrowserProcessImpl::CreateProfileManager() {
DCHECK(!created_profile_manager_ && profile_manager_.get() == NULL);
created_profile_manager_ = true;
profile_manager_.reset(new ProfileManager());
}
MetricsService* BrowserProcessImpl::metrics_service() {
if (!created_metrics_service_)
CreateMetricsService();
return metrics_service_.get();
}
ProfileManager* BrowserProcessImpl::profile_manager() {
if (!created_profile_manager_)
CreateProfileManager();
return profile_manager_.get();
}
PrefService* BrowserProcessImpl::local_state() {
if (!created_local_state_)
CreateLocalState();
return local_state_.get();
}
//--------------------------------------------------------------------------
static bool s_in_startup = false;
bool BrowserInit::ProcessCommandLine(const CommandLine& parsed_command_line,
const std::wstring& cur_dir,
PrefService* prefs, bool process_startup,
Profile* profile, int* return_code) {
return LaunchBrowser(parsed_command_line, profile, cur_dir,
process_startup, return_code);
}
bool BrowserInit::LaunchBrowser(const CommandLine& parsed_command_line,
Profile* profile, const std::wstring& cur_dir,
bool process_startup, int* return_code) {
s_in_startup = process_startup;
bool result = LaunchBrowserImpl(parsed_command_line, profile, cur_dir,
process_startup, return_code);
s_in_startup = false;
return result;
}
bool BrowserInit::LaunchBrowserImpl(const CommandLine& parsed_command_line,
Profile* profile,
const std::wstring& cur_dir,
bool process_startup,
int* return_code) {
DCHECK(profile);
// this code is a simplification of BrowserInit::LaunchWithProfile::Launch()
std::vector<GURL> urls_to_open;
urls_to_open.push_back(GURL("http://dev.chromium.org"));
urls_to_open.push_back(GURL("http://crbug.com"));
urls_to_open.push_back(GURL("http://icanhavecheezeburger.com"));
Browser* browser = NULL;
browser = OpenURLsInBrowser(browser, profile, urls_to_open);
return true;
}
// a simplification of BrowserInit::LaunchWithProfile::OpenURLsInBrowser
Browser* BrowserInit::OpenURLsInBrowser(
Browser* browser,
Profile* profile,
const std::vector<GURL>& urls) {
DCHECK(!urls.empty());
if (!browser || browser->type() != Browser::TYPE_NORMAL)
browser = Browser::Create(profile);
for (size_t i = 0; i < urls.size(); ++i) {
browser->AddTabWithURL(
urls[i], GURL(), PageTransition::START_PAGE, (i == 0), NULL);
}
browser->window()->Show();
return browser;
}
//--------------------------------------------------------------------------
UserDataManager* UserDataManager::instance_ = NULL;
UserDataManager* UserDataManager::Create() {
DCHECK(!instance_);
std::wstring user_data;
PathService::Get(chrome::DIR_USER_DATA, &user_data);
instance_ = new UserDataManager(user_data);
return instance_;
}
UserDataManager* UserDataManager::Get() {
DCHECK(instance_);
return instance_;
}
bool ShellIntegration::SetAsDefaultBrowser() {
return true;
}
bool ShellIntegration::IsDefaultBrowser() {
return true;
}
//--------------------------------------------------------------------------
namespace browser {
void RegisterAllPrefs(PrefService*, PrefService*) { }
} // namespace browser
namespace browser_shutdown {
void ReadLastShutdownInfo() { }
void Shutdown() { }
void OnShutdownStarting(ShutdownType type) { }
}
void OpenFirstRunDialog(Profile* profile) { }
GURL NewTabUIURL() {
return GURL();
}
//--------------------------------------------------------------------------
PluginService* PluginService::GetInstance() {
return Singleton<PluginService>::get();
}
PluginService::PluginService()
: main_message_loop_(MessageLoop::current()),
resource_dispatcher_host_(NULL),
ui_locale_(g_browser_process->GetApplicationLocale()),
plugin_shutdown_handler_(NULL) {
}
PluginService::~PluginService() {
}
void PluginService::SetChromePluginDataDir(const FilePath& data_dir) {
AutoLock lock(lock_);
chrome_plugin_data_dir_ = data_dir;
}
//--------------------------------------------------------------------------
void InstallJankometer(const CommandLine&) {
}
//--------------------------------------------------------------------------
void Browser::Observe(NotificationType type,
const NotificationSource& source,
const NotificationDetails& details) {
}
GURL Browser::GetHomePage() {
return GURL("http://dev.chromium.org");
}
void Browser::LoadingStateChanged(TabContents* source) {
}
//--------------------------------------------------------------------------
TabContents* TabContents::CreateWithType(TabContentsType type,
Profile* profile,
SiteInstance* instance) {
return new TabContents;
}
//--------------------------------------------------------------------------
bool RLZTracker::GetAccessPointRlz(AccessPoint point, std::wstring* rlz) {
return false;
}
bool RLZTracker::RecordProductEvent(Product product, AccessPoint point,
Event event) {
return false;
}
// We link this in for now to avoid hauling in all of WebCore (which we will
// have to eventually do)
namespace webkit_glue {
std::string GetUserAgent(const GURL& url) {
return "";
}
}
<commit_msg>whut u meAn I sp3lld iT rong?<commit_after>// Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "temp_scaffolding_stubs.h"
#include "base/file_util.h"
#include "base/thread.h"
#include "base/path_service.h"
#include "base/singleton.h"
#include "chrome/browser/browser.h"
#include "chrome/browser/browser_shutdown.h"
#include "chrome/browser/history/in_memory_history_backend.h"
#include "chrome/browser/plugin_service.h"
#include "chrome/browser/profile_manager.h"
#include "chrome/browser/rlz/rlz.h"
#include "chrome/browser/shell_integration.h"
#include "chrome/common/chrome_constants.h"
#include "chrome/common/chrome_paths.h"
#include "chrome/common/pref_service.h"
BrowserProcessImpl::BrowserProcessImpl(const CommandLine& command_line)
: main_notification_service_(new NotificationService),
memory_model_(HIGH_MEMORY_MODEL),
created_local_state_(), created_metrics_service_(),
created_profile_manager_() {
g_browser_process = this;
}
BrowserProcessImpl::~BrowserProcessImpl() {
g_browser_process = NULL;
}
void BrowserProcessImpl::CreateLocalState() {
DCHECK(!created_local_state_ && local_state_.get() == NULL);
created_local_state_ = true;
std::wstring local_state_path;
PathService::Get(chrome::FILE_LOCAL_STATE, &local_state_path);
local_state_.reset(new PrefService(local_state_path));
}
void BrowserProcessImpl::CreateMetricsService() {
DCHECK(!created_metrics_service_ && metrics_service_.get() == NULL);
created_metrics_service_ = true;
metrics_service_.reset(new MetricsService);
}
void BrowserProcessImpl::CreateProfileManager() {
DCHECK(!created_profile_manager_ && profile_manager_.get() == NULL);
created_profile_manager_ = true;
profile_manager_.reset(new ProfileManager());
}
MetricsService* BrowserProcessImpl::metrics_service() {
if (!created_metrics_service_)
CreateMetricsService();
return metrics_service_.get();
}
ProfileManager* BrowserProcessImpl::profile_manager() {
if (!created_profile_manager_)
CreateProfileManager();
return profile_manager_.get();
}
PrefService* BrowserProcessImpl::local_state() {
if (!created_local_state_)
CreateLocalState();
return local_state_.get();
}
//--------------------------------------------------------------------------
static bool s_in_startup = false;
bool BrowserInit::ProcessCommandLine(const CommandLine& parsed_command_line,
const std::wstring& cur_dir,
PrefService* prefs, bool process_startup,
Profile* profile, int* return_code) {
return LaunchBrowser(parsed_command_line, profile, cur_dir,
process_startup, return_code);
}
bool BrowserInit::LaunchBrowser(const CommandLine& parsed_command_line,
Profile* profile, const std::wstring& cur_dir,
bool process_startup, int* return_code) {
s_in_startup = process_startup;
bool result = LaunchBrowserImpl(parsed_command_line, profile, cur_dir,
process_startup, return_code);
s_in_startup = false;
return result;
}
bool BrowserInit::LaunchBrowserImpl(const CommandLine& parsed_command_line,
Profile* profile,
const std::wstring& cur_dir,
bool process_startup,
int* return_code) {
DCHECK(profile);
// this code is a simplification of BrowserInit::LaunchWithProfile::Launch()
std::vector<GURL> urls_to_open;
urls_to_open.push_back(GURL("http://dev.chromium.org"));
urls_to_open.push_back(GURL("http://crbug.com"));
urls_to_open.push_back(GURL("http://icanhascheezeburger.com"));
Browser* browser = NULL;
browser = OpenURLsInBrowser(browser, profile, urls_to_open);
return true;
}
// a simplification of BrowserInit::LaunchWithProfile::OpenURLsInBrowser
Browser* BrowserInit::OpenURLsInBrowser(
Browser* browser,
Profile* profile,
const std::vector<GURL>& urls) {
DCHECK(!urls.empty());
if (!browser || browser->type() != Browser::TYPE_NORMAL)
browser = Browser::Create(profile);
for (size_t i = 0; i < urls.size(); ++i) {
browser->AddTabWithURL(
urls[i], GURL(), PageTransition::START_PAGE, (i == 0), NULL);
}
browser->window()->Show();
return browser;
}
//--------------------------------------------------------------------------
UserDataManager* UserDataManager::instance_ = NULL;
UserDataManager* UserDataManager::Create() {
DCHECK(!instance_);
std::wstring user_data;
PathService::Get(chrome::DIR_USER_DATA, &user_data);
instance_ = new UserDataManager(user_data);
return instance_;
}
UserDataManager* UserDataManager::Get() {
DCHECK(instance_);
return instance_;
}
bool ShellIntegration::SetAsDefaultBrowser() {
return true;
}
bool ShellIntegration::IsDefaultBrowser() {
return true;
}
//--------------------------------------------------------------------------
namespace browser {
void RegisterAllPrefs(PrefService*, PrefService*) { }
} // namespace browser
namespace browser_shutdown {
void ReadLastShutdownInfo() { }
void Shutdown() { }
void OnShutdownStarting(ShutdownType type) { }
}
void OpenFirstRunDialog(Profile* profile) { }
GURL NewTabUIURL() {
return GURL();
}
//--------------------------------------------------------------------------
PluginService* PluginService::GetInstance() {
return Singleton<PluginService>::get();
}
PluginService::PluginService()
: main_message_loop_(MessageLoop::current()),
resource_dispatcher_host_(NULL),
ui_locale_(g_browser_process->GetApplicationLocale()),
plugin_shutdown_handler_(NULL) {
}
PluginService::~PluginService() {
}
void PluginService::SetChromePluginDataDir(const FilePath& data_dir) {
AutoLock lock(lock_);
chrome_plugin_data_dir_ = data_dir;
}
//--------------------------------------------------------------------------
void InstallJankometer(const CommandLine&) {
}
//--------------------------------------------------------------------------
void Browser::Observe(NotificationType type,
const NotificationSource& source,
const NotificationDetails& details) {
}
GURL Browser::GetHomePage() {
return GURL("http://dev.chromium.org");
}
void Browser::LoadingStateChanged(TabContents* source) {
}
//--------------------------------------------------------------------------
TabContents* TabContents::CreateWithType(TabContentsType type,
Profile* profile,
SiteInstance* instance) {
return new TabContents;
}
//--------------------------------------------------------------------------
bool RLZTracker::GetAccessPointRlz(AccessPoint point, std::wstring* rlz) {
return false;
}
bool RLZTracker::RecordProductEvent(Product product, AccessPoint point,
Event event) {
return false;
}
// We link this in for now to avoid hauling in all of WebCore (which we will
// have to eventually do)
namespace webkit_glue {
std::string GetUserAgent(const GURL& url) {
return "";
}
}
<|endoftext|> |
<commit_before>/*
Copyright (c) 2006, Arvid Norberg & Daniel Wallin
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 "libtorrent/pch.hpp"
#include <libtorrent/kademlia/traversal_algorithm.hpp>
#include <libtorrent/kademlia/routing_table.hpp>
#include <libtorrent/kademlia/rpc_manager.hpp>
#include <boost/bind.hpp>
using boost::bind;
using asio::ip::udp;
namespace libtorrent { namespace dht
{
#ifdef TORRENT_DHT_VERBOSE_LOGGING
TORRENT_DEFINE_LOG(traversal)
#endif
void traversal_algorithm::add_entry(node_id const& id, udp::endpoint addr, unsigned char flags)
{
if (m_failed.find(addr) != m_failed.end()) return;
result entry(id, addr, flags);
if (entry.id.is_all_zeros())
{
entry.id = generate_id();
entry.flags |= result::no_id;
}
std::vector<result>::iterator i = std::lower_bound(
m_results.begin()
, m_results.end()
, entry
, bind(
compare_ref
, bind(&result::id, _1)
, bind(&result::id, _2)
, m_target
)
);
if (i == m_results.end() || i->id != id)
{
TORRENT_ASSERT(std::find_if(m_results.begin(), m_results.end()
, bind(&result::id, _1) == id) == m_results.end());
#ifdef TORRENT_DHT_VERBOSE_LOGGING
TORRENT_LOG(traversal) << "adding result: " << id << " " << addr;
#endif
m_results.insert(i, entry);
}
}
boost::pool<>& traversal_algorithm::allocator() const
{
return m_rpc.allocator();
}
void traversal_algorithm::traverse(node_id const& id, udp::endpoint addr)
{
TORRENT_ASSERT(!id.is_all_zeros());
add_entry(id, addr, 0);
}
void traversal_algorithm::finished(node_id const& id)
{
--m_invoke_count;
add_requests();
if (m_invoke_count == 0) done();
}
// prevent request means that the total number of requests has
// overflown. This query failed because it was the oldest one.
// So, if this is true, don't make another request
void traversal_algorithm::failed(node_id const& id, bool prevent_request)
{
m_invoke_count--;
TORRENT_ASSERT(!id.is_all_zeros());
std::vector<result>::iterator i = std::find_if(
m_results.begin()
, m_results.end()
, bind(
std::equal_to<node_id>()
, bind(&result::id, _1)
, id
)
);
TORRENT_ASSERT(i != m_results.end());
if (i != m_results.end())
{
TORRENT_ASSERT(i->flags & result::queried);
m_failed.insert(i->addr);
#ifdef TORRENT_DHT_VERBOSE_LOGGING
TORRENT_LOG(traversal) << "failed: " << i->id << " " << i->addr;
#endif
// don't tell the routing table about
// node ids that we just generated ourself
if ((i->flags & result::no_id) == 0)
m_table.node_failed(id);
m_results.erase(i);
}
if (prevent_request)
{
--m_branch_factor;
if (m_branch_factor <= 0) m_branch_factor = 1;
}
add_requests();
if (m_invoke_count == 0) done();
}
namespace
{
bool bitwise_nand(unsigned char lhs, unsigned char rhs)
{
return (lhs & rhs) == 0;
}
}
void traversal_algorithm::add_requests()
{
while (m_invoke_count < m_branch_factor)
{
// Find the first node that hasn't already been queried.
// TODO: Better heuristic
std::vector<result>::iterator i = std::find_if(
m_results.begin()
, last_iterator()
, bind(
&bitwise_nand
, bind(&result::flags, _1)
, (unsigned char)result::queried
)
);
#ifdef TORRENT_DHT_VERBOSE_LOGGING
TORRENT_LOG(traversal) << "nodes left (" << this << "): " << (last_iterator() - i);
#endif
if (i == last_iterator()) break;
try
{
invoke(i->id, i->addr);
++m_invoke_count;
i->flags |= result::queried;
}
catch (std::exception& e) {}
}
}
std::vector<traversal_algorithm::result>::iterator traversal_algorithm::last_iterator()
{
return (int)m_results.size() >= m_max_results ?
m_results.begin() + m_max_results
: m_results.end();
}
} } // namespace libtorrent::dht
<commit_msg>fixed DHT assert<commit_after>/*
Copyright (c) 2006, Arvid Norberg & Daniel Wallin
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 "libtorrent/pch.hpp"
#include <libtorrent/kademlia/traversal_algorithm.hpp>
#include <libtorrent/kademlia/routing_table.hpp>
#include <libtorrent/kademlia/rpc_manager.hpp>
#include <boost/bind.hpp>
using boost::bind;
using asio::ip::udp;
namespace libtorrent { namespace dht
{
#ifdef TORRENT_DHT_VERBOSE_LOGGING
TORRENT_DEFINE_LOG(traversal)
#endif
void traversal_algorithm::add_entry(node_id const& id, udp::endpoint addr, unsigned char flags)
{
if (m_failed.find(addr) != m_failed.end()) return;
result entry(id, addr, flags);
if (entry.id.is_all_zeros())
{
entry.id = generate_id();
entry.flags |= result::no_id;
}
std::vector<result>::iterator i = std::lower_bound(
m_results.begin()
, m_results.end()
, entry
, bind(
compare_ref
, bind(&result::id, _1)
, bind(&result::id, _2)
, m_target
)
);
if (i == m_results.end() || i->id != id)
{
TORRENT_ASSERT(std::find_if(m_results.begin(), m_results.end()
, bind(&result::id, _1) == id) == m_results.end());
#ifdef TORRENT_DHT_VERBOSE_LOGGING
TORRENT_LOG(traversal) << "adding result: " << id << " " << addr;
#endif
m_results.insert(i, entry);
}
}
boost::pool<>& traversal_algorithm::allocator() const
{
return m_rpc.allocator();
}
void traversal_algorithm::traverse(node_id const& id, udp::endpoint addr)
{
#ifdef TORRENT_DHT_VERBOSE_LOGGING
TORRENT_LOG(traversal) << "node returned a list which included a node with id 0";
#endif
add_entry(id, addr, 0);
}
void traversal_algorithm::finished(node_id const& id)
{
--m_invoke_count;
add_requests();
if (m_invoke_count == 0) done();
}
// prevent request means that the total number of requests has
// overflown. This query failed because it was the oldest one.
// So, if this is true, don't make another request
void traversal_algorithm::failed(node_id const& id, bool prevent_request)
{
m_invoke_count--;
TORRENT_ASSERT(!id.is_all_zeros());
std::vector<result>::iterator i = std::find_if(
m_results.begin()
, m_results.end()
, bind(
std::equal_to<node_id>()
, bind(&result::id, _1)
, id
)
);
TORRENT_ASSERT(i != m_results.end());
if (i != m_results.end())
{
TORRENT_ASSERT(i->flags & result::queried);
m_failed.insert(i->addr);
#ifdef TORRENT_DHT_VERBOSE_LOGGING
TORRENT_LOG(traversal) << "failed: " << i->id << " " << i->addr;
#endif
// don't tell the routing table about
// node ids that we just generated ourself
if ((i->flags & result::no_id) == 0)
m_table.node_failed(id);
m_results.erase(i);
}
if (prevent_request)
{
--m_branch_factor;
if (m_branch_factor <= 0) m_branch_factor = 1;
}
add_requests();
if (m_invoke_count == 0) done();
}
namespace
{
bool bitwise_nand(unsigned char lhs, unsigned char rhs)
{
return (lhs & rhs) == 0;
}
}
void traversal_algorithm::add_requests()
{
while (m_invoke_count < m_branch_factor)
{
// Find the first node that hasn't already been queried.
// TODO: Better heuristic
std::vector<result>::iterator i = std::find_if(
m_results.begin()
, last_iterator()
, bind(
&bitwise_nand
, bind(&result::flags, _1)
, (unsigned char)result::queried
)
);
#ifdef TORRENT_DHT_VERBOSE_LOGGING
TORRENT_LOG(traversal) << "nodes left (" << this << "): " << (last_iterator() - i);
#endif
if (i == last_iterator()) break;
try
{
invoke(i->id, i->addr);
++m_invoke_count;
i->flags |= result::queried;
}
catch (std::exception& e) {}
}
}
std::vector<traversal_algorithm::result>::iterator traversal_algorithm::last_iterator()
{
return (int)m_results.size() >= m_max_results ?
m_results.begin() + m_max_results
: m_results.end();
}
} } // namespace libtorrent::dht
<|endoftext|> |
<commit_before>/*****************************************************************************
*
* This file is part of Mapnik (c++ mapping toolkit)
*
* Copyright (C) 2011 Artem Pavlenko
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*
*****************************************************************************/
#ifndef MAPNIK_TIMER_HPP
#define MAPNIK_TIMER_HPP
// stl
#include <cstdlib>
#include <string>
#include <sstream>
#include <iomanip>
#include <ctime>
#ifndef WIN32
#include <sys/time.h> // for gettimeofday() on unix
#include <sys/resource.h>
#else
#include <windows.h>
#endif
namespace mapnik {
// Try to return the time now
inline double time_now()
{
#ifndef WIN32
struct timeval t;
struct timezone tzp;
gettimeofday(&t, &tzp);
return t.tv_sec + t.tv_usec * 1e-6;
#else
LARGE_INTEGER t, f;
QueryPerformanceCounter(&t);
QueryPerformanceFrequency(&f);
return double(t.QuadPart) / double(f.QuadPart);
#endif
}
// Measure times in both wall clock time and CPU times. Results are returned in milliseconds.
class timer
{
public:
timer()
{
restart();
}
virtual ~timer()
{
}
void restart()
{
stopped_ = false;
wall_clock_start_ = time_now();
cpu_start_ = clock();
}
virtual void stop() const
{
stopped_ = true;
cpu_end_ = clock();
wall_clock_end_ = time_now();
}
double cpu_elapsed() const
{
// return elapsed CPU time in ms
if (! stopped_)
{
stop();
}
return ((double) (cpu_end_ - cpu_start_)) / CLOCKS_PER_SEC * 1000.0;
}
double wall_clock_elapsed() const
{
// return elapsed wall clock time in ms
if (! stopped_)
{
stop();
}
return (wall_clock_end_ - wall_clock_start_) * 1000.0;
}
protected:
mutable double wall_clock_start_, wall_clock_end_;
mutable clock_t cpu_start_, cpu_end_;
mutable bool stopped_;
};
// A progress_timer behaves like a timer except that the destructor displays
// an elapsed time message at an appropriate place in an appropriate form.
class progress_timer : public timer
{
public:
progress_timer(std::ostream & os, std::string const& base_message)
: os_(os),
base_message_(base_message)
{}
~progress_timer()
{
if (! stopped_)
{
stop();
}
}
void stop() const
{
timer::stop();
try
{
std::ostringstream s;
s.precision(2);
s << std::fixed;
s << wall_clock_elapsed() << "ms (cpu " << cpu_elapsed() << "ms)";
s << std::setw(30 - (int)s.tellp()) << std::right << "| " << base_message_ << "\n";
os_ << s.str();
}
catch (...) {} // eat any exceptions
}
void discard()
{
stopped_ = true;
}
private:
std::ostream & os_;
std::string base_message_;
};
};
#endif // MAPNIK_TIMER_HPP
<commit_msg>get stats output working on windows<commit_after>/*****************************************************************************
*
* This file is part of Mapnik (c++ mapping toolkit)
*
* Copyright (C) 2011 Artem Pavlenko
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*
*****************************************************************************/
#ifndef MAPNIK_TIMER_HPP
#define MAPNIK_TIMER_HPP
// stl
#include <cstdlib>
#include <string>
#include <sstream>
#include <iomanip>
#include <ctime>
#ifdef _WINDOWS
#define NOMINMAX
#include <windows.h>
#else
#include <sys/time.h> // for gettimeofday() on unix
#include <sys/resource.h>
#endif
namespace mapnik {
// Try to return the time now
inline double time_now()
{
#ifdef _WINDOWS
LARGE_INTEGER t, f;
QueryPerformanceCounter(&t);
QueryPerformanceFrequency(&f);
return double(t.QuadPart) / double(f.QuadPart);
#else
struct timeval t;
struct timezone tzp;
gettimeofday(&t, &tzp);
return t.tv_sec + t.tv_usec * 1e-6;
#endif
}
// Measure times in both wall clock time and CPU times. Results are returned in milliseconds.
class timer
{
public:
timer()
{
restart();
}
virtual ~timer()
{
}
void restart()
{
stopped_ = false;
wall_clock_start_ = time_now();
cpu_start_ = clock();
}
virtual void stop() const
{
stopped_ = true;
cpu_end_ = clock();
wall_clock_end_ = time_now();
}
double cpu_elapsed() const
{
// return elapsed CPU time in ms
if (! stopped_)
{
stop();
}
return ((double) (cpu_end_ - cpu_start_)) / CLOCKS_PER_SEC * 1000.0;
}
double wall_clock_elapsed() const
{
// return elapsed wall clock time in ms
if (! stopped_)
{
stop();
}
return (wall_clock_end_ - wall_clock_start_) * 1000.0;
}
protected:
mutable double wall_clock_start_, wall_clock_end_;
mutable clock_t cpu_start_, cpu_end_;
mutable bool stopped_;
};
// A progress_timer behaves like a timer except that the destructor displays
// an elapsed time message at an appropriate place in an appropriate form.
class progress_timer : public timer
{
public:
progress_timer(std::ostream & os, std::string const& base_message)
: os_(os),
base_message_(base_message)
{}
~progress_timer()
{
if (! stopped_)
{
stop();
}
}
void stop() const
{
timer::stop();
try
{
std::ostringstream s;
s.precision(2);
s << std::fixed;
s << wall_clock_elapsed() << "ms (cpu " << cpu_elapsed() << "ms)";
s << std::setw(30 - (int)s.tellp()) << std::right << "| " << base_message_ << "\n";
os_ << s.str();
}
catch (...) {} // eat any exceptions
}
void discard()
{
stopped_ = true;
}
private:
std::ostream & os_;
std::string base_message_;
};
};
#endif // MAPNIK_TIMER_HPP
<|endoftext|> |
<commit_before>// Copyright (c) 2005-2012 Jay Berkenbilt
//
// This file is part of qpdf. This software may be distributed under
// the terms of version 2 of the Artistic License which may be found
// in the source distribution. It is provided "as is" without express
// or implied warranty.
// Generalized Pipeline interface. By convention, subclasses of
// Pipeline are called Pl_Something.
//
// When an instance of Pipeline is created with a pointer to a next
// pipeline, that pipeline writes its data to the next one when it
// finishes with it. In order to make possible a usage style in which
// a pipeline may be passed to a function which may stick other
// pipelines in front of it, the allocator of a pipeline is
// responsible for its destruction. In other words, one pipeline
// object does not attempt to manage the memory of its successor.
//
// The client is required to call finish() before destroying a
// Pipeline in order to avoid loss of data. A Pipeline class should
// not throw an exception in the destructor if this hasn't been done
// though since doing so causes too much trouble when deleting
// pipelines during error conditions.
//
// Some pipelines are reusable (i.e., you can call write() after
// calling finish() and can call finish() multiple times) while others
// are not. It is up to the caller to use a pipeline according to its
// own restrictions.
#ifndef __PIPELINE_HH__
#define __PIPELINE_HH__
#include <qpdf/DLL.h>
#include <string>
class Pipeline
{
public:
QPDF_DLL
Pipeline(char const* identifier, Pipeline* next);
QPDF_DLL
virtual ~Pipeline();
// Subclasses should implement write and finish to do their jobs
// and then, if they are not end-of-line pipelines, call
// getNext()->write or getNext()->finish.
QPDF_DLL
virtual void write(unsigned char* data, size_t len) = 0;
QPDF_DLL
virtual void finish() = 0;
protected:
Pipeline* getNext(bool allow_null = false);
std::string identifier;
private:
// Do not implement copy or assign
Pipeline(Pipeline const&);
Pipeline& operator=(Pipeline const&);
Pipeline* next;
};
#endif // __PIPELINE_HH__
<commit_msg>Comment about non-const Pipeline data<commit_after>// Copyright (c) 2005-2012 Jay Berkenbilt
//
// This file is part of qpdf. This software may be distributed under
// the terms of version 2 of the Artistic License which may be found
// in the source distribution. It is provided "as is" without express
// or implied warranty.
// Generalized Pipeline interface. By convention, subclasses of
// Pipeline are called Pl_Something.
//
// When an instance of Pipeline is created with a pointer to a next
// pipeline, that pipeline writes its data to the next one when it
// finishes with it. In order to make possible a usage style in which
// a pipeline may be passed to a function which may stick other
// pipelines in front of it, the allocator of a pipeline is
// responsible for its destruction. In other words, one pipeline
// object does not attempt to manage the memory of its successor.
//
// The client is required to call finish() before destroying a
// Pipeline in order to avoid loss of data. A Pipeline class should
// not throw an exception in the destructor if this hasn't been done
// though since doing so causes too much trouble when deleting
// pipelines during error conditions.
//
// Some pipelines are reusable (i.e., you can call write() after
// calling finish() and can call finish() multiple times) while others
// are not. It is up to the caller to use a pipeline according to its
// own restrictions.
#ifndef __PIPELINE_HH__
#define __PIPELINE_HH__
#include <qpdf/DLL.h>
#include <string>
class Pipeline
{
public:
QPDF_DLL
Pipeline(char const* identifier, Pipeline* next);
QPDF_DLL
virtual ~Pipeline();
// Subclasses should implement write and finish to do their jobs
// and then, if they are not end-of-line pipelines, call
// getNext()->write or getNext()->finish. It would be really nice
// if write could take unsigned char const*, but this would make
// it much more difficult to write pipelines around legacy
// interfaces whose calls don't want pointers to const data. As a
// rule, pipelines should generally not be modifying the data
// passed to them. They should, instead, create new data to pass
// downstream.
QPDF_DLL
virtual void write(unsigned char* data, size_t len) = 0;
QPDF_DLL
virtual void finish() = 0;
protected:
Pipeline* getNext(bool allow_null = false);
std::string identifier;
private:
// Do not implement copy or assign
Pipeline(Pipeline const&);
Pipeline& operator=(Pipeline const&);
Pipeline* next;
};
#endif // __PIPELINE_HH__
<|endoftext|> |
<commit_before>/* -*- Mode: C++; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- */
/*
* Copyright 2015 Couchbase, 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 <chrono>
#include <iomanip>
#include <iostream>
#include <sstream>
#include <stdlib.h>
#include <cassert>
#include "isotime.h"
int main(void)
{
time_t now = 1426239360;
std::string expected("2015-03-13T02:36:00.000-07:00");
std::string timezone("TZ=America/Los_Angeles");
#ifdef _MSC_VER
timezone.assign("TZ=PST8PDT");
#endif
putenv(strdup(timezone.c_str()));
tzset();
std::string timestamp = ISOTime::generatetimestamp(now, 0);
if (timestamp != expected) {
std::cerr << "Comparison failed" << std::endl
<< " Expected [" << expected << "]" << std::endl
<< " got [" << timestamp << "]" << std::endl;
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
<commit_msg>Remove unused file<commit_after><|endoftext|> |
<commit_before>//
// File: main.cpp
// Transformations.
// y.s.n@live.com, 2015-06-08
//
// Model transformation & view transformation
// glMatrixMode(GL_MODELVIEW)
// glTranslate*
// glRotate*
// glScale*
//
// Projection transformation
// glMatrixMode(GL_PROJECTION)
// glFrustum
// glPerspective
// glOthto
//
// Viewport transformation
// glViewport
//
#include "GL/glut.h"
static int day = 200;
// dayı仯0359
void display(void)
{
glEnable(GL_DEPTH_TEST);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluPerspective(75, 1, 1, 400000000);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
gluLookAt(0, -200000000, 200000000, 0, 0, 0, 0, 0, 1);
// ƺɫġ̫
glColor3f(1.0f, 0.0f, 0.0f);
glutSolidSphere(69600000, 20, 20);
// ɫġ
glColor3f(0.0f, 0.0f, 1.0f);
glRotatef(day/360.0*360.0, 0.0f, 0.0f, -1.0f);
glTranslatef(150000000, 0.0f, 0.0f);
glutSolidSphere(15945000, 20, 20);
// ƻɫġ
glColor3f(1.0f, 1.0f, 0.0f);
glRotatef(day/30.0*360.0 - day/360.0*360.0, 0.0f, 0.0f, -1.0f);
glTranslatef(38000000, 0.0f, 0.0f);
glutSolidSphere(4345000, 20, 20);
glFlush();
}
int main(int argc, char* argv[])
{
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_RGB | GLUT_SINGLE);
glutInitWindowPosition(100, 100);
glutInitWindowSize(600, 600);
glutCreateWindow("Point Line Polygon Circle");
glutDisplayFunc(display);
glutMainLoop();
return 0;
}
<commit_msg>Minor test<commit_after>//
// File: main.cpp
// Transformations.
// y.s.n@live.com, 2015-06-08
//
// Model transformation & view transformation
// glMatrixMode(GL_MODELVIEW)
// glTranslate*
// glRotate*
// glScale*
//
// Projection transformation
// glMatrixMode(GL_PROJECTION)
// glFrustum
// glPerspective
// glOthto
//
// Viewport transformation
// glViewport
//
#include "GL/glut.h"
static int day = 1;
// dayı仯0359
void display(void)
{
glEnable(GL_DEPTH_TEST);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluPerspective(75, 1, 1, 400000000);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
gluLookAt(0, -200000000, 200000000, 0, 0, 0, 0, 0, 1);
// ƺɫġ̫
glColor3f(1.0f, 0.0f, 0.0f);
glutSolidSphere(69600000, 20, 20);
// ɫġ
glColor3f(0.0f, 0.0f, 1.0f);
glRotatef(day/360.0*360.0, 0.0f, 0.0f, -1.0f);
glTranslatef(150000000, 0.0f, 0.0f);
glutSolidSphere(15945000, 20, 20);
// ƻɫġ
glColor3f(1.0f, 1.0f, 0.0f);
glRotatef(day/30.0*360.0 - day/360.0*360.0, 0.0f, 0.0f, -1.0f);
glTranslatef(38000000, 0.0f, 0.0f);
glutSolidSphere(4345000, 20, 20);
glFlush();
day = (day + 1) % 360 + 1;
}
int main(int argc, char* argv[])
{
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_RGB | GLUT_SINGLE);
glutInitWindowPosition(100, 100);
glutInitWindowSize(600, 600);
glutCreateWindow("Point Line Polygon Circle");
glutDisplayFunc(display);
glutMainLoop();
return 0;
}
<|endoftext|> |
<commit_before>/******************************************************************************
* Copyright (C) 2015 Sahil Kang <sahil.kang@asilaycomputing.com>
*
* This file is part of gur-guile.
*
* gur-guile is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* gur-guile is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with gur-guile. If not, see <http://www.gnu.org/licenses/>.
******************************************************************************/
#include <libguile.h>
#include <gur.hpp>
static SCM gg_letters(SCM args)
{
const char* const str = scm_to_utf8_stringn(args, NULL);
SCM g_str = scm_from_utf8_string(gur::letters(str));
free(const_cast<char*>(str));
return g_str;
}
static SCM gg_accents(SCM args)
{
const char* const str = scm_to_utf8_stringn(args, NULL);
SCM g_str = scm_from_utf8_string(gur::accents(str));
free(const_cast<char*>(str));
return g_str;
}
static SCM gg_puncs(SCM args)
{
const char* const str = scm_to_utf8_stringn(args, NULL);
SCM g_str = scm_from_utf8_string(gur::puncs(str));
free(const_cast<char*>(str));
return g_str;
}
static SCM gg_digits(SCM args)
{
const char* const str = scm_to_utf8_stringn(args, NULL);
SCM g_str = scm_from_utf8_string(gur::digits(str));
free(const_cast<char*>(str));
return g_str;
}
static SCM gg_symbols(SCM args)
{
const char* const str = scm_to_utf8_stringn(args, NULL);
SCM g_str = scm_from_utf8_string(gur::symbols(str));
free(const_cast<char*>(str));
return g_str;
}
static SCM gg_comp(SCM args)
{
const char* const str = scm_to_utf8_stringn(args, NULL);
SCM g_str = scm_from_utf8_string(gur::comp(str));
free(const_cast<char*>(str));
return g_str;
}
static SCM gg_clobber(SCM args)
{
const char* const str = scm_to_utf8_stringn(args, NULL);
SCM g_str = scm_from_utf8_string(gur::clobber(str));
free(const_cast<char*>(str));
return g_str;
}
static SCM gg_unclobber(SCM args)
{
const char* const str = scm_to_utf8_stringn(args, NULL);
SCM g_str = scm_from_utf8_string(gur::unclobber(str));
free(const_cast<char*>(str));
return g_str;
}
static void init_gur_guile(void *unused)
{
scm_c_define_gsubr("letters", 1, 0, 0, (scm_t_subr)&gg_letters);
scm_c_define_gsubr("accents", 1, 0, 0, (scm_t_subr)&gg_accents);
scm_c_define_gsubr("puncs", 1, 0, 0, (scm_t_subr)&gg_puncs);
scm_c_define_gsubr("digits", 1, 0, 0, (scm_t_subr)&gg_digits);
scm_c_define_gsubr("symbols", 1, 0, 0, (scm_t_subr)&gg_symbols);
scm_c_define_gsubr("comp", 1, 0, 0, (scm_t_subr)&gg_comp);
scm_c_define_gsubr("clobber", 1, 0, 0, (scm_t_subr)&gg_clobber);
scm_c_define_gsubr("unclobber", 1, 0, 0, (scm_t_subr)&gg_unclobber);
scm_c_export("letters", NULL);
scm_c_export("accents", NULL);
scm_c_export("puncs", NULL);
scm_c_export("digits", NULL);
scm_c_export("symbols", NULL);
scm_c_export("comp", NULL);
scm_c_export("clobber", NULL);
scm_c_export("unclobber", NULL);
}
extern "C"
{
void scm_init_gur_guile_module()
{
scm_c_define_module("gur-guile", init_gur_guile, NULL);
}
}
<commit_msg>Add bool functions to determine char type<commit_after>/******************************************************************************
* Copyright (C) 2015 Sahil Kang <sahil.kang@asilaycomputing.com>
*
* This file is part of gur-guile.
*
* gur-guile is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* gur-guile is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with gur-guile. If not, see <http://www.gnu.org/licenses/>.
******************************************************************************/
#include <libguile.h>
#include <gur.hpp>
template<typename T>
static SCM is_type(const SCM &args, const T &func)
{
const char* const str = scm_to_utf8_stringn(args, NULL);
bool is_type = func(str);
free(const_cast<char*>(str));
if (is_type)
{
return SCM_BOOL_T;
}
else
{
return SCM_BOOL_F;
}
}
static SCM gg_letters(SCM args)
{
const char* const str = scm_to_utf8_stringn(args, NULL);
SCM g_str = scm_from_utf8_string(gur::letters(str));
free(const_cast<char*>(str));
return g_str;
}
static SCM gg_accents(SCM args)
{
const char* const str = scm_to_utf8_stringn(args, NULL);
SCM g_str = scm_from_utf8_string(gur::accents(str));
free(const_cast<char*>(str));
return g_str;
}
static SCM gg_puncs(SCM args)
{
const char* const str = scm_to_utf8_stringn(args, NULL);
SCM g_str = scm_from_utf8_string(gur::puncs(str));
free(const_cast<char*>(str));
return g_str;
}
static SCM gg_digits(SCM args)
{
const char* const str = scm_to_utf8_stringn(args, NULL);
SCM g_str = scm_from_utf8_string(gur::digits(str));
free(const_cast<char*>(str));
return g_str;
}
static SCM gg_symbols(SCM args)
{
const char* const str = scm_to_utf8_stringn(args, NULL);
SCM g_str = scm_from_utf8_string(gur::symbols(str));
free(const_cast<char*>(str));
return g_str;
}
static SCM gg_comp(SCM args)
{
const char* const str = scm_to_utf8_stringn(args, NULL);
SCM g_str = scm_from_utf8_string(gur::comp(str));
free(const_cast<char*>(str));
return g_str;
}
static SCM gg_clobber(SCM args)
{
const char* const str = scm_to_utf8_stringn(args, NULL);
SCM g_str = scm_from_utf8_string(gur::clobber(str));
free(const_cast<char*>(str));
return g_str;
}
static SCM gg_unclobber(SCM args)
{
const char* const str = scm_to_utf8_stringn(args, NULL);
SCM g_str = scm_from_utf8_string(gur::unclobber(str));
free(const_cast<char*>(str));
return g_str;
}
static SCM gg_is_letter(SCM args)
{
return is_type(args, (bool (*)(const char* const&))&gur::is_letter);
}
static SCM gg_is_accent(SCM args)
{
return is_type(args, (bool (*)(const char* const&))&gur::is_accent);
}
static SCM gg_is_punc(SCM args)
{
return is_type(args, (bool (*)(const char* const&))&gur::is_punc);
}
static SCM gg_is_digit(SCM args)
{
return is_type(args, (bool (*)(const char* const&))&gur::is_digit);
}
static SCM gg_is_symbol(SCM args)
{
return is_type(args, (bool (*)(const char* const&))&gur::is_symbol);
}
static void init_gur_guile(void *unused)
{
scm_c_define_gsubr("letters", 1, 0, 0, (scm_t_subr)&gg_letters);
scm_c_define_gsubr("accents", 1, 0, 0, (scm_t_subr)&gg_accents);
scm_c_define_gsubr("puncs", 1, 0, 0, (scm_t_subr)&gg_puncs);
scm_c_define_gsubr("digits", 1, 0, 0, (scm_t_subr)&gg_digits);
scm_c_define_gsubr("symbols", 1, 0, 0, (scm_t_subr)&gg_symbols);
scm_c_define_gsubr("comp", 1, 0, 0, (scm_t_subr)&gg_comp);
scm_c_define_gsubr("clobber", 1, 0, 0, (scm_t_subr)&gg_clobber);
scm_c_define_gsubr("unclobber", 1, 0, 0, (scm_t_subr)&gg_unclobber);
scm_c_define_gsubr("is-letter", 1, 0, 0, (scm_t_subr)&gg_is_letter);
scm_c_define_gsubr("is-accent", 1, 0, 0, (scm_t_subr)&gg_is_accent);
scm_c_define_gsubr("is-punc", 1, 0, 0, (scm_t_subr)&gg_is_punc);
scm_c_define_gsubr("is-digit", 1, 0, 0, (scm_t_subr)&gg_is_digit);
scm_c_define_gsubr("is-symbol", 1, 0, 0, (scm_t_subr)&gg_is_symbol);
scm_c_export("letters", NULL);
scm_c_export("accents", NULL);
scm_c_export("puncs", NULL);
scm_c_export("digits", NULL);
scm_c_export("symbols", NULL);
scm_c_export("comp", NULL);
scm_c_export("clobber", NULL);
scm_c_export("unclobber", NULL);
scm_c_export("is-letter", NULL);
scm_c_export("is-accent", NULL);
scm_c_export("is-punc", NULL);
scm_c_export("is-digit", NULL);
scm_c_export("is-symbol", NULL);
}
extern "C"
{
void scm_init_gur_guile_module()
{
scm_c_define_module("gur-guile", init_gur_guile, NULL);
}
}
<|endoftext|> |
<commit_before>//===-- LLVMTargetMachine.cpp - Implement the LLVMTargetMachine class -----===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file implements the LLVMTargetMachine class.
//
//===----------------------------------------------------------------------===//
#include "llvm/Target/TargetMachine.h"
#include "llvm/PassManager.h"
#include "llvm/Pass.h"
#include "llvm/Assembly/PrintModulePass.h"
#include "llvm/CodeGen/AsmPrinter.h"
#include "llvm/CodeGen/Passes.h"
#include "llvm/CodeGen/GCStrategy.h"
#include "llvm/CodeGen/MachineFunctionAnalysis.h"
#include "llvm/Target/TargetOptions.h"
#include "llvm/MC/MCAsmInfo.h"
#include "llvm/Target/TargetRegistry.h"
#include "llvm/Transforms/Scalar.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/FormattedStream.h"
using namespace llvm;
namespace llvm {
bool EnableFastISel;
}
static cl::opt<bool> PrintLSR("print-lsr-output", cl::Hidden,
cl::desc("Print LLVM IR produced by the loop-reduce pass"));
static cl::opt<bool> PrintISelInput("print-isel-input", cl::Hidden,
cl::desc("Print LLVM IR input to isel pass"));
static cl::opt<bool> PrintEmittedAsm("print-emitted-asm", cl::Hidden,
cl::desc("Dump emitter generated instructions as assembly"));
static cl::opt<bool> PrintGCInfo("print-gc", cl::Hidden,
cl::desc("Dump garbage collector data"));
static cl::opt<bool> VerifyMachineCode("verify-machineinstrs", cl::Hidden,
cl::desc("Verify generated machine code"),
cl::init(getenv("LLVM_VERIFY_MACHINEINSTRS")!=NULL));
// When this works it will be on by default.
static cl::opt<bool>
DisablePostRAScheduler("disable-post-RA-scheduler",
cl::desc("Disable scheduling after register allocation"),
cl::init(true));
// Enable or disable FastISel. Both options are needed, because
// FastISel is enabled by default with -fast, and we wish to be
// able to enable or disable fast-isel independently from -fast.
static cl::opt<cl::boolOrDefault>
EnableFastISelOption("fast-isel", cl::Hidden,
cl::desc("Enable the experimental \"fast\" instruction selector"));
LLVMTargetMachine::LLVMTargetMachine(const Target &T,
const std::string &TargetTriple)
: TargetMachine(T) {
AsmInfo = T.createAsmInfo(TargetTriple);
}
FileModel::Model
LLVMTargetMachine::addPassesToEmitFile(PassManagerBase &PM,
formatted_raw_ostream &Out,
CodeGenFileType FileType,
CodeGenOpt::Level OptLevel) {
// Add common CodeGen passes.
if (addCommonCodeGenPasses(PM, OptLevel))
return FileModel::Error;
// Fold redundant debug labels.
PM.add(createDebugLabelFoldingPass());
if (PrintMachineCode)
PM.add(createMachineFunctionPrinterPass(errs()));
if (addPreEmitPass(PM, OptLevel) && PrintMachineCode)
PM.add(createMachineFunctionPrinterPass(errs()));
if (OptLevel != CodeGenOpt::None)
PM.add(createCodePlacementOptPass());
switch (FileType) {
default:
break;
case TargetMachine::AssemblyFile:
if (addAssemblyEmitter(PM, OptLevel, getAsmVerbosityDefault(), Out))
return FileModel::Error;
return FileModel::AsmFile;
case TargetMachine::ObjectFile:
if (getMachOWriterInfo())
return FileModel::MachOFile;
else if (getELFWriterInfo())
return FileModel::ElfFile;
}
return FileModel::Error;
}
bool LLVMTargetMachine::addAssemblyEmitter(PassManagerBase &PM,
CodeGenOpt::Level OptLevel,
bool Verbose,
formatted_raw_ostream &Out) {
FunctionPass *Printer =
getTarget().createAsmPrinter(Out, *this, getMCAsmInfo(), Verbose);
if (!Printer)
return true;
PM.add(Printer);
return false;
}
/// addPassesToEmitFileFinish - If the passes to emit the specified file had to
/// be split up (e.g., to add an object writer pass), this method can be used to
/// finish up adding passes to emit the file, if necessary.
bool LLVMTargetMachine::addPassesToEmitFileFinish(PassManagerBase &PM,
MachineCodeEmitter *MCE,
CodeGenOpt::Level OptLevel) {
if (MCE)
addSimpleCodeEmitter(PM, OptLevel, *MCE);
if (PrintEmittedAsm)
addAssemblyEmitter(PM, OptLevel, true, ferrs());
PM.add(createGCInfoDeleter());
return false; // success!
}
/// addPassesToEmitFileFinish - If the passes to emit the specified file had to
/// be split up (e.g., to add an object writer pass), this method can be used to
/// finish up adding passes to emit the file, if necessary.
bool LLVMTargetMachine::addPassesToEmitFileFinish(PassManagerBase &PM,
JITCodeEmitter *JCE,
CodeGenOpt::Level OptLevel) {
if (JCE)
addSimpleCodeEmitter(PM, OptLevel, *JCE);
if (PrintEmittedAsm)
addAssemblyEmitter(PM, OptLevel, true, ferrs());
PM.add(createGCInfoDeleter());
return false; // success!
}
/// addPassesToEmitFileFinish - If the passes to emit the specified file had to
/// be split up (e.g., to add an object writer pass), this method can be used to
/// finish up adding passes to emit the file, if necessary.
bool LLVMTargetMachine::addPassesToEmitFileFinish(PassManagerBase &PM,
ObjectCodeEmitter *OCE,
CodeGenOpt::Level OptLevel) {
if (OCE)
addSimpleCodeEmitter(PM, OptLevel, *OCE);
if (PrintEmittedAsm)
addAssemblyEmitter(PM, OptLevel, true, ferrs());
PM.add(createGCInfoDeleter());
return false; // success!
}
/// addPassesToEmitMachineCode - Add passes to the specified pass manager to
/// get machine code emitted. This uses a MachineCodeEmitter object to handle
/// actually outputting the machine code and resolving things like the address
/// of functions. This method should returns true if machine code emission is
/// not supported.
///
bool LLVMTargetMachine::addPassesToEmitMachineCode(PassManagerBase &PM,
MachineCodeEmitter &MCE,
CodeGenOpt::Level OptLevel) {
// Add common CodeGen passes.
if (addCommonCodeGenPasses(PM, OptLevel))
return true;
if (addPreEmitPass(PM, OptLevel) && PrintMachineCode)
PM.add(createMachineFunctionPrinterPass(errs()));
addCodeEmitter(PM, OptLevel, MCE);
if (PrintEmittedAsm)
addAssemblyEmitter(PM, OptLevel, true, ferrs());
PM.add(createGCInfoDeleter());
return false; // success!
}
/// addPassesToEmitMachineCode - Add passes to the specified pass manager to
/// get machine code emitted. This uses a MachineCodeEmitter object to handle
/// actually outputting the machine code and resolving things like the address
/// of functions. This method should returns true if machine code emission is
/// not supported.
///
bool LLVMTargetMachine::addPassesToEmitMachineCode(PassManagerBase &PM,
JITCodeEmitter &JCE,
CodeGenOpt::Level OptLevel) {
// Add common CodeGen passes.
if (addCommonCodeGenPasses(PM, OptLevel))
return true;
if (addPreEmitPass(PM, OptLevel) && PrintMachineCode)
PM.add(createMachineFunctionPrinterPass(errs()));
addCodeEmitter(PM, OptLevel, JCE);
if (PrintEmittedAsm)
addAssemblyEmitter(PM, OptLevel, true, ferrs());
PM.add(createGCInfoDeleter());
return false; // success!
}
static void printAndVerify(PassManagerBase &PM,
bool allowDoubleDefs = false) {
if (PrintMachineCode)
PM.add(createMachineFunctionPrinterPass(errs()));
if (VerifyMachineCode)
PM.add(createMachineVerifierPass(allowDoubleDefs));
}
/// addCommonCodeGenPasses - Add standard LLVM codegen passes used for both
/// emitting to assembly files or machine code output.
///
bool LLVMTargetMachine::addCommonCodeGenPasses(PassManagerBase &PM,
CodeGenOpt::Level OptLevel) {
// Standard LLVM-Level Passes.
// Run loop strength reduction before anything else.
if (OptLevel != CodeGenOpt::None) {
PM.add(createLoopStrengthReducePass(getTargetLowering()));
if (PrintLSR)
PM.add(createPrintFunctionPass("\n\n*** Code after LSR ***\n", &errs()));
}
// Turn exception handling constructs into something the code generators can
// handle.
switch (getMCAsmInfo()->getExceptionHandlingType())
{
case ExceptionHandling::SjLj:
// SjLj piggy-backs on dwarf for this bit. The cleanups done apply to both
PM.add(createDwarfEHPass(getTargetLowering(), OptLevel==CodeGenOpt::None));
PM.add(createSjLjEHPass(getTargetLowering()));
break;
case ExceptionHandling::Dwarf:
PM.add(createDwarfEHPass(getTargetLowering(), OptLevel==CodeGenOpt::None));
break;
case ExceptionHandling::None:
PM.add(createLowerInvokePass(getTargetLowering()));
break;
}
PM.add(createGCLoweringPass());
// Make sure that no unreachable blocks are instruction selected.
PM.add(createUnreachableBlockEliminationPass());
if (OptLevel != CodeGenOpt::None)
PM.add(createCodeGenPreparePass(getTargetLowering()));
PM.add(createStackProtectorPass(getTargetLowering()));
if (PrintISelInput)
PM.add(createPrintFunctionPass("\n\n"
"*** Final LLVM Code input to ISel ***\n",
&errs()));
// Standard Lower-Level Passes.
// Set up a MachineFunction for the rest of CodeGen to work on.
PM.add(new MachineFunctionAnalysis(*this, OptLevel));
// Enable FastISel with -fast, but allow that to be overridden.
if (EnableFastISelOption == cl::BOU_TRUE ||
(OptLevel == CodeGenOpt::None && EnableFastISelOption != cl::BOU_FALSE))
EnableFastISel = true;
// Ask the target for an isel.
if (addInstSelector(PM, OptLevel))
return true;
// Print the instruction selected machine code...
printAndVerify(PM, /* allowDoubleDefs= */ true);
if (OptLevel != CodeGenOpt::None) {
PM.add(createMachineLICMPass());
PM.add(createMachineSinkingPass());
printAndVerify(PM, /* allowDoubleDefs= */ true);
}
// Run pre-ra passes.
if (addPreRegAlloc(PM, OptLevel))
printAndVerify(PM, /* allowDoubleDefs= */ true);
// Perform register allocation.
PM.add(createRegisterAllocator());
// Perform stack slot coloring.
if (OptLevel != CodeGenOpt::None)
// FIXME: Re-enable coloring with register when it's capable of adding
// kill markers.
PM.add(createStackSlotColoringPass(false));
printAndVerify(PM); // Print the register-allocated code
// Run post-ra passes.
if (addPostRegAlloc(PM, OptLevel))
printAndVerify(PM);
PM.add(createLowerSubregsPass());
printAndVerify(PM);
// Insert prolog/epilog code. Eliminate abstract frame index references...
PM.add(createPrologEpilogCodeInserter());
printAndVerify(PM);
// Second pass scheduler.
if (OptLevel != CodeGenOpt::None && !DisablePostRAScheduler) {
PM.add(createPostRAScheduler());
printAndVerify(PM);
}
// Branch folding must be run after regalloc and prolog/epilog insertion.
if (OptLevel != CodeGenOpt::None) {
PM.add(createBranchFoldingPass(getEnableTailMergeDefault()));
printAndVerify(PM);
}
PM.add(createGCMachineCodeAnalysisPass());
printAndVerify(PM);
if (PrintGCInfo)
PM.add(createGCInfoPrinter(errs()));
return false;
}
<commit_msg>-fast is now -O0. -fast-isel is no longer experimental.<commit_after>//===-- LLVMTargetMachine.cpp - Implement the LLVMTargetMachine class -----===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file implements the LLVMTargetMachine class.
//
//===----------------------------------------------------------------------===//
#include "llvm/Target/TargetMachine.h"
#include "llvm/PassManager.h"
#include "llvm/Pass.h"
#include "llvm/Assembly/PrintModulePass.h"
#include "llvm/CodeGen/AsmPrinter.h"
#include "llvm/CodeGen/Passes.h"
#include "llvm/CodeGen/GCStrategy.h"
#include "llvm/CodeGen/MachineFunctionAnalysis.h"
#include "llvm/Target/TargetOptions.h"
#include "llvm/MC/MCAsmInfo.h"
#include "llvm/Target/TargetRegistry.h"
#include "llvm/Transforms/Scalar.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/FormattedStream.h"
using namespace llvm;
namespace llvm {
bool EnableFastISel;
}
static cl::opt<bool> PrintLSR("print-lsr-output", cl::Hidden,
cl::desc("Print LLVM IR produced by the loop-reduce pass"));
static cl::opt<bool> PrintISelInput("print-isel-input", cl::Hidden,
cl::desc("Print LLVM IR input to isel pass"));
static cl::opt<bool> PrintEmittedAsm("print-emitted-asm", cl::Hidden,
cl::desc("Dump emitter generated instructions as assembly"));
static cl::opt<bool> PrintGCInfo("print-gc", cl::Hidden,
cl::desc("Dump garbage collector data"));
static cl::opt<bool> VerifyMachineCode("verify-machineinstrs", cl::Hidden,
cl::desc("Verify generated machine code"),
cl::init(getenv("LLVM_VERIFY_MACHINEINSTRS")!=NULL));
// When this works it will be on by default.
static cl::opt<bool>
DisablePostRAScheduler("disable-post-RA-scheduler",
cl::desc("Disable scheduling after register allocation"),
cl::init(true));
// Enable or disable FastISel. Both options are needed, because
// FastISel is enabled by default with -fast, and we wish to be
// able to enable or disable fast-isel independently from -O0.
static cl::opt<cl::boolOrDefault>
EnableFastISelOption("fast-isel", cl::Hidden,
cl::desc("Enable the \"fast\" instruction selector"));
LLVMTargetMachine::LLVMTargetMachine(const Target &T,
const std::string &TargetTriple)
: TargetMachine(T) {
AsmInfo = T.createAsmInfo(TargetTriple);
}
FileModel::Model
LLVMTargetMachine::addPassesToEmitFile(PassManagerBase &PM,
formatted_raw_ostream &Out,
CodeGenFileType FileType,
CodeGenOpt::Level OptLevel) {
// Add common CodeGen passes.
if (addCommonCodeGenPasses(PM, OptLevel))
return FileModel::Error;
// Fold redundant debug labels.
PM.add(createDebugLabelFoldingPass());
if (PrintMachineCode)
PM.add(createMachineFunctionPrinterPass(errs()));
if (addPreEmitPass(PM, OptLevel) && PrintMachineCode)
PM.add(createMachineFunctionPrinterPass(errs()));
if (OptLevel != CodeGenOpt::None)
PM.add(createCodePlacementOptPass());
switch (FileType) {
default:
break;
case TargetMachine::AssemblyFile:
if (addAssemblyEmitter(PM, OptLevel, getAsmVerbosityDefault(), Out))
return FileModel::Error;
return FileModel::AsmFile;
case TargetMachine::ObjectFile:
if (getMachOWriterInfo())
return FileModel::MachOFile;
else if (getELFWriterInfo())
return FileModel::ElfFile;
}
return FileModel::Error;
}
bool LLVMTargetMachine::addAssemblyEmitter(PassManagerBase &PM,
CodeGenOpt::Level OptLevel,
bool Verbose,
formatted_raw_ostream &Out) {
FunctionPass *Printer =
getTarget().createAsmPrinter(Out, *this, getMCAsmInfo(), Verbose);
if (!Printer)
return true;
PM.add(Printer);
return false;
}
/// addPassesToEmitFileFinish - If the passes to emit the specified file had to
/// be split up (e.g., to add an object writer pass), this method can be used to
/// finish up adding passes to emit the file, if necessary.
bool LLVMTargetMachine::addPassesToEmitFileFinish(PassManagerBase &PM,
MachineCodeEmitter *MCE,
CodeGenOpt::Level OptLevel) {
if (MCE)
addSimpleCodeEmitter(PM, OptLevel, *MCE);
if (PrintEmittedAsm)
addAssemblyEmitter(PM, OptLevel, true, ferrs());
PM.add(createGCInfoDeleter());
return false; // success!
}
/// addPassesToEmitFileFinish - If the passes to emit the specified file had to
/// be split up (e.g., to add an object writer pass), this method can be used to
/// finish up adding passes to emit the file, if necessary.
bool LLVMTargetMachine::addPassesToEmitFileFinish(PassManagerBase &PM,
JITCodeEmitter *JCE,
CodeGenOpt::Level OptLevel) {
if (JCE)
addSimpleCodeEmitter(PM, OptLevel, *JCE);
if (PrintEmittedAsm)
addAssemblyEmitter(PM, OptLevel, true, ferrs());
PM.add(createGCInfoDeleter());
return false; // success!
}
/// addPassesToEmitFileFinish - If the passes to emit the specified file had to
/// be split up (e.g., to add an object writer pass), this method can be used to
/// finish up adding passes to emit the file, if necessary.
bool LLVMTargetMachine::addPassesToEmitFileFinish(PassManagerBase &PM,
ObjectCodeEmitter *OCE,
CodeGenOpt::Level OptLevel) {
if (OCE)
addSimpleCodeEmitter(PM, OptLevel, *OCE);
if (PrintEmittedAsm)
addAssemblyEmitter(PM, OptLevel, true, ferrs());
PM.add(createGCInfoDeleter());
return false; // success!
}
/// addPassesToEmitMachineCode - Add passes to the specified pass manager to
/// get machine code emitted. This uses a MachineCodeEmitter object to handle
/// actually outputting the machine code and resolving things like the address
/// of functions. This method should returns true if machine code emission is
/// not supported.
///
bool LLVMTargetMachine::addPassesToEmitMachineCode(PassManagerBase &PM,
MachineCodeEmitter &MCE,
CodeGenOpt::Level OptLevel) {
// Add common CodeGen passes.
if (addCommonCodeGenPasses(PM, OptLevel))
return true;
if (addPreEmitPass(PM, OptLevel) && PrintMachineCode)
PM.add(createMachineFunctionPrinterPass(errs()));
addCodeEmitter(PM, OptLevel, MCE);
if (PrintEmittedAsm)
addAssemblyEmitter(PM, OptLevel, true, ferrs());
PM.add(createGCInfoDeleter());
return false; // success!
}
/// addPassesToEmitMachineCode - Add passes to the specified pass manager to
/// get machine code emitted. This uses a MachineCodeEmitter object to handle
/// actually outputting the machine code and resolving things like the address
/// of functions. This method should returns true if machine code emission is
/// not supported.
///
bool LLVMTargetMachine::addPassesToEmitMachineCode(PassManagerBase &PM,
JITCodeEmitter &JCE,
CodeGenOpt::Level OptLevel) {
// Add common CodeGen passes.
if (addCommonCodeGenPasses(PM, OptLevel))
return true;
if (addPreEmitPass(PM, OptLevel) && PrintMachineCode)
PM.add(createMachineFunctionPrinterPass(errs()));
addCodeEmitter(PM, OptLevel, JCE);
if (PrintEmittedAsm)
addAssemblyEmitter(PM, OptLevel, true, ferrs());
PM.add(createGCInfoDeleter());
return false; // success!
}
static void printAndVerify(PassManagerBase &PM,
bool allowDoubleDefs = false) {
if (PrintMachineCode)
PM.add(createMachineFunctionPrinterPass(errs()));
if (VerifyMachineCode)
PM.add(createMachineVerifierPass(allowDoubleDefs));
}
/// addCommonCodeGenPasses - Add standard LLVM codegen passes used for both
/// emitting to assembly files or machine code output.
///
bool LLVMTargetMachine::addCommonCodeGenPasses(PassManagerBase &PM,
CodeGenOpt::Level OptLevel) {
// Standard LLVM-Level Passes.
// Run loop strength reduction before anything else.
if (OptLevel != CodeGenOpt::None) {
PM.add(createLoopStrengthReducePass(getTargetLowering()));
if (PrintLSR)
PM.add(createPrintFunctionPass("\n\n*** Code after LSR ***\n", &errs()));
}
// Turn exception handling constructs into something the code generators can
// handle.
switch (getMCAsmInfo()->getExceptionHandlingType())
{
case ExceptionHandling::SjLj:
// SjLj piggy-backs on dwarf for this bit. The cleanups done apply to both
PM.add(createDwarfEHPass(getTargetLowering(), OptLevel==CodeGenOpt::None));
PM.add(createSjLjEHPass(getTargetLowering()));
break;
case ExceptionHandling::Dwarf:
PM.add(createDwarfEHPass(getTargetLowering(), OptLevel==CodeGenOpt::None));
break;
case ExceptionHandling::None:
PM.add(createLowerInvokePass(getTargetLowering()));
break;
}
PM.add(createGCLoweringPass());
// Make sure that no unreachable blocks are instruction selected.
PM.add(createUnreachableBlockEliminationPass());
if (OptLevel != CodeGenOpt::None)
PM.add(createCodeGenPreparePass(getTargetLowering()));
PM.add(createStackProtectorPass(getTargetLowering()));
if (PrintISelInput)
PM.add(createPrintFunctionPass("\n\n"
"*** Final LLVM Code input to ISel ***\n",
&errs()));
// Standard Lower-Level Passes.
// Set up a MachineFunction for the rest of CodeGen to work on.
PM.add(new MachineFunctionAnalysis(*this, OptLevel));
// Enable FastISel with -fast, but allow that to be overridden.
if (EnableFastISelOption == cl::BOU_TRUE ||
(OptLevel == CodeGenOpt::None && EnableFastISelOption != cl::BOU_FALSE))
EnableFastISel = true;
// Ask the target for an isel.
if (addInstSelector(PM, OptLevel))
return true;
// Print the instruction selected machine code...
printAndVerify(PM, /* allowDoubleDefs= */ true);
if (OptLevel != CodeGenOpt::None) {
PM.add(createMachineLICMPass());
PM.add(createMachineSinkingPass());
printAndVerify(PM, /* allowDoubleDefs= */ true);
}
// Run pre-ra passes.
if (addPreRegAlloc(PM, OptLevel))
printAndVerify(PM, /* allowDoubleDefs= */ true);
// Perform register allocation.
PM.add(createRegisterAllocator());
// Perform stack slot coloring.
if (OptLevel != CodeGenOpt::None)
// FIXME: Re-enable coloring with register when it's capable of adding
// kill markers.
PM.add(createStackSlotColoringPass(false));
printAndVerify(PM); // Print the register-allocated code
// Run post-ra passes.
if (addPostRegAlloc(PM, OptLevel))
printAndVerify(PM);
PM.add(createLowerSubregsPass());
printAndVerify(PM);
// Insert prolog/epilog code. Eliminate abstract frame index references...
PM.add(createPrologEpilogCodeInserter());
printAndVerify(PM);
// Second pass scheduler.
if (OptLevel != CodeGenOpt::None && !DisablePostRAScheduler) {
PM.add(createPostRAScheduler());
printAndVerify(PM);
}
// Branch folding must be run after regalloc and prolog/epilog insertion.
if (OptLevel != CodeGenOpt::None) {
PM.add(createBranchFoldingPass(getEnableTailMergeDefault()));
printAndVerify(PM);
}
PM.add(createGCMachineCodeAnalysisPass());
printAndVerify(PM);
if (PrintGCInfo)
PM.add(createGCInfoPrinter(errs()));
return false;
}
<|endoftext|> |
<commit_before>/*
* Copyright (C) 2018-present ScyllaDB
*/
/*
* SPDX-License-Identifier: AGPL-3.0-or-later
*/
#include <seastar/core/iostream.hh>
#include <seastar/core/temporary_buffer.hh>
#include "utils/small_vector.hh"
#include "seastarx.hh"
#pragma once
// Accumulates data sent to the memory_data_sink allowing it
// to be examined later.
class memory_data_sink_buffers {
using buffers_type = utils::small_vector<temporary_buffer<char>, 1>;
buffers_type _bufs;
size_t _size = 0;
public:
size_t size() const { return _size; }
buffers_type& buffers() { return _bufs; }
// Strong exception guarantees
void put(temporary_buffer<char>&& buf) {
auto size = buf.size();
_bufs.emplace_back(std::move(buf));
_size += size;
}
void clear() {
_bufs.clear();
_size = 0;
}
};
class memory_data_sink : public data_sink_impl {
memory_data_sink_buffers& _bufs;
public:
memory_data_sink(memory_data_sink_buffers& b) : _bufs(b) {}
virtual future<> put(net::packet data) override {
abort();
return make_ready_future<>();
}
virtual future<> put(temporary_buffer<char> buf) override {
_bufs.put(std::move(buf));
return make_ready_future<>();
}
virtual future<> flush() override {
return make_ready_future<>();
}
virtual future<> close() override {
return make_ready_future<>();
}
};
<commit_msg>utils: memory_data_sink: Override mandatory buffer_size()<commit_after>/*
* Copyright (C) 2018-present ScyllaDB
*/
/*
* SPDX-License-Identifier: AGPL-3.0-or-later
*/
#include <seastar/core/iostream.hh>
#include <seastar/core/temporary_buffer.hh>
#include "utils/small_vector.hh"
#include "seastarx.hh"
#pragma once
// Accumulates data sent to the memory_data_sink allowing it
// to be examined later.
class memory_data_sink_buffers {
using buffers_type = utils::small_vector<temporary_buffer<char>, 1>;
buffers_type _bufs;
size_t _size = 0;
public:
size_t size() const { return _size; }
buffers_type& buffers() { return _bufs; }
// Strong exception guarantees
void put(temporary_buffer<char>&& buf) {
auto size = buf.size();
_bufs.emplace_back(std::move(buf));
_size += size;
}
void clear() {
_bufs.clear();
_size = 0;
}
};
class memory_data_sink : public data_sink_impl {
memory_data_sink_buffers& _bufs;
public:
memory_data_sink(memory_data_sink_buffers& b) : _bufs(b) {}
virtual future<> put(net::packet data) override {
abort();
return make_ready_future<>();
}
virtual future<> put(temporary_buffer<char> buf) override {
_bufs.put(std::move(buf));
return make_ready_future<>();
}
virtual future<> flush() override {
return make_ready_future<>();
}
virtual future<> close() override {
return make_ready_future<>();
}
size_t buffer_size() const noexcept override {
return 128*1024;
}
};
<|endoftext|> |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.