text
stringlengths 54
60.6k
|
|---|
<commit_before>#include "implementedinfos.h"
ImplementedInfos::ImplementedInfos(Device *device)
: SysExMessage(SysExMessage::RET_INFO_LIST, SysExMessage::QUERY, device) {}
void ImplementedInfos::parseAnswerData() {
implementedInfos = new std::vector<DeviceInfoItem>();
unsigned int nInfosSize = data->size();
DeviceInfoItem info;
for (unsigned int i = 0; i < nInfosSize; i++) {
info = (DeviceInfoItem)data->at(i);
if (info != 0)
implementedInfos->push_back(info);
}
}
bool ImplementedInfos::isInfoImplemented(SysExMessage::DeviceInfoItem info) {
if (!implementedInfos)
return false;
std::vector<DeviceInfoItem>::iterator it;
for (it = implementedInfos->begin(); it != implementedInfos->end(); it++) {
if (*it == info)
return true;
}
return false;
}
<commit_msg>ignore length - byte of device name<commit_after>#include "implementedinfos.h"
ImplementedInfos::ImplementedInfos(Device *device)
: SysExMessage(SysExMessage::RET_INFO_LIST, SysExMessage::QUERY, device) {}
void ImplementedInfos::parseAnswerData() {
implementedInfos = new std::vector<DeviceInfoItem>();
unsigned int nInfosSize = data->size();
DeviceInfoItem info;
for (unsigned int i = 0; i < nInfosSize; ++i) {
info = (DeviceInfoItem)data->at(i);
if (info != 0)
implementedInfos->push_back(info);
if (info == 16)
++i;
}
}
bool ImplementedInfos::isInfoImplemented(SysExMessage::DeviceInfoItem info) {
if (!implementedInfos)
return false;
std::vector<DeviceInfoItem>::iterator it;
for (it = implementedInfos->begin(); it != implementedInfos->end(); it++) {
if (*it == info)
return true;
}
return false;
}
<|endoftext|>
|
<commit_before>/* bzflag
* Copyright (c) 1993 - 2004 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 "PlayerInfo.h"
/* system implementation headers */
#include <errno.h>
#include <assert.h>
#include <string>
/* implementation-specific common headers */
#include "TextUtils.h"
PlayerInfo::PlayerInfo(int _playerIndex) :
playerIndex(_playerIndex), state(PlayerInLimbo), flag(-1),
spamWarns(0), lastMsgTime(TimeKeeper::getCurrent()), paused(false),
pausedSince(TimeKeeper::getNullTime()), tracker(0)
{
notResponding = false;
memset (email, 0, EmailLen);
memset (callSign, 0, CallSignLen);
}
std::string PlayerInfo::getLastMsg() {
return lastMsgSent;
}
TimeKeeper PlayerInfo::getLastMsgTime() {
return lastMsgTime;
}
int PlayerInfo::getSpamWarns() {
return spamWarns;
}
void PlayerInfo::incSpamWarns() {
++spamWarns;
}
void PlayerInfo::setLastMsg(std::string msg) {
lastMsgSent = msg;
lastMsgTime = TimeKeeper::getCurrent();
}
void PlayerInfo::resetPlayer(bool ctf) {
wasRabbit = false;
lastupdate = TimeKeeper::getCurrent();
lastmsg = TimeKeeper::getCurrent();
replayState = ReplayNone;
#ifdef TIMELIMIT
playedEarly = false;
#endif
restartOnBase = ctf;
}
void PlayerInfo::setRestartOnBase(bool on) {
restartOnBase = on;
};
bool PlayerInfo::shouldRestartAtBase() {
return restartOnBase;
};
bool PlayerInfo::isPlaying() {
return state > PlayerInLimbo;
};
void PlayerInfo::signingOn() {
state = PlayerDead;
};
bool PlayerInfo::isAlive() {
return state == PlayerAlive;
};
bool PlayerInfo::isDead() {
return state == PlayerDead;
};
void PlayerInfo::setAlive() {
state = PlayerAlive;
flag = -1;
};
void PlayerInfo::setDead() {
state = PlayerDead;
};
bool PlayerInfo::isPaused() {
return paused;
};
bool PlayerInfo::isBot() {
return type == ComputerPlayer;
};
bool PlayerInfo::isHuman() {
return type == TankPlayer;
};
void *PlayerInfo::packUpdate(void *buf) {
buf = nboPackUShort(buf, uint16_t(type));
buf = nboPackUShort(buf, uint16_t(team));
return buf;
};
void *PlayerInfo::packId(void *buf) {
buf = nboPackString(buf, callSign, CallSignLen);
buf = nboPackString(buf, email, EmailLen);
return buf;
}
bool PlayerInfo::unpackEnter(void *buf, uint16_t &rejectCode, char *rejectMsg)
{
// data: type, team, name, email
uint16_t _type;
int16_t _team;
buf = nboUnpackUShort(buf, _type);
buf = nboUnpackShort(buf, _team);
type = PlayerType(_type);
team = TeamColor(_team);
buf = nboUnpackString(buf, callSign, CallSignLen);
buf = nboUnpackString(buf, email, EmailLen);
cleanCallSign();
cleanEMail();
// spoof filter holds "SERVER" for robust name comparisons
if (serverSpoofingFilter.wordCount() == 0) {
serverSpoofingFilter.addToFilter(std::string("SERVER"), std::string(""));
}
// don't allow empty callsign
if (callSign[0] == '\0') {
rejectCode = RejectBadCallsign;
strcpy(rejectMsg, "The callsign was rejected. Try a different callsign.");
return false;
}
// no spoofing the server name
if (serverSpoofingFilter.filter(callSign)) {
rejectCode = RejectRepeatCallsign;
strcpy(rejectMsg, "The callsign specified is already in use.");
return false;
}
if (!isCallSignReadable()) {
DEBUG2("rejecting unreadable callsign: %s\n", callSign);
rejectCode = RejectBadCallsign;
strcpy(rejectMsg, "The callsign was rejected. Try a different callsign.");
return false;
}
if (!isEMailReadable()) {
DEBUG2("rejecting unreadable player email: %s (%s)\n", callSign, email);
rejectCode = RejectBadEmail;
strcpy(rejectMsg, "The e-mail was rejected. Try a different e-mail.");
return false;
}
return true;
};
const char *PlayerInfo::getCallSign() const {
return callSign;
};
void PlayerInfo::cleanCallSign() {
char *sp = callSign;
char *tp = sp;
// strip leading whitespace from callsign
while (isspace(*sp)) {
sp++;
}
// strip any non-printable characters and ' and " from callsign
do {
if (isprint(*sp) && (*sp != '\'') && (*sp != '"')) {
// override modified clients that might send non-space whitespace
if (isspace(*sp)) {
*sp = ' ';
}
*tp++ = *sp;
}
} while (*++sp);
*tp = *sp;
// strip trailing whitespace from callsign
while (isspace(*--tp)) {
*tp=0;
}
};
bool PlayerInfo::isCallSignReadable() {
// callsign readability filter, make sure there are more alphanum than non
// keep a count of alpha-numerics
int alnumCount = 0;
const char *sp = callSign;
do {
if (isalnum(*sp)) {
alnumCount++;
}
} while (*++sp);
int callsignlen = strlen(callSign);
return (callsignlen <= 4) || ((float)alnumCount / (float)callsignlen > 0.5f);
};
const char *PlayerInfo::getEMail() const {
return email;
};
void PlayerInfo::cleanEMail() {
// strip leading whitespace from email
char *sp = email;
char *tp = sp;
while (isspace(*sp))
sp++;
// strip any non-printable characters and ' and " from email
do {
if (isprint(*sp) && (*sp != '\'') && (*sp != '"')) {
*tp++ = *sp;
}
} while (*++sp);
*tp = *sp;
// strip trailing whitespace from email
while (isspace(*--tp)) {
*tp=0;
}
};
bool PlayerInfo::isEMailReadable() {
// email/"team" readability filter, make sure there are more
// alphanum than non
int emailAlnumCount = 0;
char *sp = email;
do {
if (isalnum(*sp)) {
emailAlnumCount++;
}
} while (*++sp);
int emaillen = strlen(email);
return (emaillen <= 4) || (((float)emailAlnumCount / (float)emaillen) > 0.5);
};
void *PlayerInfo::packVirtualFlagCapture(void *buf) {
buf = nboPackUShort(buf, uint16_t(int(team) - 1));
buf = nboPackUShort(buf, uint16_t(1 + (int(team) % 4)));
return buf;
};
bool PlayerInfo::isTeam(TeamColor _team) const {
return team == _team;
};
bool PlayerInfo::isObserver() const {
return team == ObserverTeam;
};
TeamColor PlayerInfo::getTeam() {
return team;
};
void PlayerInfo::setTeam(TeamColor _team) {
team = _team;
};
void PlayerInfo::wasARabbit() {
team = RogueTeam;
wasRabbit = true;
};
void PlayerInfo::wasNotARabbit() {
wasRabbit = false;
};
bool PlayerInfo::isARabbitKill(PlayerInfo &victim) {
return wasRabbit || victim.team == RabbitTeam;
};
void PlayerInfo::resetFlag() {
flag = -1;
lastFlagDropTime = TimeKeeper::getCurrent();
};
bool PlayerInfo::haveFlag() const {
return flag >= 0;
}
int PlayerInfo::getFlag() const {
return flag;
};
void PlayerInfo::setFlag(int _flag) {
flag = _flag;
};
bool PlayerInfo::isFlagTransitSafe() {
return TimeKeeper::getCurrent() - lastFlagDropTime >= 2.0f;
};
const char *PlayerInfo::getClientVersion() {
return clientVersion.c_str();
};
void *PlayerInfo::setClientVersion(size_t length, void *buf) {
char *versionString = new char[length];
buf = nboUnpackString(buf, versionString, length);
clientVersion = std::string(versionString);
delete[] versionString;
DEBUG2("Player %s [%d] sent version string: %s\n",
callSign, playerIndex, clientVersion.c_str());
return buf;
}
std::string PlayerInfo::getIdleStat() {
TimeKeeper now = TimeKeeper::getCurrent();
std::string reply;
if ((state > PlayerInLimbo) && (team != ObserverTeam)) {
reply = string_util::format("%-16s : %4ds", callSign,
int(now - lastupdate));
if (paused) {
reply += string_util::format(" paused %4ds", int(now - pausedSince));
}
}
return reply;
};
bool PlayerInfo::canBeRabbit(bool relaxing) {
if (paused || notResponding || (team == ObserverTeam))
return false;
return relaxing ? (state > PlayerInLimbo) : (state == PlayerAlive);
};
void PlayerInfo::setPaused(bool _paused) {
paused = _paused;
pausedSince = TimeKeeper::getCurrent();
};
bool PlayerInfo::isTooMuchIdling(TimeKeeper tm, float kickThresh) {
bool idling = false;
if ((state > PlayerInLimbo) && (team != ObserverTeam)) {
int idletime = (int)(tm - lastupdate);
int pausetime = 0;
if (paused && tm - pausedSince > idletime)
pausetime = (int)(tm - pausedSince);
idletime = idletime > pausetime ? idletime : pausetime;
if (idletime > (tm - lastmsg < kickThresh ? 3 * kickThresh : kickThresh)) {
DEBUG1("Kicking player %s [%d] idle %d\n", callSign, playerIndex,
idletime);
idling = true;
}
}
return idling;
};
bool PlayerInfo::hasStartedToNotRespond() {
float notRespondingTime = BZDB.eval(StateDatabase::BZDB_NOTRESPONDINGTIME);
bool startingToNotRespond = false;
if (state > PlayerInLimbo) {
bool oldnr = notResponding;
notResponding = (TimeKeeper::getCurrent() - lastupdate)
> notRespondingTime;
if (!oldnr && notResponding)
startingToNotRespond = true;
}
return startingToNotRespond;
}
void PlayerInfo::hasSent(char message[]) {
lastmsg = TimeKeeper::getCurrent();
DEBUG1("Player %s [%d]: %s\n", callSign, playerIndex, message);
};
bool PlayerInfo::hasPlayedEarly() {
bool returnValue = playedEarly;
playedEarly = false;
return returnValue;
};
void PlayerInfo::setPlayedEarly() {
playedEarly = true;
};
void PlayerInfo::updateIdleTime() {
lastupdate = TimeKeeper::getCurrent();
};
void PlayerInfo::setReplayState(PlayerReplayState state) {
replayState = state;
}
PlayerReplayState PlayerInfo::getReplayState()
{
return replayState;
}
void PlayerInfo::setTrackerID(unsigned short int t)
{
tracker = t;
}
unsigned short int PlayerInfo::trackerID()
{
return tracker;
}
// Local Variables: ***
// mode:C++ ***
// tab-width: 8 ***
// c-basic-offset: 2 ***
// indent-tabs-mode: t ***
// End: ***
// ex: shiftwidth=2 tabstop=8
<commit_msg>suppose that static data should be initialized/declared so that the compiler will make some memory for it.. *ahem* compiling would help too<commit_after>/* bzflag
* Copyright (c) 1993 - 2004 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 "PlayerInfo.h"
/* system implementation headers */
#include <errno.h>
#include <assert.h>
#include <string>
/* implementation-specific common headers */
#include "TextUtils.h"
WordFilter PlayerInfo::serverSpoofingFilter;
PlayerInfo::PlayerInfo(int _playerIndex) :
playerIndex(_playerIndex), state(PlayerInLimbo), flag(-1),
spamWarns(0), lastMsgTime(TimeKeeper::getCurrent()), paused(false),
pausedSince(TimeKeeper::getNullTime()), tracker(0)
{
notResponding = false;
memset (email, 0, EmailLen);
memset (callSign, 0, CallSignLen);
}
std::string PlayerInfo::getLastMsg() {
return lastMsgSent;
}
TimeKeeper PlayerInfo::getLastMsgTime() {
return lastMsgTime;
}
int PlayerInfo::getSpamWarns() {
return spamWarns;
}
void PlayerInfo::incSpamWarns() {
++spamWarns;
}
void PlayerInfo::setLastMsg(std::string msg) {
lastMsgSent = msg;
lastMsgTime = TimeKeeper::getCurrent();
}
void PlayerInfo::resetPlayer(bool ctf) {
wasRabbit = false;
lastupdate = TimeKeeper::getCurrent();
lastmsg = TimeKeeper::getCurrent();
replayState = ReplayNone;
#ifdef TIMELIMIT
playedEarly = false;
#endif
restartOnBase = ctf;
}
void PlayerInfo::setRestartOnBase(bool on) {
restartOnBase = on;
};
bool PlayerInfo::shouldRestartAtBase() {
return restartOnBase;
};
bool PlayerInfo::isPlaying() {
return state > PlayerInLimbo;
};
void PlayerInfo::signingOn() {
state = PlayerDead;
};
bool PlayerInfo::isAlive() {
return state == PlayerAlive;
};
bool PlayerInfo::isDead() {
return state == PlayerDead;
};
void PlayerInfo::setAlive() {
state = PlayerAlive;
flag = -1;
};
void PlayerInfo::setDead() {
state = PlayerDead;
};
bool PlayerInfo::isPaused() {
return paused;
};
bool PlayerInfo::isBot() {
return type == ComputerPlayer;
};
bool PlayerInfo::isHuman() {
return type == TankPlayer;
};
void *PlayerInfo::packUpdate(void *buf) {
buf = nboPackUShort(buf, uint16_t(type));
buf = nboPackUShort(buf, uint16_t(team));
return buf;
};
void *PlayerInfo::packId(void *buf) {
buf = nboPackString(buf, callSign, CallSignLen);
buf = nboPackString(buf, email, EmailLen);
return buf;
}
bool PlayerInfo::unpackEnter(void *buf, uint16_t &rejectCode, char *rejectMsg)
{
// data: type, team, name, email
uint16_t _type;
int16_t _team;
buf = nboUnpackUShort(buf, _type);
buf = nboUnpackShort(buf, _team);
type = PlayerType(_type);
team = TeamColor(_team);
buf = nboUnpackString(buf, callSign, CallSignLen);
buf = nboUnpackString(buf, email, EmailLen);
cleanCallSign();
cleanEMail();
// spoof filter holds "SERVER" for robust name comparisons
if (serverSpoofingFilter.wordCount() == 0) {
serverSpoofingFilter.addToFilter(std::string("SERVER"), std::string(""));
}
// don't allow empty callsign
if (callSign[0] == '\0') {
rejectCode = RejectBadCallsign;
strcpy(rejectMsg, "The callsign was rejected. Try a different callsign.");
return false;
}
// no spoofing the server name
if (serverSpoofingFilter.filter(callSign)) {
rejectCode = RejectRepeatCallsign;
strcpy(rejectMsg, "The callsign specified is already in use.");
return false;
}
if (!isCallSignReadable()) {
DEBUG2("rejecting unreadable callsign: %s\n", callSign);
rejectCode = RejectBadCallsign;
strcpy(rejectMsg, "The callsign was rejected. Try a different callsign.");
return false;
}
if (!isEMailReadable()) {
DEBUG2("rejecting unreadable player email: %s (%s)\n", callSign, email);
rejectCode = RejectBadEmail;
strcpy(rejectMsg, "The e-mail was rejected. Try a different e-mail.");
return false;
}
return true;
};
const char *PlayerInfo::getCallSign() const {
return callSign;
};
void PlayerInfo::cleanCallSign() {
char *sp = callSign;
char *tp = sp;
// strip leading whitespace from callsign
while (isspace(*sp)) {
sp++;
}
// strip any non-printable characters and ' and " from callsign
do {
if (isprint(*sp) && (*sp != '\'') && (*sp != '"')) {
// override modified clients that might send non-space whitespace
if (isspace(*sp)) {
*sp = ' ';
}
*tp++ = *sp;
}
} while (*++sp);
*tp = *sp;
// strip trailing whitespace from callsign
while (isspace(*--tp)) {
*tp=0;
}
};
bool PlayerInfo::isCallSignReadable() {
// callsign readability filter, make sure there are more alphanum than non
// keep a count of alpha-numerics
int alnumCount = 0;
const char *sp = callSign;
do {
if (isalnum(*sp)) {
alnumCount++;
}
} while (*++sp);
int callsignlen = strlen(callSign);
return (callsignlen <= 4) || ((float)alnumCount / (float)callsignlen > 0.5f);
};
const char *PlayerInfo::getEMail() const {
return email;
};
void PlayerInfo::cleanEMail() {
// strip leading whitespace from email
char *sp = email;
char *tp = sp;
while (isspace(*sp))
sp++;
// strip any non-printable characters and ' and " from email
do {
if (isprint(*sp) && (*sp != '\'') && (*sp != '"')) {
*tp++ = *sp;
}
} while (*++sp);
*tp = *sp;
// strip trailing whitespace from email
while (isspace(*--tp)) {
*tp=0;
}
};
bool PlayerInfo::isEMailReadable() {
// email/"team" readability filter, make sure there are more
// alphanum than non
int emailAlnumCount = 0;
char *sp = email;
do {
if (isalnum(*sp)) {
emailAlnumCount++;
}
} while (*++sp);
int emaillen = strlen(email);
return (emaillen <= 4) || (((float)emailAlnumCount / (float)emaillen) > 0.5);
};
void *PlayerInfo::packVirtualFlagCapture(void *buf) {
buf = nboPackUShort(buf, uint16_t(int(team) - 1));
buf = nboPackUShort(buf, uint16_t(1 + (int(team) % 4)));
return buf;
};
bool PlayerInfo::isTeam(TeamColor _team) const {
return team == _team;
};
bool PlayerInfo::isObserver() const {
return team == ObserverTeam;
};
TeamColor PlayerInfo::getTeam() {
return team;
};
void PlayerInfo::setTeam(TeamColor _team) {
team = _team;
};
void PlayerInfo::wasARabbit() {
team = RogueTeam;
wasRabbit = true;
};
void PlayerInfo::wasNotARabbit() {
wasRabbit = false;
};
bool PlayerInfo::isARabbitKill(PlayerInfo &victim) {
return wasRabbit || victim.team == RabbitTeam;
};
void PlayerInfo::resetFlag() {
flag = -1;
lastFlagDropTime = TimeKeeper::getCurrent();
};
bool PlayerInfo::haveFlag() const {
return flag >= 0;
}
int PlayerInfo::getFlag() const {
return flag;
};
void PlayerInfo::setFlag(int _flag) {
flag = _flag;
};
bool PlayerInfo::isFlagTransitSafe() {
return TimeKeeper::getCurrent() - lastFlagDropTime >= 2.0f;
};
const char *PlayerInfo::getClientVersion() {
return clientVersion.c_str();
};
void *PlayerInfo::setClientVersion(size_t length, void *buf) {
char *versionString = new char[length];
buf = nboUnpackString(buf, versionString, length);
clientVersion = std::string(versionString);
delete[] versionString;
DEBUG2("Player %s [%d] sent version string: %s\n",
callSign, playerIndex, clientVersion.c_str());
return buf;
}
std::string PlayerInfo::getIdleStat() {
TimeKeeper now = TimeKeeper::getCurrent();
std::string reply;
if ((state > PlayerInLimbo) && (team != ObserverTeam)) {
reply = string_util::format("%-16s : %4ds", callSign,
int(now - lastupdate));
if (paused) {
reply += string_util::format(" paused %4ds", int(now - pausedSince));
}
}
return reply;
};
bool PlayerInfo::canBeRabbit(bool relaxing) {
if (paused || notResponding || (team == ObserverTeam))
return false;
return relaxing ? (state > PlayerInLimbo) : (state == PlayerAlive);
};
void PlayerInfo::setPaused(bool _paused) {
paused = _paused;
pausedSince = TimeKeeper::getCurrent();
};
bool PlayerInfo::isTooMuchIdling(TimeKeeper tm, float kickThresh) {
bool idling = false;
if ((state > PlayerInLimbo) && (team != ObserverTeam)) {
int idletime = (int)(tm - lastupdate);
int pausetime = 0;
if (paused && tm - pausedSince > idletime)
pausetime = (int)(tm - pausedSince);
idletime = idletime > pausetime ? idletime : pausetime;
if (idletime > (tm - lastmsg < kickThresh ? 3 * kickThresh : kickThresh)) {
DEBUG1("Kicking player %s [%d] idle %d\n", callSign, playerIndex,
idletime);
idling = true;
}
}
return idling;
};
bool PlayerInfo::hasStartedToNotRespond() {
float notRespondingTime = BZDB.eval(StateDatabase::BZDB_NOTRESPONDINGTIME);
bool startingToNotRespond = false;
if (state > PlayerInLimbo) {
bool oldnr = notResponding;
notResponding = (TimeKeeper::getCurrent() - lastupdate)
> notRespondingTime;
if (!oldnr && notResponding)
startingToNotRespond = true;
}
return startingToNotRespond;
}
void PlayerInfo::hasSent(char message[]) {
lastmsg = TimeKeeper::getCurrent();
DEBUG1("Player %s [%d]: %s\n", callSign, playerIndex, message);
};
bool PlayerInfo::hasPlayedEarly() {
bool returnValue = playedEarly;
playedEarly = false;
return returnValue;
};
void PlayerInfo::setPlayedEarly() {
playedEarly = true;
};
void PlayerInfo::updateIdleTime() {
lastupdate = TimeKeeper::getCurrent();
};
void PlayerInfo::setReplayState(PlayerReplayState state) {
replayState = state;
}
PlayerReplayState PlayerInfo::getReplayState()
{
return replayState;
}
void PlayerInfo::setTrackerID(unsigned short int t)
{
tracker = t;
}
unsigned short int PlayerInfo::trackerID()
{
return tracker;
}
// Local Variables: ***
// mode:C++ ***
// tab-width: 8 ***
// c-basic-offset: 2 ***
// indent-tabs-mode: t ***
// End: ***
// ex: shiftwidth=2 tabstop=8
<|endoftext|>
|
<commit_before>// Copyright (c) 2017 The Bitcoin developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "cashaddr.h"
#include "cashaddrenc.h"
#include "chainparams.h"
#include "random.h"
#include "test/test_bitcoin.h"
#include "uint256.h"
#include <boost/test/unit_test.hpp>
namespace {
std::vector<std::string> GetNetworks() {
return {CBaseChainParams::MAIN, CBaseChainParams::TESTNET,
CBaseChainParams::REGTEST};
}
uint160 insecure_GetRandUInt160(FastRandomContext &rand) {
uint160 n;
for (uint8_t *c = n.begin(); c != n.end(); ++c) {
*c = static_cast<uint8_t>(rand.rand32());
}
return n;
}
class DstTypeChecker : public boost::static_visitor<void> {
public:
void operator()(const CKeyID &id) { isKey = true; }
void operator()(const CScriptID &id) { isScript = true; }
void operator()(const CNoDestination &) {}
static bool IsScriptDst(const CTxDestination &d) {
DstTypeChecker checker;
boost::apply_visitor(checker, d);
return checker.isScript;
}
static bool IsKeyDst(const CTxDestination &d) {
DstTypeChecker checker;
boost::apply_visitor(checker, d);
return checker.isKey;
}
private:
DstTypeChecker() : isKey(false), isScript(false) {}
bool isKey;
bool isScript;
};
} // anon ns
BOOST_FIXTURE_TEST_SUITE(cashaddrenc_tests, BasicTestingSetup)
BOOST_AUTO_TEST_CASE(encode_decode) {
std::vector<CTxDestination> toTest = {CNoDestination{},
CKeyID(uint160S("badf00d")),
CScriptID(uint160S("f00dbad"))};
for (auto dst : toTest) {
for (auto net : GetNetworks()) {
std::string encoded = EncodeCashAddr(dst, Params(net));
CTxDestination decoded = DecodeCashAddr(encoded, Params(net));
BOOST_CHECK(dst == decoded);
}
}
}
// Check that an encoded cash address is not valid on another network.
BOOST_AUTO_TEST_CASE(invalid_on_wrong_network) {
const CTxDestination dst = CKeyID(uint160S("c0ffee"));
const CTxDestination invalidDst = CNoDestination{};
for (auto net : GetNetworks()) {
for (auto otherNet : GetNetworks()) {
if (net == otherNet) continue;
std::string encoded = EncodeCashAddr(dst, Params(net));
CTxDestination decoded = DecodeCashAddr(encoded, Params(otherNet));
BOOST_CHECK(decoded != dst);
BOOST_CHECK(decoded == invalidDst);
}
}
}
BOOST_AUTO_TEST_CASE(random_dst) {
FastRandomContext rand(true);
const size_t NUM_TESTS = 5000;
const CChainParams ¶ms = Params(CBaseChainParams::MAIN);
for (size_t i = 0; i < NUM_TESTS; ++i) {
uint160 hash = insecure_GetRandUInt160(rand);
const CTxDestination dst_key = CKeyID(hash);
const CTxDestination dst_scr = CScriptID(hash);
const std::string encoded_key = EncodeCashAddr(dst_key, params);
const CTxDestination decoded_key = DecodeCashAddr(encoded_key, params);
const std::string encoded_scr = EncodeCashAddr(dst_scr, params);
const CTxDestination decoded_scr = DecodeCashAddr(encoded_scr, params);
std::string err("cashaddr failed for hash: ");
err += hash.ToString();
BOOST_CHECK_MESSAGE(dst_key == decoded_key, err);
BOOST_CHECK_MESSAGE(dst_scr == decoded_scr, err);
BOOST_CHECK_MESSAGE(DstTypeChecker::IsKeyDst(decoded_key), err);
BOOST_CHECK_MESSAGE(DstTypeChecker::IsScriptDst(decoded_scr), err);
}
}
/**
* Cashaddr payload made of 5-bit nibbles. The last one is padded. When
* converting back to bytes, this extra padding is truncated. In order to ensure
* cashaddr are cannonicals, we check that the data we truncate is zeroed.
*/
BOOST_AUTO_TEST_CASE(check_padding) {
uint8_t version = 0;
std::vector<uint8_t> data = {version};
for (size_t i = 0; i < 33; ++i) {
data.push_back(1);
}
BOOST_CHECK_EQUAL(data.size(), 34);
const CTxDestination nodst = CNoDestination{};
const CChainParams params = Params(CBaseChainParams::MAIN);
for (uint8_t i = 0; i < 32; i++) {
data[data.size() - 1] = i;
std::string fake = cashaddr::Encode(params.CashAddrPrefix(), data);
CTxDestination dst = DecodeCashAddr(fake, params);
// We have 168 bits of payload encoded as 170 bits in 5 bits nimbles. As
// a result, we must have 2 zeros.
if (i & 0x03) {
BOOST_CHECK(dst == nodst);
} else {
BOOST_CHECK(dst != nodst);
}
}
}
/**
* We ensure type is extracted properly from the version.
*/
BOOST_AUTO_TEST_CASE(check_type) {
std::vector<uint8_t> data;
data.resize(34);
const CChainParams params = Params(CBaseChainParams::MAIN);
for (uint8_t v = 0; v < 16; v++) {
std::fill(begin(data), end(data), 0);
data[0] = v;
auto content = DecodeCashAddrContent(
cashaddr::Encode(params.CashAddrPrefix(), data), params);
BOOST_CHECK_EQUAL(content.type, v);
BOOST_CHECK_EQUAL(content.hash.size(), 20);
// Check that using the reserved bit result in a failure.
data[0] |= 0x10;
content = DecodeCashAddrContent(
cashaddr::Encode(params.CashAddrPrefix(), data), params);
BOOST_CHECK_EQUAL(content.type, 0);
BOOST_CHECK_EQUAL(content.hash.size(), 0);
}
}
/**
* We ensure size is extracted and checked properly.
*/
BOOST_AUTO_TEST_CASE(check_size) {
const CTxDestination nodst = CNoDestination{};
const CChainParams params = Params(CBaseChainParams::MAIN);
// Mapp all possible size bits in the version to the expected size of the
// hash in bytes.
std::vector<std::pair<uint8_t, uint32_t>> sizes = {
{0, 20}, {1, 24}, {2, 28}, {3, 32}, {4, 40}, {5, 48}, {6, 56}, {7, 64},
};
std::vector<uint8_t> data;
for (auto ps : sizes) {
size_t expectedSize = (12 + ps.second * 8) / 5;
data.resize(expectedSize);
std::fill(begin(data), end(data), 0);
data[1] = ps.first << 2;
auto content = DecodeCashAddrContent(
cashaddr::Encode(params.CashAddrPrefix(), data), params);
BOOST_CHECK_EQUAL(content.type, 0);
BOOST_CHECK_EQUAL(content.hash.size(), ps.second);
data.push_back(0);
content = DecodeCashAddrContent(
cashaddr::Encode(params.CashAddrPrefix(), data), params);
BOOST_CHECK_EQUAL(content.type, 0);
BOOST_CHECK_EQUAL(content.hash.size(), 0);
data.pop_back();
data.pop_back();
content = DecodeCashAddrContent(
cashaddr::Encode(params.CashAddrPrefix(), data), params);
BOOST_CHECK_EQUAL(content.type, 0);
BOOST_CHECK_EQUAL(content.hash.size(), 0);
}
}
BOOST_AUTO_TEST_CASE(test_addresses) {
const CChainParams params = Params(CBaseChainParams::MAIN);
std::vector<std::vector<uint8_t>> hash{
{118, 160, 64, 83, 189, 160, 168, 139, 218, 81,
119, 184, 106, 21, 195, 178, 159, 85, 152, 115},
{203, 72, 18, 50, 41, 156, 213, 116, 49, 81,
172, 75, 45, 99, 174, 25, 142, 123, 176, 169},
{1, 31, 40, 228, 115, 201, 95, 64, 19, 215,
213, 62, 197, 251, 195, 180, 45, 248, 237, 16}};
std::vector<std::string> pubkey = {
"bitcoincash:qpm2qsznhks23z7629mms6s4cwef74vcwvy22gdx6a",
"bitcoincash:qr95sy3j9xwd2ap32xkykttr4cvcu7as4y0qverfuy",
"bitcoincash:qqq3728yw0y47sqn6l2na30mcw6zm78dzqre909m2r"};
std::vector<std::string> script = {
"bitcoincash:ppm2qsznhks23z7629mms6s4cwef74vcwvn0h829pq",
"bitcoincash:pr95sy3j9xwd2ap32xkykttr4cvcu7as4yc93ky28e",
"bitcoincash:pqq3728yw0y47sqn6l2na30mcw6zm78dzq5ucqzc37"};
for (size_t i = 0; i < hash.size(); ++i) {
const CTxDestination dstKey = CKeyID(uint160(hash[i]));
BOOST_CHECK_EQUAL(pubkey[i], EncodeCashAddr(dstKey, params));
const CTxDestination dstScript = CScriptID(uint160(hash[i]));
BOOST_CHECK_EQUAL(script[i], EncodeCashAddr(dstScript, params));
}
}
BOOST_AUTO_TEST_SUITE_END()
<commit_msg>Fix cashaddrenc_tests/check_size<commit_after>// Copyright (c) 2017 The Bitcoin developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "cashaddr.h"
#include "cashaddrenc.h"
#include "chainparams.h"
#include "random.h"
#include "test/test_bitcoin.h"
#include "uint256.h"
#include <boost/test/unit_test.hpp>
namespace {
std::vector<std::string> GetNetworks() {
return {CBaseChainParams::MAIN, CBaseChainParams::TESTNET,
CBaseChainParams::REGTEST};
}
uint160 insecure_GetRandUInt160(FastRandomContext &rand) {
uint160 n;
for (uint8_t *c = n.begin(); c != n.end(); ++c) {
*c = static_cast<uint8_t>(rand.rand32());
}
return n;
}
class DstTypeChecker : public boost::static_visitor<void> {
public:
void operator()(const CKeyID &id) { isKey = true; }
void operator()(const CScriptID &id) { isScript = true; }
void operator()(const CNoDestination &) {}
static bool IsScriptDst(const CTxDestination &d) {
DstTypeChecker checker;
boost::apply_visitor(checker, d);
return checker.isScript;
}
static bool IsKeyDst(const CTxDestination &d) {
DstTypeChecker checker;
boost::apply_visitor(checker, d);
return checker.isKey;
}
private:
DstTypeChecker() : isKey(false), isScript(false) {}
bool isKey;
bool isScript;
};
} // anon ns
BOOST_FIXTURE_TEST_SUITE(cashaddrenc_tests, BasicTestingSetup)
BOOST_AUTO_TEST_CASE(encode_decode) {
std::vector<CTxDestination> toTest = {CNoDestination{},
CKeyID(uint160S("badf00d")),
CScriptID(uint160S("f00dbad"))};
for (auto dst : toTest) {
for (auto net : GetNetworks()) {
std::string encoded = EncodeCashAddr(dst, Params(net));
CTxDestination decoded = DecodeCashAddr(encoded, Params(net));
BOOST_CHECK(dst == decoded);
}
}
}
// Check that an encoded cash address is not valid on another network.
BOOST_AUTO_TEST_CASE(invalid_on_wrong_network) {
const CTxDestination dst = CKeyID(uint160S("c0ffee"));
const CTxDestination invalidDst = CNoDestination{};
for (auto net : GetNetworks()) {
for (auto otherNet : GetNetworks()) {
if (net == otherNet) continue;
std::string encoded = EncodeCashAddr(dst, Params(net));
CTxDestination decoded = DecodeCashAddr(encoded, Params(otherNet));
BOOST_CHECK(decoded != dst);
BOOST_CHECK(decoded == invalidDst);
}
}
}
BOOST_AUTO_TEST_CASE(random_dst) {
FastRandomContext rand(true);
const size_t NUM_TESTS = 5000;
const CChainParams ¶ms = Params(CBaseChainParams::MAIN);
for (size_t i = 0; i < NUM_TESTS; ++i) {
uint160 hash = insecure_GetRandUInt160(rand);
const CTxDestination dst_key = CKeyID(hash);
const CTxDestination dst_scr = CScriptID(hash);
const std::string encoded_key = EncodeCashAddr(dst_key, params);
const CTxDestination decoded_key = DecodeCashAddr(encoded_key, params);
const std::string encoded_scr = EncodeCashAddr(dst_scr, params);
const CTxDestination decoded_scr = DecodeCashAddr(encoded_scr, params);
std::string err("cashaddr failed for hash: ");
err += hash.ToString();
BOOST_CHECK_MESSAGE(dst_key == decoded_key, err);
BOOST_CHECK_MESSAGE(dst_scr == decoded_scr, err);
BOOST_CHECK_MESSAGE(DstTypeChecker::IsKeyDst(decoded_key), err);
BOOST_CHECK_MESSAGE(DstTypeChecker::IsScriptDst(decoded_scr), err);
}
}
/**
* Cashaddr payload made of 5-bit nibbles. The last one is padded. When
* converting back to bytes, this extra padding is truncated. In order to ensure
* cashaddr are cannonicals, we check that the data we truncate is zeroed.
*/
BOOST_AUTO_TEST_CASE(check_padding) {
uint8_t version = 0;
std::vector<uint8_t> data = {version};
for (size_t i = 0; i < 33; ++i) {
data.push_back(1);
}
BOOST_CHECK_EQUAL(data.size(), 34);
const CTxDestination nodst = CNoDestination{};
const CChainParams params = Params(CBaseChainParams::MAIN);
for (uint8_t i = 0; i < 32; i++) {
data[data.size() - 1] = i;
std::string fake = cashaddr::Encode(params.CashAddrPrefix(), data);
CTxDestination dst = DecodeCashAddr(fake, params);
// We have 168 bits of payload encoded as 170 bits in 5 bits nimbles. As
// a result, we must have 2 zeros.
if (i & 0x03) {
BOOST_CHECK(dst == nodst);
} else {
BOOST_CHECK(dst != nodst);
}
}
}
/**
* We ensure type is extracted properly from the version.
*/
BOOST_AUTO_TEST_CASE(check_type) {
std::vector<uint8_t> data;
data.resize(34);
const CChainParams params = Params(CBaseChainParams::MAIN);
for (uint8_t v = 0; v < 16; v++) {
std::fill(begin(data), end(data), 0);
data[0] = v;
auto content = DecodeCashAddrContent(
cashaddr::Encode(params.CashAddrPrefix(), data), params);
BOOST_CHECK_EQUAL(content.type, v);
BOOST_CHECK_EQUAL(content.hash.size(), 20);
// Check that using the reserved bit result in a failure.
data[0] |= 0x10;
content = DecodeCashAddrContent(
cashaddr::Encode(params.CashAddrPrefix(), data), params);
BOOST_CHECK_EQUAL(content.type, 0);
BOOST_CHECK_EQUAL(content.hash.size(), 0);
}
}
/**
* We ensure size is extracted and checked properly.
*/
BOOST_AUTO_TEST_CASE(check_size) {
const CTxDestination nodst = CNoDestination{};
const CChainParams params = Params(CBaseChainParams::MAIN);
// Mapp all possible size bits in the version to the expected size of the
// hash in bytes.
std::vector<std::pair<uint8_t, uint32_t>> sizes = {
{0, 20}, {1, 24}, {2, 28}, {3, 32}, {4, 40}, {5, 48}, {6, 56}, {7, 64},
};
std::vector<uint8_t> data;
for (auto ps : sizes) {
// Number of bytes required for a 5-bit packed version of a hash, with
// version byte. Add half a byte(4) so integer math provides the next
// multiple-of-5 that would fit all the data.
size_t expectedSize = (8 * (1 + ps.second) + 4) / 5;
data.resize(expectedSize);
std::fill(begin(data), end(data), 0);
// After conversion from 8 bit packing to 5 bit packing, the size will
// be in the second 5-bit group, shifted left twice.
data[1] = ps.first << 2;
auto content = DecodeCashAddrContent(
cashaddr::Encode(params.CashAddrPrefix(), data), params);
BOOST_CHECK_EQUAL(content.type, 0);
BOOST_CHECK_EQUAL(content.hash.size(), ps.second);
data.push_back(0);
content = DecodeCashAddrContent(
cashaddr::Encode(params.CashAddrPrefix(), data), params);
BOOST_CHECK_EQUAL(content.type, 0);
BOOST_CHECK_EQUAL(content.hash.size(), 0);
data.pop_back();
data.pop_back();
content = DecodeCashAddrContent(
cashaddr::Encode(params.CashAddrPrefix(), data), params);
BOOST_CHECK_EQUAL(content.type, 0);
BOOST_CHECK_EQUAL(content.hash.size(), 0);
}
}
BOOST_AUTO_TEST_CASE(test_addresses) {
const CChainParams params = Params(CBaseChainParams::MAIN);
std::vector<std::vector<uint8_t>> hash{
{118, 160, 64, 83, 189, 160, 168, 139, 218, 81,
119, 184, 106, 21, 195, 178, 159, 85, 152, 115},
{203, 72, 18, 50, 41, 156, 213, 116, 49, 81,
172, 75, 45, 99, 174, 25, 142, 123, 176, 169},
{1, 31, 40, 228, 115, 201, 95, 64, 19, 215,
213, 62, 197, 251, 195, 180, 45, 248, 237, 16}};
std::vector<std::string> pubkey = {
"bitcoincash:qpm2qsznhks23z7629mms6s4cwef74vcwvy22gdx6a",
"bitcoincash:qr95sy3j9xwd2ap32xkykttr4cvcu7as4y0qverfuy",
"bitcoincash:qqq3728yw0y47sqn6l2na30mcw6zm78dzqre909m2r"};
std::vector<std::string> script = {
"bitcoincash:ppm2qsznhks23z7629mms6s4cwef74vcwvn0h829pq",
"bitcoincash:pr95sy3j9xwd2ap32xkykttr4cvcu7as4yc93ky28e",
"bitcoincash:pqq3728yw0y47sqn6l2na30mcw6zm78dzq5ucqzc37"};
for (size_t i = 0; i < hash.size(); ++i) {
const CTxDestination dstKey = CKeyID(uint160(hash[i]));
BOOST_CHECK_EQUAL(pubkey[i], EncodeCashAddr(dstKey, params));
const CTxDestination dstScript = CScriptID(uint160(hash[i]));
BOOST_CHECK_EQUAL(script[i], EncodeCashAddr(dstScript, params));
}
}
BOOST_AUTO_TEST_SUITE_END()
<|endoftext|>
|
<commit_before>//-----------------------------------------------------------------------bl-
//--------------------------------------------------------------------------
//
// GRINS - General Reacting Incompressible Navier-Stokes
//
// Copyright (C) 2014-2015 Paul T. Bauman, Roy H. Stogner
// Copyright (C) 2010-2013 The PECOS Development Team
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the Version 2.1 GNU Lesser General
// Public License as published by the Free Software Foundation.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc. 51 Franklin Street, Fifth Floor,
// Boston, MA 02110-1301 USA
//
//-----------------------------------------------------------------------el-
#include "grins_config.h"
#ifdef GRINS_HAVE_CPPUNIT
#include <cppunit/extensions/HelperMacros.h>
#include <cppunit/TestCase.h>
// Testing headers
#include "test_comm.h"
#include "grins_test_paths.h"
#include "system_helper.h"
// GRINS
#include "grins/default_bc_builder.h"
namespace GRINSTesting
{
class DefaultBCBuilderTest : public CppUnit::TestCase,
public GRINS::DefaultBCBuilder // So we can test proctected methods
{
public:
CPPUNIT_TEST_SUITE( DefaultBCBuilderTest );
CPPUNIT_TEST_SUITE_END();
public:
};
CPPUNIT_TEST_SUITE_REGISTRATION( DefaultBCBuilderTest );
} // end namespace GRINSTesting
#endif // GRINS_HAVE_CPPUNIT
<commit_msg>Add test_parse_and_build_bc_id_map unit test<commit_after>//-----------------------------------------------------------------------bl-
//--------------------------------------------------------------------------
//
// GRINS - General Reacting Incompressible Navier-Stokes
//
// Copyright (C) 2014-2015 Paul T. Bauman, Roy H. Stogner
// Copyright (C) 2010-2013 The PECOS Development Team
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the Version 2.1 GNU Lesser General
// Public License as published by the Free Software Foundation.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc. 51 Franklin Street, Fifth Floor,
// Boston, MA 02110-1301 USA
//
//-----------------------------------------------------------------------el-
#include "grins_config.h"
#ifdef GRINS_HAVE_CPPUNIT
#include <cppunit/extensions/HelperMacros.h>
#include <cppunit/TestCase.h>
// Testing headers
#include "test_comm.h"
#include "grins_test_paths.h"
#include "system_helper.h"
// GRINS
#include "grins/default_bc_builder.h"
namespace GRINSTesting
{
class DefaultBCBuilderTest : public CppUnit::TestCase,
public GRINS::DefaultBCBuilder // So we can test proctected methods
{
public:
CPPUNIT_TEST_SUITE( DefaultBCBuilderTest );
CPPUNIT_TEST( test_parse_and_build_bc_id_map );
CPPUNIT_TEST_SUITE_END();
public:
void test_parse_and_build_bc_id_map()
{
std::string filename = std::string(GRINS_TEST_UNIT_INPUT_SRCDIR)+"/default_bc_builder.in";
GetPot input(filename);
std::map<std::string,std::set<GRINS::BoundaryID> > bc_id_map;
this->parse_and_build_bc_id_map(input,bc_id_map);
// Make sure we have the right sections
CPPUNIT_ASSERT_EQUAL(3,(int)bc_id_map.size());
CPPUNIT_ASSERT( bc_id_map.find("Hot") != bc_id_map.end() );
CPPUNIT_ASSERT( bc_id_map.find("Together") != bc_id_map.end() );
CPPUNIT_ASSERT( bc_id_map.find("Cold") != bc_id_map.end() );
// Make sure we have the right number and values of the bc ids
{
std::set<GRINS::BoundaryID> bc_ids = bc_id_map["Hot"];
CPPUNIT_ASSERT_EQUAL(1,(int)bc_ids.size());
CPPUNIT_ASSERT(bc_ids.find(0) != bc_ids.end());
}
// Make sure we have the right number and values of the bc ids
{
std::set<GRINS::BoundaryID> bc_ids = bc_id_map["Together"];
CPPUNIT_ASSERT_EQUAL(2,(int)bc_ids.size());
CPPUNIT_ASSERT(bc_ids.find(1) != bc_ids.end());
CPPUNIT_ASSERT(bc_ids.find(2) != bc_ids.end());
}
// Make sure we have the right number and values of the bc ids
{
std::set<GRINS::BoundaryID> bc_ids = bc_id_map["Cold"];
CPPUNIT_ASSERT_EQUAL(1,(int)bc_ids.size());
CPPUNIT_ASSERT(bc_ids.find(3) != bc_ids.end());
}
}
};
CPPUNIT_TEST_SUITE_REGISTRATION( DefaultBCBuilderTest );
} // end namespace GRINSTesting
#endif // GRINS_HAVE_CPPUNIT
<|endoftext|>
|
<commit_before>#include "UASQuickTabView.h"
#include "ui_UASQuickTabView.h"
#include <QTextCodec>
#include <QDebug>
#include <QTableWidget>
#include <QtGui>
UASQuickTabView::UASQuickTabView(QWidget *parent) :
ui(new Ui::UASQuickTabView)
{
ui->setupUi(this);
// this->setLayout(ui->gridLayout);
// ui->gridLayout->setContentsMargins(0,0,0,0);
// ui->gridLayout->setHorizontalSpacing(0);
// ui->gridLayout->setVerticalSpacing(0);
// ui->gridLayout->setSpacing(0);
// ui->gridLayout->setMargin(0);
QStringList nameList;// = new QStringList();
// nameList.append("Широта:");
// nameList.append("Долгота:");
// nameList.append("Высота:");
// nameList.append("Курс:");
// nameList.append("Крен:");
// nameList.append("Тангаж:");
nameList.append(tr("Latitude:"));
nameList.append(tr("Longitude:"));
nameList.append(tr("Altitude:"));
nameList.append(tr("Roll:"));
nameList.append(tr("Pitch:"));
nameList.append(tr("Yaw:"));
fieldNameList << "M24:GLOBAL_POSITION_INT.lat"
<< "M24:GLOBAL_POSITION_INT.lon"
<< "M24:GLOBAL_POSITION_INT.alt"
<< "M24:ATTITUDE.roll"
<< "M24:ATTITUDE.pitch"
<< "M24:ATTITUDE.yaw";
foreach(QString str, fieldNameList){
uasPropertyValueMap.insert(str, 0.0);
}
QTextCodec::setCodecForLocale(QTextCodec::codecForName("UTF-8"));
ui->tableWidget->setColumnCount(2);
ui->tableWidget->setRowCount(nameList.count());
ui->tableWidget->setLineWidth(1);
ui->tableWidget->setFrameStyle(QFrame::NoFrame);
//ui->tableWidget->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
ui->tableWidget->setStyleSheet("gridline-color : dimgray");
ui->tableWidget->setWindowFlags(/*ui->tableWidget->windowFlags()*/Qt::Widget | Qt::FramelessWindowHint);
//tableFont = new QFont("Times New Roman", 14, 3);
// tableFont.setFamily("Times New Roman");
tableFont.setPixelSize(14);
tableFont.setBold(3);
for(int i = 0; i < nameList.count(); i++) {
/* Add first column that shows lable names.*/
QTableWidgetItem* item = new QTableWidgetItem();
Q_ASSERT(item);
if (item) {
item->setText(nameList.at(i));
tableNameList.append(item);
item->setFont(tableFont);
item->setFlags(item->flags() ^ Qt::ItemIsEditable ^ Qt::ItemIsSelectable);
ui->tableWidget->setItem(i, 0, item);
}
/* Add column with values.*/
item = new QTableWidgetItem();
Q_ASSERT(item);
if (item) {
tableValueList.append(item);
item->setFont(tableFont);
item->setText("0.0");
item->setFlags(item->flags() ^ Qt::ItemIsEditable ^ Qt::ItemIsSelectable);
ui->tableWidget->setItem(i, 1, item);
}
}
setTableGeometry();
updateTimer = new QTimer(this);
connect(updateTimer,SIGNAL(timeout()),this,SLOT(updateTimerTick()));
updateTimer->start(1000);
// testTimerValue = true;
// testTimer = new QTimer(this);
// testTimer->setSingleShot(false);
// connect(testTimer,SIGNAL(timeout()),this,SLOT(testTimerExpired()));
// testTimer->start(750);
}
UASQuickTabView::~UASQuickTabView()
{
delete ui;
foreach (QTableWidgetItem* item, tableNameList) {
delete item;
}
foreach (QTableWidgetItem* item, tableValueList) {
delete item;
}
delete updateTimer;
}
void UASQuickTabView::addSource(MAVLinkDecoder *decoder)
{
connect(decoder,SIGNAL(valueChanged(int,QString,QString,QVariant,quint64)),this,SLOT(valueChanged(int,QString,QString,QVariant,quint64)));
}
void UASQuickTabView::valueChanged(const int uasId, const QString& name, const QString& unit, const QVariant &variant, const quint64 msec)
{
Q_UNUSED(uasId);
Q_UNUSED(unit);
Q_UNUSED(msec);
bool ok;
double value = variant.toDouble(&ok);
QMetaType::Type metaType = static_cast<QMetaType::Type>(variant.type());
if(!ok || metaType == QMetaType::QString || metaType == QMetaType::QByteArray)
return;
//qDebug()<<name<<" "<<value;
// if (!uasPropertyValueMap.contains(name))
// {
// if (quickViewSelectDialog)
// {
// quickViewSelectDialog->addItem(name);
// }
// }
if((name == "M24:GLOBAL_POSITION_INT.lat")||(name == "M24:GLOBAL_POSITION_INT.lon"))
uasPropertyValueMap[name] = value/10000000;
else if(name == "M24:GLOBAL_POSITION_INT.alt")
uasPropertyValueMap[name] = value/1000;
else if((name == "M24:ATTITUDE.roll")||(name == "M24:ATTITUDE.pitch")||(name == "M24:ATTITUDE.yaw"))
uasPropertyValueMap[name] = value/M_PI*180;
}
void UASQuickTabView::updateTimerTick()
{
for(int i = 0; i < fieldNameList.size(); i++){
//QString str = QString::number(uasPropertyValueMap[fieldNameList.at(i)]);
QString str = formText(fieldNameList.at(i), uasPropertyValueMap[fieldNameList.at(i)]);
ui->tableWidget->item(i,1)->setText(str);
}
}
//void UASQuickTabView::testTimerExpired(){
// if(testTimerValue == true){
// valueChanged(0,"M24:GLOBAL_POSITION_INT.lat","unit",538893530,0);
// valueChanged(0,"M24:GLOBAL_POSITION_INT.lon","unit",275296780,0);
// valueChanged(0,"M24:GLOBAL_POSITION_INT.alt","unit",272000,0);
// valueChanged(0,"M24:ATTITUDE.roll","unit",0.36814,0);
// valueChanged(0,"M24:ATTITUDE.pitch","unit",0.56715,0);
// valueChanged(0,"M24:ATTITUDE.yaw","unit",0.24715,0);
// testTimerValue = false;
// }
// else{
// valueChanged(0,"M24:GLOBAL_POSITION_INT.lat","unit",-549993530,0);
// valueChanged(0,"M24:GLOBAL_POSITION_INT.lon","unit",-277796780,0);
// valueChanged(0,"M24:GLOBAL_POSITION_INT.alt","unit",284000,0);
// valueChanged(0,"M24:ATTITUDE.roll","unit",0.35614,0);
// valueChanged(0,"M24:ATTITUDE.pitch","unit",0.46815,0);
// valueChanged(0,"M24:ATTITUDE.yaw","unit",0.67895,0);
// testTimerValue = true;
// }
//}
void UASQuickTabView::setTableGeometry(){
int rowCount = ui->tableWidget->rowCount();
//ui->tableWidget->setWi
//ui->tableWidget->verticalHeader()->sectionResized();
ui->tableWidget->resize(this->width(), this->height());
// ui->tableWidget->setColumnWidth(0, (int)((double)(ui->tableWidget->width())/2.0));
// ui->tableWidget->setColumnWidth(1, (int)((double)(ui->tableWidget->width())/2.0));
ui->tableWidget->setColumnWidth(0, ((ui->tableWidget->width())/2));
ui->tableWidget->setColumnWidth(1, ((ui->tableWidget->width())/2 + (ui->tableWidget->width())%2));
for(int i = 0; i < ui->tableWidget->rowCount() - 1; i++) {
ui->tableWidget->setRowHeight(i, (ui->tableWidget->height())/rowCount);
//ui->tableWidget->setRowHeight(i, (ui->tableWidget->height())/6);
}
ui->tableWidget->setRowHeight(ui->tableWidget->rowCount() - 1, ((ui->tableWidget->height())/rowCount) + ((ui->tableWidget->height())%rowCount));
}
QString UASQuickTabView::formText(QString name, double value){
QString str;
if(name == "M24:GLOBAL_POSITION_INT.lat"){
if(value >= 0){
str = QString::number(value,'f',5);
str += 0x00B0;
str += tr(" N");
}
else if(value < 0){
value *=-1;
str = QString::number(value,'f',5);
str += 0x00B0;
str += tr(" S");
}
}
else if(name == "M24:GLOBAL_POSITION_INT.lon"){
if(value >= 0){
str = QString::number(value,'f',5);
str += 0x00B0;
str += tr(" E");
}
else if(value < 0){
value *=-1;
str = QString::number(value,'f',5);
str += 0x00B0;
str += tr(" W");
}
}
else if(name == "M24:GLOBAL_POSITION_INT.alt"){
str = QString::number(value,'f',1);
str +=tr(" m.");
}
else if((name == "M24:ATTITUDE.roll")||(name == "M24:ATTITUDE.pitch")||(name == "M24:ATTITUDE.yaw")){
str = QString::number(value,'f',2);
str += 0x00B0;
}
return str;
}
void UASQuickTabView::resizeEvent(QResizeEvent *event){
setTableGeometry();
}
<commit_msg>Minor fixes. Cleaned up code.<commit_after>#include "UASQuickTabView.h"
#include "ui_UASQuickTabView.h"
#include <QTextCodec>
#include <QDebug>
#include <QTableWidget>
#include <QtGui>
UASQuickTabView::UASQuickTabView(QWidget *parent) :
ui(new Ui::UASQuickTabView)
{
ui->setupUi(this);
// this->setLayout(ui->gridLayout);
// ui->gridLayout->setContentsMargins(0,0,0,0);
// ui->gridLayout->setHorizontalSpacing(0);
// ui->gridLayout->setVerticalSpacing(0);
// ui->gridLayout->setSpacing(0);
// ui->gridLayout->setMargin(0);
QStringList nameList;// = new QStringList();
// nameList.append("Широта:");
// nameList.append("Долгота:");
// nameList.append("Высота:");
// nameList.append("Курс:");
// nameList.append("Крен:");
// nameList.append("Тангаж:");
nameList.append(tr("Latitude:"));
nameList.append(tr("Longitude:"));
nameList.append(tr("Altitude:"));
nameList.append(tr("Roll:"));
nameList.append(tr("Pitch:"));
nameList.append(tr("Yaw:"));
fieldNameList << "M24:GLOBAL_POSITION_INT.lat"
<< "M24:GLOBAL_POSITION_INT.lon"
<< "M24:GLOBAL_POSITION_INT.alt"
<< "M24:ATTITUDE.roll"
<< "M24:ATTITUDE.pitch"
<< "M24:ATTITUDE.yaw";
foreach(QString str, fieldNameList){
uasPropertyValueMap.insert(str, 0.0);
}
QTextCodec::setCodecForLocale(QTextCodec::codecForName("UTF-8"));
ui->tableWidget->setColumnCount(2);
ui->tableWidget->setRowCount(nameList.count());
ui->tableWidget->setLineWidth(1);
ui->tableWidget->setFrameStyle(QFrame::NoFrame);
//ui->tableWidget->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
ui->tableWidget->setStyleSheet("gridline-color : dimgray");
ui->tableWidget->setWindowFlags(/*ui->tableWidget->windowFlags()*/Qt::Widget | Qt::FramelessWindowHint);
//tableFont = new QFont("Times New Roman", 14, 3);
// tableFont.setFamily("Times New Roman");
tableFont.setPixelSize(14);
tableFont.setBold(3);
for(int i = 0; i < nameList.count(); i++) {
/* Add first column that shows lable names.*/
QTableWidgetItem* item = new QTableWidgetItem();
Q_ASSERT(item);
if (item) {
item->setText(nameList.at(i));
tableNameList.append(item);
item->setFont(tableFont);
item->setFlags(item->flags() ^ Qt::ItemIsEditable ^ Qt::ItemIsSelectable);
ui->tableWidget->setItem(i, 0, item);
}
/* Add column with values.*/
item = new QTableWidgetItem();
Q_ASSERT(item);
if (item) {
tableValueList.append(item);
item->setFont(tableFont);
item->setText("0.0");
item->setFlags(item->flags() ^ Qt::ItemIsEditable ^ Qt::ItemIsSelectable);
ui->tableWidget->setItem(i, 1, item);
}
}
setTableGeometry();
updateTimer = new QTimer(this);
connect(updateTimer,SIGNAL(timeout()),this,SLOT(updateTimerTick()));
updateTimer->start(1000);
// testTimerValue = true;
// testTimer = new QTimer(this);
// testTimer->setSingleShot(false);
// connect(testTimer,SIGNAL(timeout()),this,SLOT(testTimerExpired()));
// testTimer->start(750);
}
UASQuickTabView::~UASQuickTabView()
{
delete ui;
foreach (QTableWidgetItem* item, tableNameList) {
delete item;
}
foreach (QTableWidgetItem* item, tableValueList) {
delete item;
}
delete updateTimer;
}
void UASQuickTabView::addSource(MAVLinkDecoder *decoder)
{
connect(decoder,SIGNAL(valueChanged(int,QString,QString,QVariant,quint64)),this,SLOT(valueChanged(int,QString,QString,QVariant,quint64)));
}
void UASQuickTabView::valueChanged(const int uasId, const QString& name, const QString& unit, const QVariant &variant, const quint64 msec)
{
Q_UNUSED(uasId);
Q_UNUSED(unit);
Q_UNUSED(msec);
bool ok;
double value = variant.toDouble(&ok);
QMetaType::Type metaType = static_cast<QMetaType::Type>(variant.type());
if(!ok || metaType == QMetaType::QString || metaType == QMetaType::QByteArray)
return;
//qDebug()<<name<<" "<<value;
// if (!uasPropertyValueMap.contains(name))
// {
// if (quickViewSelectDialog)
// {
// quickViewSelectDialog->addItem(name);
// }
// }
if((name == "M24:GLOBAL_POSITION_INT.lat")||(name == "M24:GLOBAL_POSITION_INT.lon"))
uasPropertyValueMap[name] = value/10000000;
else if(name == "M24:GLOBAL_POSITION_INT.alt")
uasPropertyValueMap[name] = value/1000;
else if((name == "M24:ATTITUDE.roll")||(name == "M24:ATTITUDE.pitch")||(name == "M24:ATTITUDE.yaw"))
uasPropertyValueMap[name] = value/M_PI*180;
}
void UASQuickTabView::updateTimerTick()
{
for(int i = 0; i < fieldNameList.size(); i++){
//QString str = QString::number(uasPropertyValueMap[fieldNameList.at(i)]);
QString str = formText(fieldNameList.at(i), uasPropertyValueMap[fieldNameList.at(i)]);
ui->tableWidget->item(i,1)->setText(str);
}
}
//void UASQuickTabView::testTimerExpired(){
// if(testTimerValue == true){
// valueChanged(0,"M24:GLOBAL_POSITION_INT.lat","unit",538893530,0);
// valueChanged(0,"M24:GLOBAL_POSITION_INT.lon","unit",275296780,0);
// valueChanged(0,"M24:GLOBAL_POSITION_INT.alt","unit",272000,0);
// valueChanged(0,"M24:ATTITUDE.roll","unit",0.36814,0);
// valueChanged(0,"M24:ATTITUDE.pitch","unit",0.56715,0);
// valueChanged(0,"M24:ATTITUDE.yaw","unit",0.24715,0);
// testTimerValue = false;
// }
// else{
// valueChanged(0,"M24:GLOBAL_POSITION_INT.lat","unit",-549993530,0);
// valueChanged(0,"M24:GLOBAL_POSITION_INT.lon","unit",-277796780,0);
// valueChanged(0,"M24:GLOBAL_POSITION_INT.alt","unit",284000,0);
// valueChanged(0,"M24:ATTITUDE.roll","unit",0.35614,0);
// valueChanged(0,"M24:ATTITUDE.pitch","unit",0.46815,0);
// valueChanged(0,"M24:ATTITUDE.yaw","unit",0.67895,0);
// testTimerValue = true;
// }
//}
void UASQuickTabView::setTableGeometry(){
ui->tableWidget->resize(this->width(), this->height());
ui->tableWidget->setColumnWidth(0, ((ui->tableWidget->width())/2));
ui->tableWidget->setColumnWidth(1, ((ui->tableWidget->width())/2 + (ui->tableWidget->width())%2));
int rowCount = ui->tableWidget->rowCount();
for(int i = 0; i < rowCount - 1; i++) {
ui->tableWidget->setRowHeight(i, (ui->tableWidget->height()) / rowCount);
//ui->tableWidget->setRowHeight(i, (ui->tableWidget->height())/6);
}
ui->tableWidget->setRowHeight(rowCount - 1, ((ui->tableWidget->height()) / rowCount) + ((ui->tableWidget->height()) % rowCount));
}
QString UASQuickTabView::formText(QString name, double value){
QString str;
if(name == "M24:GLOBAL_POSITION_INT.lat"){
if(value >= 0){
str = QString::number(value,'f',5);
str += 0x00B0;
str += tr(" N");
}
else if(value < 0){
value *=-1;
str = QString::number(value,'f',5);
str += 0x00B0;
str += tr(" S");
}
}
else if(name == "M24:GLOBAL_POSITION_INT.lon"){
if(value >= 0){
str = QString::number(value,'f',5);
str += 0x00B0;
str += tr(" E");
}
else if(value < 0){
value *=-1;
str = QString::number(value,'f',5);
str += 0x00B0;
str += tr(" W");
}
}
else if(name == "M24:GLOBAL_POSITION_INT.alt"){
str = QString::number(value,'f',1);
str +=tr(" m.");
}
else if((name == "M24:ATTITUDE.roll")||(name == "M24:ATTITUDE.pitch")||(name == "M24:ATTITUDE.yaw")){
str = QString::number(value,'f',2);
str += 0x00B0;
}
return str;
}
void UASQuickTabView::resizeEvent(QResizeEvent *event){
setTableGeometry();
}
<|endoftext|>
|
<commit_before>/*
* Copyright (C) 2011 Collabora Ltd. <http://www.collabora.co.uk/>
* @author Andre Moreira Magalhaes <andre.magalhaes@collabora.co.uk>
* Copyright (C) 2011 David Edmundson <kde@davidedmundson.co.uk>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include "sasl-auth-op.h"
#include "x-telepathy-password-auth-operation.h"
#include <TelepathyQt/PendingVariantMap>
#include <KDebug>
#include <KLocalizedString>
SaslAuthOp::SaslAuthOp(const Tp::AccountPtr &account,
const Tp::ChannelPtr &channel)
: Tp::PendingOperation(channel),
m_account(account),
m_channel(channel),
m_saslIface(channel->interface<Tp::Client::ChannelInterfaceSASLAuthenticationInterface>())
{
connect(m_saslIface->requestAllProperties(),
SIGNAL(finished(Tp::PendingOperation*)),
SLOT(gotProperties(Tp::PendingOperation*)));
}
SaslAuthOp::~SaslAuthOp()
{
}
void SaslAuthOp::gotProperties(Tp::PendingOperation *op)
{
if (op->isError()) {
kWarning() << "Unable to retrieve available SASL mechanisms";
m_channel->requestClose();
setFinishedWithError(op->errorName(), op->errorMessage());
return;
}
Tp::PendingVariantMap *pvm = qobject_cast<Tp::PendingVariantMap*>(op);
QVariantMap props = qdbus_cast<QVariantMap>(pvm->result());
QStringList mechanisms = qdbus_cast<QStringList>(props.value("AvailableMechanisms"));
kDebug() << mechanisms;
if (mechanisms.contains(QLatin1String("X-TELEPATHY-PASSWORD"))) {
// everything ok, we can return from handleChannels now
emit ready(this);
XTelepathyPasswordAuthOperation *authop = new XTelepathyPasswordAuthOperation(m_account, m_saslIface, qdbus_cast<bool>(props.value("CanTryAgain")));
connect (authop, SIGNAL(finished(Tp::PendingOperation*)), SLOT(onAuthOperationFinished(Tp::PendingOperation*)));
uint status = qdbus_cast<uint>(props.value("SASLStatus"));
QString error = qdbus_cast<QString>(props.value("SASLError"));
QVariantMap errorDetails = qdbus_cast<QVariantMap>(props.value("SASLErrorDetails"));
authop->onSASLStatusChanged(status, error, errorDetails);
} else {
kWarning() << "X-TELEPATHY-PASSWORD is the only supported SASL mechanism and is not available:" << mechanisms;
m_channel->requestClose();
setFinishedWithError(TP_QT_ERROR_NOT_IMPLEMENTED,
QLatin1String("X-TELEPATHY-PASSWORD is the only supported SASL mechanism and is not available"));
return;
}
}
void SaslAuthOp::onAuthOperationFinished(Tp::PendingOperation *op)
{
m_channel->requestClose();
if(op->isError()) {
setFinishedWithError(op->errorName(), op->errorMessage());
} else {
setFinished();
}
}
#include "sasl-auth-op.moc"
<commit_msg>Cleanup<commit_after>/*
* Copyright (C) 2011 Collabora Ltd. <http://www.collabora.co.uk/>
* @author Andre Moreira Magalhaes <andre.magalhaes@collabora.co.uk>
* Copyright (C) 2011 David Edmundson <kde@davidedmundson.co.uk>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include "sasl-auth-op.h"
#include "x-telepathy-password-auth-operation.h"
#include <TelepathyQt/PendingVariantMap>
#include <KDebug>
#include <KLocalizedString>
SaslAuthOp::SaslAuthOp(const Tp::AccountPtr &account,
const Tp::ChannelPtr &channel)
: Tp::PendingOperation(channel),
m_account(account),
m_channel(channel),
m_saslIface(channel->interface<Tp::Client::ChannelInterfaceSASLAuthenticationInterface>())
{
connect(m_saslIface->requestAllProperties(),
SIGNAL(finished(Tp::PendingOperation*)),
SLOT(gotProperties(Tp::PendingOperation*)));
}
SaslAuthOp::~SaslAuthOp()
{
}
void SaslAuthOp::gotProperties(Tp::PendingOperation *op)
{
if (op->isError()) {
kWarning() << "Unable to retrieve available SASL mechanisms";
m_channel->requestClose();
setFinishedWithError(op->errorName(), op->errorMessage());
return;
}
Tp::PendingVariantMap *pvm = qobject_cast<Tp::PendingVariantMap*>(op);
QVariantMap props = qdbus_cast<QVariantMap>(pvm->result());
QStringList mechanisms = qdbus_cast<QStringList>(props.value("AvailableMechanisms"));
kDebug() << mechanisms;
if (mechanisms.contains(QLatin1String("X-TELEPATHY-PASSWORD"))) {
// everything ok, we can return from handleChannels now
emit ready(this);
XTelepathyPasswordAuthOperation *authop = new XTelepathyPasswordAuthOperation(m_account, m_saslIface, qdbus_cast<bool>(props.value("CanTryAgain")));
connect (authop,
SIGNAL(finished(Tp::PendingOperation*)),
SLOT(onAuthOperationFinished(Tp::PendingOperation*)));
uint status = qdbus_cast<uint>(props.value("SASLStatus"));
QString error = qdbus_cast<QString>(props.value("SASLError"));
QVariantMap errorDetails = qdbus_cast<QVariantMap>(props.value("SASLErrorDetails"));
authop->onSASLStatusChanged(status, error, errorDetails);
} else {
kWarning() << "X-TELEPATHY-PASSWORD is the only supported SASL mechanism and is not available:" << mechanisms;
m_channel->requestClose();
setFinishedWithError(TP_QT_ERROR_NOT_IMPLEMENTED,
QLatin1String("X-TELEPATHY-PASSWORD is the only supported SASL mechanism and is not available"));
return;
}
}
void SaslAuthOp::onAuthOperationFinished(Tp::PendingOperation *op)
{
m_channel->requestClose();
if(op->isError()) {
setFinishedWithError(op->errorName(), op->errorMessage());
} else {
setFinished();
}
}
#include "sasl-auth-op.moc"
<|endoftext|>
|
<commit_before>/*****************************************************************************
* Media Library
*****************************************************************************
* Copyright (C) 2015 Hugo Beauzée-Luyssen, Videolabs
*
* Authors: Hugo Beauzée-Luyssen<hugo@beauzee.fr>
*
* This program 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 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 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 Street, Fifth Floor, Boston MA 02110-1301, USA.
*****************************************************************************/
#include "Tests.h"
#include "IHistoryEntry.h"
#include "History.h"
#include "Media.h"
class HistoryTest : public Tests
{
};
TEST_F( HistoryTest, InsertMrl )
{
ml->addToHistory( "upnp://stream" );
auto hList = ml->history();
ASSERT_EQ( 1u, hList.size() );
auto h = hList[0];
ASSERT_EQ( nullptr, h->media() );
ASSERT_EQ( h->mrl(), "upnp://stream" );
ASSERT_NE( 0u, h->insertionDate() );
}
TEST_F( HistoryTest, InsertMedia )
{
auto media = ml->addFile( "media.mkv" );
ml->addToHistory( media );
auto hList = ml->history();
ASSERT_EQ( 1u, hList.size() );
auto h = hList[0];
ASSERT_NE( nullptr, h->media() );
ASSERT_EQ( media->id(), h->media()->id() );
ASSERT_EQ( h->mrl(), "" );
ASSERT_NE( 0u, h->insertionDate() );
}
TEST_F( HistoryTest, MaxEntries )
{
for ( auto i = 0u; i < History::MaxEntries; ++i )
{
ml->addToHistory( std::to_string( i ) );
}
auto hList = ml->history();
ASSERT_EQ( History::MaxEntries, hList.size() );
ml->addToHistory( "new-media" );
hList = ml->history();
ASSERT_EQ( History::MaxEntries, hList.size() );
ASSERT_EQ( "1", hList[99]->mrl() );
}
TEST_F( HistoryTest, Ordering )
{
ml->addToHistory( "first-stream" );
std::this_thread::sleep_for( std::chrono::seconds( 1 ) );
ml->addToHistory( "second-stream" );
auto hList = ml->history();
ASSERT_EQ( 2u, hList.size() );
ASSERT_EQ( hList[0]->mrl(), "second-stream" );
ASSERT_EQ( hList[1]->mrl(), "first-stream" );
}
TEST_F( HistoryTest, UpdateInsertionDate )
{
ml->addToHistory( "stream" );
auto hList = ml->history();
ASSERT_EQ( 1u, hList.size() );
auto date = hList[0]->insertionDate();
std::this_thread::sleep_for( std::chrono::seconds( 1 ) );
ml->addToHistory( "stream" );
hList = ml->history();
ASSERT_EQ( 1u, hList.size() );
ASSERT_NE( date, hList[0]->insertionDate() );
}
TEST_F( HistoryTest, DeleteMedia )
{
auto m = ml->addFile( "media.mkv" );
ml->addToHistory( m );
auto hList = ml->history();
ASSERT_EQ( 1u, hList.size() );
auto f = m->files()[0];
m->removeFile( static_cast<File&>( *f ) );
hList = ml->history();
ASSERT_EQ( 0u, hList.size() );
}
<commit_msg>HistoryTests: Remove impossible to predict assertion<commit_after>/*****************************************************************************
* Media Library
*****************************************************************************
* Copyright (C) 2015 Hugo Beauzée-Luyssen, Videolabs
*
* Authors: Hugo Beauzée-Luyssen<hugo@beauzee.fr>
*
* This program 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 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 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 Street, Fifth Floor, Boston MA 02110-1301, USA.
*****************************************************************************/
#include "Tests.h"
#include "IHistoryEntry.h"
#include "History.h"
#include "Media.h"
class HistoryTest : public Tests
{
};
TEST_F( HistoryTest, InsertMrl )
{
ml->addToHistory( "upnp://stream" );
auto hList = ml->history();
ASSERT_EQ( 1u, hList.size() );
auto h = hList[0];
ASSERT_EQ( nullptr, h->media() );
ASSERT_EQ( h->mrl(), "upnp://stream" );
ASSERT_NE( 0u, h->insertionDate() );
}
TEST_F( HistoryTest, InsertMedia )
{
auto media = ml->addFile( "media.mkv" );
ml->addToHistory( media );
auto hList = ml->history();
ASSERT_EQ( 1u, hList.size() );
auto h = hList[0];
ASSERT_NE( nullptr, h->media() );
ASSERT_EQ( media->id(), h->media()->id() );
ASSERT_EQ( h->mrl(), "" );
ASSERT_NE( 0u, h->insertionDate() );
}
TEST_F( HistoryTest, MaxEntries )
{
for ( auto i = 0u; i < History::MaxEntries; ++i )
{
ml->addToHistory( std::to_string( i ) );
}
auto hList = ml->history();
ASSERT_EQ( History::MaxEntries, hList.size() );
ml->addToHistory( "new-media" );
hList = ml->history();
ASSERT_EQ( History::MaxEntries, hList.size() );
}
TEST_F( HistoryTest, Ordering )
{
ml->addToHistory( "first-stream" );
std::this_thread::sleep_for( std::chrono::seconds( 1 ) );
ml->addToHistory( "second-stream" );
auto hList = ml->history();
ASSERT_EQ( 2u, hList.size() );
ASSERT_EQ( hList[0]->mrl(), "second-stream" );
ASSERT_EQ( hList[1]->mrl(), "first-stream" );
}
TEST_F( HistoryTest, UpdateInsertionDate )
{
ml->addToHistory( "stream" );
auto hList = ml->history();
ASSERT_EQ( 1u, hList.size() );
auto date = hList[0]->insertionDate();
std::this_thread::sleep_for( std::chrono::seconds( 1 ) );
ml->addToHistory( "stream" );
hList = ml->history();
ASSERT_EQ( 1u, hList.size() );
ASSERT_NE( date, hList[0]->insertionDate() );
}
TEST_F( HistoryTest, DeleteMedia )
{
auto m = ml->addFile( "media.mkv" );
ml->addToHistory( m );
auto hList = ml->history();
ASSERT_EQ( 1u, hList.size() );
auto f = m->files()[0];
m->removeFile( static_cast<File&>( *f ) );
hList = ml->history();
ASSERT_EQ( 0u, hList.size() );
}
<|endoftext|>
|
<commit_before>#include "gtest/gtest.h"
TEST(FooTest, HandleNoneZeroInput) {
EXPECT_EQ(2, 2);
EXPECT_EQ(6, 3 + 3);
}
int main(int argc, char *argv[]) {
testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
<commit_msg>unit test<commit_after>#include "gtest/gtest.h"
#include "socket.h"
#include "ioloop.h"
TEST(FooTest, HandleNoneZeroInput) {
EXPECT_EQ(2, 2);
EXPECT_EQ(6, 3 + 3);
}
#define SOCKET_CONTINER_CAPACITY 10
class SocketUnittest: public testing::Test {
protected:
virtual void SetUp() {
m_io = NULL;
memset(m_sockets, 0, sizeof(m_sockets));
}
virtual void TearDown() {
m_io->Release();
for (int i = 0; i < SOCKET_CONTINER_CAPACITY; ++i) {
if (m_sockets[i]) {
delete m_sockets[i];
m_sockets[i] = NULL;
}
delete m_sockets;
}
}
IOLoop* m_io;
Socket* m_sockets[SOCKET_CONTINER_CAPACITY];
};
int main(int argc, char *argv[]) {
testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
<|endoftext|>
|
<commit_before>// Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2012 The Bitcoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "keystore.h"
#include "script.h"
bool CKeyStore::GetPubKey(const CKeyID &address, CPubKey &vchPubKeyOut) const
{
CKey key;
if (!GetKey(address, key))
return false;
vchPubKeyOut = key.GetPubKey();
return true;
}
bool CBasicKeyStore::AddKey(const CKey& key)
{
bool fCompressed = false;
CSecret secret = key.GetSecret(fCompressed);
{
LOCK(cs_KeyStore);
mapKeys[key.GetPubKey().GetID()] = make_pair(secret, fCompressed);
}
return true;
}
bool CBasicKeyStore::AddCScript(const CScript& redeemScript)
{
{
LOCK(cs_KeyStore);
mapScripts[redeemScript.GetID()] = redeemScript;
}
return true;
}
bool CBasicKeyStore::HaveCScript(const CScriptID& hash) const
{
bool result;
{
LOCK(cs_KeyStore);
result = (mapScripts.count(hash) > 0);
}
return result;
}
bool CBasicKeyStore::GetCScript(const CScriptID &hash, CScript& redeemScriptOut) const
{
{
LOCK(cs_KeyStore);
ScriptMap::const_iterator mi = mapScripts.find(hash);
if (mi != mapScripts.end())
{
redeemScriptOut = (*mi).second;
return true;
}
}
return false;
}
bool CCryptoKeyStore::SetCrypted()
{
{
LOCK(cs_KeyStore);
if (fUseCrypto)
return true;
if (!mapKeys.empty())
return false;
fUseCrypto = true;
}
return true;
}
bool CCryptoKeyStore::Lock()
{
if (!SetCrypted())
return false;
{
LOCK(cs_KeyStore);
vMasterKey.clear();
}
NotifyStatusChanged(this);
return true;
}
bool CCryptoKeyStore::Unlock(const CKeyingMaterial& vMasterKeyIn)
{
{
LOCK(cs_KeyStore);
if (!SetCrypted())
return false;
CryptedKeyMap::const_iterator mi = mapCryptedKeys.begin();
for (; mi != mapCryptedKeys.end(); ++mi)
{
const CPubKey &vchPubKey = (*mi).second.first;
const std::vector<unsigned char> &vchCryptedSecret = (*mi).second.second;
CSecret vchSecret;
if(!DecryptSecret(vMasterKeyIn, vchCryptedSecret, vchPubKey.GetHash(), vchSecret))
return false;
if (vchSecret.size() != 32)
return false;
CKey key;
key.SetPubKey(vchPubKey);
key.SetSecret(vchSecret);
if (key.GetPubKey() == vchPubKey)
break;
return false;
}
vMasterKey = vMasterKeyIn;
}
NotifyStatusChanged(this);
return true;
}
bool CCryptoKeyStore::AddKey(const CKey& key)
{
{
LOCK(cs_KeyStore);
if (!IsCrypted())
return CBasicKeyStore::AddKey(key);
if (IsLocked())
return false;
std::vector<unsigned char> vchCryptedSecret;
CPubKey vchPubKey = key.GetPubKey();
bool fCompressed;
if (!EncryptSecret(vMasterKey, key.GetSecret(fCompressed), vchPubKey.GetHash(), vchCryptedSecret))
return false;
if (!AddCryptedKey(key.GetPubKey(), vchCryptedSecret))
return false;
}
return true;
}
bool CCryptoKeyStore::AddCryptedKey(const CPubKey &vchPubKey, const std::vector<unsigned char> &vchCryptedSecret)
{
{
LOCK(cs_KeyStore);
if (!SetCrypted())
return false;
mapCryptedKeys[vchPubKey.GetID()] = make_pair(vchPubKey, vchCryptedSecret);
}
return true;
}
bool CCryptoKeyStore::GetKey(const CKeyID &address, CKey& keyOut) const
{
{
LOCK(cs_KeyStore);
if (!IsCrypted())
return CBasicKeyStore::GetKey(address, keyOut);
CryptedKeyMap::const_iterator mi = mapCryptedKeys.find(address);
if (mi != mapCryptedKeys.end())
{
const CPubKey &vchPubKey = (*mi).second.first;
const std::vector<unsigned char> &vchCryptedSecret = (*mi).second.second;
CSecret vchSecret;
if (!DecryptSecret(vMasterKey, vchCryptedSecret, vchPubKey.GetHash(), vchSecret))
return false;
if (vchSecret.size() != 32)
return false;
keyOut.SetPubKey(vchPubKey);
keyOut.SetSecret(vchSecret);
return true;
}
}
return false;
}
bool CCryptoKeyStore::GetPubKey(const CKeyID &address, CPubKey& vchPubKeyOut) const
{
{
LOCK(cs_KeyStore);
if (!IsCrypted())
return CKeyStore::GetPubKey(address, vchPubKeyOut);
CryptedKeyMap::const_iterator mi = mapCryptedKeys.find(address);
if (mi != mapCryptedKeys.end())
{
vchPubKeyOut = (*mi).second.first;
return true;
}
}
return false;
}
bool CCryptoKeyStore::EncryptKeys(CKeyingMaterial& vMasterKeyIn)
{
{
LOCK(cs_KeyStore);
if (!mapCryptedKeys.empty() || IsCrypted())
return false;
fUseCrypto = true;
BOOST_FOREACH(KeyMap::value_type& mKey, mapKeys)
{
CKey key;
if (!key.SetSecret(mKey.second.first, mKey.second.second))
return false;
const CPubKey vchPubKey = key.GetPubKey();
std::vector<unsigned char> vchCryptedSecret;
bool fCompressed;
if (!EncryptSecret(vMasterKeyIn, key.GetSecret(fCompressed), vchPubKey.GetHash(), vchCryptedSecret))
return false;
if (!AddCryptedKey(vchPubKey, vchCryptedSecret))
return false;
}
mapKeys.clear();
}
return true;
}
<commit_msg>Update to v3<commit_after>// Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2012 The Bitcoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
// Copyright (c) 2013-2014 Memorycoin Dev Team
#include "keystore.h"
#include "script.h"
bool CKeyStore::GetPubKey(const CKeyID &address, CPubKey &vchPubKeyOut) const
{
CKey key;
if (!GetKey(address, key))
return false;
vchPubKeyOut = key.GetPubKey();
return true;
}
bool CBasicKeyStore::AddKey(const CKey& key)
{
bool fCompressed = false;
CSecret secret = key.GetSecret(fCompressed);
{
LOCK(cs_KeyStore);
mapKeys[key.GetPubKey().GetID()] = make_pair(secret, fCompressed);
}
return true;
}
bool CBasicKeyStore::AddCScript(const CScript& redeemScript)
{
{
LOCK(cs_KeyStore);
mapScripts[redeemScript.GetID()] = redeemScript;
}
return true;
}
bool CBasicKeyStore::HaveCScript(const CScriptID& hash) const
{
bool result;
{
LOCK(cs_KeyStore);
result = (mapScripts.count(hash) > 0);
}
return result;
}
bool CBasicKeyStore::GetCScript(const CScriptID &hash, CScript& redeemScriptOut) const
{
{
LOCK(cs_KeyStore);
ScriptMap::const_iterator mi = mapScripts.find(hash);
if (mi != mapScripts.end())
{
redeemScriptOut = (*mi).second;
return true;
}
}
return false;
}
bool CCryptoKeyStore::SetCrypted()
{
{
LOCK(cs_KeyStore);
if (fUseCrypto)
return true;
if (!mapKeys.empty())
return false;
fUseCrypto = true;
}
return true;
}
bool CCryptoKeyStore::Lock()
{
if (!SetCrypted())
return false;
{
LOCK(cs_KeyStore);
vMasterKey.clear();
}
NotifyStatusChanged(this);
return true;
}
bool CCryptoKeyStore::Unlock(const CKeyingMaterial& vMasterKeyIn)
{
{
LOCK(cs_KeyStore);
if (!SetCrypted())
return false;
CryptedKeyMap::const_iterator mi = mapCryptedKeys.begin();
for (; mi != mapCryptedKeys.end(); ++mi)
{
const CPubKey &vchPubKey = (*mi).second.first;
const std::vector<unsigned char> &vchCryptedSecret = (*mi).second.second;
CSecret vchSecret;
if(!DecryptSecret(vMasterKeyIn, vchCryptedSecret, vchPubKey.GetHash(), vchSecret))
return false;
if (vchSecret.size() != 32)
return false;
CKey key;
key.SetPubKey(vchPubKey);
key.SetSecret(vchSecret);
if (key.GetPubKey() == vchPubKey)
break;
return false;
}
vMasterKey = vMasterKeyIn;
}
NotifyStatusChanged(this);
return true;
}
bool CCryptoKeyStore::AddKey(const CKey& key)
{
{
LOCK(cs_KeyStore);
if (!IsCrypted())
return CBasicKeyStore::AddKey(key);
if (IsLocked())
return false;
std::vector<unsigned char> vchCryptedSecret;
CPubKey vchPubKey = key.GetPubKey();
bool fCompressed;
if (!EncryptSecret(vMasterKey, key.GetSecret(fCompressed), vchPubKey.GetHash(), vchCryptedSecret))
return false;
if (!AddCryptedKey(key.GetPubKey(), vchCryptedSecret))
return false;
}
return true;
}
bool CCryptoKeyStore::AddCryptedKey(const CPubKey &vchPubKey, const std::vector<unsigned char> &vchCryptedSecret)
{
{
LOCK(cs_KeyStore);
if (!SetCrypted())
return false;
mapCryptedKeys[vchPubKey.GetID()] = make_pair(vchPubKey, vchCryptedSecret);
}
return true;
}
bool CCryptoKeyStore::GetKey(const CKeyID &address, CKey& keyOut) const
{
{
LOCK(cs_KeyStore);
if (!IsCrypted())
return CBasicKeyStore::GetKey(address, keyOut);
CryptedKeyMap::const_iterator mi = mapCryptedKeys.find(address);
if (mi != mapCryptedKeys.end())
{
const CPubKey &vchPubKey = (*mi).second.first;
const std::vector<unsigned char> &vchCryptedSecret = (*mi).second.second;
CSecret vchSecret;
if (!DecryptSecret(vMasterKey, vchCryptedSecret, vchPubKey.GetHash(), vchSecret))
return false;
if (vchSecret.size() != 32)
return false;
keyOut.SetPubKey(vchPubKey);
keyOut.SetSecret(vchSecret);
return true;
}
}
return false;
}
bool CCryptoKeyStore::GetPubKey(const CKeyID &address, CPubKey& vchPubKeyOut) const
{
{
LOCK(cs_KeyStore);
if (!IsCrypted())
return CKeyStore::GetPubKey(address, vchPubKeyOut);
CryptedKeyMap::const_iterator mi = mapCryptedKeys.find(address);
if (mi != mapCryptedKeys.end())
{
vchPubKeyOut = (*mi).second.first;
return true;
}
}
return false;
}
bool CCryptoKeyStore::EncryptKeys(CKeyingMaterial& vMasterKeyIn)
{
{
LOCK(cs_KeyStore);
if (!mapCryptedKeys.empty() || IsCrypted())
return false;
fUseCrypto = true;
BOOST_FOREACH(KeyMap::value_type& mKey, mapKeys)
{
CKey key;
if (!key.SetSecret(mKey.second.first, mKey.second.second))
return false;
const CPubKey vchPubKey = key.GetPubKey();
std::vector<unsigned char> vchCryptedSecret;
bool fCompressed;
if (!EncryptSecret(vMasterKeyIn, key.GetSecret(fCompressed), vchPubKey.GetHash(), vchCryptedSecret))
return false;
if (!AddCryptedKey(vchPubKey, vchCryptedSecret))
return false;
}
mapKeys.clear();
}
return true;
}
<|endoftext|>
|
<commit_before>// $Id$
// The libMesh Finite Element Library.
// Copyright (C) 2002-2008 Benjamin S. Kirk, John W. Peterson, Roy H. Stogner
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
// C++ includes
// Local Includes
#include "mesh_base.h"
#include "elem.h"
#include "tree.h"
#include "point_locator_tree.h"
#include "mesh_tools.h"
//------------------------------------------------------------------
// PointLocator methods
PointLocatorTree::PointLocatorTree (const MeshBase& mesh,
const PointLocatorBase* master) :
PointLocatorBase (mesh,master),
_tree (NULL),
_element (NULL),
_out_of_mesh_mode(false)
{
this->init(Trees::NODES);
}
PointLocatorTree::PointLocatorTree (const MeshBase& mesh,
const Trees::BuildType build_type,
const PointLocatorBase* master) :
PointLocatorBase (mesh,master),
_tree (NULL),
_element (NULL),
_out_of_mesh_mode(false)
{
this->init(build_type);
}
PointLocatorTree::~PointLocatorTree ()
{
this->clear ();
}
void PointLocatorTree::clear ()
{
// only delete the tree when we are the master
if (this->_tree != NULL)
{
if (this->_master == NULL)
// we own the tree
delete this->_tree;
else
// someone else owns and therefore deletes the tree
this->_tree = NULL;
}
}
void PointLocatorTree::init (const Trees::BuildType build_type)
{
libmesh_assert (this->_tree == NULL);
if (this->_initialized)
{
libMesh::err << "ERROR: Already initialized! Will ignore this call..."
<< std::endl;
}
else
{
if (this->_master == NULL)
{
if (this->_mesh.mesh_dimension() == 3)
_tree = new Trees::OctTree (this->_mesh, 200, build_type);
else
{
// A 1D/2D mesh in 3D space needs special consideration.
// If the mesh is planar XY, we want to build a QuadTree
// to search efficiently. If the mesh is truly a manifold,
// then we need an octree
bool is_planar_xy = false;
// Build the bounding box for the mesh. If the delta-z bound is
// negligibly small then we can use a quadtree.
{
MeshTools::BoundingBox bbox = MeshTools::bounding_box(this->_mesh);
const Real
Dx = bbox.second(0) - bbox.first(0),
Dz = bbox.second(2) - bbox.first(2);
if (std::abs(Dz/(Dx + 1.e-20)) < 1e-10)
is_planar_xy = true;
}
if (is_planar_xy)
_tree = new Trees::QuadTree (this->_mesh, 200, build_type);
else
_tree = new Trees::OctTree (this->_mesh, 200, build_type);
}
}
else
{
// We are _not_ the master. Let our Tree point to
// the master's tree. But for this we first transform
// the master in a state for which we are friends.
// And make sure the master @e has a tree!
const PointLocatorTree* my_master =
libmesh_cast_ptr<const PointLocatorTree*>(this->_master);
if (my_master->initialized())
this->_tree = my_master->_tree;
else
{
libMesh::err << "ERROR: Initialize master first, then servants!"
<< std::endl;
libmesh_error();
}
}
// Not all PointLocators may own a tree, but all of them
// use their own element pointer. Let the element pointer
// be unique for every interpolator.
// Suppose the interpolators are used concurrently
// at different locations in the mesh, then it makes quite
// sense to have unique start elements.
this->_element = NULL;
}
// ready for take-off
this->_initialized = true;
}
const Elem* PointLocatorTree::operator() (const Point& p) const
{
libmesh_assert (this->_initialized);
// First check the element from last time before asking the tree
if (this->_element==NULL || !(this->_element->contains_point(p)))
{
// ask the tree
this->_element = this->_tree->find_element (p);
if (this->_element == NULL)
{
/* No element seems to contain this point. If out-of-mesh
mode is enabled, just return NULL. If not, however, we
have to perform a linear search before we call \p
libmesh_error() since in the case of curved elements, the
bounding box computed in \p TreeNode::insert(const
Elem*) might be slightly inaccurate. */
if(!_out_of_mesh_mode)
{
MeshBase::const_element_iterator pos = this->_mesh.active_elements_begin();
const MeshBase::const_element_iterator end_pos = this->_mesh.active_elements_end();
for ( ; pos != end_pos; ++pos)
if ((*pos)->contains_point(p))
return this->_element = (*pos);
if (this->_element == NULL)
{
libMesh::err << std::endl
<< " ******** Serious Problem. Could not find an Element "
<< "in the Mesh"
<< std:: endl
<< " ******** that contains the Point "
<< p;
libmesh_error();
}
}
}
}
// the element should be active
libmesh_assert (this->_element->active());
// return the element
return this->_element;
}
void PointLocatorTree::enable_out_of_mesh_mode (void)
{
/* Out-of-mesh mode is currently only supported if all of the
elements have affine mappings. The reason is that for quadratic
mappings, it is not easy to construct a relyable bounding box of
the element, and thus, the fallback linear search in \p
operator() is required. Hence, out-of-mesh mode would be
extremely slow. */
if(!_out_of_mesh_mode)
{
#ifdef DEBUG
MeshBase::const_element_iterator pos = this->_mesh.active_elements_begin();
const MeshBase::const_element_iterator end_pos = this->_mesh.active_elements_end();
for ( ; pos != end_pos; ++pos)
if (!(*pos)->has_affine_map())
{
libMesh::err << "ERROR: Out-of-mesh mode is currently only supported if all elements have affine mappings." << std::endl;
libmesh_error();
}
#endif
_out_of_mesh_mode = true;
}
}
void PointLocatorTree::disable_out_of_mesh_mode (void)
{
_out_of_mesh_mode = false;
}
<commit_msg>Fixed the overzealous assertion bug Yujie caught<commit_after>// $Id$
// The libMesh Finite Element Library.
// Copyright (C) 2002-2008 Benjamin S. Kirk, John W. Peterson, Roy H. Stogner
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
// C++ includes
// Local Includes
#include "mesh_base.h"
#include "elem.h"
#include "tree.h"
#include "point_locator_tree.h"
#include "mesh_tools.h"
//------------------------------------------------------------------
// PointLocator methods
PointLocatorTree::PointLocatorTree (const MeshBase& mesh,
const PointLocatorBase* master) :
PointLocatorBase (mesh,master),
_tree (NULL),
_element (NULL),
_out_of_mesh_mode(false)
{
this->init(Trees::NODES);
}
PointLocatorTree::PointLocatorTree (const MeshBase& mesh,
const Trees::BuildType build_type,
const PointLocatorBase* master) :
PointLocatorBase (mesh,master),
_tree (NULL),
_element (NULL),
_out_of_mesh_mode(false)
{
this->init(build_type);
}
PointLocatorTree::~PointLocatorTree ()
{
this->clear ();
}
void PointLocatorTree::clear ()
{
// only delete the tree when we are the master
if (this->_tree != NULL)
{
if (this->_master == NULL)
// we own the tree
delete this->_tree;
else
// someone else owns and therefore deletes the tree
this->_tree = NULL;
}
}
void PointLocatorTree::init (const Trees::BuildType build_type)
{
libmesh_assert (this->_tree == NULL);
if (this->_initialized)
{
libMesh::err << "ERROR: Already initialized! Will ignore this call..."
<< std::endl;
}
else
{
if (this->_master == NULL)
{
if (this->_mesh.mesh_dimension() == 3)
_tree = new Trees::OctTree (this->_mesh, 200, build_type);
else
{
// A 1D/2D mesh in 3D space needs special consideration.
// If the mesh is planar XY, we want to build a QuadTree
// to search efficiently. If the mesh is truly a manifold,
// then we need an octree
bool is_planar_xy = false;
// Build the bounding box for the mesh. If the delta-z bound is
// negligibly small then we can use a quadtree.
{
MeshTools::BoundingBox bbox = MeshTools::bounding_box(this->_mesh);
const Real
Dx = bbox.second(0) - bbox.first(0),
Dz = bbox.second(2) - bbox.first(2);
if (std::abs(Dz/(Dx + 1.e-20)) < 1e-10)
is_planar_xy = true;
}
if (is_planar_xy)
_tree = new Trees::QuadTree (this->_mesh, 200, build_type);
else
_tree = new Trees::OctTree (this->_mesh, 200, build_type);
}
}
else
{
// We are _not_ the master. Let our Tree point to
// the master's tree. But for this we first transform
// the master in a state for which we are friends.
// And make sure the master @e has a tree!
const PointLocatorTree* my_master =
libmesh_cast_ptr<const PointLocatorTree*>(this->_master);
if (my_master->initialized())
this->_tree = my_master->_tree;
else
{
libMesh::err << "ERROR: Initialize master first, then servants!"
<< std::endl;
libmesh_error();
}
}
// Not all PointLocators may own a tree, but all of them
// use their own element pointer. Let the element pointer
// be unique for every interpolator.
// Suppose the interpolators are used concurrently
// at different locations in the mesh, then it makes quite
// sense to have unique start elements.
this->_element = NULL;
}
// ready for take-off
this->_initialized = true;
}
const Elem* PointLocatorTree::operator() (const Point& p) const
{
libmesh_assert (this->_initialized);
// First check the element from last time before asking the tree
if (this->_element==NULL || !(this->_element->contains_point(p)))
{
// ask the tree
this->_element = this->_tree->find_element (p);
if (this->_element == NULL)
{
/* No element seems to contain this point. If out-of-mesh
mode is enabled, just return NULL. If not, however, we
have to perform a linear search before we call \p
libmesh_error() since in the case of curved elements, the
bounding box computed in \p TreeNode::insert(const
Elem*) might be slightly inaccurate. */
if(!_out_of_mesh_mode)
{
MeshBase::const_element_iterator pos = this->_mesh.active_elements_begin();
const MeshBase::const_element_iterator end_pos = this->_mesh.active_elements_end();
for ( ; pos != end_pos; ++pos)
if ((*pos)->contains_point(p))
return this->_element = (*pos);
if (this->_element == NULL)
{
libMesh::err << std::endl
<< " ******** Serious Problem. Could not find an Element "
<< "in the Mesh"
<< std:: endl
<< " ******** that contains the Point "
<< p;
libmesh_error();
}
}
}
}
// If we found an element, it should be active
libmesh_assert (!this->_element || this->_element->active());
// return the element
return this->_element;
}
void PointLocatorTree::enable_out_of_mesh_mode (void)
{
/* Out-of-mesh mode is currently only supported if all of the
elements have affine mappings. The reason is that for quadratic
mappings, it is not easy to construct a relyable bounding box of
the element, and thus, the fallback linear search in \p
operator() is required. Hence, out-of-mesh mode would be
extremely slow. */
if(!_out_of_mesh_mode)
{
#ifdef DEBUG
MeshBase::const_element_iterator pos = this->_mesh.active_elements_begin();
const MeshBase::const_element_iterator end_pos = this->_mesh.active_elements_end();
for ( ; pos != end_pos; ++pos)
if (!(*pos)->has_affine_map())
{
libMesh::err << "ERROR: Out-of-mesh mode is currently only supported if all elements have affine mappings." << std::endl;
libmesh_error();
}
#endif
_out_of_mesh_mode = true;
}
}
void PointLocatorTree::disable_out_of_mesh_mode (void)
{
_out_of_mesh_mode = false;
}
<|endoftext|>
|
<commit_before>/* -------------------------------------------------------------------------- */
/* Copyright 2002-2011, OpenNebula Project Leads (OpenNebula.org) */
/* */
/* 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 "LibVirtDriver.h"
#include "Nebula.h"
#include <sstream>
#include <fstream>
#include <libgen.h>
/* ************************************************************************** */
/* Virtual Network :: Database Access Functions */
/* ************************************************************************** */
const char * LibVirtDriver::vmware_vnm_name = "vmware";
int LibVirtDriver::deployment_description_vmware(
const VirtualMachine * vm,
const string& file_name) const
{
ofstream file;
int num;
vector<const Attribute *> attrs;
string vcpu;
string memory;
int memory_in_kb = 0;
string arch = "";
const VectorAttribute * disk;
const VectorAttribute * context;
string type = "";
string target = "";
string bus = "";
string ro = "";
string source = "";
string datastore = "";
string driver = "";
string default_driver = "";
bool readonly;
const VectorAttribute * nic;
string network_id = "";
string mac = "";
string bridge = "";
string script = "";
string model = "";
const VectorAttribute * raw;
string data;
// ------------------------------------------------------------------------
file.open(file_name.c_str(), ios::out);
if (file.fail() == true)
{
goto error_vmware_file;
}
// ------------------------------------------------------------------------
// Starting XML document
// ------------------------------------------------------------------------
file << "<domain type='" << emulator << "'>" << endl;
// ------------------------------------------------------------------------
// Domain name
// ------------------------------------------------------------------------
file << "\t<name>one-" << vm->get_oid() << "</name>" << endl;
// ------------------------------------------------------------------------
// CPU
// ------------------------------------------------------------------------
vm->get_template_attribute("VCPU", vcpu);
if(vcpu.empty())
{
get_default("VCPU", vcpu);
}
if (!vcpu.empty())
{
file << "\t<vcpu>" << vcpu << "</vcpu>" << endl;
}
// ------------------------------------------------------------------------
// Memory
// ------------------------------------------------------------------------
vm->get_template_attribute("MEMORY",memory);
if (memory.empty())
{
get_default("MEMORY",memory);
}
if (!memory.empty())
{
memory_in_kb = atoi(memory.c_str()) * 1024;
file << "\t<memory>" << memory_in_kb << "</memory>" << endl;
}
else
{
goto error_vmware_memory;
}
// ------------------------------------------------------------------------
// OS and boot options
// ------------------------------------------------------------------------
num = vm->get_template_attribute("OS",attrs);
// Get values & defaults
if ( num > 0 )
{
const VectorAttribute * os;
os = dynamic_cast<const VectorAttribute *>(attrs[0]);
if( os != 0 )
{
arch = os->vector_value("ARCH");
}
}
if ( arch.empty() )
{
get_default("OS","ARCH",arch);
if (arch.empty())
{
goto error_vmware_arch;
}
}
// Start writing to the file with the info we got
file << "\t<os>" << endl;
file << "\t\t<type arch='" << arch << "'>hvm</type>" << endl;
file << "\t</os>" << endl;
attrs.clear();
// ------------------------------------------------------------------------
// Disks
// ------------------------------------------------------------------------
file << "\t<devices>" << endl;
get_default("DISK","DRIVER",default_driver);
num = vm->get_template_attribute("DISK",attrs);
if (num!=0)
{
get_default("DATASTORE", datastore);
}
for (int i=0; i < num ;i++)
{
disk = dynamic_cast<const VectorAttribute *>(attrs[i]);
if ( disk == 0 )
{
continue;
}
type = disk->vector_value("TYPE");
target = disk->vector_value("TARGET");
ro = disk->vector_value("READONLY");
bus = disk->vector_value("BUS");
source = disk->vector_value("SOURCE");
driver = disk->vector_value("DRIVER");
if (target.empty())
{
goto error_vmware_disk;
}
readonly = false;
if ( !ro.empty() )
{
transform(ro.begin(),ro.end(),ro.begin(),(int(*)(int))toupper);
if ( ro == "YES" )
{
readonly = true;
}
}
if (type.empty() == false)
{
transform(type.begin(),type.end(),type.begin(),(int(*)(int))toupper);
}
if ( type == "BLOCK" )
{
file << "\t\t<disk type='block' device='disk'>" << endl;
file << "\t\t\t<source file=[" << datastore << "] " << vm->get_oid()
<< "/images/disk." << i << "'/>" << endl;
}
else if ( type == "CDROM" )
{
file << "\t\t<disk type='file' device='cdrom'>" << endl;
file << "\t\t\t<source file=[" << datastore << "] " << vm->get_oid()
<< "/images/disk." << i << ".iso'/>" << endl;
}
else
{
file << "\t\t<disk type='file' device='disk'>" << endl
<< "\t\t\t<source file='[" << datastore <<"] " << vm->get_oid()
<< "/images/disk." << i << "/disk.vmdk'/>" << endl;
}
file << "\t\t\t<target dev='" << target << "'";
if (!bus.empty())
{
file << " bus='" << bus << "'/>" << endl;
}
else
{
file << "/>" << endl;
}
if ( !driver.empty() )
{
file << "\t\t\t<driver name='" << driver << "'/>" << endl;
}
else
{
if (!default_driver.empty())
{
file << "\t\t\t<driver name='" <<
default_driver << "'/>" << endl;
}
}
if (readonly)
{
file << "\t\t\t<readonly/>" << endl;
}
file << "\t\t</disk>" << endl;
}
attrs.clear();
// ------------------------------------------------------------------------
// Context Device
// ------------------------------------------------------------------------
if ( vm->get_template_attribute("CONTEXT",attrs) == 1 )
{
context = dynamic_cast<const VectorAttribute *>(attrs[0]);
target = context->vector_value("TARGET");
if ( !target.empty() )
{
file << "\t\t<disk type='file' device='cdrom'>" << endl;
file << "\t\t\t<source file='[" << datastore <<"] " << vm->get_oid()
<< "/disk." << num << ".iso'/>" << endl;
file << "\t\t\t<target dev='" << target << "'/>" << endl;
file << "\t\t\t<readonly/>" << endl;
file << "\t\t</disk>" << endl;
}
else
{
vm->log("VMM", Log::WARNING, "Could not find target device to"
" attach context, will continue without it.");
}
}
attrs.clear();
// ------------------------------------------------------------------------
// Network interfaces
// ------------------------------------------------------------------------
num = vm->get_template_attribute("NIC",attrs);
for(int i=0; i<num; i++)
{
nic = dynamic_cast<const VectorAttribute *>(attrs[i]);
if ( nic == 0 )
{
continue;
}
network_id = nic->vector_value("NETWORK_ID");
mac = nic->vector_value("MAC");
target = nic->vector_value("TARGET");
script = nic->vector_value("SCRIPT");
model = nic->vector_value("MODEL");
bridge = "one-pg-";
bridge.append(network_id);
file << "\t\t<interface type='bridge'>" << endl;
file << "\t\t\t<source bridge='" << bridge << "'/>" << endl;
if( !mac.empty() )
{
file << "\t\t\t<mac address='" << mac << "'/>" << endl;
}
if( !target.empty() )
{
file << "\t\t\t<target dev='" << target << "'/>" << endl;
}
if( !script.empty() )
{
file << "\t\t\t<script path='" << script << "'/>" << endl;
}
if( !model.empty() )
{
file << "\t\t\t<model type='" << model << "'/>" << endl;
}
file << "\t\t</interface>" << endl;
}
attrs.clear();
file << "\t</devices>" << endl;
// ------------------------------------------------------------------------
// Raw VMware attributes
// ------------------------------------------------------------------------
num = vm->get_template_attribute("RAW",attrs);
for(int i=0; i<num;i++)
{
raw = dynamic_cast<const VectorAttribute *>(attrs[i]);
if ( raw == 0 )
{
continue;
}
type = raw->vector_value("TYPE");
transform(type.begin(),type.end(),type.begin(),(int(*)(int))toupper);
if ( type == "VMWARE" )
{
data = raw->vector_value("DATA");
file << "\t" << data << endl;
}
}
file << "</domain>" << endl;
file.close();
return 0;
error_vmware_file:
vm->log("VMM", Log::ERROR, "Could not open VMWARE deployment file.");
return -1;
error_vmware_arch:
vm->log("VMM", Log::ERROR, "No ARCH defined and no default provided.");
file.close();
return -1;
error_vmware_memory:
vm->log("VMM", Log::ERROR, "No MEMORY defined and no default provided.");
file.close();
return -1;
error_vmware_disk:
vm->log("VMM", Log::ERROR, "Wrong target value in DISK.");
file.close();
return -1;
}
<commit_msg>feature #1020: VMware networking traditional method also supported (dummy drivers)<commit_after>/* -------------------------------------------------------------------------- */
/* Copyright 2002-2011, OpenNebula Project Leads (OpenNebula.org) */
/* */
/* 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 "LibVirtDriver.h"
#include "Nebula.h"
#include <sstream>
#include <fstream>
#include <libgen.h>
/* ************************************************************************** */
/* Virtual Network :: Database Access Functions */
/* ************************************************************************** */
const char * LibVirtDriver::vmware_vnm_name = "vmware";
int LibVirtDriver::deployment_description_vmware(
const VirtualMachine * vm,
const string& file_name) const
{
ofstream file;
int num;
vector<const Attribute *> attrs;
string vcpu;
string memory;
int memory_in_kb = 0;
string arch = "";
const VectorAttribute * disk;
const VectorAttribute * context;
string type = "";
string target = "";
string bus = "";
string ro = "";
string source = "";
string datastore = "";
string driver = "";
string default_driver = "";
bool readonly;
const VectorAttribute * nic;
string network_id = "";
string mac = "";
string bridge = "";
string script = "";
string model = "";
const VectorAttribute * raw;
string data;
// ------------------------------------------------------------------------
file.open(file_name.c_str(), ios::out);
if (file.fail() == true)
{
goto error_vmware_file;
}
// ------------------------------------------------------------------------
// Starting XML document
// ------------------------------------------------------------------------
file << "<domain type='" << emulator << "'>" << endl;
// ------------------------------------------------------------------------
// Domain name
// ------------------------------------------------------------------------
file << "\t<name>one-" << vm->get_oid() << "</name>" << endl;
// ------------------------------------------------------------------------
// CPU
// ------------------------------------------------------------------------
vm->get_template_attribute("VCPU", vcpu);
if(vcpu.empty())
{
get_default("VCPU", vcpu);
}
if (!vcpu.empty())
{
file << "\t<vcpu>" << vcpu << "</vcpu>" << endl;
}
// ------------------------------------------------------------------------
// Memory
// ------------------------------------------------------------------------
vm->get_template_attribute("MEMORY",memory);
if (memory.empty())
{
get_default("MEMORY",memory);
}
if (!memory.empty())
{
memory_in_kb = atoi(memory.c_str()) * 1024;
file << "\t<memory>" << memory_in_kb << "</memory>" << endl;
}
else
{
goto error_vmware_memory;
}
// ------------------------------------------------------------------------
// OS and boot options
// ------------------------------------------------------------------------
num = vm->get_template_attribute("OS",attrs);
// Get values & defaults
if ( num > 0 )
{
const VectorAttribute * os;
os = dynamic_cast<const VectorAttribute *>(attrs[0]);
if( os != 0 )
{
arch = os->vector_value("ARCH");
}
}
if ( arch.empty() )
{
get_default("OS","ARCH",arch);
if (arch.empty())
{
goto error_vmware_arch;
}
}
// Start writing to the file with the info we got
file << "\t<os>" << endl;
file << "\t\t<type arch='" << arch << "'>hvm</type>" << endl;
file << "\t</os>" << endl;
attrs.clear();
// ------------------------------------------------------------------------
// Disks
// ------------------------------------------------------------------------
file << "\t<devices>" << endl;
get_default("DISK","DRIVER",default_driver);
num = vm->get_template_attribute("DISK",attrs);
if (num!=0)
{
get_default("DATASTORE", datastore);
}
for (int i=0; i < num ;i++)
{
disk = dynamic_cast<const VectorAttribute *>(attrs[i]);
if ( disk == 0 )
{
continue;
}
type = disk->vector_value("TYPE");
target = disk->vector_value("TARGET");
ro = disk->vector_value("READONLY");
bus = disk->vector_value("BUS");
source = disk->vector_value("SOURCE");
driver = disk->vector_value("DRIVER");
if (target.empty())
{
goto error_vmware_disk;
}
readonly = false;
if ( !ro.empty() )
{
transform(ro.begin(),ro.end(),ro.begin(),(int(*)(int))toupper);
if ( ro == "YES" )
{
readonly = true;
}
}
if (type.empty() == false)
{
transform(type.begin(),type.end(),type.begin(),(int(*)(int))toupper);
}
if ( type == "BLOCK" )
{
file << "\t\t<disk type='block' device='disk'>" << endl;
file << "\t\t\t<source file=[" << datastore << "] " << vm->get_oid()
<< "/images/disk." << i << "'/>" << endl;
}
else if ( type == "CDROM" )
{
file << "\t\t<disk type='file' device='cdrom'>" << endl;
file << "\t\t\t<source file=[" << datastore << "] " << vm->get_oid()
<< "/images/disk." << i << ".iso'/>" << endl;
}
else
{
file << "\t\t<disk type='file' device='disk'>" << endl
<< "\t\t\t<source file='[" << datastore <<"] " << vm->get_oid()
<< "/images/disk." << i << "/disk.vmdk'/>" << endl;
}
file << "\t\t\t<target dev='" << target << "'";
if (!bus.empty())
{
file << " bus='" << bus << "'/>" << endl;
}
else
{
file << "/>" << endl;
}
if ( !driver.empty() )
{
file << "\t\t\t<driver name='" << driver << "'/>" << endl;
}
else
{
if (!default_driver.empty())
{
file << "\t\t\t<driver name='" <<
default_driver << "'/>" << endl;
}
}
if (readonly)
{
file << "\t\t\t<readonly/>" << endl;
}
file << "\t\t</disk>" << endl;
}
attrs.clear();
// ------------------------------------------------------------------------
// Context Device
// ------------------------------------------------------------------------
if ( vm->get_template_attribute("CONTEXT",attrs) == 1 )
{
context = dynamic_cast<const VectorAttribute *>(attrs[0]);
target = context->vector_value("TARGET");
if ( !target.empty() )
{
file << "\t\t<disk type='file' device='cdrom'>" << endl;
file << "\t\t\t<source file='[" << datastore <<"] " << vm->get_oid()
<< "/disk." << num << ".iso'/>" << endl;
file << "\t\t\t<target dev='" << target << "'/>" << endl;
file << "\t\t\t<readonly/>" << endl;
file << "\t\t</disk>" << endl;
}
else
{
vm->log("VMM", Log::WARNING, "Could not find target device to"
" attach context, will continue without it.");
}
}
attrs.clear();
// ------------------------------------------------------------------------
// Network interfaces
// ------------------------------------------------------------------------
num = vm->get_template_attribute("NIC",attrs);
for(int i=0; i<num; i++)
{
nic = dynamic_cast<const VectorAttribute *>(attrs[i]);
if ( nic == 0 )
{
continue;
}
network_id = nic->vector_value("NETWORK_ID");
mac = nic->vector_value("MAC");
target = nic->vector_value("TARGET");
script = nic->vector_value("SCRIPT");
model = nic->vector_value("MODEL");
if (vm->get_vnm_mad() == LibVirtDriver::vmware_vnm_name)
{
bridge = "one-pg-";
bridge.append(network_id);
}
else
{
bridge = nic->vector_value("BRIDGE");
}
file << "\t\t<interface type='bridge'>" << endl;
file << "\t\t\t<source bridge='" << bridge << "'/>" << endl;
if( !mac.empty() )
{
file << "\t\t\t<mac address='" << mac << "'/>" << endl;
}
if( !target.empty() )
{
file << "\t\t\t<target dev='" << target << "'/>" << endl;
}
if( !script.empty() )
{
file << "\t\t\t<script path='" << script << "'/>" << endl;
}
if( !model.empty() )
{
file << "\t\t\t<model type='" << model << "'/>" << endl;
}
file << "\t\t</interface>" << endl;
}
attrs.clear();
file << "\t</devices>" << endl;
// ------------------------------------------------------------------------
// Raw VMware attributes
// ------------------------------------------------------------------------
num = vm->get_template_attribute("RAW",attrs);
for(int i=0; i<num;i++)
{
raw = dynamic_cast<const VectorAttribute *>(attrs[i]);
if ( raw == 0 )
{
continue;
}
type = raw->vector_value("TYPE");
transform(type.begin(),type.end(),type.begin(),(int(*)(int))toupper);
if ( type == "VMWARE" )
{
data = raw->vector_value("DATA");
file << "\t" << data << endl;
}
}
file << "</domain>" << endl;
file.close();
return 0;
error_vmware_file:
vm->log("VMM", Log::ERROR, "Could not open VMWARE deployment file.");
return -1;
error_vmware_arch:
vm->log("VMM", Log::ERROR, "No ARCH defined and no default provided.");
file.close();
return -1;
error_vmware_memory:
vm->log("VMM", Log::ERROR, "No MEMORY defined and no default provided.");
file.close();
return -1;
error_vmware_disk:
vm->log("VMM", Log::ERROR, "Wrong target value in DISK.");
file.close();
return -1;
}
<|endoftext|>
|
<commit_before>/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the License. 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.
*
* The Original Code is Hunspell, based on MySpell.
*
* The Initial Developers of the Original Code are
* Kevin Hendricks (MySpell) and Németh László (Hunspell).
* Portions created by the Initial Developers are Copyright (C) 2002-2005
* the Initial Developers. All Rights Reserved.
*
* Contributor(s): David Einstein, Davide Prina, Giuseppe Modugno,
* Gianluca Turconi, Simon Brouwer, Noll János, Bíró Árpád,
* Goldman Eleonóra, Sarlós Tamás, Bencsáth Boldizsár, Halácsy Péter,
* Dvornik László, Gefferth András, Nagy Viktor, Varga Dániel, Chris Halls,
* Rene Engelhard, Bram Moolenaar, Dafydd Jones, Harri Pitkänen
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
#ifndef _ATYPES_HXX_
#define _ATYPES_HXX_
#ifndef HUNSPELL_WARNING
#include <stdio.h>
#ifdef HUNSPELL_WARNING_ON
#define HUNSPELL_WARNING fprintf
#else
// empty inline function to switch off warnings (instead of the C99 standard
// variadic macros)
static inline void HUNSPELL_WARNING(FILE*, const char*, ...) {}
#endif
#endif
// HUNSTEM def.
#define HUNSTEM
#include "hashmgr.hxx"
#include "w_char.hxx"
#include <algorithm>
#include <string>
#define SETSIZE 256
#define CONTSIZE 65536
// AffEntry options
#define aeXPRODUCT (1 << 0)
#define aeUTF8 (1 << 1)
#define aeALIASF (1 << 2)
#define aeALIASM (1 << 3)
#define aeLONGCOND (1 << 4)
// compound options
#define IN_CPD_NOT 0
#define IN_CPD_BEGIN 1
#define IN_CPD_END 2
#define IN_CPD_OTHER 3
// info options
#define SPELL_COMPOUND (1 << 0)
#define SPELL_FORBIDDEN (1 << 1)
#define SPELL_ALLCAP (1 << 2)
#define SPELL_NOCAP (1 << 3)
#define SPELL_INITCAP (1 << 4)
#define SPELL_ORIGCAP (1 << 5)
#define SPELL_WARN (1 << 6)
#define MAXLNLEN 8192
#define MINCPDLEN 3
#define MAXCOMPOUND 10
#define MAXCONDLEN 20
#define MAXCONDLEN_1 (MAXCONDLEN - sizeof(char*))
#define MAXACC 1000
#define FLAG unsigned short
#define FLAG_NULL 0x00
#define FREE_FLAG(a) a = 0
#define TESTAFF(a, b, c) (std::binary_search(a, a + c, b))
struct guessword {
char* word;
bool allow;
char* orig;
};
typedef std::vector<std::string> mapentry;
typedef std::vector<FLAG> flagentry;
struct patentry {
std::string pattern;
std::string pattern2;
std::string pattern3;
FLAG cond;
FLAG cond2;
patentry()
: cond(FLAG_NULL)
, cond2(FLAG_NULL) {
}
};
#endif
<commit_msg>MAXLNLEN removed from library constraints<commit_after>/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the License. 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.
*
* The Original Code is Hunspell, based on MySpell.
*
* The Initial Developers of the Original Code are
* Kevin Hendricks (MySpell) and Németh László (Hunspell).
* Portions created by the Initial Developers are Copyright (C) 2002-2005
* the Initial Developers. All Rights Reserved.
*
* Contributor(s): David Einstein, Davide Prina, Giuseppe Modugno,
* Gianluca Turconi, Simon Brouwer, Noll János, Bíró Árpád,
* Goldman Eleonóra, Sarlós Tamás, Bencsáth Boldizsár, Halácsy Péter,
* Dvornik László, Gefferth András, Nagy Viktor, Varga Dániel, Chris Halls,
* Rene Engelhard, Bram Moolenaar, Dafydd Jones, Harri Pitkänen
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
#ifndef _ATYPES_HXX_
#define _ATYPES_HXX_
#ifndef HUNSPELL_WARNING
#include <stdio.h>
#ifdef HUNSPELL_WARNING_ON
#define HUNSPELL_WARNING fprintf
#else
// empty inline function to switch off warnings (instead of the C99 standard
// variadic macros)
static inline void HUNSPELL_WARNING(FILE*, const char*, ...) {}
#endif
#endif
// HUNSTEM def.
#define HUNSTEM
#include "hashmgr.hxx"
#include "w_char.hxx"
#include <algorithm>
#include <string>
#define SETSIZE 256
#define CONTSIZE 65536
// AffEntry options
#define aeXPRODUCT (1 << 0)
#define aeUTF8 (1 << 1)
#define aeALIASF (1 << 2)
#define aeALIASM (1 << 3)
#define aeLONGCOND (1 << 4)
// compound options
#define IN_CPD_NOT 0
#define IN_CPD_BEGIN 1
#define IN_CPD_END 2
#define IN_CPD_OTHER 3
// info options
#define SPELL_COMPOUND (1 << 0)
#define SPELL_FORBIDDEN (1 << 1)
#define SPELL_ALLCAP (1 << 2)
#define SPELL_NOCAP (1 << 3)
#define SPELL_INITCAP (1 << 4)
#define SPELL_ORIGCAP (1 << 5)
#define SPELL_WARN (1 << 6)
#define MINCPDLEN 3
#define MAXCOMPOUND 10
#define MAXCONDLEN 20
#define MAXCONDLEN_1 (MAXCONDLEN - sizeof(char*))
#define MAXACC 1000
#define FLAG unsigned short
#define FLAG_NULL 0x00
#define FREE_FLAG(a) a = 0
#define TESTAFF(a, b, c) (std::binary_search(a, a + c, b))
struct guessword {
char* word;
bool allow;
char* orig;
};
typedef std::vector<std::string> mapentry;
typedef std::vector<FLAG> flagentry;
struct patentry {
std::string pattern;
std::string pattern2;
std::string pattern3;
FLAG cond;
FLAG cond2;
patentry()
: cond(FLAG_NULL)
, cond2(FLAG_NULL) {
}
};
#endif
<|endoftext|>
|
<commit_before>/*
Copyright (c) 2003, Arvid Norberg
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in
the documentation and/or other materials provided with the distribution.
* Neither the name of the author nor the names of its
contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
#include <cctype>
#include <algorithm>
#ifdef _MSC_VER
#pragma warning(push, 1)
#endif
#include <boost/optional.hpp>
#ifdef _MSC_VER
#pragma warning(pop)
#endif
#include "libtorrent/identify_client.hpp"
#include "libtorrent/fingerprint.hpp"
namespace
{
using namespace libtorrent;
int decode_digit(char c)
{
if (std::isdigit(c)) return c - '0';
return unsigned(c) - 'A' + 10;
}
// takes a peer id and returns a valid boost::optional
// object if the peer id matched the azureus style encoding
// the returned fingerprint contains information about the
// client's id
boost::optional<fingerprint> parse_az_style(const peer_id& id)
{
fingerprint ret("..", 0, 0, 0, 0);
if (id[0] != '-' || !std::isprint(id[1]) || (id[2] < '0')
|| (id[3] < '0') || (id[4] < '0')
|| (id[5] < '0') || (id[6] < '0')
|| id[7] != '-')
return boost::optional<fingerprint>();
ret.name[0] = id[1];
ret.name[1] = id[2];
ret.major_version = decode_digit(id[3]);
ret.minor_version = decode_digit(id[4]);
ret.revision_version = decode_digit(id[5]);
ret.tag_version = decode_digit(id[6]);
return boost::optional<fingerprint>(ret);
}
// checks if a peer id can possibly contain a shadow-style
// identification
boost::optional<fingerprint> parse_shadow_style(const peer_id& id)
{
fingerprint ret("..", 0, 0, 0, 0);
if (!std::isalnum(id[0]))
return boost::optional<fingerprint>();
if (std::equal(id.begin()+4, id.begin()+6, "--"))
{
if ((id[1] < '0') || (id[2] < '0')
|| (id[3] < '0'))
return boost::optional<fingerprint>();
ret.major_version = decode_digit(id[1]);
ret.minor_version = decode_digit(id[2]);
ret.revision_version = decode_digit(id[3]);
}
else
{
if (id[8] != 0 || id[1] > 127 || id[2] > 127 || id[3] > 127)
return boost::optional<fingerprint>();
ret.major_version = id[1];
ret.minor_version = id[2];
ret.revision_version = id[3];
}
ret.name[0] = id[0];
ret.name[1] = 0;
ret.tag_version = 0;
return boost::optional<fingerprint>(ret);
}
// checks if a peer id can possibly contain a mainline-style
// identification
boost::optional<fingerprint> parse_mainline_style(const peer_id& id)
{
char ids[21];
std::copy(id.begin(), id.end(), ids);
ids[20] = 0;
fingerprint ret("..", 0, 0, 0, 0);
ret.name[1] = 0;
ret.tag_version = 0;
if (sscanf(ids, "%c%d-%d-%d--", &ret.name[0], &ret.major_version, &ret.minor_version
, &ret.revision_version) != 4
|| !std::isprint(ret.name[0]))
return boost::optional<fingerprint>();
return boost::optional<fingerprint>(ret);
}
typedef std::pair<char const*, char const*> map_entry;
// only support BitTorrentSpecification
// must be ordered alphabetically
map_entry name_map[] =
{
map_entry("A", "ABC")
, map_entry("AR", "Arctic Torrent")
, map_entry("AX", "BitPump")
, map_entry("AZ", "Azureus")
, map_entry("BB", "BitBuddy")
, map_entry("BC", "BitComet")
, map_entry("BS", "BTSlave")
, map_entry("BX", "BittorrentX")
, map_entry("CD", "Enhanced CTorrent")
, map_entry("CT", "CTorrent")
, map_entry("ES", "electric sheep")
, map_entry("KT", "KTorrent")
, map_entry("LP", "lphant")
, map_entry("LT", "libtorrent")
, map_entry("M", "Mainline")
, map_entry("MP", "MooPolice")
, map_entry("MT", "Moonlight Torrent")
, map_entry("O", "Osprey Permaseed")
, map_entry("R", "Tribler")
, map_entry("S", "Shadow")
, map_entry("SB", "Swiftbit")
, map_entry("SN", "ShareNet")
, map_entry("SS", "SwarmScope")
, map_entry("SZ", "Shareaza")
, map_entry("T", "BitTornado")
, map_entry("TN", "Torrent.NET")
, map_entry("TR", "Transmission")
, map_entry("TS", "TorrentStorm")
, map_entry("U", "UPnP")
, map_entry("UL", "uLeecher")
, map_entry("UT", "MicroTorrent")
, map_entry("XT", "XanTorrent")
, map_entry("ZT", "ZipTorrent")
, map_entry("lt", "libTorrent (libtorrent.rakshasa.no/)")
, map_entry("pX", "pHoeniX")
, map_entry("qB", "qBittorrent")
};
bool compare_first_string(map_entry const& lhs, map_entry const& rhs)
{
return lhs.first[0] < rhs.first[0]
|| ((lhs.first[0] == rhs.first[0]) && (lhs.first[1] < rhs.first[1]));
}
std::string lookup(fingerprint const& f)
{
std::stringstream identity;
const int size = sizeof(name_map)/sizeof(name_map[0]);
map_entry* i =
std::lower_bound(name_map, name_map + size
, map_entry(f.name, ""), &compare_first_string);
#ifndef NDEBUG
for (int i = 1; i < size; ++i)
{
assert(compare_first_string(name_map[i-1]
, name_map[i]));
}
#endif
if (i < name_map + size && std::equal(f.name, f.name + 2, i->first))
identity << i->second;
else
{
identity << f.name[0];
if (f.name[1] != 0) identity << f.name[1];
}
identity << " " << (int)f.major_version
<< "." << (int)f.minor_version
<< "." << (int)f.revision_version;
if (f.name[1] != 0)
identity << "." << (int)f.tag_version;
return identity.str();
}
bool find_string(unsigned char const* id, char const* search)
{
return std::equal(search, search + std::strlen(search), id);
}
}
namespace libtorrent
{
boost::optional<fingerprint> client_fingerprint(peer_id const& p)
{
// look for azureus style id
boost::optional<fingerprint> f;
f = parse_az_style(p);
if (f) return f;
// look for shadow style id
f = parse_shadow_style(p);
if (f) return f;
// look for mainline style id
f = parse_mainline_style(p);
if (f) return f;
return f;
}
std::string identify_client(peer_id const& p)
{
peer_id::const_iterator PID = p.begin();
boost::optional<fingerprint> f;
if (p.is_all_zeros()) return "Unknown";
// ----------------------
// non standard encodings
// ----------------------
if (find_string(PID, "Deadman Walking-")) return "Deadman";
if (find_string(PID + 5, "Azureus")) return "Azureus 2.0.3.2";
if (find_string(PID, "DansClient")) return "XanTorrent";
if (find_string(PID + 4, "btfans")) return "SimpleBT";
if (find_string(PID, "PRC.P---")) return "Bittorrent Plus! II";
if (find_string(PID, "P87.P---")) return "Bittorrent Plus!";
if (find_string(PID, "S587Plus")) return "Bittorrent Plus!";
if (find_string(PID, "martini")) return "Martini Man";
if (find_string(PID, "Plus---")) return "Bittorrent Plus";
if (find_string(PID, "turbobt")) return "TurboBT";
if (find_string(PID, "a00---0")) return "Swarmy";
if (find_string(PID, "a02---0")) return "Swarmy";
if (find_string(PID, "T00---0")) return "Teeweety";
if (find_string(PID, "BTDWV-")) return "Deadman Walking";
if (find_string(PID + 2, "BS")) return "BitSpirit";
if (find_string(PID, "btuga")) return "BTugaXP";
if (find_string(PID, "oernu")) return "BTugaXP";
if (find_string(PID, "Mbrst")) return "Burst!";
if (find_string(PID, "Plus")) return "Plus!";
if (find_string(PID, "-Qt-")) return "Qt";
if (find_string(PID, "exbc")) return "BitComet";
if (find_string(PID, "-G3")) return "G3 Torrent";
if (find_string(PID, "XBT")) return "XBT";
if (find_string(PID, "OP")) return "Opera";
if (find_string(PID, "-BOW") && PID[7] == '-')
return "Bits on Wheels " + std::string(PID + 4, PID + 7);
if (find_string(PID, "eX"))
{
std::string user(PID + 2, PID + 14);
return std::string("eXeem ('") + user.c_str() + "')";
}
if (std::equal(PID, PID + 13, "\0\0\0\0\0\0\0\0\0\0\0\0\x97"))
return "Experimental 3.2.1b2";
if (std::equal(PID, PID + 13, "\0\0\0\0\0\0\0\0\0\0\0\0\0"))
return "Experimental 3.1";
// look for azureus style id
f = parse_az_style(p);
if (f) return lookup(*f);
// look for shadow style id
f = parse_shadow_style(p);
if (f) return lookup(*f);
// look for mainline style id
f = parse_mainline_style(p);
if (f) return lookup(*f);
if (std::equal(PID, PID + 12, "\0\0\0\0\0\0\0\0\0\0\0\0"))
return "Generic";
std::string unknown("Unknown [");
for (peer_id::const_iterator i = p.begin(); i != p.end(); ++i)
{
unknown += std::isprint(*i)?*i:'.';
}
unknown += "]";
return unknown;
}
}
<commit_msg>added Deluge client id<commit_after>/*
Copyright (c) 2003, Arvid Norberg
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in
the documentation and/or other materials provided with the distribution.
* Neither the name of the author nor the names of its
contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
#include <cctype>
#include <algorithm>
#ifdef _MSC_VER
#pragma warning(push, 1)
#endif
#include <boost/optional.hpp>
#ifdef _MSC_VER
#pragma warning(pop)
#endif
#include "libtorrent/identify_client.hpp"
#include "libtorrent/fingerprint.hpp"
namespace
{
using namespace libtorrent;
int decode_digit(char c)
{
if (std::isdigit(c)) return c - '0';
return unsigned(c) - 'A' + 10;
}
// takes a peer id and returns a valid boost::optional
// object if the peer id matched the azureus style encoding
// the returned fingerprint contains information about the
// client's id
boost::optional<fingerprint> parse_az_style(const peer_id& id)
{
fingerprint ret("..", 0, 0, 0, 0);
if (id[0] != '-' || !std::isprint(id[1]) || (id[2] < '0')
|| (id[3] < '0') || (id[4] < '0')
|| (id[5] < '0') || (id[6] < '0')
|| id[7] != '-')
return boost::optional<fingerprint>();
ret.name[0] = id[1];
ret.name[1] = id[2];
ret.major_version = decode_digit(id[3]);
ret.minor_version = decode_digit(id[4]);
ret.revision_version = decode_digit(id[5]);
ret.tag_version = decode_digit(id[6]);
return boost::optional<fingerprint>(ret);
}
// checks if a peer id can possibly contain a shadow-style
// identification
boost::optional<fingerprint> parse_shadow_style(const peer_id& id)
{
fingerprint ret("..", 0, 0, 0, 0);
if (!std::isalnum(id[0]))
return boost::optional<fingerprint>();
if (std::equal(id.begin()+4, id.begin()+6, "--"))
{
if ((id[1] < '0') || (id[2] < '0')
|| (id[3] < '0'))
return boost::optional<fingerprint>();
ret.major_version = decode_digit(id[1]);
ret.minor_version = decode_digit(id[2]);
ret.revision_version = decode_digit(id[3]);
}
else
{
if (id[8] != 0 || id[1] > 127 || id[2] > 127 || id[3] > 127)
return boost::optional<fingerprint>();
ret.major_version = id[1];
ret.minor_version = id[2];
ret.revision_version = id[3];
}
ret.name[0] = id[0];
ret.name[1] = 0;
ret.tag_version = 0;
return boost::optional<fingerprint>(ret);
}
// checks if a peer id can possibly contain a mainline-style
// identification
boost::optional<fingerprint> parse_mainline_style(const peer_id& id)
{
char ids[21];
std::copy(id.begin(), id.end(), ids);
ids[20] = 0;
fingerprint ret("..", 0, 0, 0, 0);
ret.name[1] = 0;
ret.tag_version = 0;
if (sscanf(ids, "%c%d-%d-%d--", &ret.name[0], &ret.major_version, &ret.minor_version
, &ret.revision_version) != 4
|| !std::isprint(ret.name[0]))
return boost::optional<fingerprint>();
return boost::optional<fingerprint>(ret);
}
typedef std::pair<char const*, char const*> map_entry;
// only support BitTorrentSpecification
// must be ordered alphabetically
map_entry name_map[] =
{
map_entry("A", "ABC")
, map_entry("AR", "Arctic Torrent")
, map_entry("AX", "BitPump")
, map_entry("AZ", "Azureus")
, map_entry("BB", "BitBuddy")
, map_entry("BC", "BitComet")
, map_entry("BS", "BTSlave")
, map_entry("BX", "BittorrentX")
, map_entry("CD", "Enhanced CTorrent")
, map_entry("CT", "CTorrent")
, map_entry("DE", "Deluge")
, map_entry("ES", "electric sheep")
, map_entry("KT", "KTorrent")
, map_entry("LP", "lphant")
, map_entry("LT", "libtorrent")
, map_entry("M", "Mainline")
, map_entry("MP", "MooPolice")
, map_entry("MT", "Moonlight Torrent")
, map_entry("O", "Osprey Permaseed")
, map_entry("R", "Tribler")
, map_entry("S", "Shadow")
, map_entry("SB", "Swiftbit")
, map_entry("SN", "ShareNet")
, map_entry("SS", "SwarmScope")
, map_entry("SZ", "Shareaza")
, map_entry("T", "BitTornado")
, map_entry("TN", "Torrent.NET")
, map_entry("TR", "Transmission")
, map_entry("TS", "TorrentStorm")
, map_entry("U", "UPnP")
, map_entry("UL", "uLeecher")
, map_entry("UT", "MicroTorrent")
, map_entry("XT", "XanTorrent")
, map_entry("ZT", "ZipTorrent")
, map_entry("lt", "libTorrent (libtorrent.rakshasa.no/)")
, map_entry("pX", "pHoeniX")
, map_entry("qB", "qBittorrent")
};
bool compare_first_string(map_entry const& lhs, map_entry const& rhs)
{
return lhs.first[0] < rhs.first[0]
|| ((lhs.first[0] == rhs.first[0]) && (lhs.first[1] < rhs.first[1]));
}
std::string lookup(fingerprint const& f)
{
std::stringstream identity;
const int size = sizeof(name_map)/sizeof(name_map[0]);
map_entry* i =
std::lower_bound(name_map, name_map + size
, map_entry(f.name, ""), &compare_first_string);
#ifndef NDEBUG
for (int i = 1; i < size; ++i)
{
assert(compare_first_string(name_map[i-1]
, name_map[i]));
}
#endif
if (i < name_map + size && std::equal(f.name, f.name + 2, i->first))
identity << i->second;
else
{
identity << f.name[0];
if (f.name[1] != 0) identity << f.name[1];
}
identity << " " << (int)f.major_version
<< "." << (int)f.minor_version
<< "." << (int)f.revision_version;
if (f.name[1] != 0)
identity << "." << (int)f.tag_version;
return identity.str();
}
bool find_string(unsigned char const* id, char const* search)
{
return std::equal(search, search + std::strlen(search), id);
}
}
namespace libtorrent
{
boost::optional<fingerprint> client_fingerprint(peer_id const& p)
{
// look for azureus style id
boost::optional<fingerprint> f;
f = parse_az_style(p);
if (f) return f;
// look for shadow style id
f = parse_shadow_style(p);
if (f) return f;
// look for mainline style id
f = parse_mainline_style(p);
if (f) return f;
return f;
}
std::string identify_client(peer_id const& p)
{
peer_id::const_iterator PID = p.begin();
boost::optional<fingerprint> f;
if (p.is_all_zeros()) return "Unknown";
// ----------------------
// non standard encodings
// ----------------------
if (find_string(PID, "Deadman Walking-")) return "Deadman";
if (find_string(PID + 5, "Azureus")) return "Azureus 2.0.3.2";
if (find_string(PID, "DansClient")) return "XanTorrent";
if (find_string(PID + 4, "btfans")) return "SimpleBT";
if (find_string(PID, "PRC.P---")) return "Bittorrent Plus! II";
if (find_string(PID, "P87.P---")) return "Bittorrent Plus!";
if (find_string(PID, "S587Plus")) return "Bittorrent Plus!";
if (find_string(PID, "martini")) return "Martini Man";
if (find_string(PID, "Plus---")) return "Bittorrent Plus";
if (find_string(PID, "turbobt")) return "TurboBT";
if (find_string(PID, "a00---0")) return "Swarmy";
if (find_string(PID, "a02---0")) return "Swarmy";
if (find_string(PID, "T00---0")) return "Teeweety";
if (find_string(PID, "BTDWV-")) return "Deadman Walking";
if (find_string(PID + 2, "BS")) return "BitSpirit";
if (find_string(PID, "btuga")) return "BTugaXP";
if (find_string(PID, "oernu")) return "BTugaXP";
if (find_string(PID, "Mbrst")) return "Burst!";
if (find_string(PID, "Plus")) return "Plus!";
if (find_string(PID, "-Qt-")) return "Qt";
if (find_string(PID, "exbc")) return "BitComet";
if (find_string(PID, "-G3")) return "G3 Torrent";
if (find_string(PID, "XBT")) return "XBT";
if (find_string(PID, "OP")) return "Opera";
if (find_string(PID, "-BOW") && PID[7] == '-')
return "Bits on Wheels " + std::string(PID + 4, PID + 7);
if (find_string(PID, "eX"))
{
std::string user(PID + 2, PID + 14);
return std::string("eXeem ('") + user.c_str() + "')";
}
if (std::equal(PID, PID + 13, "\0\0\0\0\0\0\0\0\0\0\0\0\x97"))
return "Experimental 3.2.1b2";
if (std::equal(PID, PID + 13, "\0\0\0\0\0\0\0\0\0\0\0\0\0"))
return "Experimental 3.1";
// look for azureus style id
f = parse_az_style(p);
if (f) return lookup(*f);
// look for shadow style id
f = parse_shadow_style(p);
if (f) return lookup(*f);
// look for mainline style id
f = parse_mainline_style(p);
if (f) return lookup(*f);
if (std::equal(PID, PID + 12, "\0\0\0\0\0\0\0\0\0\0\0\0"))
return "Generic";
std::string unknown("Unknown [");
for (peer_id::const_iterator i = p.begin(); i != p.end(); ++i)
{
unknown += std::isprint(*i)?*i:'.';
}
unknown += "]";
return unknown;
}
}
<|endoftext|>
|
<commit_before>/*
Copyright (c) 2003, Arvid Norberg
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in
the documentation and/or other materials provided with the distribution.
* Neither the name of the author nor the names of its
contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
#include "libtorrent/pch.hpp"
#include <cctype>
#include <algorithm>
#ifdef _MSC_VER
#pragma warning(push, 1)
#endif
#include <boost/optional.hpp>
#ifdef _MSC_VER
#pragma warning(pop)
#endif
#include "libtorrent/identify_client.hpp"
#include "libtorrent/fingerprint.hpp"
namespace
{
using namespace libtorrent;
int decode_digit(char c)
{
if (std::isdigit(c)) return c - '0';
return unsigned(c) - 'A' + 10;
}
// takes a peer id and returns a valid boost::optional
// object if the peer id matched the azureus style encoding
// the returned fingerprint contains information about the
// client's id
boost::optional<fingerprint> parse_az_style(const peer_id& id)
{
fingerprint ret("..", 0, 0, 0, 0);
if (id[0] != '-' || !std::isprint(id[1]) || (id[2] < '0')
|| (id[3] < '0') || (id[4] < '0')
|| (id[5] < '0') || (id[6] < '0')
|| id[7] != '-')
return boost::optional<fingerprint>();
ret.name[0] = id[1];
ret.name[1] = id[2];
ret.major_version = decode_digit(id[3]);
ret.minor_version = decode_digit(id[4]);
ret.revision_version = decode_digit(id[5]);
ret.tag_version = decode_digit(id[6]);
return boost::optional<fingerprint>(ret);
}
// checks if a peer id can possibly contain a shadow-style
// identification
boost::optional<fingerprint> parse_shadow_style(const peer_id& id)
{
fingerprint ret("..", 0, 0, 0, 0);
if (!std::isalnum(id[0]))
return boost::optional<fingerprint>();
if (std::equal(id.begin()+4, id.begin()+6, "--"))
{
if ((id[1] < '0') || (id[2] < '0')
|| (id[3] < '0'))
return boost::optional<fingerprint>();
ret.major_version = decode_digit(id[1]);
ret.minor_version = decode_digit(id[2]);
ret.revision_version = decode_digit(id[3]);
}
else
{
if (id[8] != 0 || id[1] > 127 || id[2] > 127 || id[3] > 127)
return boost::optional<fingerprint>();
ret.major_version = id[1];
ret.minor_version = id[2];
ret.revision_version = id[3];
}
ret.name[0] = id[0];
ret.name[1] = 0;
ret.tag_version = 0;
return boost::optional<fingerprint>(ret);
}
// checks if a peer id can possibly contain a mainline-style
// identification
boost::optional<fingerprint> parse_mainline_style(const peer_id& id)
{
char ids[21];
std::copy(id.begin(), id.end(), ids);
ids[20] = 0;
fingerprint ret("..", 0, 0, 0, 0);
ret.name[1] = 0;
ret.tag_version = 0;
if (sscanf(ids, "%c%d-%d-%d--", &ret.name[0], &ret.major_version, &ret.minor_version
, &ret.revision_version) != 4
|| !std::isprint(ret.name[0]))
return boost::optional<fingerprint>();
return boost::optional<fingerprint>(ret);
}
struct map_entry
{
char const* id;
char const* name;
};
// only support BitTorrentSpecification
// must be ordered alphabetically
map_entry name_map[] =
{
{"A", "ABC"}
, {"AG", "Ares"}
, {"AR", "Arctic Torrent"}
, {"AV", "Avicora"}
, {"AX", "BitPump"}
, {"AZ", "Azureus"}
, {"A~", "Ares"}
, {"BB", "BitBuddy"}
, {"BC", "BitComet"}
, {"BF", "Bitflu"}
, {"BG", "BTG"}
, {"BR", "BitRocket"}
, {"BS", "BTSlave"}
, {"BX", "BittorrentX"}
, {"CD", "Enhanced CTorrent"}
, {"CT", "CTorrent"}
, {"DE", "Deluge Torrent"}
, {"EB", "EBit"}
, {"ES", "electric sheep"}
, {"HL", "Halite"}
, {"HN", "Hydranode"}
, {"KT", "KTorrent"}
, {"LK", "Linkage"}
, {"LP", "lphant"}
, {"LT", "libtorrent"}
, {"M", "Mainline"}
, {"ML", "MLDonkey"}
, {"MO", "Mono Torrent"}
, {"MP", "MooPolice"}
, {"MT", "Moonlight Torrent"}
, {"O", "Osprey Permaseed"}
, {"PD", "Pando"}
, {"Q", "BTQueue"}
, {"QT", "Qt 4"}
, {"R", "Tribler"}
, {"S", "Shadow"}
, {"SB", "Swiftbit"}
, {"SN", "ShareNet"}
, {"SS", "SwarmScope"}
, {"SZ", "Shareaza"}
, {"S~", "Shareaza (beta)"}
, {"T", "BitTornado"}
, {"TN", "Torrent.NET"}
, {"TR", "Transmission"}
, {"TS", "TorrentStorm"}
, {"TT", "TuoTu"}
, {"U", "UPnP"}
, {"UL", "uLeecher"}
, {"UT", "MicroTorrent"}
, {"XT", "XanTorrent"}
, {"XX", "Xtorrent"}
, {"ZT", "ZipTorrent"}
, {"lt", "libTorrent (libtorrent.rakshasa.no/}"}
, {"pX", "pHoeniX"}
, {"qB", "qBittorrent"}
};
bool compare_id(map_entry const& lhs, map_entry const& rhs)
{
return lhs.id[0] < rhs.id[0]
|| ((lhs.id[0] == rhs.id[0]) && (lhs.id[1] < rhs.id[1]));
}
std::string lookup(fingerprint const& f)
{
std::stringstream identity;
const int size = sizeof(name_map)/sizeof(name_map[0]);
map_entry tmp = {f.name, ""};
map_entry* i =
std::lower_bound(name_map, name_map + size
, tmp, &compare_id);
#ifndef NDEBUG
for (int i = 1; i < size; ++i)
{
assert(compare_id(name_map[i-1]
, name_map[i]));
}
#endif
if (i < name_map + size && std::equal(f.name, f.name + 2, i->id))
identity << i->name;
else
{
identity << f.name[0];
if (f.name[1] != 0) identity << f.name[1];
}
identity << " " << (int)f.major_version
<< "." << (int)f.minor_version
<< "." << (int)f.revision_version;
if (f.name[1] != 0)
identity << "." << (int)f.tag_version;
return identity.str();
}
bool find_string(unsigned char const* id, char const* search)
{
return std::equal(search, search + std::strlen(search), id);
}
}
namespace libtorrent
{
boost::optional<fingerprint> client_fingerprint(peer_id const& p)
{
// look for azureus style id
boost::optional<fingerprint> f;
f = parse_az_style(p);
if (f) return f;
// look for shadow style id
f = parse_shadow_style(p);
if (f) return f;
// look for mainline style id
f = parse_mainline_style(p);
if (f) return f;
return f;
}
std::string identify_client(peer_id const& p)
{
peer_id::const_iterator PID = p.begin();
boost::optional<fingerprint> f;
if (p.is_all_zeros()) return "Unknown";
// ----------------------
// non standard encodings
// ----------------------
if (find_string(PID, "Deadman Walking-")) return "Deadman";
if (find_string(PID + 5, "Azureus")) return "Azureus 2.0.3.2";
if (find_string(PID, "DansClient")) return "XanTorrent";
if (find_string(PID + 4, "btfans")) return "SimpleBT";
if (find_string(PID, "PRC.P---")) return "Bittorrent Plus! II";
if (find_string(PID, "P87.P---")) return "Bittorrent Plus!";
if (find_string(PID, "S587Plus")) return "Bittorrent Plus!";
if (find_string(PID, "martini")) return "Martini Man";
if (find_string(PID, "Plus---")) return "Bittorrent Plus";
if (find_string(PID, "turbobt")) return "TurboBT";
if (find_string(PID, "a00---0")) return "Swarmy";
if (find_string(PID, "a02---0")) return "Swarmy";
if (find_string(PID, "T00---0")) return "Teeweety";
if (find_string(PID, "BTDWV-")) return "Deadman Walking";
if (find_string(PID + 2, "BS")) return "BitSpirit";
if (find_string(PID, "btuga")) return "BTugaXP";
if (find_string(PID, "oernu")) return "BTugaXP";
if (find_string(PID, "Mbrst")) return "Burst!";
if (find_string(PID, "Plus")) return "Plus!";
if (find_string(PID, "-Qt-")) return "Qt";
if (find_string(PID, "exbc")) return "BitComet";
if (find_string(PID, "-G3")) return "G3 Torrent";
if (find_string(PID, "XBT")) return "XBT";
if (find_string(PID, "OP")) return "Opera";
if (find_string(PID, "-BOW") && PID[7] == '-')
return "Bits on Wheels " + std::string(PID + 4, PID + 7);
if (find_string(PID, "eX"))
{
std::string user(PID + 2, PID + 14);
return std::string("eXeem ('") + user.c_str() + "')";
}
if (std::equal(PID, PID + 13, "\0\0\0\0\0\0\0\0\0\0\0\0\x97"))
return "Experimental 3.2.1b2";
if (std::equal(PID, PID + 13, "\0\0\0\0\0\0\0\0\0\0\0\0\0"))
return "Experimental 3.1";
// look for azureus style id
f = parse_az_style(p);
if (f) return lookup(*f);
// look for shadow style id
f = parse_shadow_style(p);
if (f) return lookup(*f);
// look for mainline style id
f = parse_mainline_style(p);
if (f) return lookup(*f);
if (std::equal(PID, PID + 12, "\0\0\0\0\0\0\0\0\0\0\0\0"))
return "Generic";
std::string unknown("Unknown [");
for (peer_id::const_iterator i = p.begin(); i != p.end(); ++i)
{
unknown += std::isprint(*i)?*i:'.';
}
unknown += "]";
return unknown;
}
}
<commit_msg>updated identify client<commit_after>/*
Copyright (c) 2003, Arvid Norberg
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in
the documentation and/or other materials provided with the distribution.
* Neither the name of the author nor the names of its
contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
#include "libtorrent/pch.hpp"
#include <cctype>
#include <algorithm>
#ifdef _MSC_VER
#pragma warning(push, 1)
#endif
#include <boost/optional.hpp>
#ifdef _MSC_VER
#pragma warning(pop)
#endif
#include "libtorrent/identify_client.hpp"
#include "libtorrent/fingerprint.hpp"
namespace
{
using namespace libtorrent;
int decode_digit(char c)
{
if (std::isdigit(c)) return c - '0';
return unsigned(c) - 'A' + 10;
}
// takes a peer id and returns a valid boost::optional
// object if the peer id matched the azureus style encoding
// the returned fingerprint contains information about the
// client's id
boost::optional<fingerprint> parse_az_style(const peer_id& id)
{
fingerprint ret("..", 0, 0, 0, 0);
if (id[0] != '-' || !std::isprint(id[1]) || (id[2] < '0')
|| (id[3] < '0') || (id[4] < '0')
|| (id[5] < '0') || (id[6] < '0')
|| id[7] != '-')
return boost::optional<fingerprint>();
ret.name[0] = id[1];
ret.name[1] = id[2];
ret.major_version = decode_digit(id[3]);
ret.minor_version = decode_digit(id[4]);
ret.revision_version = decode_digit(id[5]);
ret.tag_version = decode_digit(id[6]);
return boost::optional<fingerprint>(ret);
}
// checks if a peer id can possibly contain a shadow-style
// identification
boost::optional<fingerprint> parse_shadow_style(const peer_id& id)
{
fingerprint ret("..", 0, 0, 0, 0);
if (!std::isalnum(id[0]))
return boost::optional<fingerprint>();
if (std::equal(id.begin()+4, id.begin()+6, "--"))
{
if ((id[1] < '0') || (id[2] < '0')
|| (id[3] < '0'))
return boost::optional<fingerprint>();
ret.major_version = decode_digit(id[1]);
ret.minor_version = decode_digit(id[2]);
ret.revision_version = decode_digit(id[3]);
}
else
{
if (id[8] != 0 || id[1] > 127 || id[2] > 127 || id[3] > 127)
return boost::optional<fingerprint>();
ret.major_version = id[1];
ret.minor_version = id[2];
ret.revision_version = id[3];
}
ret.name[0] = id[0];
ret.name[1] = 0;
ret.tag_version = 0;
return boost::optional<fingerprint>(ret);
}
// checks if a peer id can possibly contain a mainline-style
// identification
boost::optional<fingerprint> parse_mainline_style(const peer_id& id)
{
char ids[21];
std::copy(id.begin(), id.end(), ids);
ids[20] = 0;
fingerprint ret("..", 0, 0, 0, 0);
ret.name[1] = 0;
ret.tag_version = 0;
if (sscanf(ids, "%c%d-%d-%d--", &ret.name[0], &ret.major_version, &ret.minor_version
, &ret.revision_version) != 4
|| !std::isprint(ret.name[0]))
return boost::optional<fingerprint>();
return boost::optional<fingerprint>(ret);
}
struct map_entry
{
char const* id;
char const* name;
};
// only support BitTorrentSpecification
// must be ordered alphabetically
map_entry name_map[] =
{
{"A", "ABC"}
, {"AG", "Ares"}
, {"AR", "Arctic Torrent"}
, {"AV", "Avicora"}
, {"AX", "BitPump"}
, {"AZ", "Azureus"}
, {"A~", "Ares"}
, {"BB", "BitBuddy"}
, {"BC", "BitComet"}
, {"BF", "Bitflu"}
, {"BG", "BTG"}
, {"BR", "BitRocket"}
, {"BS", "BTSlave"}
, {"BX", "BittorrentX"}
, {"CD", "Enhanced CTorrent"}
, {"CT", "CTorrent"}
, {"DE", "Deluge Torrent"}
, {"EB", "EBit"}
, {"ES", "electric sheep"}
, {"HL", "Halite"}
, {"HN", "Hydranode"}
, {"KT", "KTorrent"}
, {"LK", "Linkage"}
, {"LP", "lphant"}
, {"LT", "libtorrent"}
, {"M", "Mainline"}
, {"ML", "MLDonkey"}
, {"MO", "Mono Torrent"}
, {"MP", "MooPolice"}
, {"MT", "Moonlight Torrent"}
, {"O", "Osprey Permaseed"}
, {"PD", "Pando"}
, {"Q", "BTQueue"}
, {"QT", "Qt 4"}
, {"R", "Tribler"}
, {"S", "Shadow"}
, {"SB", "Swiftbit"}
, {"SN", "ShareNet"}
, {"SS", "SwarmScope"}
, {"SZ", "Shareaza"}
, {"S~", "Shareaza (beta)"}
, {"T", "BitTornado"}
, {"TN", "Torrent.NET"}
, {"TR", "Transmission"}
, {"TS", "TorrentStorm"}
, {"TT", "TuoTu"}
, {"U", "UPnP"}
, {"UL", "uLeecher"}
, {"UT", "MicroTorrent"}
, {"XT", "XanTorrent"}
, {"XX", "Xtorrent"}
, {"ZT", "ZipTorrent"}
, {"lt", "rTorrent"}
, {"pX", "pHoeniX"}
, {"qB", "qBittorrent"}
};
bool compare_id(map_entry const& lhs, map_entry const& rhs)
{
return lhs.id[0] < rhs.id[0]
|| ((lhs.id[0] == rhs.id[0]) && (lhs.id[1] < rhs.id[1]));
}
std::string lookup(fingerprint const& f)
{
std::stringstream identity;
const int size = sizeof(name_map)/sizeof(name_map[0]);
map_entry tmp = {f.name, ""};
map_entry* i =
std::lower_bound(name_map, name_map + size
, tmp, &compare_id);
#ifndef NDEBUG
for (int i = 1; i < size; ++i)
{
assert(compare_id(name_map[i-1]
, name_map[i]));
}
#endif
if (i < name_map + size && std::equal(f.name, f.name + 2, i->id))
identity << i->name;
else
{
identity << f.name[0];
if (f.name[1] != 0) identity << f.name[1];
}
identity << " " << (int)f.major_version
<< "." << (int)f.minor_version
<< "." << (int)f.revision_version;
if (f.name[1] != 0)
identity << "." << (int)f.tag_version;
return identity.str();
}
bool find_string(unsigned char const* id, char const* search)
{
return std::equal(search, search + std::strlen(search), id);
}
}
namespace libtorrent
{
boost::optional<fingerprint> client_fingerprint(peer_id const& p)
{
// look for azureus style id
boost::optional<fingerprint> f;
f = parse_az_style(p);
if (f) return f;
// look for shadow style id
f = parse_shadow_style(p);
if (f) return f;
// look for mainline style id
f = parse_mainline_style(p);
if (f) return f;
return f;
}
std::string identify_client(peer_id const& p)
{
peer_id::const_iterator PID = p.begin();
boost::optional<fingerprint> f;
if (p.is_all_zeros()) return "Unknown";
// ----------------------
// non standard encodings
// ----------------------
if (find_string(PID, "Deadman Walking-")) return "Deadman";
if (find_string(PID + 5, "Azureus")) return "Azureus 2.0.3.2";
if (find_string(PID, "DansClient")) return "XanTorrent";
if (find_string(PID + 4, "btfans")) return "SimpleBT";
if (find_string(PID, "PRC.P---")) return "Bittorrent Plus! II";
if (find_string(PID, "P87.P---")) return "Bittorrent Plus!";
if (find_string(PID, "S587Plus")) return "Bittorrent Plus!";
if (find_string(PID, "martini")) return "Martini Man";
if (find_string(PID, "Plus---")) return "Bittorrent Plus";
if (find_string(PID, "turbobt")) return "TurboBT";
if (find_string(PID, "a00---0")) return "Swarmy";
if (find_string(PID, "a02---0")) return "Swarmy";
if (find_string(PID, "T00---0")) return "Teeweety";
if (find_string(PID, "BTDWV-")) return "Deadman Walking";
if (find_string(PID + 2, "BS")) return "BitSpirit";
if (find_string(PID, "btuga")) return "BTugaXP";
if (find_string(PID, "oernu")) return "BTugaXP";
if (find_string(PID, "Mbrst")) return "Burst!";
if (find_string(PID, "Plus")) return "Plus!";
if (find_string(PID, "-Qt-")) return "Qt";
if (find_string(PID, "exbc")) return "BitComet";
if (find_string(PID, "-G3")) return "G3 Torrent";
if (find_string(PID, "XBT")) return "XBT";
if (find_string(PID, "OP")) return "Opera";
if (find_string(PID, "-BOW") && PID[7] == '-')
return "Bits on Wheels " + std::string(PID + 4, PID + 7);
if (find_string(PID, "eX"))
{
std::string user(PID + 2, PID + 14);
return std::string("eXeem ('") + user.c_str() + "')";
}
if (std::equal(PID, PID + 13, "\0\0\0\0\0\0\0\0\0\0\0\0\x97"))
return "Experimental 3.2.1b2";
if (std::equal(PID, PID + 13, "\0\0\0\0\0\0\0\0\0\0\0\0\0"))
return "Experimental 3.1";
// look for azureus style id
f = parse_az_style(p);
if (f) return lookup(*f);
// look for shadow style id
f = parse_shadow_style(p);
if (f) return lookup(*f);
// look for mainline style id
f = parse_mainline_style(p);
if (f) return lookup(*f);
if (std::equal(PID, PID + 12, "\0\0\0\0\0\0\0\0\0\0\0\0"))
return "Generic";
std::string unknown("Unknown [");
for (peer_id::const_iterator i = p.begin(); i != p.end(); ++i)
{
unknown += std::isprint(*i)?*i:'.';
}
unknown += "]";
return unknown;
}
}
<|endoftext|>
|
<commit_before>/*
* Copyright © 2016 Red Hat, Inc
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library. If not, see <http://www.gnu.org/licenses/>.
*
* Authors:
* Jan Grulich <jgrulich@redhat.com>
*/
#include <QApplication>
#include <QDBusConnection>
#include <QLoggingCategory>
#include "desktopportal.h"
#include "appchooser.h"
#include "dbus/AppChooserAdaptor.h"
#include "filechooser.h"
#include "dbus/FileChooserAdaptor.h"
Q_LOGGING_CATEGORY(XdgDesktopPortalKde, "xdg-desktop-portal-kde")
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
a.setQuitOnLastWindowClosed(false);
QDBusConnection sessionBus = QDBusConnection::sessionBus();
if (sessionBus.registerService(QLatin1String("org.freedesktop.impl.portal.desktop.kde"))) {
DesktopPortal *desktopPortal = new DesktopPortal(&a);
if (sessionBus.registerVirtualObject(QLatin1String("/org/freedesktop/portal/desktop"), desktopPortal, QDBusConnection::VirtualObjectRegisterOption::SingleNode)) {
qCDebug(XdgDesktopPortalKde) << "Desktop portal registered successfuly";
} else {
qCDebug(XdgDesktopPortalKde) << "Failed to register desktop portal";
}
} else {
qCDebug(XdgDesktopPortalKde) << "Failed to register org.freedesktop.impl.portal.desktop.kde service";
}
return a.exec();
}
<commit_msg>Remove unused and unexisting headers<commit_after>/*
* Copyright © 2016 Red Hat, Inc
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library. If not, see <http://www.gnu.org/licenses/>.
*
* Authors:
* Jan Grulich <jgrulich@redhat.com>
*/
#include <QApplication>
#include <QDBusConnection>
#include <QLoggingCategory>
#include "desktopportal.h"
Q_LOGGING_CATEGORY(XdgDesktopPortalKde, "xdg-desktop-portal-kde")
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
a.setQuitOnLastWindowClosed(false);
QDBusConnection sessionBus = QDBusConnection::sessionBus();
if (sessionBus.registerService(QLatin1String("org.freedesktop.impl.portal.desktop.kde"))) {
DesktopPortal *desktopPortal = new DesktopPortal(&a);
if (sessionBus.registerVirtualObject(QLatin1String("/org/freedesktop/portal/desktop"), desktopPortal, QDBusConnection::VirtualObjectRegisterOption::SingleNode)) {
qCDebug(XdgDesktopPortalKde) << "Desktop portal registered successfuly";
} else {
qCDebug(XdgDesktopPortalKde) << "Failed to register desktop portal";
}
} else {
qCDebug(XdgDesktopPortalKde) << "Failed to register org.freedesktop.impl.portal.desktop.kde service";
}
return a.exec();
}
<|endoftext|>
|
<commit_before>/* The MIT License (MIT)
*
* Copyright (c) 2014-2018 David Medina and Tim Warburton
*
* 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
*/
#include <fstream>
#include <occa.hpp>
#include <occa/lang/modes/serial.hpp>
#include <occa/lang/modes/openmp.hpp>
#include <occa/lang/modes/opencl.hpp>
#include <occa/lang/modes/cuda.hpp>
using namespace occa;
// Global to make it accessible to autocomplete
cli::command occaCommand;
std::string envEcho(const std::string &arg) {
std::string ret = env::var(arg);
return (ret.size() ? ret : "[NOT SET]");
}
template <class TM>
std::string envEcho(const std::string &arg, const TM &defaultValue) {
std::string ret = env::var(arg);
return (ret.size() ? ret : toString(defaultValue));
}
bool removeDir(const std::string &dir, const bool promptCheck = true) {
if (!sys::dirExists(dir)) {
return false;
}
std::string input;
std::cout << " Removing [" << dir << "]";
if (promptCheck) {
std::cout << ", are you sure? [y/n]: ";
std::cin >> input;
strip(input);
} else {
std::cout << '\n';
input = "y";
}
if (input == "y") {
std::string command = "rm -rf " + dir;
ignoreResult( system(command.c_str()) );
} else if (input != "n") {
std::cout << " Input must be [y] or [n], ignoring clear command\n";
}
return true;
}
bool runClear(const cli::command &command,
jsonArray order,
jsonObject options,
jsonArray arguments) {
jsonObject::const_iterator it = options.begin();
if (it == options.end()) {
return false;
}
bool removedSomething = false;
const bool promptCheck = (options.find("yes") == options.end());
while (it != options.end()) {
if (it->first == "all") {
removedSomething |= removeDir(env::OCCA_CACHE_DIR, promptCheck);
} else if (it->first == "lib") {
const jsonArray &libGroups = it->second.array();
for (int i = 0; i < (int) libGroups.size(); ++i) {
const jsonArray &libs = libGroups[i].array();
for (int j = 0; j < (int) libs.size(); ++j) {
removedSomething |= removeDir(io::libraryPath() +
(std::string) libs[j],
promptCheck);
}
}
} else if (it->first == "libraries") {
removedSomething |= removeDir(io::libraryPath(), promptCheck);
} else if (it->first == "kernels") {
removedSomething |= removeDir(io::cachePath(), promptCheck);
} else if (it->first == "locks") {
const std::string lockPath = env::OCCA_CACHE_DIR + "locks/";
removedSomething |= removeDir(lockPath, promptCheck);
}
++it;
}
if (!removedSomething) {
std::cout << " Nothing to remove.\n";
}
return true;
}
bool runVersion(const cli::command &command,
jsonArray order,
jsonObject options,
jsonArray arguments) {
jsonObject::const_iterator it = options.begin();
if (it == options.end()) {
std::cout << OCCA_VERSION_STR << '\n';
}
else if (options.find("okl") != options.end()) {
std::cout << OKL_VERSION_STR << '\n';
}
return true;
}
bool runCache(const cli::command &command,
jsonArray order,
jsonObject options,
jsonArray arguments) {
std::string libDir = (io::libraryPath()
+ (std::string) arguments[0]
+ "/");
sys::mkpath(libDir);
const int fileCount = arguments.size();
for (int i = 1; i < fileCount; ++i) {
const std::string srcFile = arguments[i];
const std::string destFile = libDir + io::basename(srcFile);
if (!sys::fileExists(srcFile)) {
std::cerr << yellow("Warning") << ": File '"
<< srcFile << "' does not exist\n";
continue;
}
std::ifstream src(srcFile.c_str(), std::ios::binary);
std::ofstream dest(destFile.c_str(), std::ios::binary);
dest << src.rdbuf();
src.close();
dest.close();
}
return true;
}
bool runTranslate(const cli::command &command,
jsonArray order,
jsonObject options,
jsonArray arguments) {
const std::string mode = options["mode"][0][0];
const std::string filename = arguments[0];
if (!io::exists(filename)) {
occa::printError("File [" + filename + "] doesn't exist" );
::exit(1);
}
properties props;
json &propsList = options["props"];
const int propsCount = propsList.size();
for (int i = 0; i < propsCount; ++i) {
props += occa::properties((std::string) propsList[i][0]);
}
lang::parser_t *parser = NULL;
if (mode == "Serial") {
parser = new lang::okl::serialParser(props);
} else if (mode == "OpenMP") {
parser = new lang::okl::openmpParser(props);
} else if (mode == "OpenCL") {
parser = new lang::okl::openclParser(props);
} else if (mode == "CUDA") {
parser = new lang::okl::cudaParser(props);
}
if (!parser) {
occa::printError("Unable to translate for mode [" + mode + "]");
::exit(1);
}
parser->parseFile(filename);
bool success = parser->succeeded();
if (success) {
std::cout << parser->toString();
}
delete parser;
return success;
}
bool runEnv(const cli::command &command,
jsonArray order,
jsonObject options,
jsonArray arguments) {
std::cout << " Basic:\n"
<< " - OCCA_DIR : " << envEcho("OCCA_DIR") << "\n"
<< " - OCCA_CACHE_DIR : " << envEcho("OCCA_CACHE_DIR") << "\n"
<< " - OCCA_VERBOSE : " << envEcho("OCCA_VERBOSE") << "\n"
<< " - OCCA_UNSAFE : " << OCCA_UNSAFE << "\n"
<< " Makefile:\n"
<< " - CXX : " << envEcho("CXX") << "\n"
<< " - CXXFLAGS : " << envEcho("CXXFLAGS") << "\n"
<< " - FC : " << envEcho("FC") << "\n"
<< " - FCFLAGS : " << envEcho("FCFLAGS") << "\n"
<< " - LDFLAGS : " << envEcho("LDFLAGS") << "\n"
<< " Backend Support:\n"
<< " - OCCA_OPENMP_ENABLED : " << envEcho("OCCA_OPENMP_ENABLED", OCCA_OPENMP_ENABLED) << "\n"
<< " - OCCA_OPENCL_ENABLED : " << envEcho("OCCA_OPENCL_ENABLED", OCCA_OPENCL_ENABLED) << "\n"
<< " - OCCA_CUDA_ENABLED : " << envEcho("OCCA_CUDA_ENABLED", OCCA_CUDA_ENABLED) << "\n"
<< " Run-Time Options:\n"
<< " - OCCA_CXX : " << envEcho("OCCA_CXX") << "\n"
<< " - OCCA_CXXFLAGS : " << envEcho("OCCA_CXXFLAGS") << "\n"
<< " - OCCA_INCLUDE_PATH : " << envEcho("OCCA_INCLUDE_PATH") << "\n"
<< " - OCCA_LIBRARY_PATH : " << envEcho("OCCA_LIBRARY_PATH") << "\n"
<< " - OCCA_OPENCL_COMPILER_FLAGS : " << envEcho("OCCA_OPENCL_COMPILER_FLAGS") << "\n"
<< " - OCCA_CUDA_COMPILER : " << envEcho("OCCA_CUDA_COMPILER") << "\n"
<< " - OCCA_CUDA_COMPILER_FLAGS : " << envEcho("OCCA_CUDA_COMPILER_FLAGS") << "\n";
return true;
}
bool runInfo(const cli::command &command,
jsonArray order,
jsonObject options,
jsonArray arguments) {
printModeInfo();
return true;
}
bool runModes(const cli::command &command,
jsonArray order,
jsonObject options,
jsonArray arguments) {
strToModeMap &modes = modeMap();
strToModeMap::iterator it = modes.begin();
while (it != modes.end()) {
std::cout << it->first << '\n';
++it;
}
return true;
}
bool runBashAutocomplete(const cli::command &command,
jsonArray order,
jsonObject options,
jsonArray arguments) {
occaCommand.printBashAutocomplete();
return true;
}
int main(const int argc, const char **argv) {
cli::command versionCommand;
versionCommand
.withName("version")
.withCallback(runVersion)
.withDescription("Prints OCCA library version")
.addOption(cli::option("okl",
"Print the OKL language version")
.stopsExpansion());
cli::command cacheCommand;
cacheCommand
.withName("cache")
.withCallback(runCache)
.withDescription("Cache kernels")
.addArgument("LIBRARY",
"Library where kernels will be cached under",
true)
.addRepetitiveArgument("FILE",
"OKL files that will be cached.",
true);
cli::command clearCommand;
clearCommand
.withName("clear")
.withCallback(runClear)
.withDescription("Clears cached files and cache locks")
.addOption(cli::option('a', "all",
"Clear cached kernels, cached libraries, and locks.")
.stopsExpansion())
.addOption(cli::option("kernels",
"Clear cached kernels."))
.addOption(cli::option('l', "lib",
"Clear cached library.")
.reusable()
.expandsFunction("ls ${OCCA_CACHE_DIR:-${HOME}/.occa}/libraries"))
.addOption(cli::option("libraries",
"Clear cached libraries."))
.addOption(cli::option('o', "locks",
"Clear cache locks"))
.addOption(cli::option('y', "yes",
"Automatically answer everything with [y/yes]"));
cli::command translateCommand;
translateCommand
.withName("translate")
.withCallback(runTranslate)
.withDescription("Translate kernels")
.addOption(cli::option('m', "mode",
"Output mode")
.isRequired()
.withArgs(1)
.expandsFunction("occa modes"))
.addOption(cli::option('p', "props",
"Kernel properties")
.reusable()
.withArgs(1))
.addArgument("FILE",
"An .okl file",
true);
cli::command envCommand;
envCommand
.withName("env")
.withCallback(runEnv)
.withDescription("Print environment variables used in OCCA");
cli::command infoCommand;
infoCommand
.withName("info")
.withCallback(runInfo)
.withDescription("Prints information about available backend modes");
cli::command modesCommand;
modesCommand
.withName("modes")
.withCallback(runModes)
.withDescription("Prints available backend modes");
cli::command autocompleteBash;
autocompleteBash
.withName("bash")
.withCallback(runBashAutocomplete)
.withDescription("Prints bash functions to autocomplete occa commands and arguments");
cli::command autocompleteCommand;
autocompleteCommand
.withName("autocomplete")
.withDescription("Prints shell functions to autocomplete occa commands and arguments")
.requiresCommand()
.addCommand(autocompleteBash);
occaCommand
.withDescription("Can be used to display information of cache kernels.")
.requiresCommand()
.addCommand(versionCommand)
.addCommand(cacheCommand)
.addCommand(clearCommand)
.addCommand(translateCommand)
.addCommand(envCommand)
.addCommand(infoCommand)
.addCommand(modesCommand)
.addCommand(autocompleteCommand)
.run(argc, (const char**) argv);
return 0;
}
<commit_msg>[CLI] Added compile option<commit_after>/* The MIT License (MIT)
*
* Copyright (c) 2014-2018 David Medina and Tim Warburton
*
* 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
*/
#include <fstream>
#include <occa.hpp>
#include <occa/lang/modes/serial.hpp>
#include <occa/lang/modes/openmp.hpp>
#include <occa/lang/modes/opencl.hpp>
#include <occa/lang/modes/cuda.hpp>
using namespace occa;
// Global to make it accessible to autocomplete
cli::command occaCommand;
std::string envEcho(const std::string &arg) {
std::string ret = env::var(arg);
return (ret.size() ? ret : "[NOT SET]");
}
template <class TM>
std::string envEcho(const std::string &arg, const TM &defaultValue) {
std::string ret = env::var(arg);
return (ret.size() ? ret : toString(defaultValue));
}
bool removeDir(const std::string &dir, const bool promptCheck = true) {
if (!sys::dirExists(dir)) {
return false;
}
std::string input;
std::cout << " Removing [" << dir << "]";
if (promptCheck) {
std::cout << ", are you sure? [y/n]: ";
std::cin >> input;
strip(input);
} else {
std::cout << '\n';
input = "y";
}
if (input == "y") {
std::string command = "rm -rf " + dir;
ignoreResult( system(command.c_str()) );
} else if (input != "n") {
std::cout << " Input must be [y] or [n], ignoring clear command\n";
}
return true;
}
bool runClear(const cli::command &command,
jsonArray order,
jsonObject options,
jsonArray arguments) {
jsonObject::const_iterator it = options.begin();
if (it == options.end()) {
return false;
}
bool removedSomething = false;
const bool promptCheck = (options.find("yes") == options.end());
while (it != options.end()) {
if (it->first == "all") {
removedSomething |= removeDir(env::OCCA_CACHE_DIR, promptCheck);
} else if (it->first == "lib") {
const jsonArray &libGroups = it->second.array();
for (int i = 0; i < (int) libGroups.size(); ++i) {
const jsonArray &libs = libGroups[i].array();
for (int j = 0; j < (int) libs.size(); ++j) {
removedSomething |= removeDir(io::libraryPath() +
(std::string) libs[j],
promptCheck);
}
}
} else if (it->first == "libraries") {
removedSomething |= removeDir(io::libraryPath(), promptCheck);
} else if (it->first == "kernels") {
removedSomething |= removeDir(io::cachePath(), promptCheck);
} else if (it->first == "locks") {
const std::string lockPath = env::OCCA_CACHE_DIR + "locks/";
removedSomething |= removeDir(lockPath, promptCheck);
}
++it;
}
if (!removedSomething) {
std::cout << " Nothing to remove.\n";
}
return true;
}
bool runVersion(const cli::command &command,
jsonArray order,
jsonObject options,
jsonArray arguments) {
jsonObject::const_iterator it = options.begin();
if (it == options.end()) {
std::cout << OCCA_VERSION_STR << '\n';
}
else if (options.find("okl") != options.end()) {
std::cout << OKL_VERSION_STR << '\n';
}
return true;
}
bool runCache(const cli::command &command,
jsonArray order,
jsonObject options,
jsonArray arguments) {
std::string libDir = (io::libraryPath()
+ (std::string) arguments[0]
+ "/");
sys::mkpath(libDir);
const int fileCount = arguments.size();
for (int i = 1; i < fileCount; ++i) {
const std::string srcFile = arguments[i];
const std::string destFile = libDir + io::basename(srcFile);
if (!sys::fileExists(srcFile)) {
std::cerr << yellow("Warning") << ": File '"
<< srcFile << "' does not exist\n";
continue;
}
std::ifstream src(srcFile.c_str(), std::ios::binary);
std::ofstream dest(destFile.c_str(), std::ios::binary);
dest << src.rdbuf();
src.close();
dest.close();
}
return true;
}
properties getOptionProperties(jsonObject &options,
const std::string optionName) {
properties props;
jsonObject::iterator it = options.find(optionName);
if (it == options.end()) {
return props;
}
json &propsList = it->second;
const int propsCount = propsList.size();
for (int i = 0; i < propsCount; ++i) {
props += occa::properties((std::string) propsList[i][0]);
}
return props;
}
bool runTranslate(const cli::command &command,
jsonArray order,
jsonObject options,
jsonArray arguments) {
const std::string mode = options["mode"][0][0];
const std::string filename = arguments[0];
if (!io::exists(filename)) {
occa::printError("File [" + filename + "] doesn't exist" );
::exit(1);
}
properties kernelProps = getOptionProperties(options, "kernel-props");
lang::parser_t *parser = NULL;
if (mode == "Serial") {
parser = new lang::okl::serialParser(kernelProps);
} else if (mode == "OpenMP") {
parser = new lang::okl::openmpParser(kernelProps);
} else if (mode == "OpenCL") {
parser = new lang::okl::openclParser(kernelProps);
} else if (mode == "CUDA") {
parser = new lang::okl::cudaParser(kernelProps);
}
if (!parser) {
occa::printError("Unable to translate for mode [" + mode + "]");
::exit(1);
}
parser->parseFile(filename);
bool success = parser->succeeded();
if (success) {
std::cout << parser->toString();
}
delete parser;
return success;
}
bool runCompile(const cli::command &command,
jsonArray order,
jsonObject options,
jsonArray arguments) {
const std::string filename = arguments[0];
const std::string kernelName = arguments[1];
if (!io::exists(filename)) {
occa::printError("File [" + filename + "] doesn't exist" );
::exit(1);
}
properties deviceProps = getOptionProperties(options, "device-props");
properties kernelProps = getOptionProperties(options, "kernel-props");
kernelProps["verbose"] = true;
occa::device device(deviceProps);
device.buildKernel(filename, kernelName, kernelProps);
return true;
}
bool runEnv(const cli::command &command,
jsonArray order,
jsonObject options,
jsonArray arguments) {
std::cout << " Basic:\n"
<< " - OCCA_DIR : " << envEcho("OCCA_DIR") << "\n"
<< " - OCCA_CACHE_DIR : " << envEcho("OCCA_CACHE_DIR") << "\n"
<< " - OCCA_VERBOSE : " << envEcho("OCCA_VERBOSE") << "\n"
<< " - OCCA_UNSAFE : " << OCCA_UNSAFE << "\n"
<< " Makefile:\n"
<< " - CXX : " << envEcho("CXX") << "\n"
<< " - CXXFLAGS : " << envEcho("CXXFLAGS") << "\n"
<< " - FC : " << envEcho("FC") << "\n"
<< " - FCFLAGS : " << envEcho("FCFLAGS") << "\n"
<< " - LDFLAGS : " << envEcho("LDFLAGS") << "\n"
<< " Backend Support:\n"
<< " - OCCA_OPENMP_ENABLED : " << envEcho("OCCA_OPENMP_ENABLED", OCCA_OPENMP_ENABLED) << "\n"
<< " - OCCA_OPENCL_ENABLED : " << envEcho("OCCA_OPENCL_ENABLED", OCCA_OPENCL_ENABLED) << "\n"
<< " - OCCA_CUDA_ENABLED : " << envEcho("OCCA_CUDA_ENABLED", OCCA_CUDA_ENABLED) << "\n"
<< " Run-Time Options:\n"
<< " - OCCA_CXX : " << envEcho("OCCA_CXX") << "\n"
<< " - OCCA_CXXFLAGS : " << envEcho("OCCA_CXXFLAGS") << "\n"
<< " - OCCA_INCLUDE_PATH : " << envEcho("OCCA_INCLUDE_PATH") << "\n"
<< " - OCCA_LIBRARY_PATH : " << envEcho("OCCA_LIBRARY_PATH") << "\n"
<< " - OCCA_OPENCL_COMPILER_FLAGS : " << envEcho("OCCA_OPENCL_COMPILER_FLAGS") << "\n"
<< " - OCCA_CUDA_COMPILER : " << envEcho("OCCA_CUDA_COMPILER") << "\n"
<< " - OCCA_CUDA_COMPILER_FLAGS : " << envEcho("OCCA_CUDA_COMPILER_FLAGS") << "\n";
return true;
}
bool runInfo(const cli::command &command,
jsonArray order,
jsonObject options,
jsonArray arguments) {
printModeInfo();
return true;
}
bool runModes(const cli::command &command,
jsonArray order,
jsonObject options,
jsonArray arguments) {
strToModeMap &modes = modeMap();
strToModeMap::iterator it = modes.begin();
while (it != modes.end()) {
std::cout << it->first << '\n';
++it;
}
return true;
}
bool runBashAutocomplete(const cli::command &command,
jsonArray order,
jsonObject options,
jsonArray arguments) {
occaCommand.printBashAutocomplete();
return true;
}
int main(const int argc, const char **argv) {
cli::command versionCommand;
versionCommand
.withName("version")
.withCallback(runVersion)
.withDescription("Prints OCCA library version")
.addOption(cli::option("okl",
"Print the OKL language version")
.stopsExpansion());
cli::command cacheCommand;
cacheCommand
.withName("cache")
.withCallback(runCache)
.withDescription("Cache kernels")
.addArgument("LIBRARY",
"Library where kernels will be cached under",
true)
.addRepetitiveArgument("FILE",
"OKL files that will be cached.",
true);
cli::command clearCommand;
clearCommand
.withName("clear")
.withCallback(runClear)
.withDescription("Clears cached files and cache locks")
.addOption(cli::option('a', "all",
"Clear cached kernels, cached libraries, and locks.")
.stopsExpansion())
.addOption(cli::option("kernels",
"Clear cached kernels."))
.addOption(cli::option('l', "lib",
"Clear cached library.")
.reusable()
.expandsFunction("ls ${OCCA_CACHE_DIR:-${HOME}/.occa}/libraries"))
.addOption(cli::option("libraries",
"Clear cached libraries."))
.addOption(cli::option('o', "locks",
"Clear cache locks"))
.addOption(cli::option('y', "yes",
"Automatically answer everything with [y/yes]"));
cli::command translateCommand;
translateCommand
.withName("translate")
.withCallback(runTranslate)
.withDescription("Translate kernels")
.addOption(cli::option('m', "mode",
"Output mode")
.isRequired()
.withArgs(1)
.expandsFunction("occa modes"))
.addOption(cli::option('k', "kernel-props",
"Kernel properties")
.reusable()
.withArgs(1))
.addArgument("FILE",
"An .okl file",
true);
cli::command compileCommand;
compileCommand
.withName("compile")
.withCallback(runCompile)
.withDescription("Compile kernels")
.addOption(cli::option('d', "device-props",
"Device properties")
.reusable()
.withArgs(1))
.addOption(cli::option('k', "kernel-props",
"Kernel properties")
.reusable()
.withArgs(1))
.addArgument("FILE",
"An .okl file",
true)
.addArgument("KERNEL",
"Kernel name",
true);
cli::command envCommand;
envCommand
.withName("env")
.withCallback(runEnv)
.withDescription("Print environment variables used in OCCA");
cli::command infoCommand;
infoCommand
.withName("info")
.withCallback(runInfo)
.withDescription("Prints information about available backend modes");
cli::command modesCommand;
modesCommand
.withName("modes")
.withCallback(runModes)
.withDescription("Prints available backend modes");
cli::command autocompleteBash;
autocompleteBash
.withName("bash")
.withCallback(runBashAutocomplete)
.withDescription("Prints bash functions to autocomplete occa commands and arguments");
cli::command autocompleteCommand;
autocompleteCommand
.withName("autocomplete")
.withDescription("Prints shell functions to autocomplete occa commands and arguments")
.requiresCommand()
.addCommand(autocompleteBash);
occaCommand
.withDescription("Can be used to display information of cache kernels.")
.requiresCommand()
.addCommand(versionCommand)
.addCommand(cacheCommand)
.addCommand(clearCommand)
.addCommand(translateCommand)
.addCommand(compileCommand)
.addCommand(envCommand)
.addCommand(infoCommand)
.addCommand(modesCommand)
.addCommand(autocompleteCommand)
.run(argc, (const char**) argv);
return 0;
}
<|endoftext|>
|
<commit_before>//===--- Heap.cpp - Swift Language Heap Logic -----------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
//
// Implementations of the Swift heap
//
//===----------------------------------------------------------------------===//
#include "swift/Runtime/HeapObject.h"
#include "swift/Runtime/Heap.h"
#include "Private.h"
#include "swift/Runtime/Debug.h"
#include <stdlib.h>
using namespace swift;
void *swift::swift_slowAlloc(size_t size, size_t alignMask) {
// FIXME: use posix_memalign if alignMask is larger than the system guarantee.
void *p = malloc(size);
if (!p) swift::crash("Could not allocate memory.");
return p;
}
void swift::swift_slowDealloc(void *ptr, size_t bytes, size_t alignMask) {
free(ptr);
}
<commit_msg>[Runtime] Fix swift_slowAlloc to respect its alignMask parameter.<commit_after>//===--- Heap.cpp - Swift Language Heap Logic -----------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
//
// Implementations of the Swift heap
//
//===----------------------------------------------------------------------===//
#include "swift/Runtime/HeapObject.h"
#include "swift/Runtime/Heap.h"
#include "Private.h"
#include "swift/Runtime/Debug.h"
#include <stdlib.h>
using namespace swift;
void *swift::swift_slowAlloc(size_t size, size_t alignMask) {
void *p = AlignedAlloc(size, alignMask + 1);
if (!p) swift::crash("Could not allocate memory.");
return p;
}
void swift::swift_slowDealloc(void *ptr, size_t bytes, size_t alignMask) {
AlignedFree(ptr);
}
<|endoftext|>
|
<commit_before>#ifndef SERIALIZABLE_H
#define SERIALIZABLE_H
#include <string>
#include <type_traits>
#include "manager.hpp"
#define SERIAL_START void serializer (JsonTree* _json_tree_, bool _json_op_, string _json_path_) {serialize (_json_op_, _json_path_, _json_tree_,
#define SERIAL_END ); }
namespace json {
class Serializable {
public:
inline void serializeIn (JsonTree& tree, string p) {
serializer(&tree, false, p);
}
inline void serializeOut (JsonTree& tree, string p) {
serializer(&tree, true, p);
}
protected:
virtual void serializer (JsonTree* tree, bool b, string path) = 0;
template <class... Args>
static void serialize (bool _json_op_, string _json_path_, JsonTree* _json_tree_, Args... args) {
if (_json_op_){
_json_tree_->erase(_json_path_);
_json_tree_->addVector(_json_path_);
retribution (_json_tree_, 0, _json_path_, args...);
} else {
int i = 0;
int size = _json_tree_->getSizeAt(_json_path_);
initialize (_json_tree_, [&] ()
{
int aux = i;
if (i < size - 1)
i++;
return _json_path_ + "." + to_string(aux);
},
args...);
}
}
// Write
template <typename t>
void static retribution (JsonTree* tree, int index, string path, t* element) {
tree->add(*element, path);
}
template <class t, class... Args>
void static retribution (JsonTree* tree, int index, string path, t element, Args... args) {
tree->add(*element, path);
retribution (tree, index+1, path, args...);
}
// Vector
template <class t>
void static retribution (JsonTree* tree, int index, string path, vector <t>* vect) {
tree->addVector(path);
path = path + "." + to_string(index);
for (int j = 0; j < vect->size(); j++)
retribution (tree, j, path, &(*vect)[j]);
}
template <class t, class... Args>
void static retribution (JsonTree* tree, int index, string path, vector<t>* vect, Args... args) {
tree->addVector(path);
string newPath = path + "." + to_string(index);
for (int j = 0; j < vect->size(); j++)
retribution (tree, j, newPath, &(*vect)[j]);
retribution (tree, index+1, path, args...);
}
// Read
template <typename t, class func>
void static initialize (JsonTree* tree, func functor, t* element) {
tree->get(*element, functor());
}
template <class t, class func, class... Args>
void static initialize (JsonTree* tree, func functor, t* element, Args... args) {
tree->get(*element, functor());
initialize (tree, functor, args...);
}
// Vector
template <class t, class func>
void static initialize (JsonTree* tree, func functor, vector <t>* vect) {
string newPath = functor();
int size = tree->getSizeAt(newPath);
vect->resize (size);
int i = 0;
for (int j = 0; j < size; j++) {
initialize (tree, [&] () {
return newPath + "." + to_string(i);
}, &(*vect)[j]);
i++;
}
}
template <class t, class func, class... Args>
void static initialize (JsonTree* tree, func functor, vector <t>* vect, Args... args) {
string newPath = functor();
int size = tree->getSizeAt(newPath);
vect->resize (size);
int i = 0;
for (int j = 0; j < vect->size(); j++) {
initialize (tree, [&] () {
return newPath + "." + to_string(i);
}, &(*vect)[j]);
i++;
}
initialize (tree, functor, args...);
}
//Pointers of SERIALIZABLE classes
template <class t, class func>
typename std::enable_if<std::is_base_of<Serializable, t>::value, void>::type
static initialize (JsonTree* tree, func functor, t** element) {
*element = new t ();
(*element)->serializeIn (*tree, functor());
}
template <class t, class func, class... Args>
typename std::enable_if<std::is_base_of<Serializable, t>::value, void>::type
static initialize (JsonTree* tree, func functor, t** element, Args... args) {
*element = new t ();
(*element)->serializeIn (*tree, functor());
initialize (tree, functor, args...);
}
//Pointers of NON SERIALIZABLE classes
template <class t, class func>
typename std::enable_if<std::is_fundamental<t>::value, void>::type
static initialize (JsonTree* tree, func functor, t** element) {
*element = new t ();
tree->get(**element, functor());
}
template <class t, class func, class... Args>
typename std::enable_if<std::is_fundamental<t>::value, void>::type
static initialize (JsonTree* tree, func functor, t** element, Args... args) {
*element = new t ();
tree->get(**element, functor());
initialize (tree, functor, args...);
}
};
}
#endif // SERIALIZABLE_H
<commit_msg>Construcción con puteros mejorada<commit_after>#ifndef SERIALIZABLE_H
#define SERIALIZABLE_H
#include <string>
#include <type_traits>
#include "manager.hpp"
#define SERIAL_START void serializer (JsonTree* _json_tree_, bool _json_op_, string _json_path_) {serialize (_json_op_, _json_path_, _json_tree_,
#define SERIAL_END ); }
namespace json {
class Serializable {
public:
inline void serializeIn (JsonTree& tree, string p) {
serializer(&tree, false, p);
}
inline void serializeOut (JsonTree& tree, string p) {
serializer(&tree, true, p);
}
protected:
virtual void serializer (JsonTree* tree, bool b, string path) = 0;
template <class... Args>
static void serialize (bool _json_op_, string _json_path_, JsonTree* _json_tree_, Args... args) {
if (_json_op_){
_json_tree_->erase(_json_path_);
_json_tree_->addVector(_json_path_);
retribution (_json_tree_, 0, _json_path_, args...);
} else {
int i = 0;
int size = _json_tree_->getSizeAt(_json_path_);
initialize (_json_tree_, [&] ()
{
int aux = i;
if (i < size - 1)
i++;
return _json_path_ + "." + to_string(aux);
},
args...);
}
}
// Write
// NON SERIALIZABLE classes
template <typename t>
typename std::enable_if<!std::is_base_of<Serializable, t>::value, void>::type
static retribution (JsonTree* tree, int index, string path, t* element) {
tree->add(*element, path);
}
template <class t, class... Args>
typename std::enable_if<!std::is_base_of<Serializable, t>::value, void>::type
static retribution (JsonTree* tree, int index, string path, t element, Args... args) {
tree->add(*element, path);
retribution (tree, index+1, path, args...);
}
// SERIALIZABLE classes
template <typename t>
typename std::enable_if<std::is_base_of<Serializable, t>::value, void>::type
static retribution (JsonTree* tree, int index, string path, t* element) {
//tree->add(*element, path);
}
template <class t, class... Args>
typename std::enable_if<std::is_base_of<Serializable, t>::value, void>::type
static retribution (JsonTree* tree, int index, string path, t* element, Args... args) {
//tree->add(*element, path);
retribution (tree, index+1, path, args...);
}
// Vector
template <class t>
void static retribution (JsonTree* tree, int index, string path, vector <t>* vect) {
tree->addVector(path);
path = path + "." + to_string(index);
for (int j = 0; j < vect->size(); j++)
retribution (tree, j, path, &(*vect)[j]);
}
template <class t, class... Args>
void static retribution (JsonTree* tree, int index, string path, vector<t>* vect, Args... args) {
tree->addVector(path);
string newPath = path + "." + to_string(index);
for (int j = 0; j < vect->size(); j++)
retribution (tree, j, newPath, &(*vect)[j]);
retribution (tree, index+1, path, args...);
}
// Pointers of SERIALIZABLE classes
template <typename t>
typename std::enable_if<std::is_base_of<Serializable, t>::value, void>::type
static retribution (JsonTree* tree, int index, string path, t** element) {
//tree->add(*element, path);
}
template <class t, class... Args>
typename std::enable_if<std::is_base_of<Serializable, t>::value, void>::type
static retribution (JsonTree* tree, int index, string path, t** element, Args... args) {
//tree->add(*element, path);
retribution (tree, index+1, path, args...);
}
// Pointers of NON SERIALIZABLE classes
template <typename t>
typename std::enable_if<!std::is_base_of<Serializable, t>::value, void>::type
static retribution (JsonTree* tree, int index, string path, t** element) {
tree->add(**element, path);
}
template <class t, class... Args>
typename std::enable_if<!std::is_base_of<Serializable, t>::value, void>::type
static retribution (JsonTree* tree, int index, string path, t** element, Args... args) {
tree->add(**element, path);
retribution (tree, index+1, path, args...);
}
// Read
// NON SERIALIZABLE classes
template <typename t, class func>
typename std::enable_if<!std::is_base_of<Serializable, t>::value, void>::type
static initialize (JsonTree* tree, func functor, t* element) {
tree->get(*element, functor());
}
template <class t, class func, class... Args>
typename std::enable_if<!std::is_base_of<Serializable, t>::value, void>::type
static initialize (JsonTree* tree, func functor, t* element, Args... args) {
tree->get(*element, functor());
initialize (tree, functor, args...);
}
// SERIALIZABLE classes
template <typename t, class func>
typename std::enable_if<std::is_base_of<Serializable, t>::value, void>::type
static initialize (JsonTree* tree, func functor, t* element) {
element->serializeIn (*tree, functor());
}
template <class t, class func, class... Args>
typename std::enable_if<std::is_base_of<Serializable, t>::value, void>::type
static initialize (JsonTree* tree, func functor, t* element, Args... args) {
element->serializeIn (*tree, functor());
initialize (tree, functor, args...);
}
// Vector
template <class t, class func>
void static initialize (JsonTree* tree, func functor, vector <t>* vect) {
string newPath = functor();
int size = tree->getSizeAt(newPath);
vect->resize (size);
int i = 0;
for (int j = 0; j < size; j++) {
initialize (tree, [&] () {
return newPath + "." + to_string(i);
}, &(*vect)[j]);
i++;
}
}
template <class t, class func, class... Args>
void static initialize (JsonTree* tree, func functor, vector <t>* vect, Args... args) {
string newPath = functor();
int size = tree->getSizeAt(newPath);
vect->resize (size);
int i = 0;
for (int j = 0; j < vect->size(); j++) {
initialize (tree, [&] () {
return newPath + "." + to_string(i);
}, &(*vect)[j]);
i++;
}
initialize (tree, functor, args...);
}
// Pointers of SERIALIZABLE classes
template <class t, class func>
typename std::enable_if<std::is_base_of<Serializable, t>::value, void>::type
static initialize (JsonTree* tree, func functor, t** element) {
*element = new t ();
(*element)->serializeIn (*tree, functor());
}
template <class t, class func, class... Args>
typename std::enable_if<std::is_base_of<Serializable, t>::value, void>::type
static initialize (JsonTree* tree, func functor, t** element, Args... args) {
*element = new t ();
(*element)->serializeIn (*tree, functor());
initialize (tree, functor, args...);
}
// Pointers of NON SERIALIZABLE classes
template <class t, class func>
typename std::enable_if<!std::is_base_of<Serializable, t>::value, void>::type
static initialize (JsonTree* tree, func functor, t** element) {
*element = new t ();
tree->get(**element, functor());
}
template <class t, class func, class... Args>
typename std::enable_if<!std::is_base_of<Serializable, t>::value, void>::type
static initialize (JsonTree* tree, func functor, t** element, Args... args) {
*element = new t ();
tree->get(**element, functor());
initialize (tree, functor, args...);
}
};
}
#endif // SERIALIZABLE_H
<|endoftext|>
|
<commit_before><commit_msg>Remove unnecessary include<commit_after><|endoftext|>
|
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: rlrcitem.cxx,v $
*
* $Revision: 1.8 $
*
* last change: $Author: obo $ $Date: 2006-09-17 04:36:29 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_svx.hxx"
// INCLUDE ---------------------------------------------------------------
#ifndef _SFXRECTITEM_HXX
#include <svtools/rectitem.hxx>
#endif
#define ITEMID_LRSPACE 0
#define ITEMID_ULSPACE 0
#define ITEMID_TABSTOP 0
#define ITEMID_PROTECT 0
#include "dialogs.hrc"
#include "ruler.hxx"
#include "lrspitem.hxx"
#include "ulspitem.hxx"
#include "tstpitem.hxx"
#include "protitem.hxx"
#include "rlrcitem.hxx"
#include "rulritem.hxx"
#ifndef _SFXENUMITEM_HXX
#include <svtools/eitem.hxx>
#endif
// class SvxRulerItem ----------------------------------------------------
SvxRulerItem::SvxRulerItem(USHORT _nId, SvxRuler &rRul, SfxBindings &rBindings)
: SfxControllerItem(_nId, rBindings),
rRuler(rRul)
{
}
// -----------------------------------------------------------------------
void SvxRulerItem::StateChanged( USHORT nSID, SfxItemState eState,
const SfxPoolItem* pState)
{
// SFX_ITEM_DONTCARE => pState == -1 => PTR_CAST buff
if ( eState != SFX_ITEM_AVAILABLE )
pState = 0;
switch(nSID)
{
// Linker / rechter Seitenrand
case SID_RULER_LR_MIN_MAX:
{
const SfxRectangleItem *pItem = PTR_CAST(SfxRectangleItem, pState);
rRuler.UpdateFrameMinMax(pItem);
break;
}
case SID_ATTR_LONG_LRSPACE:
{
const SvxLongLRSpaceItem *pItem = PTR_CAST(SvxLongLRSpaceItem, pState);
DBG_ASSERT(pState? 0 != pItem: TRUE, "SvxLRSpaceItem erwartet");
rRuler.UpdateFrame(pItem);
break;
}
case SID_ATTR_LONG_ULSPACE:
{
const SvxLongULSpaceItem *pItem = PTR_CAST(SvxLongULSpaceItem, pState);
DBG_ASSERT(pState? 0 != pItem: TRUE, "SvxULSpaceItem erwartet");
rRuler.UpdateFrame(pItem);
break;
}
case SID_ATTR_TABSTOP_VERTICAL:
case SID_ATTR_TABSTOP:
{
const SvxTabStopItem *pItem = PTR_CAST(SvxTabStopItem, pState);
DBG_ASSERT(pState? 0 != pItem: TRUE, "SvxTabStopItem erwartet");
rRuler.Update(pItem);
break;
}
case SID_ATTR_PARA_LRSPACE_VERTICAL:
case SID_ATTR_PARA_LRSPACE:
{
const SvxLRSpaceItem *pItem = PTR_CAST(SvxLRSpaceItem, pState);
DBG_ASSERT(pState? 0 != pItem: TRUE, "SvxLRSpaceItem erwartet");
rRuler.UpdatePara(pItem);
break;
}
case SID_RULER_BORDERS_VERTICAL:
case SID_RULER_BORDERS:
case SID_RULER_ROWS:
case SID_RULER_ROWS_VERTICAL:
{
const SvxColumnItem *pItem = PTR_CAST(SvxColumnItem, pState);
DBG_ASSERT(pState? 0 != pItem: TRUE, "SvxColumnItem erwartet");
#ifdef DBG_UTIL
if(pItem)
{
if(pItem->IsConsistent())
rRuler.Update(pItem, nSID);
else
DBG_ERROR("Spaltenitem corrupted");
}
else
rRuler.Update(pItem, nSID);
#else
rRuler.Update(pItem, nSID);
#endif
break;
}
case SID_RULER_PAGE_POS:
{ // Position Seite, Seitenbreite
const SvxPagePosSizeItem *pItem = PTR_CAST(SvxPagePosSizeItem, pState);
DBG_ASSERT(pState? 0 != pItem: TRUE, "SvxPagePosSizeItem erwartet");
rRuler.Update(pItem);
break;
}
case SID_RULER_OBJECT:
{ // Object-Selektion
const SvxObjectItem *pItem = PTR_CAST(SvxObjectItem, pState);
DBG_ASSERT(pState? 0 != pItem: TRUE, "SvxObjectItem erwartet");
rRuler.Update(pItem);
break;
}
case SID_RULER_PROTECT:
{
const SvxProtectItem *pItem = PTR_CAST(SvxProtectItem, pState);
DBG_ASSERT(pState? 0 != pItem: TRUE, "SvxProtectItem erwartet");
rRuler.Update(pItem);
break;
}
case SID_RULER_BORDER_DISTANCE:
{
const SvxLRSpaceItem *pItem = PTR_CAST(SvxLRSpaceItem, pState);
DBG_ASSERT(pState? 0 != pItem: TRUE, "SvxLRSpaceItem erwartet");
rRuler.UpdateParaBorder(pItem);
}
break;
case SID_RULER_TEXT_RIGHT_TO_LEFT :
{
const SfxBoolItem *pItem = PTR_CAST(SfxBoolItem, pState);
DBG_ASSERT(pState? 0 != pItem: TRUE, "SfxBoolItem erwartet");
rRuler.UpdateTextRTL(pItem);
}
break;
}
}
<commit_msg>INTEGRATION: CWS pchfix04 (1.8.124); FILE MERGED 2007/02/05 12:13:55 os 1.8.124.1: #i73604# usage of ITEMID_* removed<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: rlrcitem.cxx,v $
*
* $Revision: 1.9 $
*
* last change: $Author: kz $ $Date: 2007-05-10 14:41:00 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_svx.hxx"
// INCLUDE ---------------------------------------------------------------
#ifndef _SFXRECTITEM_HXX
#include <svtools/rectitem.hxx>
#endif
#include "dialogs.hrc"
#include "ruler.hxx"
#include "lrspitem.hxx"
#include "ulspitem.hxx"
#include "tstpitem.hxx"
#include "protitem.hxx"
#include "rlrcitem.hxx"
#include "rulritem.hxx"
#ifndef _SFXENUMITEM_HXX
#include <svtools/eitem.hxx>
#endif
// class SvxRulerItem ----------------------------------------------------
SvxRulerItem::SvxRulerItem(USHORT _nId, SvxRuler &rRul, SfxBindings &rBindings)
: SfxControllerItem(_nId, rBindings),
rRuler(rRul)
{
}
// -----------------------------------------------------------------------
void SvxRulerItem::StateChanged( USHORT nSID, SfxItemState eState,
const SfxPoolItem* pState)
{
// SFX_ITEM_DONTCARE => pState == -1 => PTR_CAST buff
if ( eState != SFX_ITEM_AVAILABLE )
pState = 0;
switch(nSID)
{
// Linker / rechter Seitenrand
case SID_RULER_LR_MIN_MAX:
{
const SfxRectangleItem *pItem = PTR_CAST(SfxRectangleItem, pState);
rRuler.UpdateFrameMinMax(pItem);
break;
}
case SID_ATTR_LONG_LRSPACE:
{
const SvxLongLRSpaceItem *pItem = PTR_CAST(SvxLongLRSpaceItem, pState);
DBG_ASSERT(pState? 0 != pItem: TRUE, "SvxLRSpaceItem erwartet");
rRuler.UpdateFrame(pItem);
break;
}
case SID_ATTR_LONG_ULSPACE:
{
const SvxLongULSpaceItem *pItem = PTR_CAST(SvxLongULSpaceItem, pState);
DBG_ASSERT(pState? 0 != pItem: TRUE, "SvxULSpaceItem erwartet");
rRuler.UpdateFrame(pItem);
break;
}
case SID_ATTR_TABSTOP_VERTICAL:
case SID_ATTR_TABSTOP:
{
const SvxTabStopItem *pItem = PTR_CAST(SvxTabStopItem, pState);
DBG_ASSERT(pState? 0 != pItem: TRUE, "SvxTabStopItem erwartet");
rRuler.Update(pItem);
break;
}
case SID_ATTR_PARA_LRSPACE_VERTICAL:
case SID_ATTR_PARA_LRSPACE:
{
const SvxLRSpaceItem *pItem = PTR_CAST(SvxLRSpaceItem, pState);
DBG_ASSERT(pState? 0 != pItem: TRUE, "SvxLRSpaceItem erwartet");
rRuler.UpdatePara(pItem);
break;
}
case SID_RULER_BORDERS_VERTICAL:
case SID_RULER_BORDERS:
case SID_RULER_ROWS:
case SID_RULER_ROWS_VERTICAL:
{
const SvxColumnItem *pItem = PTR_CAST(SvxColumnItem, pState);
DBG_ASSERT(pState? 0 != pItem: TRUE, "SvxColumnItem erwartet");
#ifdef DBG_UTIL
if(pItem)
{
if(pItem->IsConsistent())
rRuler.Update(pItem, nSID);
else
DBG_ERROR("Spaltenitem corrupted");
}
else
rRuler.Update(pItem, nSID);
#else
rRuler.Update(pItem, nSID);
#endif
break;
}
case SID_RULER_PAGE_POS:
{ // Position Seite, Seitenbreite
const SvxPagePosSizeItem *pItem = PTR_CAST(SvxPagePosSizeItem, pState);
DBG_ASSERT(pState? 0 != pItem: TRUE, "SvxPagePosSizeItem erwartet");
rRuler.Update(pItem);
break;
}
case SID_RULER_OBJECT:
{ // Object-Selektion
const SvxObjectItem *pItem = PTR_CAST(SvxObjectItem, pState);
DBG_ASSERT(pState? 0 != pItem: TRUE, "SvxObjectItem erwartet");
rRuler.Update(pItem);
break;
}
case SID_RULER_PROTECT:
{
const SvxProtectItem *pItem = PTR_CAST(SvxProtectItem, pState);
DBG_ASSERT(pState? 0 != pItem: TRUE, "SvxProtectItem erwartet");
rRuler.Update(pItem);
break;
}
case SID_RULER_BORDER_DISTANCE:
{
const SvxLRSpaceItem *pItem = PTR_CAST(SvxLRSpaceItem, pState);
DBG_ASSERT(pState? 0 != pItem: TRUE, "SvxLRSpaceItem erwartet");
rRuler.UpdateParaBorder(pItem);
}
break;
case SID_RULER_TEXT_RIGHT_TO_LEFT :
{
const SfxBoolItem *pItem = PTR_CAST(SfxBoolItem, pState);
DBG_ASSERT(pState? 0 != pItem: TRUE, "SfxBoolItem erwartet");
rRuler.UpdateTextRTL(pItem);
}
break;
}
}
<|endoftext|>
|
<commit_before>/******************************************************************************
* Copyright (C) 2018 Kitsune Ral <kitsune-ral@users.sf.net>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include "util.h"
#include <QtCore/QRegularExpression>
#include <QtCore/QStandardPaths>
#include <QtCore/QDir>
#include <QtCore/QStringBuilder>
static const auto RegExpOptions =
QRegularExpression::CaseInsensitiveOption
| QRegularExpression::OptimizeOnFirstUsageOption
| QRegularExpression::UseUnicodePropertiesOption;
// Converts all that looks like a URL into HTML links
static void linkifyUrls(QString& htmlEscapedText)
{
// regexp is originally taken from Konsole (https://github.com/KDE/konsole)
// full url:
// protocolname:// or www. followed by anything other than whitespaces,
// <, >, ' or ", and ends before whitespaces, <, >, ', ", ], !, ), :,
// comma or dot
// Note: outer parentheses are a part of C++ raw string delimiters, not of
// the regex (see http://en.cppreference.com/w/cpp/language/string_literal).
// Note2: yet another pair of outer parentheses are \1 in the replacement.
static const QRegularExpression FullUrlRegExp(QStringLiteral(
R"(((www\.(?!\.)|(https?|ftp|magnet)://)(&(?![lg]t;)|[^&\s<>'"])+(&(?![lg]t;)|[^&!,.\s<>'"\]):])))"
), RegExpOptions);
// email address:
// [word chars, dots or dashes]@[word chars, dots or dashes].[word chars]
static const QRegularExpression EmailAddressRegExp(QStringLiteral(
R"((mailto:)?(\b(\w|\.|-)+@(\w|\.|-)+\.\w+\b))"
), RegExpOptions);
// An interim liberal implementation of
// https://matrix.org/docs/spec/appendices.html#identifier-grammar
static const QRegularExpression MxIdRegExp(QStringLiteral(
R"((^|[^<>/])([!#@][-a-z0-9_=/.]{1,252}:[-.a-z0-9]+))"
), RegExpOptions);
// NOTE: htmlEscapedText is already HTML-escaped! No literal <,>,&
htmlEscapedText.replace(EmailAddressRegExp,
QStringLiteral(R"(<a href="mailto:\2">\1\2</a>)"));
htmlEscapedText.replace(FullUrlRegExp,
QStringLiteral(R"(<a href="\1">\1</a>)"));
htmlEscapedText.replace(MxIdRegExp,
QStringLiteral(R"(\1<a href="https://matrix.to/#/\2">\2</a>)"));
}
QString QMatrixClient::prettyPrint(const QString& plainText)
{
auto pt = QStringLiteral("<span style='white-space:pre-wrap'>") +
plainText.toHtmlEscaped() + QStringLiteral("</span>");
pt.replace('\n', QStringLiteral("<br/>"));
linkifyUrls(pt);
return pt;
}
QString QMatrixClient::cacheLocation(const QString& dirName)
{
const QString cachePath =
QStandardPaths::writableLocation(QStandardPaths::CacheLocation)
% '/' % dirName % '/';
QDir dir;
if (!dir.exists(cachePath))
dir.mkpath(cachePath);
return cachePath;
}
// Tests for function_traits<>
#ifdef Q_CC_CLANG
#pragma clang diagnostic push
#pragma ide diagnostic ignored "OCSimplifyInspection"
#endif
using namespace QMatrixClient;
int f();
static_assert(std::is_same<fn_return_t<decltype(f)>, int>::value,
"Test fn_return_t<>");
void f1(int);
static_assert(function_traits<decltype(f1)>::arg_number == 1,
"Test fn_arg_number");
void f2(int, QString);
static_assert(std::is_same<fn_arg_t<decltype(f2), 1>, QString>::value,
"Test fn_arg_t<>");
struct S { int mf(); };
static_assert(is_callable_v<decltype(&S::mf)>, "Test member function");
static_assert(returns<int, decltype(&S::mf)>(), "Test returns<> with member function");
struct Fo { int operator()(); };
static_assert(is_callable_v<Fo>, "Test is_callable<> with function object");
static_assert(function_traits<Fo>::arg_number == 0, "Test function object");
static_assert(std::is_same<fn_return_t<Fo>, int>::value,
"Test return type of function object");
struct Fo1 { void operator()(int); };
static_assert(function_traits<Fo1>::arg_number == 1, "Test function object 1");
static_assert(is_callable_v<Fo1>, "Test is_callable<> with function object 1");
static_assert(std::is_same<fn_arg_t<Fo1>, int>(),
"Test fn_arg_t defaulting to first argument");
#if (!defined(_MSC_VER) || _MSC_VER >= 1910)
static auto l = [] { return 1; };
static_assert(is_callable_v<decltype(l)>, "Test is_callable_v<> with lambda");
static_assert(std::is_same<fn_return_t<decltype(l)>, int>::value,
"Test fn_return_t<> with lambda");
#endif
template <typename T>
struct fn_object
{
static int smf(double) { return 0; }
};
template <>
struct fn_object<QString>
{
void operator()(QString);
};
static_assert(is_callable_v<fn_object<QString>>, "Test function object");
static_assert(returns<void, fn_object<QString>>(),
"Test returns<> with function object");
static_assert(!is_callable_v<fn_object<int>>, "Test non-function object");
// FIXME: These two don't work
//static_assert(is_callable_v<decltype(&fn_object<int>::smf)>,
// "Test static member function");
//static_assert(returns<int, decltype(&fn_object<int>::smf)>(),
// "Test returns<> with static member function");
template <typename T>
QString ft(T&&);
static_assert(std::is_same<fn_arg_t<decltype(ft<QString>)>, QString&&>(),
"Test function templates");
#ifdef Q_CC_CLANG
#pragma clang diagnostic pop
#endif
<commit_msg>linkifyUrls(): fix linkification of emails containing "www."<commit_after>/******************************************************************************
* Copyright (C) 2018 Kitsune Ral <kitsune-ral@users.sf.net>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include "util.h"
#include <QtCore/QRegularExpression>
#include <QtCore/QStandardPaths>
#include <QtCore/QDir>
#include <QtCore/QStringBuilder>
static const auto RegExpOptions =
QRegularExpression::CaseInsensitiveOption
| QRegularExpression::OptimizeOnFirstUsageOption
| QRegularExpression::UseUnicodePropertiesOption;
// Converts all that looks like a URL into HTML links
static void linkifyUrls(QString& htmlEscapedText)
{
// regexp is originally taken from Konsole (https://github.com/KDE/konsole)
// full url:
// protocolname:// or www. followed by anything other than whitespaces,
// <, >, ' or ", and ends before whitespaces, <, >, ', ", ], !, ), :,
// comma or dot
// Note: outer parentheses are a part of C++ raw string delimiters, not of
// the regex (see http://en.cppreference.com/w/cpp/language/string_literal).
// Note2: the next-outer parentheses are \N in the replacement.
static const QRegularExpression FullUrlRegExp(QStringLiteral(
R"(\b((www\.(?!\.)(?!(\w|\.|-)+@)|(https?|ftp|magnet)://)(&(?![lg]t;)|[^&\s<>'"])+(&(?![lg]t;)|[^&!,.\s<>'"\]):])))"
), RegExpOptions);
// email address:
// [word chars, dots or dashes]@[word chars, dots or dashes].[word chars]
static const QRegularExpression EmailAddressRegExp(QStringLiteral(
R"(\b(mailto:)?((\w|\.|-)+@(\w|\.|-)+\.\w+\b))"
), RegExpOptions);
// An interim liberal implementation of
// https://matrix.org/docs/spec/appendices.html#identifier-grammar
static const QRegularExpression MxIdRegExp(QStringLiteral(
R"((^|[^<>/])([!#@][-a-z0-9_=/.]{1,252}:[-.a-z0-9]+))"
), RegExpOptions);
// NOTE: htmlEscapedText is already HTML-escaped! No literal <,>,&,"
htmlEscapedText.replace(EmailAddressRegExp,
QStringLiteral(R"(<a href="mailto:\2">\1\2</a>)"));
htmlEscapedText.replace(FullUrlRegExp,
QStringLiteral(R"(<a href="\1">\1</a>)"));
htmlEscapedText.replace(MxIdRegExp,
QStringLiteral(R"(\1<a href="https://matrix.to/#/\2">\2</a>)"));
}
QString QMatrixClient::prettyPrint(const QString& plainText)
{
auto pt = QStringLiteral("<span style='white-space:pre-wrap'>") +
plainText.toHtmlEscaped() + QStringLiteral("</span>");
pt.replace('\n', QStringLiteral("<br/>"));
linkifyUrls(pt);
return pt;
}
QString QMatrixClient::cacheLocation(const QString& dirName)
{
const QString cachePath =
QStandardPaths::writableLocation(QStandardPaths::CacheLocation)
% '/' % dirName % '/';
QDir dir;
if (!dir.exists(cachePath))
dir.mkpath(cachePath);
return cachePath;
}
// Tests for function_traits<>
#ifdef Q_CC_CLANG
#pragma clang diagnostic push
#pragma ide diagnostic ignored "OCSimplifyInspection"
#endif
using namespace QMatrixClient;
int f();
static_assert(std::is_same<fn_return_t<decltype(f)>, int>::value,
"Test fn_return_t<>");
void f1(int);
static_assert(function_traits<decltype(f1)>::arg_number == 1,
"Test fn_arg_number");
void f2(int, QString);
static_assert(std::is_same<fn_arg_t<decltype(f2), 1>, QString>::value,
"Test fn_arg_t<>");
struct S { int mf(); };
static_assert(is_callable_v<decltype(&S::mf)>, "Test member function");
static_assert(returns<int, decltype(&S::mf)>(), "Test returns<> with member function");
struct Fo { int operator()(); };
static_assert(is_callable_v<Fo>, "Test is_callable<> with function object");
static_assert(function_traits<Fo>::arg_number == 0, "Test function object");
static_assert(std::is_same<fn_return_t<Fo>, int>::value,
"Test return type of function object");
struct Fo1 { void operator()(int); };
static_assert(function_traits<Fo1>::arg_number == 1, "Test function object 1");
static_assert(is_callable_v<Fo1>, "Test is_callable<> with function object 1");
static_assert(std::is_same<fn_arg_t<Fo1>, int>(),
"Test fn_arg_t defaulting to first argument");
#if (!defined(_MSC_VER) || _MSC_VER >= 1910)
static auto l = [] { return 1; };
static_assert(is_callable_v<decltype(l)>, "Test is_callable_v<> with lambda");
static_assert(std::is_same<fn_return_t<decltype(l)>, int>::value,
"Test fn_return_t<> with lambda");
#endif
template <typename T>
struct fn_object
{
static int smf(double) { return 0; }
};
template <>
struct fn_object<QString>
{
void operator()(QString);
};
static_assert(is_callable_v<fn_object<QString>>, "Test function object");
static_assert(returns<void, fn_object<QString>>(),
"Test returns<> with function object");
static_assert(!is_callable_v<fn_object<int>>, "Test non-function object");
// FIXME: These two don't work
//static_assert(is_callable_v<decltype(&fn_object<int>::smf)>,
// "Test static member function");
//static_assert(returns<int, decltype(&fn_object<int>::smf)>(),
// "Test returns<> with static member function");
template <typename T>
QString ft(T&&);
static_assert(std::is_same<fn_arg_t<decltype(ft<QString>)>, QString&&>(),
"Test function templates");
#ifdef Q_CC_CLANG
#pragma clang diagnostic pop
#endif
<|endoftext|>
|
<commit_before><commit_msg>i115391 corected from isLocked to IsPasteResize which was used in modifiers for CustomShape and TextShape (cherry picked from commit 473a118a62842270b85713d0ab0dc247b5778439)<commit_after><|endoftext|>
|
<commit_before>/*************************************************************************
*
* $RCSfile: linkmgr.cxx,v $
*
* $Revision: 1.2 $
*
* last change: $Author: jp $ $Date: 2000-09-26 12:08:24 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#pragma hdrstop
#include <sot/dtrans.hxx>
#ifndef _SV_EXCHANGE_HXX //autogen
#include <vcl/exchange.hxx>
#endif
#ifndef _LNKBASE_HXX //autogen
#include <so3/lnkbase.hxx>
#endif
#ifndef _URLOBJ_HXX //autogen
#include <tools/urlobj.hxx>
#endif
#ifndef _FSYS_HXX //autogen
#include <tools/fsys.hxx>
#endif
#ifndef _IPOBJ_HXX //autogen
#include <so3/ipobj.hxx>
#endif
#ifndef _SFXSTRITEM_HXX //autogen
#include <svtools/stritem.hxx>
#endif
#ifndef _SFXENUMITEM_HXX //autogen
#include <svtools/eitem.hxx>
#endif
#ifndef _SFXINTITEM_HXX //autogen
#include <svtools/intitem.hxx>
#endif
#ifndef _SFXRECTITEM_HXX //autogen
#include <svtools/rectitem.hxx>
#endif
#ifndef _SFX_OBJSH_HXX //autogen
#include <sfx2/objsh.hxx>
#endif
#ifndef _SFX_INTERNO_HXX //autogen
#include <sfx2/interno.hxx>
#endif
#ifndef _SFXDISPATCH_HXX //autogen
#include <sfx2/dispatch.hxx>
#endif
#ifndef _UNOTOOLS_CHARCLASS_HXX
#include <unotools/charclass.hxx>
#endif
#include "linkmgr.hxx"
#include "fileobj.hxx"
#include "fobjcach.hxx"
#include "dialmgr.hxx"
#include "dialogs.hrc"
#include "unolingu.hxx"
class SvxInternalLink : public SvPseudoObject
{
public:
SvxInternalLink() {}
virtual BOOL Connect( SvBaseLink& );
};
class ImplCastBaseLink : public SvBaseLink
{
public:
ImplCastBaseLink() : SvBaseLink( 0, 0 ) {}
void SetObject( SvPseudoObject* pObj ) { SetObj( pObj ); }
};
SvxLinkManager::SvxLinkManager( SvPersist * pCacheCont )
: SvLinkManager( pCacheCont )
{
}
SvPseudoObjectRef SvxLinkManager::CreateObj( SvBaseLink & rLink )
{
switch( rLink.GetObjType() )
{
case OBJECT_CLIENT_FILE:
case OBJECT_CLIENT_GRF:
return new SvFileObject();
case OBJECT_INTERN:
return new SvxInternalLink();
}
return SvLinkManager::CreateObj( rLink );
}
BOOL SvxLinkManager::InsertFileLink( SvBaseLink& rLink,
USHORT nFileType,
const String& rFileNm,
const String* pFilterNm,
const String* pRange )
{
if( !( OBJECT_CLIENT_SO & rLink.GetObjectType() ))
return FALSE;
String sCmd( rFileNm );
sCmd += cTokenSeperator;
if( pRange )
sCmd += *pRange;
if( pFilterNm )
( sCmd += cTokenSeperator ) += *pFilterNm;
return SvLinkManager::InsertLink( rLink, nFileType,
LINKUPDATE_ONCALL, &sCmd );
}
BOOL SvxLinkManager::InsertFileLink( SvBaseLink& rLink )
{
if( OBJECT_CLIENT_FILE == ( OBJECT_CLIENT_FILE & rLink.GetObjectType() ))
return SvLinkManager::InsertLink( rLink, rLink.GetObjectType(),
LINKUPDATE_ONCALL );
return FALSE;
}
// erfrage die Strings fuer den Dialog
BOOL SvxLinkManager::GetDisplayNames( const SvBaseLink& rLink,
String* pType,
String* pFile,
String* pLink,
String* pFilter ) const
{
BOOL bRet = FALSE;
const SvLinkName* pLNm = rLink.GetLinkSourceName();
if( pLNm )
switch( rLink.GetObjectType() )
{
case OBJECT_CLIENT_FILE:
case OBJECT_CLIENT_GRF:
{
USHORT nPos = 0;
String sCmd( pLNm->GetName() );
String sFile( sCmd.GetToken( 0, cTokenSeperator, nPos ) );
String sRange( sCmd.GetToken( 0, cTokenSeperator, nPos ) );
if( pFile )
*pFile = sFile;
if( pLink )
*pLink = sRange;
if( pFilter )
*pFilter = sCmd.Copy( nPos );
if( pType )
*pType = String( ResId(
OBJECT_CLIENT_FILE == rLink.GetObjectType()
? RID_SVXSTR_FILELINK
: RID_SVXSTR_GRAFIKLINK
, DIALOG_MGR() ));
bRet = TRUE;
}
break;
default:
bRet = SvLinkManager::GetDisplayNames( rLink, pType, pFile,
pLink, pFilter );
break;
}
return bRet;
}
// eine Uebertragung wird abgebrochen, also alle DownloadMedien canceln
// (ist zur Zeit nur fuer die FileLinks interressant!)
void SvxLinkManager::CancelTransfers()
{
SvFileObject* pFileObj;
SvBaseLink* pLnk;
const SvBaseLinks& rLnks = GetLinks();
for( USHORT n = rLnks.Count(); n; )
if( 0 != ( pLnk = &(*rLnks[ --n ])) &&
OBJECT_CLIENT_FILE == (OBJECT_CLIENT_FILE & pLnk->GetObjType()) &&
0 != ( pFileObj = (SvFileObject*)pLnk->GetObj() ) )
// 0 != ( pFileObj = (SvFileObject*)SvFileObject::ClassFactory()->
// CastAndAddRef( pLnk->GetObj() )) )
pFileObj->CancelTransfers();
}
void SvxLinkManager::SetTransferPriority( SvBaseLink& rLink, USHORT nPrio )
{
SvFileObject* pFileObj =
// (SvFileObject*)SvFileObject::ClassFactory()->
// CastAndAddRef( rLink.GetObj() );
OBJECT_CLIENT_FILE == (OBJECT_CLIENT_FILE & rLink.GetObjType()) ?
(SvFileObject*)rLink.GetObj() : 0;
if( pFileObj )
pFileObj->SetTransferPriority( nPrio );
}
void SvxLinkManager::PrepareReload( SvBaseLink* pLnk )
{
FileObjCache_Impl* pCache = ::GetCache();
SvFileObject* pFileObj;
if( pLnk ) // einen speziellen?
{
if( OBJECT_CLIENT_FILE == (OBJECT_CLIENT_FILE & pLnk->GetObjType()) &&
0 != ( pFileObj = (SvFileObject*)pLnk->GetObj() ) )
{
pCache->Remove( *pFileObj );
pLnk->SetUseCache( FALSE );
}
return ;
}
// dann eben alle
const SvBaseLinks& rLnks = GetLinks();
for( USHORT n = rLnks.Count(); n; )
if( 0 != ( pLnk = &(*rLnks[ --n ])) &&
OBJECT_CLIENT_FILE == (OBJECT_CLIENT_FILE & pLnk->GetObjType()) &&
0 != ( pFileObj = (SvFileObject*)pLnk->GetObj() ) )
{
pCache->Remove( *pFileObj );
}
}
// um Status Informationen aus dem FileObject an den BaseLink zu
// senden, gibt es eine eigene ClipBoardId. Das SvData-Object hat
// dann die entsprechenden Informationen als String.
// Wird zur Zeit fuer FileObject in Verbindung mit JavaScript benoetigt
// - das braucht Informationen ueber Load/Abort/Error
ULONG SvxLinkManager::RegisterStatusInfoId()
{
static ULONG nFormat = 0;
if( !nFormat )
{
// wie sieht die neue Schnittstelle aus?
// nFormat = Exchange::RegisterFormatName( "StatusInfo vom SvxInternalLink" );
nFormat = Exchange::RegisterFormatName(
String( RTL_CONSTASCII_STRINGPARAM(
"StatusInfo vom SvxInternalLink" ),
RTL_TEXTENCODING_MS_1252 ));
}
return nFormat;
}
BOOL SvxInternalLink::Connect( SvBaseLink& rLink )
{
String sTopic, sItem, sReferer;
if( rLink.GetLinkManager() &&
rLink.GetLinkManager()->GetDisplayNames( rLink, 0, &sTopic, &sItem ) )
{
// erstmal nur ueber die DocumentShells laufen und die mit dem
// Namen heraussuchen:
CharClass aCC( SvxCreateLocale( LANGUAGE_SYSTEM ));
String sNm( sTopic ), sTmp;
aCC.toLower( sNm );
TypeId aType( TYPE(SfxObjectShell) );
BOOL bFirst = TRUE;
SfxObjectShell* pShell = 0;
SvPersist* pPersist = rLink.GetLinkManager()->GetCacheContainer();
SvInPlaceObjectRef aRef( pPersist );
if( aRef.Is() )
{
// sch... SFX das gerade gelesen Doc hat noch keinen Namen und
// steht noch nicht in der Doc. Liste
pShell = ((SfxInPlaceObject*)&aRef)->GetObjectShell();
if( pShell && pShell->GetMedium() )
{
sReferer = pShell->GetMedium()->GetName();
if( !pShell->HasName() )
{
sTmp = sReferer;
INetURLObject aURL( sTmp );
if ( aURL.GetProtocol() == INET_PROT_FILE )
sTmp = aURL.getFSysPath( INetURLObject::FSYS_DETECT );
}
}
}
if ( !pShell )
{
bFirst = FALSE;
pShell = SfxObjectShell::GetFirst( &aType );
}
while( pShell )
{
if( !sTmp.Len() )
sTmp = pShell->GetTitle( SFX_TITLE_FULLNAME );
aCC.toLower( sTmp );
if( sTmp == sNm ) // die wollen wir haben
{
SvPseudoObject* pNewObj = pShell->DdeCreateHotLink( sItem );
if( pNewObj )
{
((ImplCastBaseLink&)rLink).SetObject( pNewObj );
pNewObj->AddDataAdvise( &rLink, rLink.GetContentType(),
LINKUPDATE_ONCALL == rLink.GetUpdateMode()
? ADVISEMODE_ONLYONCE
: 0 );
}
return 0 != pNewObj;
}
if( bFirst )
{
bFirst = FALSE;
pShell = SfxObjectShell::GetFirst( &aType );
}
else
pShell = SfxObjectShell::GetNext( *pShell, &aType );
sTmp.Erase();
}
}
DirEntry aFileNm( GUI2FSYS( sTopic ) );
aFileNm.ToAbs();
if( FSYS_KIND_FILE == FileStat( aFileNm ).GetKind() )
{
// File vorhanden
// dann versuche die Datei zu laden:
SfxStringItem aName( SID_FILE_NAME, aFileNm.GetFull() );
SfxBoolItem aNewView(SID_OPEN_NEW_VIEW, TRUE);
// SfxBoolItem aHidden(SID_HIDDEN, TRUE);
// minimiert!
SfxUInt16Item aViewStat( SID_VIEW_ZOOM_MODE, 0 );
SfxRectangleItem aRectItem( SID_VIEW_POS_SIZE, Rectangle() );
SfxStringItem aReferer( SID_REFERER, sReferer );
SfxBoolItem aSilent(SID_SILENT, TRUE);
const SfxPoolItem* pRet = SFX_APP()->GetDispatcher().Execute(
SID_OPENDOC, SFX_CALLMODE_SYNCHRON,
&aName, &aNewView,
&aViewStat,&aRectItem/*aHidden*/,
&aSilent, &aReferer, 0L );
SfxObjectShell* pShell;
if( pRet && pRet->ISA( SfxViewFrameItem ) &&
((SfxViewFrameItem*)pRet)->GetFrame() &&
0 != ( pShell = ((SfxViewFrameItem*)pRet)
->GetFrame()->GetObjectShell() ) )
{
SvPseudoObject* pNewObj = pShell->DdeCreateHotLink( sItem );
if( pNewObj )
{
((ImplCastBaseLink&)rLink).SetObject( pNewObj );
pNewObj->AddDataAdvise( &rLink, rLink.GetContentType(),
LINKUPDATE_ONCALL == rLink.GetUpdateMode()
? ADVISEMODE_ONLYONCE
: 0 );
//JP 13.04.96: interne Links sind nicht am Closed interresiert!
// pNewObj->AddConnectAdvise( &rLink, ADVISE_CLOSED );
}
return 0 != pNewObj;
}
}
return FALSE;
}
<commit_msg>SFXDISPATHER removed<commit_after>/*************************************************************************
*
* $RCSfile: linkmgr.cxx,v $
*
* $Revision: 1.3 $
*
* last change: $Author: jp $ $Date: 2000-09-26 13:19:07 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#pragma hdrstop
#include <sot/dtrans.hxx>
#ifndef _SV_EXCHANGE_HXX //autogen
#include <vcl/exchange.hxx>
#endif
#ifndef _LNKBASE_HXX //autogen
#include <so3/lnkbase.hxx>
#endif
#ifndef _URLOBJ_HXX //autogen
#include <tools/urlobj.hxx>
#endif
#ifndef _FSYS_HXX //autogen
#include <tools/fsys.hxx>
#endif
#ifndef _IPOBJ_HXX //autogen
#include <so3/ipobj.hxx>
#endif
#ifndef _SFXSTRITEM_HXX //autogen
#include <svtools/stritem.hxx>
#endif
#ifndef _SFXENUMITEM_HXX //autogen
#include <svtools/eitem.hxx>
#endif
#ifndef _SFXINTITEM_HXX //autogen
#include <svtools/intitem.hxx>
#endif
#ifndef _SFXRECTITEM_HXX //autogen
#include <svtools/rectitem.hxx>
#endif
#ifndef _SFX_OBJSH_HXX //autogen
#include <sfx2/objsh.hxx>
#endif
#ifndef _SFX_INTERNO_HXX //autogen
#include <sfx2/interno.hxx>
#endif
#ifndef _SFXDISPATCH_HXX //autogen
#include <sfx2/dispatch.hxx>
#endif
#ifndef _UNOTOOLS_CHARCLASS_HXX
#include <unotools/charclass.hxx>
#endif
#include "linkmgr.hxx"
#include "fileobj.hxx"
#include "fobjcach.hxx"
#include "dialmgr.hxx"
#include "dialogs.hrc"
#include "unolingu.hxx"
class SvxInternalLink : public SvPseudoObject
{
public:
SvxInternalLink() {}
virtual BOOL Connect( SvBaseLink& );
};
class ImplCastBaseLink : public SvBaseLink
{
public:
ImplCastBaseLink() : SvBaseLink( 0, 0 ) {}
void SetObject( SvPseudoObject* pObj ) { SetObj( pObj ); }
};
SvxLinkManager::SvxLinkManager( SvPersist * pCacheCont )
: SvLinkManager( pCacheCont )
{
}
SvPseudoObjectRef SvxLinkManager::CreateObj( SvBaseLink & rLink )
{
switch( rLink.GetObjType() )
{
case OBJECT_CLIENT_FILE:
case OBJECT_CLIENT_GRF:
return new SvFileObject();
case OBJECT_INTERN:
return new SvxInternalLink();
}
return SvLinkManager::CreateObj( rLink );
}
BOOL SvxLinkManager::InsertFileLink( SvBaseLink& rLink,
USHORT nFileType,
const String& rFileNm,
const String* pFilterNm,
const String* pRange )
{
if( !( OBJECT_CLIENT_SO & rLink.GetObjectType() ))
return FALSE;
String sCmd( rFileNm );
sCmd += cTokenSeperator;
if( pRange )
sCmd += *pRange;
if( pFilterNm )
( sCmd += cTokenSeperator ) += *pFilterNm;
return SvLinkManager::InsertLink( rLink, nFileType,
LINKUPDATE_ONCALL, &sCmd );
}
BOOL SvxLinkManager::InsertFileLink( SvBaseLink& rLink )
{
if( OBJECT_CLIENT_FILE == ( OBJECT_CLIENT_FILE & rLink.GetObjectType() ))
return SvLinkManager::InsertLink( rLink, rLink.GetObjectType(),
LINKUPDATE_ONCALL );
return FALSE;
}
// erfrage die Strings fuer den Dialog
BOOL SvxLinkManager::GetDisplayNames( const SvBaseLink& rLink,
String* pType,
String* pFile,
String* pLink,
String* pFilter ) const
{
BOOL bRet = FALSE;
const SvLinkName* pLNm = rLink.GetLinkSourceName();
if( pLNm )
switch( rLink.GetObjectType() )
{
case OBJECT_CLIENT_FILE:
case OBJECT_CLIENT_GRF:
{
USHORT nPos = 0;
String sCmd( pLNm->GetName() );
String sFile( sCmd.GetToken( 0, cTokenSeperator, nPos ) );
String sRange( sCmd.GetToken( 0, cTokenSeperator, nPos ) );
if( pFile )
*pFile = sFile;
if( pLink )
*pLink = sRange;
if( pFilter )
*pFilter = sCmd.Copy( nPos );
if( pType )
*pType = String( ResId(
OBJECT_CLIENT_FILE == rLink.GetObjectType()
? RID_SVXSTR_FILELINK
: RID_SVXSTR_GRAFIKLINK
, DIALOG_MGR() ));
bRet = TRUE;
}
break;
default:
bRet = SvLinkManager::GetDisplayNames( rLink, pType, pFile,
pLink, pFilter );
break;
}
return bRet;
}
// eine Uebertragung wird abgebrochen, also alle DownloadMedien canceln
// (ist zur Zeit nur fuer die FileLinks interressant!)
void SvxLinkManager::CancelTransfers()
{
SvFileObject* pFileObj;
SvBaseLink* pLnk;
const SvBaseLinks& rLnks = GetLinks();
for( USHORT n = rLnks.Count(); n; )
if( 0 != ( pLnk = &(*rLnks[ --n ])) &&
OBJECT_CLIENT_FILE == (OBJECT_CLIENT_FILE & pLnk->GetObjType()) &&
0 != ( pFileObj = (SvFileObject*)pLnk->GetObj() ) )
// 0 != ( pFileObj = (SvFileObject*)SvFileObject::ClassFactory()->
// CastAndAddRef( pLnk->GetObj() )) )
pFileObj->CancelTransfers();
}
void SvxLinkManager::SetTransferPriority( SvBaseLink& rLink, USHORT nPrio )
{
SvFileObject* pFileObj =
// (SvFileObject*)SvFileObject::ClassFactory()->
// CastAndAddRef( rLink.GetObj() );
OBJECT_CLIENT_FILE == (OBJECT_CLIENT_FILE & rLink.GetObjType()) ?
(SvFileObject*)rLink.GetObj() : 0;
if( pFileObj )
pFileObj->SetTransferPriority( nPrio );
}
void SvxLinkManager::PrepareReload( SvBaseLink* pLnk )
{
FileObjCache_Impl* pCache = ::GetCache();
SvFileObject* pFileObj;
if( pLnk ) // einen speziellen?
{
if( OBJECT_CLIENT_FILE == (OBJECT_CLIENT_FILE & pLnk->GetObjType()) &&
0 != ( pFileObj = (SvFileObject*)pLnk->GetObj() ) )
{
pCache->Remove( *pFileObj );
pLnk->SetUseCache( FALSE );
}
return ;
}
// dann eben alle
const SvBaseLinks& rLnks = GetLinks();
for( USHORT n = rLnks.Count(); n; )
if( 0 != ( pLnk = &(*rLnks[ --n ])) &&
OBJECT_CLIENT_FILE == (OBJECT_CLIENT_FILE & pLnk->GetObjType()) &&
0 != ( pFileObj = (SvFileObject*)pLnk->GetObj() ) )
{
pCache->Remove( *pFileObj );
}
}
// um Status Informationen aus dem FileObject an den BaseLink zu
// senden, gibt es eine eigene ClipBoardId. Das SvData-Object hat
// dann die entsprechenden Informationen als String.
// Wird zur Zeit fuer FileObject in Verbindung mit JavaScript benoetigt
// - das braucht Informationen ueber Load/Abort/Error
ULONG SvxLinkManager::RegisterStatusInfoId()
{
static ULONG nFormat = 0;
if( !nFormat )
{
// wie sieht die neue Schnittstelle aus?
// nFormat = Exchange::RegisterFormatName( "StatusInfo vom SvxInternalLink" );
nFormat = Exchange::RegisterFormatName(
String( RTL_CONSTASCII_STRINGPARAM(
"StatusInfo vom SvxInternalLink" ),
RTL_TEXTENCODING_MS_1252 ));
}
return nFormat;
}
BOOL SvxInternalLink::Connect( SvBaseLink& rLink )
{
String sTopic, sItem, sReferer;
if( rLink.GetLinkManager() &&
rLink.GetLinkManager()->GetDisplayNames( rLink, 0, &sTopic, &sItem ) )
{
// erstmal nur ueber die DocumentShells laufen und die mit dem
// Namen heraussuchen:
CharClass aCC( SvxCreateLocale( LANGUAGE_SYSTEM ));
String sNm( sTopic ), sTmp;
aCC.toLower( sNm );
TypeId aType( TYPE(SfxObjectShell) );
BOOL bFirst = TRUE;
SfxObjectShell* pShell = 0;
SvPersist* pPersist = rLink.GetLinkManager()->GetCacheContainer();
SvInPlaceObjectRef aRef( pPersist );
if( aRef.Is() )
{
// sch... SFX das gerade gelesen Doc hat noch keinen Namen und
// steht noch nicht in der Doc. Liste
pShell = ((SfxInPlaceObject*)&aRef)->GetObjectShell();
if( pShell && pShell->GetMedium() )
{
sReferer = pShell->GetMedium()->GetName();
if( !pShell->HasName() )
{
sTmp = sReferer;
INetURLObject aURL( sTmp );
if ( aURL.GetProtocol() == INET_PROT_FILE )
sTmp = aURL.getFSysPath( INetURLObject::FSYS_DETECT );
}
}
}
if ( !pShell )
{
bFirst = FALSE;
pShell = SfxObjectShell::GetFirst( &aType );
}
while( pShell )
{
if( !sTmp.Len() )
sTmp = pShell->GetTitle( SFX_TITLE_FULLNAME );
aCC.toLower( sTmp );
if( sTmp == sNm ) // die wollen wir haben
{
SvPseudoObject* pNewObj = pShell->DdeCreateHotLink( sItem );
if( pNewObj )
{
((ImplCastBaseLink&)rLink).SetObject( pNewObj );
pNewObj->AddDataAdvise( &rLink, rLink.GetContentType(),
LINKUPDATE_ONCALL == rLink.GetUpdateMode()
? ADVISEMODE_ONLYONCE
: 0 );
}
return 0 != pNewObj;
}
if( bFirst )
{
bFirst = FALSE;
pShell = SfxObjectShell::GetFirst( &aType );
}
else
pShell = SfxObjectShell::GetNext( *pShell, &aType );
sTmp.Erase();
}
}
DirEntry aFileNm( GUI2FSYS( sTopic ) );
aFileNm.ToAbs();
if( FSYS_KIND_FILE == FileStat( aFileNm ).GetKind() )
{
// File vorhanden
// dann versuche die Datei zu laden:
SfxStringItem aName( SID_FILE_NAME, aFileNm.GetFull() );
SfxBoolItem aNewView(SID_OPEN_NEW_VIEW, TRUE);
// SfxBoolItem aHidden(SID_HIDDEN, TRUE);
// minimiert!
SfxUInt16Item aViewStat( SID_VIEW_ZOOM_MODE, 0 );
SfxRectangleItem aRectItem( SID_VIEW_POS_SIZE, Rectangle() );
SfxStringItem aReferer( SID_REFERER, sReferer );
SfxBoolItem aSilent(SID_SILENT, TRUE);
const SfxPoolItem* pRet = SfxViewFrame::Current()->GetDispatcher()->
Execute( SID_OPENDOC, SFX_CALLMODE_SYNCHRON,
&aName, &aNewView,
&aViewStat,&aRectItem/*aHidden*/,
&aSilent, &aReferer, 0L );
SfxObjectShell* pShell;
if( pRet && pRet->ISA( SfxViewFrameItem ) &&
((SfxViewFrameItem*)pRet)->GetFrame() &&
0 != ( pShell = ((SfxViewFrameItem*)pRet)
->GetFrame()->GetObjectShell() ) )
{
SvPseudoObject* pNewObj = pShell->DdeCreateHotLink( sItem );
if( pNewObj )
{
((ImplCastBaseLink&)rLink).SetObject( pNewObj );
pNewObj->AddDataAdvise( &rLink, rLink.GetContentType(),
LINKUPDATE_ONCALL == rLink.GetUpdateMode()
? ADVISEMODE_ONLYONCE
: 0 );
//JP 13.04.96: interne Links sind nicht am Closed interresiert!
// pNewObj->AddConnectAdvise( &rLink, ADVISE_CLOSED );
}
return 0 != pNewObj;
}
}
return FALSE;
}
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* $RCSfile: dbgloop.hxx,v $
*
* $Revision: 1.1.1.1 $
*
* last change: $Author: hr $ $Date: 2000-09-19 00:08:20 $
*
* 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 _DBGLOOP_HXX
#define _DBGLOOP_HXX
#ifndef PRODUCT
#ifndef _SOLAR_H
#include <tools/solar.h>
#endif
class SvStream;
#define DBG_MAX_STACK 20 // Verschachtelungstiefe
#define DBG_MAX_LOOP 1000 // das Abbruchkriterium
class DbgLoopStack
{
USHORT aCount[DBG_MAX_STACK];
USHORT nPtr;
const void *pDbg;
void Reset();
public:
DbgLoopStack();
void Push( const void *pThis );
void Pop();
void Print( SvStream &rOS ) const; //$ ostream
};
class DbgLoop
{
friend inline void PrintLoopStack( SvStream &rOS ); //$ ostream
static DbgLoopStack aDbgLoopStack;
public:
inline DbgLoop( const void *pThis ) { aDbgLoopStack.Push( pThis ); }
inline ~DbgLoop() { aDbgLoopStack.Pop(); }
};
inline void PrintLoopStack( SvStream &rOS ) //$ ostream
{
DbgLoop::aDbgLoopStack.Print( rOS );
}
#define DBG_LOOP DbgLoop aDbgLoop( (const void*)this );
#define DBG_LOOP_RESET DbgLoop aDbgLoop( 0 );
#else
#define DBG_LOOP
#define DBG_LOOP_RESET
#endif
#endif
<commit_msg>INTEGRATION: CWS ooo19126 (1.1.1.1.1462); FILE MERGED 2005/09/05 13:39:54 rt 1.1.1.1.1462.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: dbgloop.hxx,v $
*
* $Revision: 1.2 $
*
* last change: $Author: rt $ $Date: 2005-09-09 03:44:10 $
*
* 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 _DBGLOOP_HXX
#define _DBGLOOP_HXX
#ifndef PRODUCT
#ifndef _SOLAR_H
#include <tools/solar.h>
#endif
class SvStream;
#define DBG_MAX_STACK 20 // Verschachtelungstiefe
#define DBG_MAX_LOOP 1000 // das Abbruchkriterium
class DbgLoopStack
{
USHORT aCount[DBG_MAX_STACK];
USHORT nPtr;
const void *pDbg;
void Reset();
public:
DbgLoopStack();
void Push( const void *pThis );
void Pop();
void Print( SvStream &rOS ) const; //$ ostream
};
class DbgLoop
{
friend inline void PrintLoopStack( SvStream &rOS ); //$ ostream
static DbgLoopStack aDbgLoopStack;
public:
inline DbgLoop( const void *pThis ) { aDbgLoopStack.Push( pThis ); }
inline ~DbgLoop() { aDbgLoopStack.Pop(); }
};
inline void PrintLoopStack( SvStream &rOS ) //$ ostream
{
DbgLoop::aDbgLoopStack.Print( rOS );
}
#define DBG_LOOP DbgLoop aDbgLoop( (const void*)this );
#define DBG_LOOP_RESET DbgLoop aDbgLoop( 0 );
#else
#define DBG_LOOP
#define DBG_LOOP_RESET
#endif
#endif
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: dflyobj.hxx,v $
*
* $Revision: 1.9 $
*
* last change: $Author: ihi $ $Date: 2006-11-14 15:10:15 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#ifndef _DFLYOBJ_HXX
#define _DFLYOBJ_HXX
#ifndef _SVDOVIRT_HXX //autogen
#include <svx/svdovirt.hxx>
#endif
class SwFlyFrm;
class SwFrmFmt;
class SdrObjMacroHitRec;
const UINT32 SWGInventor = UINT32('S')*0x00000001+
UINT32('W')*0x00000100+
UINT32('G')*0x00010000;
const UINT16 SwFlyDrawObjIdentifier = 0x0001;
const UINT16 SwDrawFirst = 0x0001;
//---------------------------------------
//SwFlyDrawObj, Die DrawObjekte fuer Flys.
class SwFlyDrawObj : public SdrObject
{
virtual sdr::properties::BaseProperties* CreateObjectSpecificProperties();
public:
TYPEINFO();
SwFlyDrawObj();
~SwFlyDrawObj();
virtual sal_Bool DoPaintObject(XOutputDevice& rOut, const SdrPaintInfoRec& rInfoRec) const;
//Damit eine Instanz dieser Klasse beim laden erzeugt werden kann
//(per Factory).
virtual UINT32 GetObjInventor() const;
virtual UINT16 GetObjIdentifier() const;
virtual UINT16 GetObjVersion() const;
};
//---------------------------------------
//SwVirtFlyDrawObj, die virtuellen Objekte fuer Flys.
//Flys werden immer mit virtuellen Objekten angezeigt. Nur so koennen sie
//ggf. mehrfach angezeigt werden (Kopf-/Fusszeilen).
class SwVirtFlyDrawObj : public SdrVirtObj
{
SwFlyFrm *pFlyFrm;
public:
TYPEINFO();
SwVirtFlyDrawObj(SdrObject& rNew, SwFlyFrm* pFly);
~SwVirtFlyDrawObj();
//Ueberladene Methoden der Basisklasse SdrVirtObj
virtual SdrObject* CheckHit(const Point& rPnt, USHORT nTol, const SetOfByte* pVisiLayer) const;
virtual sal_Bool DoPaintObject(XOutputDevice& rOut, const SdrPaintInfoRec& rInfoRec) const;
virtual void TakeObjInfo( SdrObjTransformInfoRec& rInfo ) const;
//Wir nehemen die Groessenbehandlung vollstaendig selbst in die Hand.
virtual const Rectangle& GetCurrentBoundRect() const;
virtual void RecalcBoundRect();
virtual void RecalcSnapRect();
virtual const Rectangle& GetSnapRect() const;
virtual void SetSnapRect(const Rectangle& rRect);
virtual void NbcSetSnapRect(const Rectangle& rRect);
virtual const Rectangle& GetLogicRect() const;
virtual void SetLogicRect(const Rectangle& rRect);
virtual void NbcSetLogicRect(const Rectangle& rRect);
virtual ::basegfx::B2DPolyPolygon TakeXorPoly(sal_Bool bDetail) const;
virtual void NbcMove (const Size& rSiz);
virtual void NbcResize(const Point& rRef, const Fraction& xFact,
const Fraction& yFact);
virtual void Move (const Size& rSiz);
virtual void Resize(const Point& rRef, const Fraction& xFact,
const Fraction& yFact);
const SwFrmFmt *GetFmt() const;
SwFrmFmt *GetFmt();
// Get Methoden fuer die Fly Verpointerung
SwFlyFrm* GetFlyFrm() { return pFlyFrm; }
const SwFlyFrm* GetFlyFrm() const { return pFlyFrm; }
void SetRect() const;
// ist eine URL an einer Grafik gesetzt, dann ist das ein Makro-Object
virtual FASTBOOL HasMacro() const;
virtual SdrObject* CheckMacroHit (const SdrObjMacroHitRec& rRec) const;
virtual Pointer GetMacroPointer (const SdrObjMacroHitRec& rRec) const;
};
#endif
<commit_msg>INTEGRATION: CWS changefileheader (1.9.644); FILE MERGED 2008/04/01 15:57:09 thb 1.9.644.2: #i85898# Stripping all external header guards 2008/03/31 16:54:12 rt 1.9.644.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: dflyobj.hxx,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.
*
************************************************************************/
#ifndef _DFLYOBJ_HXX
#define _DFLYOBJ_HXX
#include <svx/svdovirt.hxx>
class SwFlyFrm;
class SwFrmFmt;
class SdrObjMacroHitRec;
const UINT32 SWGInventor = UINT32('S')*0x00000001+
UINT32('W')*0x00000100+
UINT32('G')*0x00010000;
const UINT16 SwFlyDrawObjIdentifier = 0x0001;
const UINT16 SwDrawFirst = 0x0001;
//---------------------------------------
//SwFlyDrawObj, Die DrawObjekte fuer Flys.
class SwFlyDrawObj : public SdrObject
{
virtual sdr::properties::BaseProperties* CreateObjectSpecificProperties();
public:
TYPEINFO();
SwFlyDrawObj();
~SwFlyDrawObj();
virtual sal_Bool DoPaintObject(XOutputDevice& rOut, const SdrPaintInfoRec& rInfoRec) const;
//Damit eine Instanz dieser Klasse beim laden erzeugt werden kann
//(per Factory).
virtual UINT32 GetObjInventor() const;
virtual UINT16 GetObjIdentifier() const;
virtual UINT16 GetObjVersion() const;
};
//---------------------------------------
//SwVirtFlyDrawObj, die virtuellen Objekte fuer Flys.
//Flys werden immer mit virtuellen Objekten angezeigt. Nur so koennen sie
//ggf. mehrfach angezeigt werden (Kopf-/Fusszeilen).
class SwVirtFlyDrawObj : public SdrVirtObj
{
SwFlyFrm *pFlyFrm;
public:
TYPEINFO();
SwVirtFlyDrawObj(SdrObject& rNew, SwFlyFrm* pFly);
~SwVirtFlyDrawObj();
//Ueberladene Methoden der Basisklasse SdrVirtObj
virtual SdrObject* CheckHit(const Point& rPnt, USHORT nTol, const SetOfByte* pVisiLayer) const;
virtual sal_Bool DoPaintObject(XOutputDevice& rOut, const SdrPaintInfoRec& rInfoRec) const;
virtual void TakeObjInfo( SdrObjTransformInfoRec& rInfo ) const;
//Wir nehemen die Groessenbehandlung vollstaendig selbst in die Hand.
virtual const Rectangle& GetCurrentBoundRect() const;
virtual void RecalcBoundRect();
virtual void RecalcSnapRect();
virtual const Rectangle& GetSnapRect() const;
virtual void SetSnapRect(const Rectangle& rRect);
virtual void NbcSetSnapRect(const Rectangle& rRect);
virtual const Rectangle& GetLogicRect() const;
virtual void SetLogicRect(const Rectangle& rRect);
virtual void NbcSetLogicRect(const Rectangle& rRect);
virtual ::basegfx::B2DPolyPolygon TakeXorPoly(sal_Bool bDetail) const;
virtual void NbcMove (const Size& rSiz);
virtual void NbcResize(const Point& rRef, const Fraction& xFact,
const Fraction& yFact);
virtual void Move (const Size& rSiz);
virtual void Resize(const Point& rRef, const Fraction& xFact,
const Fraction& yFact);
const SwFrmFmt *GetFmt() const;
SwFrmFmt *GetFmt();
// Get Methoden fuer die Fly Verpointerung
SwFlyFrm* GetFlyFrm() { return pFlyFrm; }
const SwFlyFrm* GetFlyFrm() const { return pFlyFrm; }
void SetRect() const;
// ist eine URL an einer Grafik gesetzt, dann ist das ein Makro-Object
virtual FASTBOOL HasMacro() const;
virtual SdrObject* CheckMacroHit (const SdrObjMacroHitRec& rRec) const;
virtual Pointer GetMacroPointer (const SdrObjMacroHitRec& rRec) const;
};
#endif
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: portxt.hxx,v $
*
* $Revision: 1.8 $
*
* last change: $Author: rt $ $Date: 2005-09-09 05:03:20 $
*
* 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 _PORTXT_HXX
#define _PORTXT_HXX
#ifdef GCC
#include <sys/types.h>
#else
#include <new.h> //fuer size_t, FIXEDMEM aus tools
#endif
#ifndef _SVMEMPOOL_HXX //autogen
#include <tools/mempool.hxx>
#endif
#include "porlin.hxx"
class SwTxtGuess;
/*************************************************************************
* class SwTxtPortion
*************************************************************************/
class SwTxtPortion : public SwLinePortion
{
void BreakCut( SwTxtFormatInfo &rInf, const SwTxtGuess &rGuess );
void BreakUnderflow( SwTxtFormatInfo &rInf );
sal_Bool _Format( SwTxtFormatInfo &rInf );
public:
inline SwTxtPortion(){ SetWhichPor( POR_TXT ); }
SwTxtPortion( const SwLinePortion &rPortion );
virtual void Paint( const SwTxtPaintInfo &rInf ) const;
virtual sal_Bool Format( SwTxtFormatInfo &rInf );
virtual void FormatEOL( SwTxtFormatInfo &rInf );
virtual xub_StrLen GetCrsrOfst( const KSHORT nOfst ) const;
virtual SwPosSize GetTxtSize( const SwTxtSizeInfo &rInfo ) const;
virtual sal_Bool GetExpTxt( const SwTxtSizeInfo &rInf, XubString &rTxt ) const;
virtual long CalcSpacing( long nSpaceAdd, const SwTxtSizeInfo &rInf ) const;
// zaehlt die Spaces fuer Blocksatz
xub_StrLen GetSpaceCnt( const SwTxtSizeInfo &rInf, xub_StrLen& rCnt ) const;
sal_Bool CreateHyphen( SwTxtFormatInfo &rInf, SwTxtGuess &rGuess );
// Accessibility: pass information about this portion to the PortionHandler
virtual void HandlePortion( SwPortionHandler& rPH ) const;
OUTPUT_OPERATOR
DECL_FIXEDMEMPOOL_NEWDEL(SwTxtPortion)
};
/*************************************************************************
* class SwHolePortion
*************************************************************************/
class SwHolePortion : public SwLinePortion
{
KSHORT nBlankWidth;
public:
SwHolePortion( const SwTxtPortion &rPor );
inline const KSHORT GetBlankWidth( ) const { return nBlankWidth; }
inline void SetBlankWidth( const KSHORT nNew ) { nBlankWidth = nNew; }
virtual SwLinePortion *Compress();
virtual sal_Bool Format( SwTxtFormatInfo &rInf );
virtual void Paint( const SwTxtPaintInfo &rInf ) const;
// Accessibility: pass information about this portion to the PortionHandler
virtual void HandlePortion( SwPortionHandler& rPH ) const;
OUTPUT_OPERATOR
DECL_FIXEDMEMPOOL_NEWDEL(SwHolePortion)
};
CLASSIO( SwTxtPortion )
CLASSIO( SwHolePortion )
#endif
<commit_msg>INTEGRATION: CWS writercorehandoff (1.7.48); FILE MERGED 2005/09/13 14:36:58 tra 1.7.48.2: RESYNC: (1.7-1.8); FILE MERGED 2005/06/06 09:28:05 tra 1.7.48.1: Unnecessary includes removed #i50348#<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: portxt.hxx,v $
*
* $Revision: 1.9 $
*
* last change: $Author: hr $ $Date: 2006-08-14 16:42:42 $
*
* 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 _PORTXT_HXX
#define _PORTXT_HXX
#ifdef GCC
#include <sys/types.h>
#else
#include <new.h> //fuer size_t, FIXEDMEM aus tools
#endif
#ifndef _SVMEMPOOL_HXX //autogen
#include <tools/mempool.hxx>
#endif
#include "porlin.hxx"
class SwTxtGuess;
/*************************************************************************
* class SwTxtPortion
*************************************************************************/
class SwTxtPortion : public SwLinePortion
{
void BreakCut( SwTxtFormatInfo &rInf, const SwTxtGuess &rGuess );
void BreakUnderflow( SwTxtFormatInfo &rInf );
sal_Bool _Format( SwTxtFormatInfo &rInf );
public:
inline SwTxtPortion(){ SetWhichPor( POR_TXT ); }
SwTxtPortion( const SwLinePortion &rPortion );
virtual void Paint( const SwTxtPaintInfo &rInf ) const;
virtual sal_Bool Format( SwTxtFormatInfo &rInf );
virtual void FormatEOL( SwTxtFormatInfo &rInf );
virtual xub_StrLen GetCrsrOfst( const KSHORT nOfst ) const;
virtual SwPosSize GetTxtSize( const SwTxtSizeInfo &rInfo ) const;
virtual sal_Bool GetExpTxt( const SwTxtSizeInfo &rInf, XubString &rTxt ) const;
virtual long CalcSpacing( long nSpaceAdd, const SwTxtSizeInfo &rInf ) const;
// zaehlt die Spaces fuer Blocksatz
xub_StrLen GetSpaceCnt( const SwTxtSizeInfo &rInf, xub_StrLen& rCnt ) const;
sal_Bool CreateHyphen( SwTxtFormatInfo &rInf, SwTxtGuess &rGuess );
// Accessibility: pass information about this portion to the PortionHandler
virtual void HandlePortion( SwPortionHandler& rPH ) const;
OUTPUT_OPERATOR
DECL_FIXEDMEMPOOL_NEWDEL(SwTxtPortion)
};
/*************************************************************************
* class SwHolePortion
*************************************************************************/
class SwHolePortion : public SwLinePortion
{
KSHORT nBlankWidth;
public:
SwHolePortion( const SwTxtPortion &rPor );
inline const KSHORT GetBlankWidth( ) const { return nBlankWidth; }
inline void SetBlankWidth( const KSHORT nNew ) { nBlankWidth = nNew; }
virtual SwLinePortion *Compress();
virtual sal_Bool Format( SwTxtFormatInfo &rInf );
virtual void Paint( const SwTxtPaintInfo &rInf ) const;
// Accessibility: pass information about this portion to the PortionHandler
virtual void HandlePortion( SwPortionHandler& rPH ) const;
OUTPUT_OPERATOR
DECL_FIXEDMEMPOOL_NEWDEL(SwHolePortion)
};
CLASSIO( SwTxtPortion )
CLASSIO( SwHolePortion )
#endif
<|endoftext|>
|
<commit_before><commit_msg>tdf#88230 Blind fix for IOS-only code<commit_after><|endoftext|>
|
<commit_before>/***************************************************************************
copyright : (C) 2002 - 2008 by Scott Wheeler
email : wheeler@kde.org
***************************************************************************/
/***************************************************************************
* This library is free software; you can redistribute it and/or modify *
* it under the terms of the GNU Lesser General Public License version *
* 2.1 as published by the Free Software Foundation. *
* *
* This library is distributed in the hope that it will be useful, but *
* WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU *
* Lesser General Public License for more details. *
* *
* You should have received a copy of the GNU Lesser General Public *
* License along with this library; if not, write to the Free Software *
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA *
* 02110-1301 USA *
* *
* Alternatively, this file is available under the Mozilla Public *
* License Version 1.1. You may obtain a copy of the License at *
* http://www.mozilla.org/MPL/ *
***************************************************************************/
#include <tdebug.h>
#include <tfile.h>
#include "id3v1tag.h"
#include "id3v1genres.h"
using namespace TagLib;
using namespace ID3v1;
class ID3v1::Tag::TagPrivate
{
public:
TagPrivate() : file(0), tagOffset(-1), track(0), genre(255) {}
File *file;
long tagOffset;
String title;
String artist;
String album;
String year;
String comment;
uchar track;
uchar genre;
static const StringHandler *stringHandler;
};
static const StringHandler defaultStringHandler;
const ID3v1::StringHandler *ID3v1::Tag::TagPrivate::stringHandler = &defaultStringHandler;
////////////////////////////////////////////////////////////////////////////////
// StringHandler implementation
////////////////////////////////////////////////////////////////////////////////
String ID3v1::StringHandler::parse(const ByteVector &data) const
{
return String(data, String::Latin1).stripWhiteSpace();
}
ByteVector ID3v1::StringHandler::render(const String &s) const
{
if(!s.isLatin1())
{
return ByteVector();
}
return s.data(String::Latin1);
}
////////////////////////////////////////////////////////////////////////////////
// public methods
////////////////////////////////////////////////////////////////////////////////
ID3v1::Tag::Tag() : TagLib::Tag()
{
d = new TagPrivate;
}
ID3v1::Tag::Tag(File *file, long tagOffset) : TagLib::Tag()
{
d = new TagPrivate;
d->file = file;
d->tagOffset = tagOffset;
read();
}
ID3v1::Tag::~Tag()
{
delete d;
}
ByteVector ID3v1::Tag::render() const
{
ByteVector data;
data.append(fileIdentifier());
data.append(TagPrivate::stringHandler->render(d->title).resize(30));
data.append(TagPrivate::stringHandler->render(d->artist).resize(30));
data.append(TagPrivate::stringHandler->render(d->album).resize(30));
data.append(TagPrivate::stringHandler->render(d->year).resize(4));
data.append(TagPrivate::stringHandler->render(d->comment).resize(28));
data.append(char(0));
data.append(char(d->track));
data.append(char(d->genre));
return data;
}
ByteVector ID3v1::Tag::fileIdentifier()
{
return ByteVector::fromCString("TAG");
}
String ID3v1::Tag::title() const
{
return d->title;
}
String ID3v1::Tag::artist() const
{
return d->artist;
}
String ID3v1::Tag::album() const
{
return d->album;
}
String ID3v1::Tag::comment() const
{
return d->comment;
}
String ID3v1::Tag::genre() const
{
return ID3v1::genre(d->genre);
}
TagLib::uint ID3v1::Tag::year() const
{
return d->year.toInt();
}
TagLib::uint ID3v1::Tag::track() const
{
return d->track;
}
void ID3v1::Tag::setTitle(const String &s)
{
d->title = s;
}
void ID3v1::Tag::setArtist(const String &s)
{
d->artist = s;
}
void ID3v1::Tag::setAlbum(const String &s)
{
d->album = s;
}
void ID3v1::Tag::setComment(const String &s)
{
d->comment = s;
}
void ID3v1::Tag::setGenre(const String &s)
{
d->genre = ID3v1::genreIndex(s);
}
void ID3v1::Tag::setYear(uint i)
{
d->year = i > 0 ? String::number(i) : String::null;
}
void ID3v1::Tag::setTrack(uint i)
{
d->track = i < 256 ? i : 0;
}
void ID3v1::Tag::setStringHandler(const StringHandler *handler)
{
TagPrivate::stringHandler = handler;
}
////////////////////////////////////////////////////////////////////////////////
// protected methods
////////////////////////////////////////////////////////////////////////////////
void ID3v1::Tag::read()
{
if(d->file && d->file->isValid()) {
d->file->seek(d->tagOffset);
// read the tag -- always 128 bytes
ByteVector data = d->file->readBlock(128);
// some initial sanity checking
if(data.size() == 128 && data.startsWith("TAG"))
parse(data);
else
debug("ID3v1 tag is not valid or could not be read at the specified offset.");
}
}
void ID3v1::Tag::parse(const ByteVector &data)
{
int offset = 3;
d->title = TagPrivate::stringHandler->parse(data.mid(offset, 30));
offset += 30;
d->artist = TagPrivate::stringHandler->parse(data.mid(offset, 30));
offset += 30;
d->album = TagPrivate::stringHandler->parse(data.mid(offset, 30));
offset += 30;
d->year = TagPrivate::stringHandler->parse(data.mid(offset, 4));
offset += 4;
// Check for ID3v1.1 -- Note that ID3v1 *does not* support "track zero" -- this
// is not a bug in TagLib. Since a zeroed byte is what we would expect to
// indicate the end of a C-String, specifically the comment string, a value of
// zero must be assumed to be just that.
if(data[offset + 28] == 0 && data[offset + 29] != 0) {
// ID3v1.1 detected
d->comment = TagPrivate::stringHandler->parse(data.mid(offset, 28));
d->track = uchar(data[offset + 29]);
}
else
d->comment = data.mid(offset, 30);
offset += 30;
d->genre = uchar(data[offset]);
}
<commit_msg>Additional change to previous fix.<commit_after>/***************************************************************************
copyright : (C) 2002 - 2008 by Scott Wheeler
email : wheeler@kde.org
***************************************************************************/
/***************************************************************************
* This library is free software; you can redistribute it and/or modify *
* it under the terms of the GNU Lesser General Public License version *
* 2.1 as published by the Free Software Foundation. *
* *
* This library is distributed in the hope that it will be useful, but *
* WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU *
* Lesser General Public License for more details. *
* *
* You should have received a copy of the GNU Lesser General Public *
* License along with this library; if not, write to the Free Software *
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA *
* 02110-1301 USA *
* *
* Alternatively, this file is available under the Mozilla Public *
* License Version 1.1. You may obtain a copy of the License at *
* http://www.mozilla.org/MPL/ *
***************************************************************************/
#include <tdebug.h>
#include <tfile.h>
#include "id3v1tag.h"
#include "id3v1genres.h"
using namespace TagLib;
using namespace ID3v1;
class ID3v1::Tag::TagPrivate
{
public:
TagPrivate() : file(0), tagOffset(-1), track(0), genre(255) {}
File *file;
long tagOffset;
String title;
String artist;
String album;
String year;
String comment;
uchar track;
uchar genre;
static const StringHandler *stringHandler;
};
static const StringHandler defaultStringHandler;
const ID3v1::StringHandler *ID3v1::Tag::TagPrivate::stringHandler = &defaultStringHandler;
////////////////////////////////////////////////////////////////////////////////
// StringHandler implementation
////////////////////////////////////////////////////////////////////////////////
String ID3v1::StringHandler::parse(const ByteVector &data) const
{
return String(data, String::Latin1).stripWhiteSpace();
}
ByteVector ID3v1::StringHandler::render(const String &s) const
{
if(!s.isLatin1())
{
return ByteVector();
}
return s.data(String::Latin1);
}
////////////////////////////////////////////////////////////////////////////////
// public methods
////////////////////////////////////////////////////////////////////////////////
ID3v1::Tag::Tag() : TagLib::Tag()
{
d = new TagPrivate;
}
ID3v1::Tag::Tag(File *file, long tagOffset) : TagLib::Tag()
{
d = new TagPrivate;
d->file = file;
d->tagOffset = tagOffset;
read();
}
ID3v1::Tag::~Tag()
{
delete d;
}
ByteVector ID3v1::Tag::render() const
{
ByteVector data;
data.append(fileIdentifier());
data.append(TagPrivate::stringHandler->render(d->title).resize(30));
data.append(TagPrivate::stringHandler->render(d->artist).resize(30));
data.append(TagPrivate::stringHandler->render(d->album).resize(30));
data.append(TagPrivate::stringHandler->render(d->year).resize(4));
data.append(TagPrivate::stringHandler->render(d->comment).resize(28));
data.append(char(0));
data.append(char(d->track));
data.append(char(d->genre));
return data;
}
ByteVector ID3v1::Tag::fileIdentifier()
{
return ByteVector::fromCString("TAG");
}
String ID3v1::Tag::title() const
{
return d->title;
}
String ID3v1::Tag::artist() const
{
return d->artist;
}
String ID3v1::Tag::album() const
{
return d->album;
}
String ID3v1::Tag::comment() const
{
return d->comment;
}
String ID3v1::Tag::genre() const
{
return ID3v1::genre(d->genre);
}
TagLib::uint ID3v1::Tag::year() const
{
return d->year.toInt();
}
TagLib::uint ID3v1::Tag::track() const
{
return d->track;
}
void ID3v1::Tag::setTitle(const String &s)
{
d->title = s;
}
void ID3v1::Tag::setArtist(const String &s)
{
d->artist = s;
}
void ID3v1::Tag::setAlbum(const String &s)
{
d->album = s;
}
void ID3v1::Tag::setComment(const String &s)
{
d->comment = s;
}
void ID3v1::Tag::setGenre(const String &s)
{
d->genre = ID3v1::genreIndex(s);
}
void ID3v1::Tag::setYear(uint i)
{
d->year = i > 0 ? String::number(i) : String::null;
}
void ID3v1::Tag::setTrack(uint i)
{
d->track = i < 256 ? i : 0;
}
void ID3v1::Tag::setStringHandler(const StringHandler *handler)
{
if (TagPrivate::stringHandler != &defaultStringHandler)
delete TagPrivate::stringHandler;
TagPrivate::stringHandler = handler;
}
////////////////////////////////////////////////////////////////////////////////
// protected methods
////////////////////////////////////////////////////////////////////////////////
void ID3v1::Tag::read()
{
if(d->file && d->file->isValid()) {
d->file->seek(d->tagOffset);
// read the tag -- always 128 bytes
ByteVector data = d->file->readBlock(128);
// some initial sanity checking
if(data.size() == 128 && data.startsWith("TAG"))
parse(data);
else
debug("ID3v1 tag is not valid or could not be read at the specified offset.");
}
}
void ID3v1::Tag::parse(const ByteVector &data)
{
int offset = 3;
d->title = TagPrivate::stringHandler->parse(data.mid(offset, 30));
offset += 30;
d->artist = TagPrivate::stringHandler->parse(data.mid(offset, 30));
offset += 30;
d->album = TagPrivate::stringHandler->parse(data.mid(offset, 30));
offset += 30;
d->year = TagPrivate::stringHandler->parse(data.mid(offset, 4));
offset += 4;
// Check for ID3v1.1 -- Note that ID3v1 *does not* support "track zero" -- this
// is not a bug in TagLib. Since a zeroed byte is what we would expect to
// indicate the end of a C-String, specifically the comment string, a value of
// zero must be assumed to be just that.
if(data[offset + 28] == 0 && data[offset + 29] != 0) {
// ID3v1.1 detected
d->comment = TagPrivate::stringHandler->parse(data.mid(offset, 28));
d->track = uchar(data[offset + 29]);
}
else
d->comment = data.mid(offset, 30);
offset += 30;
d->genre = uchar(data[offset]);
}
<|endoftext|>
|
<commit_before>/***************************************************************************
copyright : (C) 2002 - 2008 by Scott Wheeler
email : wheeler@kde.org
***************************************************************************/
/***************************************************************************
* This library is free software; you can redistribute it and/or modify *
* it under the terms of the GNU Lesser General Public License version *
* 2.1 as published by the Free Software Foundation. *
* *
* This library is distributed in the hope that it will be useful, but *
* WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU *
* Lesser General Public License for more details. *
* *
* You should have received a copy of the GNU Lesser General Public *
* License along with this library; if not, write to the Free Software *
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA *
* 02110-1301 USA *
* *
* Alternatively, this file is available under the Mozilla Public *
* License Version 1.1. You may obtain a copy of the License at *
* http://www.mozilla.org/MPL/ *
***************************************************************************/
#include "tfilestream.h"
#include "tstring.h"
#include "tdebug.h"
#ifdef _WIN32
# include <windows.h>
#else
# include <stdio.h>
# include <unistd.h>
#endif
using namespace TagLib;
namespace
{
#ifdef _WIN32
// Uses Win32 native API instead of POSIX API to reduce the resource consumption.
typedef FileName FileNameHandle;
typedef HANDLE FileHandle;
const uint BufferSize = 8192;
const FileHandle InvalidFileHandle = INVALID_HANDLE_VALUE;
inline FileHandle openFile(const FileName &path, bool readOnly)
{
const DWORD access = readOnly ? GENERIC_READ : (GENERIC_READ | GENERIC_WRITE);
if(!path.wstr().empty())
return CreateFileW(path.wstr().c_str(), access, FILE_SHARE_READ, NULL, OPEN_EXISTING, 0, NULL);
else if(!path.str().empty())
return CreateFileA(path.str().c_str(), access, FILE_SHARE_READ, NULL, OPEN_EXISTING, 0, NULL);
else
return InvalidFileHandle;
}
inline void closeFile(FileHandle file)
{
CloseHandle(file);
}
inline size_t readFile(FileHandle file, ByteVector &buffer)
{
DWORD length;
if(ReadFile(file, buffer.data(), static_cast<DWORD>(buffer.size()), &length, NULL))
return static_cast<size_t>(length);
else
return 0;
}
inline size_t writeFile(FileHandle file, const ByteVector &buffer)
{
DWORD length;
if(WriteFile(file, buffer.data(), static_cast<DWORD>(buffer.size()), &length, NULL))
return static_cast<size_t>(length);
else
return 0;
}
# ifndef NDEBUG
// Convert a string in a local encoding into a UTF-16 string.
// Debugging use only. In actual use, file names in local encodings are passed to
// CreateFileA() without any conversions.
String fileNameToString(const FileName &name)
{
if(!name.wstr().empty()) {
return String(name.wstr());
}
else if(!name.str().empty()) {
const int len = MultiByteToWideChar(CP_ACP, 0, name.str().c_str(), -1, NULL, 0);
if(len == 0)
return String::null;
wstring wstr(len, L'\0');
MultiByteToWideChar(CP_ACP, 0, name.str().c_str(), -1, &wstr[0], len);
return String(wstr);
}
else {
return String::null;
}
}
# endif
#else // _WIN32
struct FileNameHandle : public std::string
{
FileNameHandle(FileName name) : std::string(name) {}
operator FileName () const { return c_str(); }
};
typedef FILE* FileHandle;
const uint BufferSize = 8192;
const FileHandle InvalidFileHandle = 0;
inline FileHandle openFile(const FileName &path, bool readOnly)
{
return fopen(path, readOnly ? "rb" : "rb+");
}
inline void closeFile(FileHandle file)
{
fclose(file);
}
inline size_t readFile(FileHandle file, ByteVector &buffer)
{
return fread(buffer.data(), sizeof(char), buffer.size(), file);
}
inline size_t writeFile(FileHandle file, const ByteVector &buffer)
{
return fwrite(buffer.data(), sizeof(char), buffer.size(), file);
}
#endif // _WIN32
}
class FileStream::FileStreamPrivate
{
public:
FileStreamPrivate(const FileName &fileName)
: file(InvalidFileHandle)
, name(fileName)
, readOnly(true)
{
}
FileHandle file;
FileNameHandle name;
bool readOnly;
};
////////////////////////////////////////////////////////////////////////////////
// public members
////////////////////////////////////////////////////////////////////////////////
FileStream::FileStream(FileName fileName, bool openReadOnly)
: d(new FileStreamPrivate(fileName))
{
// First try with read / write mode, if that fails, fall back to read only.
if(!openReadOnly)
d->file = openFile(fileName, false);
if(d->file != InvalidFileHandle)
d->readOnly = false;
else
d->file = openFile(fileName, true);
if(d->file == InvalidFileHandle)
{
# ifdef _WIN32
debug("Could not open file " + fileNameToString(fileName));
# else
debug("Could not open file " + String(static_cast<const char *>(d->name)));
# endif
}
}
FileStream::~FileStream()
{
if(isOpen())
closeFile(d->file);
delete d;
}
FileName FileStream::name() const
{
return d->name;
}
ByteVector FileStream::readBlock(ulong length)
{
if(!isOpen()) {
debug("File::readBlock() -- invalid file.");
return ByteVector::null;
}
if(length == 0)
return ByteVector::null;
const ulong streamLength = static_cast<ulong>(FileStream::length());
if(length > bufferSize() && length > streamLength)
length = streamLength;
ByteVector buffer(static_cast<uint>(length));
const size_t count = readFile(d->file, buffer);
buffer.resize(static_cast<uint>(count));
return buffer;
}
void FileStream::writeBlock(const ByteVector &data)
{
if(!isOpen()) {
debug("File::writeBlock() -- invalid file.");
return;
}
if(readOnly()) {
debug("File::writeBlock() -- read only file.");
return;
}
writeFile(d->file, data);
}
void FileStream::insert(const ByteVector &data, ulong start, ulong replace)
{
if(!isOpen()) {
debug("File::insert() -- invalid file.");
return;
}
if(readOnly()) {
debug("File::insert() -- read only file.");
return;
}
if(data.size() == replace) {
seek(start);
writeBlock(data);
return;
}
else if(data.size() < replace) {
seek(start);
writeBlock(data);
removeBlock(start + data.size(), replace - data.size());
return;
}
// Woohoo! Faster (about 20%) than id3lib at last. I had to get hardcore
// and avoid TagLib's high level API for rendering just copying parts of
// the file that don't contain tag data.
//
// Now I'll explain the steps in this ugliness:
// First, make sure that we're working with a buffer that is longer than
// the *differnce* in the tag sizes. We want to avoid overwriting parts
// that aren't yet in memory, so this is necessary.
ulong bufferLength = bufferSize();
while(data.size() - replace > bufferLength)
bufferLength += bufferSize();
// Set where to start the reading and writing.
long readPosition = start + replace;
long writePosition = start;
ByteVector buffer = data;
ByteVector aboutToOverwrite(static_cast<uint>(bufferLength));
while(true)
{
// Seek to the current read position and read the data that we're about
// to overwrite. Appropriately increment the readPosition.
seek(readPosition);
const size_t bytesRead = readFile(d->file, aboutToOverwrite);
aboutToOverwrite.resize(bytesRead);
readPosition += bufferLength;
// Check to see if we just read the last block. We need to call clear()
// if we did so that the last write succeeds.
if(bytesRead < bufferLength)
clear();
// Seek to the write position and write our buffer. Increment the
// writePosition.
seek(writePosition);
writeBlock(buffer);
// We hit the end of the file.
if(bytesRead == 0)
break;
writePosition += buffer.size();
// Make the current buffer the data that we read in the beginning.
buffer = aboutToOverwrite;
}
}
void FileStream::removeBlock(ulong start, ulong length)
{
if(!isOpen()) {
debug("File::removeBlock() -- invalid file.");
return;
}
ulong bufferLength = bufferSize();
long readPosition = start + length;
long writePosition = start;
ByteVector buffer(static_cast<uint>(bufferLength));
for(size_t bytesRead = -1; bytesRead != 0;)
{
seek(readPosition);
bytesRead = readFile(d->file, buffer);
readPosition += bytesRead;
// Check to see if we just read the last block. We need to call clear()
// if we did so that the last write succeeds.
if(bytesRead < buffer.size()) {
clear();
buffer.resize(bytesRead);
}
seek(writePosition);
writeFile(d->file, buffer);
writePosition += bytesRead;
}
truncate(writePosition);
}
bool FileStream::readOnly() const
{
return d->readOnly;
}
bool FileStream::isOpen() const
{
return (d->file != InvalidFileHandle);
}
void FileStream::seek(long offset, Position p)
{
if(!isOpen()) {
debug("File::seek() -- invalid file.");
return;
}
#ifdef _WIN32
DWORD whence;
switch(p) {
case Beginning:
whence = FILE_BEGIN;
break;
case Current:
whence = FILE_CURRENT;
break;
case End:
whence = FILE_END;
break;
default:
debug("FileStream::seek() -- Invalid Position value.");
return;
}
SetFilePointer(d->file, offset, NULL, whence);
if(GetLastError() != NO_ERROR) {
debug("File::seek() -- Failed to set the file pointer.");
}
#else
int whence;
switch(p) {
case Beginning:
whence = SEEK_SET;
break;
case Current:
whence = SEEK_CUR;
break;
case End:
whence = SEEK_END;
break;
default:
debug("FileStream::seek() -- Invalid Position value.");
return;
}
fseek(d->file, offset, whence);
#endif
}
void FileStream::clear()
{
#ifdef _WIN32
// NOP
#else
clearerr(d->file);
#endif
}
long FileStream::tell() const
{
#ifdef _WIN32
const DWORD position = SetFilePointer(d->file, 0, NULL, FILE_CURRENT);
if(GetLastError() == NO_ERROR) {
return static_cast<long>(position);
}
else {
debug("File::tell() -- Failed to get the file pointer.");
return 0;
}
#else
return ftell(d->file);
#endif
}
long FileStream::length()
{
if(!isOpen()) {
debug("File::length() -- invalid file.");
return 0;
}
#ifdef _WIN32
const DWORD fileSize = GetFileSize(d->file, NULL);
if(GetLastError() == NO_ERROR) {
return static_cast<ulong>(fileSize);
}
else {
debug("File::length() -- Failed to get the file size.");
return 0;
}
#else
const long curpos = tell();
seek(0, End);
const long endpos = tell();
seek(curpos, Beginning);
return endpos;
#endif
}
////////////////////////////////////////////////////////////////////////////////
// protected members
////////////////////////////////////////////////////////////////////////////////
void FileStream::truncate(long length)
{
#ifdef _WIN32
const long currentPos = tell();
seek(length);
SetEndOfFile(d->file);
if(GetLastError() != NO_ERROR) {
debug("File::truncate() -- Failed to truncate the file.");
}
seek(currentPos);
#else
const int error = ftruncate(fileno(d->file), length);
if(error != 0) {
debug("FileStream::truncate() -- Coundn't truncate the file.");
}
#endif
}
TagLib::uint FileStream::bufferSize()
{
return BufferSize;
}
<commit_msg>Fixed compilation error with GCC4.2<commit_after>/***************************************************************************
copyright : (C) 2002 - 2008 by Scott Wheeler
email : wheeler@kde.org
***************************************************************************/
/***************************************************************************
* This library is free software; you can redistribute it and/or modify *
* it under the terms of the GNU Lesser General Public License version *
* 2.1 as published by the Free Software Foundation. *
* *
* This library is distributed in the hope that it will be useful, but *
* WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU *
* Lesser General Public License for more details. *
* *
* You should have received a copy of the GNU Lesser General Public *
* License along with this library; if not, write to the Free Software *
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA *
* 02110-1301 USA *
* *
* Alternatively, this file is available under the Mozilla Public *
* License Version 1.1. You may obtain a copy of the License at *
* http://www.mozilla.org/MPL/ *
***************************************************************************/
#include "tfilestream.h"
#include "tstring.h"
#include "tdebug.h"
#ifdef _WIN32
# include <windows.h>
#else
# include <stdio.h>
# include <unistd.h>
#endif
using namespace TagLib;
namespace
{
#ifdef _WIN32
// Uses Win32 native API instead of POSIX API to reduce the resource consumption.
typedef FileName FileNameHandle;
typedef HANDLE FileHandle;
const TagLib::uint BufferSize = 8192;
const FileHandle InvalidFileHandle = INVALID_HANDLE_VALUE;
inline FileHandle openFile(const FileName &path, bool readOnly)
{
const DWORD access = readOnly ? GENERIC_READ : (GENERIC_READ | GENERIC_WRITE);
if(!path.wstr().empty())
return CreateFileW(path.wstr().c_str(), access, FILE_SHARE_READ, NULL, OPEN_EXISTING, 0, NULL);
else if(!path.str().empty())
return CreateFileA(path.str().c_str(), access, FILE_SHARE_READ, NULL, OPEN_EXISTING, 0, NULL);
else
return InvalidFileHandle;
}
inline void closeFile(FileHandle file)
{
CloseHandle(file);
}
inline size_t readFile(FileHandle file, ByteVector &buffer)
{
DWORD length;
if(ReadFile(file, buffer.data(), static_cast<DWORD>(buffer.size()), &length, NULL))
return static_cast<size_t>(length);
else
return 0;
}
inline size_t writeFile(FileHandle file, const ByteVector &buffer)
{
DWORD length;
if(WriteFile(file, buffer.data(), static_cast<DWORD>(buffer.size()), &length, NULL))
return static_cast<size_t>(length);
else
return 0;
}
# ifndef NDEBUG
// Convert a string in a local encoding into a UTF-16 string.
// Debugging use only. In actual use, file names in local encodings are passed to
// CreateFileA() without any conversions.
String fileNameToString(const FileName &name)
{
if(!name.wstr().empty()) {
return String(name.wstr());
}
else if(!name.str().empty()) {
const int len = MultiByteToWideChar(CP_ACP, 0, name.str().c_str(), -1, NULL, 0);
if(len == 0)
return String::null;
wstring wstr(len, L'\0');
MultiByteToWideChar(CP_ACP, 0, name.str().c_str(), -1, &wstr[0], len);
return String(wstr);
}
else {
return String::null;
}
}
# endif
#else // _WIN32
struct FileNameHandle : public std::string
{
FileNameHandle(FileName name) : std::string(name) {}
operator FileName () const { return c_str(); }
};
typedef FILE* FileHandle;
const TagLib::uint BufferSize = 8192;
const FileHandle InvalidFileHandle = 0;
inline FileHandle openFile(const FileName &path, bool readOnly)
{
return fopen(path, readOnly ? "rb" : "rb+");
}
inline void closeFile(FileHandle file)
{
fclose(file);
}
inline size_t readFile(FileHandle file, ByteVector &buffer)
{
return fread(buffer.data(), sizeof(char), buffer.size(), file);
}
inline size_t writeFile(FileHandle file, const ByteVector &buffer)
{
return fwrite(buffer.data(), sizeof(char), buffer.size(), file);
}
#endif // _WIN32
}
class FileStream::FileStreamPrivate
{
public:
FileStreamPrivate(const FileName &fileName)
: file(InvalidFileHandle)
, name(fileName)
, readOnly(true)
{
}
FileHandle file;
FileNameHandle name;
bool readOnly;
};
////////////////////////////////////////////////////////////////////////////////
// public members
////////////////////////////////////////////////////////////////////////////////
FileStream::FileStream(FileName fileName, bool openReadOnly)
: d(new FileStreamPrivate(fileName))
{
// First try with read / write mode, if that fails, fall back to read only.
if(!openReadOnly)
d->file = openFile(fileName, false);
if(d->file != InvalidFileHandle)
d->readOnly = false;
else
d->file = openFile(fileName, true);
if(d->file == InvalidFileHandle)
{
# ifdef _WIN32
debug("Could not open file " + fileNameToString(fileName));
# else
debug("Could not open file " + String(static_cast<const char *>(d->name)));
# endif
}
}
FileStream::~FileStream()
{
if(isOpen())
closeFile(d->file);
delete d;
}
FileName FileStream::name() const
{
return d->name;
}
ByteVector FileStream::readBlock(ulong length)
{
if(!isOpen()) {
debug("File::readBlock() -- invalid file.");
return ByteVector::null;
}
if(length == 0)
return ByteVector::null;
const ulong streamLength = static_cast<ulong>(FileStream::length());
if(length > bufferSize() && length > streamLength)
length = streamLength;
ByteVector buffer(static_cast<uint>(length));
const size_t count = readFile(d->file, buffer);
buffer.resize(static_cast<uint>(count));
return buffer;
}
void FileStream::writeBlock(const ByteVector &data)
{
if(!isOpen()) {
debug("File::writeBlock() -- invalid file.");
return;
}
if(readOnly()) {
debug("File::writeBlock() -- read only file.");
return;
}
writeFile(d->file, data);
}
void FileStream::insert(const ByteVector &data, ulong start, ulong replace)
{
if(!isOpen()) {
debug("File::insert() -- invalid file.");
return;
}
if(readOnly()) {
debug("File::insert() -- read only file.");
return;
}
if(data.size() == replace) {
seek(start);
writeBlock(data);
return;
}
else if(data.size() < replace) {
seek(start);
writeBlock(data);
removeBlock(start + data.size(), replace - data.size());
return;
}
// Woohoo! Faster (about 20%) than id3lib at last. I had to get hardcore
// and avoid TagLib's high level API for rendering just copying parts of
// the file that don't contain tag data.
//
// Now I'll explain the steps in this ugliness:
// First, make sure that we're working with a buffer that is longer than
// the *differnce* in the tag sizes. We want to avoid overwriting parts
// that aren't yet in memory, so this is necessary.
ulong bufferLength = bufferSize();
while(data.size() - replace > bufferLength)
bufferLength += bufferSize();
// Set where to start the reading and writing.
long readPosition = start + replace;
long writePosition = start;
ByteVector buffer = data;
ByteVector aboutToOverwrite(static_cast<uint>(bufferLength));
while(true)
{
// Seek to the current read position and read the data that we're about
// to overwrite. Appropriately increment the readPosition.
seek(readPosition);
const size_t bytesRead = readFile(d->file, aboutToOverwrite);
aboutToOverwrite.resize(bytesRead);
readPosition += bufferLength;
// Check to see if we just read the last block. We need to call clear()
// if we did so that the last write succeeds.
if(bytesRead < bufferLength)
clear();
// Seek to the write position and write our buffer. Increment the
// writePosition.
seek(writePosition);
writeBlock(buffer);
// We hit the end of the file.
if(bytesRead == 0)
break;
writePosition += buffer.size();
// Make the current buffer the data that we read in the beginning.
buffer = aboutToOverwrite;
}
}
void FileStream::removeBlock(ulong start, ulong length)
{
if(!isOpen()) {
debug("File::removeBlock() -- invalid file.");
return;
}
ulong bufferLength = bufferSize();
long readPosition = start + length;
long writePosition = start;
ByteVector buffer(static_cast<uint>(bufferLength));
for(size_t bytesRead = -1; bytesRead != 0;)
{
seek(readPosition);
bytesRead = readFile(d->file, buffer);
readPosition += bytesRead;
// Check to see if we just read the last block. We need to call clear()
// if we did so that the last write succeeds.
if(bytesRead < buffer.size()) {
clear();
buffer.resize(bytesRead);
}
seek(writePosition);
writeFile(d->file, buffer);
writePosition += bytesRead;
}
truncate(writePosition);
}
bool FileStream::readOnly() const
{
return d->readOnly;
}
bool FileStream::isOpen() const
{
return (d->file != InvalidFileHandle);
}
void FileStream::seek(long offset, Position p)
{
if(!isOpen()) {
debug("File::seek() -- invalid file.");
return;
}
#ifdef _WIN32
DWORD whence;
switch(p) {
case Beginning:
whence = FILE_BEGIN;
break;
case Current:
whence = FILE_CURRENT;
break;
case End:
whence = FILE_END;
break;
default:
debug("FileStream::seek() -- Invalid Position value.");
return;
}
SetFilePointer(d->file, offset, NULL, whence);
if(GetLastError() != NO_ERROR) {
debug("File::seek() -- Failed to set the file pointer.");
}
#else
int whence;
switch(p) {
case Beginning:
whence = SEEK_SET;
break;
case Current:
whence = SEEK_CUR;
break;
case End:
whence = SEEK_END;
break;
default:
debug("FileStream::seek() -- Invalid Position value.");
return;
}
fseek(d->file, offset, whence);
#endif
}
void FileStream::clear()
{
#ifdef _WIN32
// NOP
#else
clearerr(d->file);
#endif
}
long FileStream::tell() const
{
#ifdef _WIN32
const DWORD position = SetFilePointer(d->file, 0, NULL, FILE_CURRENT);
if(GetLastError() == NO_ERROR) {
return static_cast<long>(position);
}
else {
debug("File::tell() -- Failed to get the file pointer.");
return 0;
}
#else
return ftell(d->file);
#endif
}
long FileStream::length()
{
if(!isOpen()) {
debug("File::length() -- invalid file.");
return 0;
}
#ifdef _WIN32
const DWORD fileSize = GetFileSize(d->file, NULL);
if(GetLastError() == NO_ERROR) {
return static_cast<ulong>(fileSize);
}
else {
debug("File::length() -- Failed to get the file size.");
return 0;
}
#else
const long curpos = tell();
seek(0, End);
const long endpos = tell();
seek(curpos, Beginning);
return endpos;
#endif
}
////////////////////////////////////////////////////////////////////////////////
// protected members
////////////////////////////////////////////////////////////////////////////////
void FileStream::truncate(long length)
{
#ifdef _WIN32
const long currentPos = tell();
seek(length);
SetEndOfFile(d->file);
if(GetLastError() != NO_ERROR) {
debug("File::truncate() -- Failed to truncate the file.");
}
seek(currentPos);
#else
const int error = ftruncate(fileno(d->file), length);
if(error != 0) {
debug("FileStream::truncate() -- Coundn't truncate the file.");
}
#endif
}
TagLib::uint FileStream::bufferSize()
{
return BufferSize;
}
<|endoftext|>
|
<commit_before>#ifndef UNIQUE_EVERSEEN_HPP
#define UNIQUE_EVERSEEN_HPP
#include "filter.hpp"
#include <type_traits>
#include <functional>
#include <utility>
#include <unordered_set>
#include <iterator>
namespace iter
{
//the container type must be usable in an unordered_map to achieve constant
//performance checking if it has ever been seen
template <typename Container>
auto unique_everseen(Container&& container)
-> Filter<std::function<bool(decltype(container.front()))>,Container>
{
using elem_t = decltype(container.front());
std::unordered_set<typename std::remove_reference<elem_t>::type> elem_seen;
std::function<bool(elem_t)> func = [elem_seen](elem_t e) mutable
//has to be captured by value because it goes out of scope when the
//function returns
{
if (elem_seen.find(e) == std::end(elem_seen)){
elem_seen.insert(e);
return true;
} else {
return false;
}
};
return filter(func,std::forward<Container>(container));
}
}
#endif //UNIQUE_EVERSEEN_HPP
<commit_msg>removes .front() requirement on Container<commit_after>#ifndef UNIQUE_EVERSEEN_HPP
#define UNIQUE_EVERSEEN_HPP
#include "iterbase.hpp"
#include "filter.hpp"
#include <type_traits>
#include <functional>
#include <utility>
#include <unordered_set>
#include <iterator>
namespace iter
{
//the container type must be usable in an unordered_map to achieve constant
//performance checking if it has ever been seen
template <typename Container>
auto unique_everseen(Container&& container)
-> Filter<std::function<bool(iterator_deref<Container>)>,Container>
{
using elem_t = iterator_deref<Container>;
std::unordered_set<typename std::remove_reference<elem_t>::type> elem_seen;
std::function<bool(elem_t)> func = [elem_seen](elem_t e) mutable
//has to be captured by value because it goes out of scope when the
//function returns
{
if (elem_seen.find(e) == std::end(elem_seen)){
elem_seen.insert(e);
return true;
} else {
return false;
}
};
return filter(func,std::forward<Container>(container));
}
}
#endif //UNIQUE_EVERSEEN_HPP
<|endoftext|>
|
<commit_before>/*===================================================================
BlueBerry Platform
Copyright (c) German Cancer Research Center,
Division of Medical and Biological Informatics.
All rights reserved.
This software is distributed WITHOUT ANY WARRANTY; without
even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE.
See LICENSE.txt or http://www.mitk.org for details.
===================================================================*/
#ifndef NOMINMAX
#define NOMINMAX
#endif
#include "berryInternalPlatform.h"
#include "berryLog.h"
#include "berryLogImpl.h"
#include "berryPlatform.h"
#include "berryPlatformException.h"
#include "berryDebugUtil.h"
#include "berryPlatformException.h"
#include "berryCTKPluginActivator.h"
#include "berryPlatformException.h"
#include "berryApplicationContainer.h"
#include "berryProduct.h"
#include "berryIBranding.h"
//#include "event/berryPlatformEvents.h"
//#include "berryPlatformLogChannel.h"
#include <berryIApplicationContext.h>
#include <berryIPreferencesService.h>
#include <berryIExtensionRegistry.h>
#include <berryIProduct.h>
#include <service/datalocation/ctkLocation.h>
#include <service/debug/ctkDebugOptions.h>
#include <ctkPluginContext.h>
#include <ctkPlugin.h>
#include <ctkPluginException.h>
#include <ctkPluginFrameworkLauncher.h>
#include <QCoreApplication>
#include <QDesktopServices>
#include <QDebug>
#include <QMutexLocker>
namespace berry {
QMutex InternalPlatform::m_Mutex;
bool InternalPlatform::DEBUG = false;
bool InternalPlatform::DEBUG_PLUGIN_PREFERENCES = false;
InternalPlatform::InternalPlatform()
: m_Initialized(false)
, m_ConsoleLog(false)
, m_Context(nullptr)
{
}
InternalPlatform::~InternalPlatform()
{
}
InternalPlatform* InternalPlatform::GetInstance()
{
QMutexLocker lock(&m_Mutex);
static InternalPlatform instance;
return &instance;
}
bool InternalPlatform::ConsoleLog() const
{
return m_ConsoleLog;
}
QVariant InternalPlatform::GetOption(const QString& option, const QVariant& defaultValue) const
{
ctkDebugOptions* options = GetDebugOptions();
if (options != nullptr)
{
return options->getOption(option, defaultValue);
}
return QVariant();
}
IAdapterManager* InternalPlatform::GetAdapterManager() const
{
AssertInitialized();
return nullptr;
}
SmartPointer<IProduct> InternalPlatform::GetProduct() const
{
if (product.IsNotNull()) return product;
ApplicationContainer* container = org_blueberry_core_runtime_Activator::GetContainer();
IBranding* branding = container == nullptr ? nullptr : container->GetBranding();
if (branding == nullptr) return IProduct::Pointer();
IProduct::Pointer brandingProduct = branding->GetProduct();
if (!brandingProduct)
{
brandingProduct = new Product(branding);
}
product = brandingProduct;
return product;
}
void InternalPlatform::InitializePluginPaths()
{
QMutexLocker lock(&m_Mutex);
// Add search paths for Qt plugins
foreach(QString qtPluginPath, m_Context->getProperty(Platform::PROP_QTPLUGIN_PATH).toStringList())
{
if (QFile::exists(qtPluginPath))
{
QCoreApplication::addLibraryPath(qtPluginPath);
}
else if (m_ConsoleLog)
{
BERRY_WARN << "Qt plugin path does not exist: " << qtPluginPath.toStdString();
}
}
// Add a default search path. It is assumed that installed applications
// provide their Qt plugins in that path.
static const QString defaultQtPluginPath = QCoreApplication::applicationDirPath() + "/plugins";
if (QFile::exists(defaultQtPluginPath))
{
QCoreApplication::addLibraryPath(defaultQtPluginPath);
}
if (m_ConsoleLog)
{
std::string pathList;
foreach(QString libPath, QCoreApplication::libraryPaths())
{
pathList += (pathList.empty() ? "" : ", ") + libPath.toStdString();
}
BERRY_INFO << "Qt library search paths: " << pathList;
}
/*
m_ConfigPath.setPath(m_Context->getProperty("application.configDir").toString());
m_InstancePath.setPath(m_Context->getProperty("application.dir").toString());
QString installPath = m_Context->getProperty(Platform::PROP_HOME).toString();
if (installPath.isEmpty())
{
m_InstallPath = m_InstancePath;
}
else {
m_InstallPath.setPath(installPath);
}
QString dataLocation = m_Context->getProperty(Platform::PROP_STORAGE_DIR).toString();
if (!storageDir.isEmpty())
{
if (dataLocation.at(dataLocation.size()-1) != '/')
{
dataLocation += '/';
}
m_UserPath.setPath(dataLocation);
}
else
{
// Append a hash value of the absolute path of the executable to the data location.
// This allows to start the same application from different build or install trees.
dataLocation = QStandardPaths::writableLocation(QStandardPaths::GenericDataLocation) + this->getOrganizationName() + "/" + this->getApplicationName() + '_';
dataLocation += QString::number(qHash(QCoreApplication::applicationDirPath())) + "/";
m_UserPath.setPath(dataLocation);
}
BERRY_INFO(m_ConsoleLog) << "Framework storage dir: " << m_UserPath.absolutePath();
QFileInfo userFile(m_UserPath.absolutePath());
if (!QDir().mkpath(userFile.absoluteFilePath()) || !userFile.isWritable())
{
QString tmpPath = QDir::temp().absoluteFilePath(QString::fromStdString(this->commandName()));
BERRY_WARN << "Storage dir " << userFile.absoluteFilePath() << " is not writable. Falling back to temporary path " << tmpPath;
QDir().mkpath(tmpPath);
userFile.setFile(tmpPath);
}
m_BaseStatePath.setPath(m_UserPath.absolutePath() + "/bb-metadata/bb-plugins");
QString logPath(m_UserPath.absoluteFilePath(QString::fromStdString(this->commandName()) + ".log"));
m_PlatformLogChannel = new Poco::SimpleFileChannel(logPath.toStdString());
*/
}
ctkDebugOptions* InternalPlatform::GetDebugOptions() const
{
return m_DebugTracker.isNull() ? nullptr : m_DebugTracker->getService();
}
IApplicationContext* InternalPlatform::GetApplicationContext() const
{
QList<ctkServiceReference> refs;
try
{
refs = m_Context->getServiceReferences<IApplicationContext>("(blueberry.application.type=main.thread)");
}
catch (const std::invalid_argument&)
{
return nullptr;
}
if (refs.isEmpty()) return nullptr;
// assumes the application context is available as a service
IApplicationContext* result = m_Context->getService<IApplicationContext>(refs.front());
if (result != nullptr)
{
m_Context->ungetService(refs.front());
return result;
}
return nullptr;
}
void InternalPlatform::Start(ctkPluginContext* context)
{
this->m_Context = context;
m_ConsoleLog = m_Context->getProperty(ctkPluginFrameworkLauncher::PROP_CONSOLE_LOG).toBool();
OpenServiceTrackers();
this->InitializePluginPaths();
#ifdef BLUEBERRY_DEBUG_SMARTPOINTER
DebugUtil::RestoreState(m_UserPath);
#endif
InitializeDebugFlags();
this->m_Initialized = true;
}
void InternalPlatform::Stop(ctkPluginContext* /*context*/)
{
AssertInitialized();
this->m_Initialized = false;
CloseServiceTrackers();
#ifdef BLUEBERRY_DEBUG_SMARTPOINTER
DebugUtil::SaveState(m_UserPath);
#endif
this->m_Context = nullptr;
}
void InternalPlatform::AssertInitialized() const
{
if (!m_Initialized)
{
throw PlatformException("The Platform has not been initialized yet!");
}
}
void InternalPlatform::OpenServiceTrackers()
{
ctkPluginContext* context = this->m_Context;
instanceLocation.reset(new ctkServiceTracker<ctkLocation*>(context, ctkLDAPSearchFilter(ctkLocation::INSTANCE_FILTER)));
instanceLocation->open();
userLocation.reset(new ctkServiceTracker<ctkLocation*>(context, ctkLDAPSearchFilter(ctkLocation::USER_FILTER)));
userLocation->open();
configurationLocation.reset(new ctkServiceTracker<ctkLocation*>(context, ctkLDAPSearchFilter(ctkLocation::CONFIGURATION_FILTER)));
configurationLocation->open();
installLocation.reset(new ctkServiceTracker<ctkLocation*>(context, ctkLDAPSearchFilter(ctkLocation::INSTALL_FILTER)));
installLocation->open();
m_PreferencesTracker.reset(new ctkServiceTracker<berry::IPreferencesService*>(context));
m_PreferencesTracker->open();
m_RegistryTracker.reset(new ctkServiceTracker<berry::IExtensionRegistry*>(context));
m_RegistryTracker->open();
m_DebugTracker.reset(new ctkServiceTracker<ctkDebugOptions*>(context));
m_DebugTracker->open();
}
void InternalPlatform::CloseServiceTrackers()
{
if (!m_PreferencesTracker.isNull())
{
m_PreferencesTracker->close();
m_PreferencesTracker.reset();
}
if (!m_RegistryTracker.isNull())
{
m_RegistryTracker->close();
m_RegistryTracker.reset();
}
if (!m_DebugTracker.isNull())
{
m_DebugTracker->close();
m_DebugTracker.reset();
}
if (!configurationLocation.isNull()) {
configurationLocation->close();
configurationLocation.reset();
}
if (!installLocation.isNull()) {
installLocation->close();
installLocation.reset();
}
if (!instanceLocation.isNull()) {
instanceLocation->close();
instanceLocation.reset();
}
if (!userLocation.isNull()) {
userLocation->close();
userLocation.reset();
}
}
void InternalPlatform::InitializeDebugFlags()
{
DEBUG = this->GetOption(Platform::PI_RUNTIME + "/debug", false).toBool();
if (DEBUG)
{
DEBUG_PLUGIN_PREFERENCES = GetOption(Platform::PI_RUNTIME + "/preferences/plugin", false).toBool();
}
}
IExtensionRegistry* InternalPlatform::GetExtensionRegistry()
{
return m_RegistryTracker.isNull() ? nullptr : m_RegistryTracker->getService();
}
IPreferencesService *InternalPlatform::GetPreferencesService()
{
return m_PreferencesTracker.isNull() ? nullptr : m_PreferencesTracker->getService();
}
ctkLocation* InternalPlatform::GetConfigurationLocation()
{
this->AssertInitialized();
return configurationLocation->getService();
}
ctkLocation* InternalPlatform::GetInstallLocation()
{
this->AssertInitialized();
return installLocation->getService();
}
ctkLocation* InternalPlatform::GetInstanceLocation()
{
this->AssertInitialized();
return instanceLocation->getService();
}
QDir InternalPlatform::GetStateLocation(const QSharedPointer<ctkPlugin>& plugin)
{
ctkLocation* service = GetInstanceLocation();
if (service == nullptr)
{
throw ctkIllegalStateException("No instance data can be specified.");
}
QUrl url = GetInstanceLocation()->getDataArea(plugin->getSymbolicName());
if (!url.isValid())
{
throw ctkIllegalStateException("The instance data location has not been specified yet.");
}
QDir location(url.toLocalFile());
if (!location.exists())
{
if (!location.mkpath(location.absolutePath()))
{
throw PlatformException(QString("Could not create plugin state location \"%1\"").arg(location.absolutePath()));
}
}
return location;
}
//PlatformEvents& InternalPlatform::GetEvents()
//{
// return m_Events;
//}
ctkLocation* InternalPlatform::GetUserLocation()
{
this->AssertInitialized();
return userLocation->getService();
}
ILog *InternalPlatform::GetLog(const QSharedPointer<ctkPlugin> &plugin) const
{
LogImpl* result = m_Logs.value(plugin->getPluginId());
if (result != nullptr)
return result;
// ExtendedLogService logService = (ExtendedLogService) extendedLogTracker.getService();
// Logger logger = logService == null ? null : logService.getLogger(bundle, PlatformLogWriter.EQUINOX_LOGGER_NAME);
// result = new Log(bundle, logger);
// ExtendedLogReaderService logReader = (ExtendedLogReaderService) logReaderTracker.getService();
// logReader.addLogListener(result, result);
// logs.put(bundle, result);
// return result;
result = new LogImpl(plugin);
m_Logs.insert(plugin->getPluginId(), result);
return result;
}
bool InternalPlatform::IsRunning() const
{
QMutexLocker lock(&m_Mutex);
try
{
return m_Initialized && m_Context && m_Context->getPlugin()->getState() == ctkPlugin::ACTIVE;
}
catch (const ctkIllegalStateException&)
{
return false;
}
}
QSharedPointer<ctkPlugin> InternalPlatform::GetPlugin(const QString &symbolicName)
{
QList<QSharedPointer<ctkPlugin> > plugins = m_Context->getPlugins();
QSharedPointer<ctkPlugin> res(nullptr);
foreach(QSharedPointer<ctkPlugin> plugin, plugins)
{
if ((plugin->getState() & (ctkPlugin::INSTALLED | ctkPlugin::UNINSTALLED)) == 0 &&
plugin->getSymbolicName() == symbolicName)
{
if (res.isNull())
{
res = plugin;
}
else if (res->getVersion().compare(plugin->getVersion()) < 0)
{
res = plugin;
}
}
}
return res;
}
QList<QSharedPointer<ctkPlugin> > InternalPlatform::GetPlugins(const QString &symbolicName, const QString &version)
{
QList<QSharedPointer<ctkPlugin> > plugins = m_Context->getPlugins();
QMap<ctkVersion, QSharedPointer<ctkPlugin> > selected;
ctkVersion versionObj(version);
foreach(QSharedPointer<ctkPlugin> plugin, plugins)
{
if ((plugin->getState() & (ctkPlugin::INSTALLED | ctkPlugin::UNINSTALLED)) == 0 &&
plugin->getSymbolicName() == symbolicName)
{
if (plugin->getVersion().compare(versionObj) > -1)
{
selected.insert(plugin->getVersion(), plugin);
}
}
}
QList<QSharedPointer<ctkPlugin> > sortedPlugins = selected.values();
QList<QSharedPointer<ctkPlugin> > reversePlugins;
qCopyBackward(sortedPlugins.begin(), sortedPlugins.end(), reversePlugins.end());
return reversePlugins;
}
QStringList InternalPlatform::GetApplicationArgs() const
{
QStringList result;
IApplicationContext* appContext = this->GetApplicationContext();
if (appContext)
{
QHash<QString, QVariant> args = appContext->GetArguments();
result = args[IApplicationContext::APPLICATION_ARGS].toStringList();
}
return result;
}
}
<commit_msg>Skip empty Qt plugin paths<commit_after>/*===================================================================
BlueBerry Platform
Copyright (c) German Cancer Research Center,
Division of Medical and Biological Informatics.
All rights reserved.
This software is distributed WITHOUT ANY WARRANTY; without
even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE.
See LICENSE.txt or http://www.mitk.org for details.
===================================================================*/
#ifndef NOMINMAX
#define NOMINMAX
#endif
#include "berryInternalPlatform.h"
#include "berryLog.h"
#include "berryLogImpl.h"
#include "berryPlatform.h"
#include "berryPlatformException.h"
#include "berryDebugUtil.h"
#include "berryPlatformException.h"
#include "berryCTKPluginActivator.h"
#include "berryPlatformException.h"
#include "berryApplicationContainer.h"
#include "berryProduct.h"
#include "berryIBranding.h"
//#include "event/berryPlatformEvents.h"
//#include "berryPlatformLogChannel.h"
#include <berryIApplicationContext.h>
#include <berryIPreferencesService.h>
#include <berryIExtensionRegistry.h>
#include <berryIProduct.h>
#include <service/datalocation/ctkLocation.h>
#include <service/debug/ctkDebugOptions.h>
#include <ctkPluginContext.h>
#include <ctkPlugin.h>
#include <ctkPluginException.h>
#include <ctkPluginFrameworkLauncher.h>
#include <QCoreApplication>
#include <QDesktopServices>
#include <QDebug>
#include <QMutexLocker>
namespace berry {
QMutex InternalPlatform::m_Mutex;
bool InternalPlatform::DEBUG = false;
bool InternalPlatform::DEBUG_PLUGIN_PREFERENCES = false;
InternalPlatform::InternalPlatform()
: m_Initialized(false)
, m_ConsoleLog(false)
, m_Context(nullptr)
{
}
InternalPlatform::~InternalPlatform()
{
}
InternalPlatform* InternalPlatform::GetInstance()
{
QMutexLocker lock(&m_Mutex);
static InternalPlatform instance;
return &instance;
}
bool InternalPlatform::ConsoleLog() const
{
return m_ConsoleLog;
}
QVariant InternalPlatform::GetOption(const QString& option, const QVariant& defaultValue) const
{
ctkDebugOptions* options = GetDebugOptions();
if (options != nullptr)
{
return options->getOption(option, defaultValue);
}
return QVariant();
}
IAdapterManager* InternalPlatform::GetAdapterManager() const
{
AssertInitialized();
return nullptr;
}
SmartPointer<IProduct> InternalPlatform::GetProduct() const
{
if (product.IsNotNull()) return product;
ApplicationContainer* container = org_blueberry_core_runtime_Activator::GetContainer();
IBranding* branding = container == nullptr ? nullptr : container->GetBranding();
if (branding == nullptr) return IProduct::Pointer();
IProduct::Pointer brandingProduct = branding->GetProduct();
if (!brandingProduct)
{
brandingProduct = new Product(branding);
}
product = brandingProduct;
return product;
}
void InternalPlatform::InitializePluginPaths()
{
QMutexLocker lock(&m_Mutex);
// Add search paths for Qt plugins
for(const auto qtPluginPath : m_Context->getProperty(Platform::PROP_QTPLUGIN_PATH).toStringList())
{
if (qtPluginPath.isEmpty())
continue;
if (QFile::exists(qtPluginPath))
{
QCoreApplication::addLibraryPath(qtPluginPath);
}
else if (m_ConsoleLog)
{
BERRY_WARN << "Qt plugin path does not exist: " << qtPluginPath.toStdString();
}
}
// Add a default search path. It is assumed that installed applications
// provide their Qt plugins in that path.
static const QString defaultQtPluginPath = QCoreApplication::applicationDirPath() + "/plugins";
if (QFile::exists(defaultQtPluginPath))
{
QCoreApplication::addLibraryPath(defaultQtPluginPath);
}
if (m_ConsoleLog)
{
std::string pathList;
foreach(QString libPath, QCoreApplication::libraryPaths())
{
pathList += (pathList.empty() ? "" : ", ") + libPath.toStdString();
}
BERRY_INFO << "Qt library search paths: " << pathList;
}
/*
m_ConfigPath.setPath(m_Context->getProperty("application.configDir").toString());
m_InstancePath.setPath(m_Context->getProperty("application.dir").toString());
QString installPath = m_Context->getProperty(Platform::PROP_HOME).toString();
if (installPath.isEmpty())
{
m_InstallPath = m_InstancePath;
}
else {
m_InstallPath.setPath(installPath);
}
QString dataLocation = m_Context->getProperty(Platform::PROP_STORAGE_DIR).toString();
if (!storageDir.isEmpty())
{
if (dataLocation.at(dataLocation.size()-1) != '/')
{
dataLocation += '/';
}
m_UserPath.setPath(dataLocation);
}
else
{
// Append a hash value of the absolute path of the executable to the data location.
// This allows to start the same application from different build or install trees.
dataLocation = QStandardPaths::writableLocation(QStandardPaths::GenericDataLocation) + this->getOrganizationName() + "/" + this->getApplicationName() + '_';
dataLocation += QString::number(qHash(QCoreApplication::applicationDirPath())) + "/";
m_UserPath.setPath(dataLocation);
}
BERRY_INFO(m_ConsoleLog) << "Framework storage dir: " << m_UserPath.absolutePath();
QFileInfo userFile(m_UserPath.absolutePath());
if (!QDir().mkpath(userFile.absoluteFilePath()) || !userFile.isWritable())
{
QString tmpPath = QDir::temp().absoluteFilePath(QString::fromStdString(this->commandName()));
BERRY_WARN << "Storage dir " << userFile.absoluteFilePath() << " is not writable. Falling back to temporary path " << tmpPath;
QDir().mkpath(tmpPath);
userFile.setFile(tmpPath);
}
m_BaseStatePath.setPath(m_UserPath.absolutePath() + "/bb-metadata/bb-plugins");
QString logPath(m_UserPath.absoluteFilePath(QString::fromStdString(this->commandName()) + ".log"));
m_PlatformLogChannel = new Poco::SimpleFileChannel(logPath.toStdString());
*/
}
ctkDebugOptions* InternalPlatform::GetDebugOptions() const
{
return m_DebugTracker.isNull() ? nullptr : m_DebugTracker->getService();
}
IApplicationContext* InternalPlatform::GetApplicationContext() const
{
QList<ctkServiceReference> refs;
try
{
refs = m_Context->getServiceReferences<IApplicationContext>("(blueberry.application.type=main.thread)");
}
catch (const std::invalid_argument&)
{
return nullptr;
}
if (refs.isEmpty()) return nullptr;
// assumes the application context is available as a service
IApplicationContext* result = m_Context->getService<IApplicationContext>(refs.front());
if (result != nullptr)
{
m_Context->ungetService(refs.front());
return result;
}
return nullptr;
}
void InternalPlatform::Start(ctkPluginContext* context)
{
this->m_Context = context;
m_ConsoleLog = m_Context->getProperty(ctkPluginFrameworkLauncher::PROP_CONSOLE_LOG).toBool();
OpenServiceTrackers();
this->InitializePluginPaths();
#ifdef BLUEBERRY_DEBUG_SMARTPOINTER
DebugUtil::RestoreState(m_UserPath);
#endif
InitializeDebugFlags();
this->m_Initialized = true;
}
void InternalPlatform::Stop(ctkPluginContext* /*context*/)
{
AssertInitialized();
this->m_Initialized = false;
CloseServiceTrackers();
#ifdef BLUEBERRY_DEBUG_SMARTPOINTER
DebugUtil::SaveState(m_UserPath);
#endif
this->m_Context = nullptr;
}
void InternalPlatform::AssertInitialized() const
{
if (!m_Initialized)
{
throw PlatformException("The Platform has not been initialized yet!");
}
}
void InternalPlatform::OpenServiceTrackers()
{
ctkPluginContext* context = this->m_Context;
instanceLocation.reset(new ctkServiceTracker<ctkLocation*>(context, ctkLDAPSearchFilter(ctkLocation::INSTANCE_FILTER)));
instanceLocation->open();
userLocation.reset(new ctkServiceTracker<ctkLocation*>(context, ctkLDAPSearchFilter(ctkLocation::USER_FILTER)));
userLocation->open();
configurationLocation.reset(new ctkServiceTracker<ctkLocation*>(context, ctkLDAPSearchFilter(ctkLocation::CONFIGURATION_FILTER)));
configurationLocation->open();
installLocation.reset(new ctkServiceTracker<ctkLocation*>(context, ctkLDAPSearchFilter(ctkLocation::INSTALL_FILTER)));
installLocation->open();
m_PreferencesTracker.reset(new ctkServiceTracker<berry::IPreferencesService*>(context));
m_PreferencesTracker->open();
m_RegistryTracker.reset(new ctkServiceTracker<berry::IExtensionRegistry*>(context));
m_RegistryTracker->open();
m_DebugTracker.reset(new ctkServiceTracker<ctkDebugOptions*>(context));
m_DebugTracker->open();
}
void InternalPlatform::CloseServiceTrackers()
{
if (!m_PreferencesTracker.isNull())
{
m_PreferencesTracker->close();
m_PreferencesTracker.reset();
}
if (!m_RegistryTracker.isNull())
{
m_RegistryTracker->close();
m_RegistryTracker.reset();
}
if (!m_DebugTracker.isNull())
{
m_DebugTracker->close();
m_DebugTracker.reset();
}
if (!configurationLocation.isNull()) {
configurationLocation->close();
configurationLocation.reset();
}
if (!installLocation.isNull()) {
installLocation->close();
installLocation.reset();
}
if (!instanceLocation.isNull()) {
instanceLocation->close();
instanceLocation.reset();
}
if (!userLocation.isNull()) {
userLocation->close();
userLocation.reset();
}
}
void InternalPlatform::InitializeDebugFlags()
{
DEBUG = this->GetOption(Platform::PI_RUNTIME + "/debug", false).toBool();
if (DEBUG)
{
DEBUG_PLUGIN_PREFERENCES = GetOption(Platform::PI_RUNTIME + "/preferences/plugin", false).toBool();
}
}
IExtensionRegistry* InternalPlatform::GetExtensionRegistry()
{
return m_RegistryTracker.isNull() ? nullptr : m_RegistryTracker->getService();
}
IPreferencesService *InternalPlatform::GetPreferencesService()
{
return m_PreferencesTracker.isNull() ? nullptr : m_PreferencesTracker->getService();
}
ctkLocation* InternalPlatform::GetConfigurationLocation()
{
this->AssertInitialized();
return configurationLocation->getService();
}
ctkLocation* InternalPlatform::GetInstallLocation()
{
this->AssertInitialized();
return installLocation->getService();
}
ctkLocation* InternalPlatform::GetInstanceLocation()
{
this->AssertInitialized();
return instanceLocation->getService();
}
QDir InternalPlatform::GetStateLocation(const QSharedPointer<ctkPlugin>& plugin)
{
ctkLocation* service = GetInstanceLocation();
if (service == nullptr)
{
throw ctkIllegalStateException("No instance data can be specified.");
}
QUrl url = GetInstanceLocation()->getDataArea(plugin->getSymbolicName());
if (!url.isValid())
{
throw ctkIllegalStateException("The instance data location has not been specified yet.");
}
QDir location(url.toLocalFile());
if (!location.exists())
{
if (!location.mkpath(location.absolutePath()))
{
throw PlatformException(QString("Could not create plugin state location \"%1\"").arg(location.absolutePath()));
}
}
return location;
}
//PlatformEvents& InternalPlatform::GetEvents()
//{
// return m_Events;
//}
ctkLocation* InternalPlatform::GetUserLocation()
{
this->AssertInitialized();
return userLocation->getService();
}
ILog *InternalPlatform::GetLog(const QSharedPointer<ctkPlugin> &plugin) const
{
LogImpl* result = m_Logs.value(plugin->getPluginId());
if (result != nullptr)
return result;
// ExtendedLogService logService = (ExtendedLogService) extendedLogTracker.getService();
// Logger logger = logService == null ? null : logService.getLogger(bundle, PlatformLogWriter.EQUINOX_LOGGER_NAME);
// result = new Log(bundle, logger);
// ExtendedLogReaderService logReader = (ExtendedLogReaderService) logReaderTracker.getService();
// logReader.addLogListener(result, result);
// logs.put(bundle, result);
// return result;
result = new LogImpl(plugin);
m_Logs.insert(plugin->getPluginId(), result);
return result;
}
bool InternalPlatform::IsRunning() const
{
QMutexLocker lock(&m_Mutex);
try
{
return m_Initialized && m_Context && m_Context->getPlugin()->getState() == ctkPlugin::ACTIVE;
}
catch (const ctkIllegalStateException&)
{
return false;
}
}
QSharedPointer<ctkPlugin> InternalPlatform::GetPlugin(const QString &symbolicName)
{
QList<QSharedPointer<ctkPlugin> > plugins = m_Context->getPlugins();
QSharedPointer<ctkPlugin> res(nullptr);
foreach(QSharedPointer<ctkPlugin> plugin, plugins)
{
if ((plugin->getState() & (ctkPlugin::INSTALLED | ctkPlugin::UNINSTALLED)) == 0 &&
plugin->getSymbolicName() == symbolicName)
{
if (res.isNull())
{
res = plugin;
}
else if (res->getVersion().compare(plugin->getVersion()) < 0)
{
res = plugin;
}
}
}
return res;
}
QList<QSharedPointer<ctkPlugin> > InternalPlatform::GetPlugins(const QString &symbolicName, const QString &version)
{
QList<QSharedPointer<ctkPlugin> > plugins = m_Context->getPlugins();
QMap<ctkVersion, QSharedPointer<ctkPlugin> > selected;
ctkVersion versionObj(version);
foreach(QSharedPointer<ctkPlugin> plugin, plugins)
{
if ((plugin->getState() & (ctkPlugin::INSTALLED | ctkPlugin::UNINSTALLED)) == 0 &&
plugin->getSymbolicName() == symbolicName)
{
if (plugin->getVersion().compare(versionObj) > -1)
{
selected.insert(plugin->getVersion(), plugin);
}
}
}
QList<QSharedPointer<ctkPlugin> > sortedPlugins = selected.values();
QList<QSharedPointer<ctkPlugin> > reversePlugins;
qCopyBackward(sortedPlugins.begin(), sortedPlugins.end(), reversePlugins.end());
return reversePlugins;
}
QStringList InternalPlatform::GetApplicationArgs() const
{
QStringList result;
IApplicationContext* appContext = this->GetApplicationContext();
if (appContext)
{
QHash<QString, QVariant> args = appContext->GetArguments();
result = args[IApplicationContext::APPLICATION_ARGS].toStringList();
}
return result;
}
}
<|endoftext|>
|
<commit_before>
#include "../../Flare.h"
#include "FlareWeaponStatus.h"
#include "../Components/FlareRoundButton.h"
#include "../../Spacecrafts/FlareWeapon.h"
#include "../../Spacecrafts/FlareSpacecraft.h"
#define LOCTEXT_NAMESPACE "FlareWeaponStatus"
/*----------------------------------------------------
Construct
----------------------------------------------------*/
void SFlareWeaponStatus::Construct(const FArguments& InArgs)
{
// Args
PlayerShip = InArgs._PlayerShip;
TargetWeaponGroupIndex = InArgs._TargetWeaponGroupIndex;
// Setup
ComponentHealth = 1.0;
CurrentAlpha = 0;
FadeInTime = 0.5f;
FadeOutTime = 1.0f;
// Content
const FFlareStyleCatalog& Theme = FFlareStyleSet::GetDefaultTheme();
const FSlateBrush* Icon = FFlareStyleSet::GetIcon("Mouse_Nothing_Black");
if (PlayerShip && TargetWeaponGroupIndex >= 0)
{
TargetWeaponGroup = PlayerShip->GetWeaponsSystem()->GetWeaponGroup(TargetWeaponGroupIndex);
Icon = &TargetWeaponGroup->Description->MeshPreviewBrush;
}
else
{
TargetWeaponGroup = NULL;
}
// Structure
ChildSlot
.VAlign(VAlign_Center)
.HAlign(HAlign_Left)
.Padding(Theme.ContentPadding)
[
SNew(SHorizontalBox)
// Button
+ SHorizontalBox::Slot()
.AutoWidth()
[
SNew(SFlareRoundButton)
.ShowText(false)
.InvertedBackground(true)
.Icon(Icon)
.IconColor(this, &SFlareWeaponStatus::GetIconColor)
.HighlightColor(this, &SFlareWeaponStatus::GetHighlightColor)
]
// Text
+ SHorizontalBox::Slot()
.AutoWidth()
.VAlign(VAlign_Center)
.Padding(Theme.ContentPadding)
[
SNew(STextBlock)
.TextStyle(&Theme.SmallFont)
.Text(this, &SFlareWeaponStatus::GetText)
.ColorAndOpacity(this, &SFlareWeaponStatus::GetTextColor)
.ShadowColorAndOpacity(this, &SFlareWeaponStatus::GetShadowColor)
]
];
}
/*----------------------------------------------------
Callbacks
----------------------------------------------------*/
void SFlareWeaponStatus::Tick(const FGeometry& AllottedGeometry, const double InCurrentTime, const float InDeltaTime)
{
SCompoundWidget::Tick(AllottedGeometry, InCurrentTime, InDeltaTime);
// Get the selection state for this weapon
float IsSelected = false;
float IsSelecting = false;
if (PlayerShip)
{
IsSelected = (PlayerShip->GetWeaponsSystem()->GetActiveWeaponGroupIndex() == TargetWeaponGroupIndex);
AFlarePlayerController* PC = PlayerShip->GetPC();
if (PC)
{
IsSelecting = PC->IsSelectingWeapon();
}
}
// Health
if (PlayerShip && TargetWeaponGroupIndex >= 0)
{
ComponentHealth = PlayerShip->GetDamageSystem()->GetWeaponGroupHealth(TargetWeaponGroupIndex);
}
else
{
ComponentHealth = 1.0;
}
// Update animation state
if (IsSelected)
{
CurrentAlpha += InDeltaTime / FadeInTime;
}
else if (IsSelecting)
{
if (CurrentAlpha >= 0.5f)
{
CurrentAlpha -= InDeltaTime / FadeOutTime;
}
else
{
CurrentAlpha += InDeltaTime / FadeInTime;
CurrentAlpha = FMath::Clamp(CurrentAlpha, 0.0f, 0.5f);
}
}
else
{
CurrentAlpha -= InDeltaTime / FadeOutTime;
}
CurrentAlpha = FMath::Clamp(CurrentAlpha, 0.0f, 1.0f);
}
FText SFlareWeaponStatus::GetText() const
{
FText Text;
if (TargetWeaponGroup)
{
// Generic info
FString NameInfo = TargetWeaponGroup->Description->Name.ToString();
FString CountInfo = FString::FromInt(TargetWeaponGroup->Weapons.Num()) + "x ";
FString HealthInfo = FString::FromInt(100 * ComponentHealth) + "%";
// Get ammo count
int32 RemainingAmmo = 0;
for (int32 i = 0; i < TargetWeaponGroup->Weapons.Num(); i++)
{
RemainingAmmo += TargetWeaponGroup->Weapons[i]->GetCurrentAmmo();
}
FString AmmoInfo = FString::FromInt(RemainingAmmo) + " " + LOCTEXT("Rounds", "rounds").ToString();
// Final string
Text = FText::FromString(CountInfo + NameInfo + "\n" + AmmoInfo + "\n" + HealthInfo);
}
return Text;
}
FSlateColor SFlareWeaponStatus::GetHighlightColor() const
{
const FFlareStyleCatalog& Theme = FFlareStyleSet::GetDefaultTheme();
FLinearColor NormalColor = Theme.NeutralColor;
FLinearColor DamageColor = Theme.EnemyColor;
// Update alpha
FLinearColor Color = FMath::Lerp(DamageColor, NormalColor, ComponentHealth);
Color.A *= Theme.DefaultAlpha * CurrentAlpha;
return Color;
}
FSlateColor SFlareWeaponStatus::GetIconColor() const
{
FLinearColor NormalColor = FLinearColor::White;
NormalColor.A *= CurrentAlpha;
return NormalColor;
}
FSlateColor SFlareWeaponStatus::GetTextColor() const
{
const FFlareStyleCatalog& Theme = FFlareStyleSet::GetDefaultTheme();
FLinearColor NormalColor = Theme.NeutralColor;
NormalColor.A *= Theme.DefaultAlpha * CurrentAlpha;
return NormalColor;
}
FLinearColor SFlareWeaponStatus::GetShadowColor() const
{
const FFlareStyleCatalog& Theme = FFlareStyleSet::GetDefaultTheme();
FLinearColor NormalColor = Theme.InvertedColor;
NormalColor.A *= Theme.DefaultAlpha * CurrentAlpha;
return NormalColor;
}
#undef LOCTEXT_NAMESPACE
<commit_msg>Don't count ammo from destroyed weapons<commit_after>
#include "../../Flare.h"
#include "FlareWeaponStatus.h"
#include "../Components/FlareRoundButton.h"
#include "../../Spacecrafts/FlareWeapon.h"
#include "../../Spacecrafts/FlareSpacecraft.h"
#define LOCTEXT_NAMESPACE "FlareWeaponStatus"
/*----------------------------------------------------
Construct
----------------------------------------------------*/
void SFlareWeaponStatus::Construct(const FArguments& InArgs)
{
// Args
PlayerShip = InArgs._PlayerShip;
TargetWeaponGroupIndex = InArgs._TargetWeaponGroupIndex;
// Setup
ComponentHealth = 1.0;
CurrentAlpha = 0;
FadeInTime = 0.5f;
FadeOutTime = 1.0f;
// Content
const FFlareStyleCatalog& Theme = FFlareStyleSet::GetDefaultTheme();
const FSlateBrush* Icon = FFlareStyleSet::GetIcon("Mouse_Nothing_Black");
if (PlayerShip && TargetWeaponGroupIndex >= 0)
{
TargetWeaponGroup = PlayerShip->GetWeaponsSystem()->GetWeaponGroup(TargetWeaponGroupIndex);
Icon = &TargetWeaponGroup->Description->MeshPreviewBrush;
}
else
{
TargetWeaponGroup = NULL;
}
// Structure
ChildSlot
.VAlign(VAlign_Center)
.HAlign(HAlign_Left)
.Padding(Theme.ContentPadding)
[
SNew(SHorizontalBox)
// Button
+ SHorizontalBox::Slot()
.AutoWidth()
[
SNew(SFlareRoundButton)
.ShowText(false)
.InvertedBackground(true)
.Icon(Icon)
.IconColor(this, &SFlareWeaponStatus::GetIconColor)
.HighlightColor(this, &SFlareWeaponStatus::GetHighlightColor)
]
// Text
+ SHorizontalBox::Slot()
.AutoWidth()
.VAlign(VAlign_Center)
.Padding(Theme.ContentPadding)
[
SNew(STextBlock)
.TextStyle(&Theme.SmallFont)
.Text(this, &SFlareWeaponStatus::GetText)
.ColorAndOpacity(this, &SFlareWeaponStatus::GetTextColor)
.ShadowColorAndOpacity(this, &SFlareWeaponStatus::GetShadowColor)
]
];
}
/*----------------------------------------------------
Callbacks
----------------------------------------------------*/
void SFlareWeaponStatus::Tick(const FGeometry& AllottedGeometry, const double InCurrentTime, const float InDeltaTime)
{
SCompoundWidget::Tick(AllottedGeometry, InCurrentTime, InDeltaTime);
// Get the selection state for this weapon
float IsSelected = false;
float IsSelecting = false;
if (PlayerShip)
{
IsSelected = (PlayerShip->GetWeaponsSystem()->GetActiveWeaponGroupIndex() == TargetWeaponGroupIndex);
AFlarePlayerController* PC = PlayerShip->GetPC();
if (PC)
{
IsSelecting = PC->IsSelectingWeapon();
}
}
// Health
if (PlayerShip && TargetWeaponGroupIndex >= 0)
{
ComponentHealth = PlayerShip->GetDamageSystem()->GetWeaponGroupHealth(TargetWeaponGroupIndex);
}
else
{
ComponentHealth = 1.0;
}
// Update animation state
if (IsSelected)
{
CurrentAlpha += InDeltaTime / FadeInTime;
}
else if (IsSelecting)
{
if (CurrentAlpha >= 0.5f)
{
CurrentAlpha -= InDeltaTime / FadeOutTime;
}
else
{
CurrentAlpha += InDeltaTime / FadeInTime;
CurrentAlpha = FMath::Clamp(CurrentAlpha, 0.0f, 0.5f);
}
}
else
{
CurrentAlpha -= InDeltaTime / FadeOutTime;
}
CurrentAlpha = FMath::Clamp(CurrentAlpha, 0.0f, 1.0f);
}
FText SFlareWeaponStatus::GetText() const
{
FText Text;
if (TargetWeaponGroup)
{
// Generic info
FString NameInfo = TargetWeaponGroup->Description->Name.ToString();
FString CountInfo = FString::FromInt(TargetWeaponGroup->Weapons.Num()) + "x ";
FString HealthInfo = FString::FromInt(100 * ComponentHealth) + "%";
// Get ammo count
int32 RemainingAmmo = 0;
for (int32 i = 0; i < TargetWeaponGroup->Weapons.Num(); i++)
{
if(TargetWeaponGroup->Weapons[i]->GetDamageRatio() <= 0.)
{
// Don't count ammo from destroyed components
continue;
}
RemainingAmmo += TargetWeaponGroup->Weapons[i]->GetCurrentAmmo();
}
FString AmmoInfo = FString::FromInt(RemainingAmmo) + " " + LOCTEXT("Rounds", "rounds").ToString();
// Final string
Text = FText::FromString(CountInfo + NameInfo + "\n" + AmmoInfo + "\n" + HealthInfo);
}
return Text;
}
FSlateColor SFlareWeaponStatus::GetHighlightColor() const
{
const FFlareStyleCatalog& Theme = FFlareStyleSet::GetDefaultTheme();
FLinearColor NormalColor = Theme.NeutralColor;
FLinearColor DamageColor = Theme.EnemyColor;
// Update alpha
FLinearColor Color = FMath::Lerp(DamageColor, NormalColor, ComponentHealth);
Color.A *= Theme.DefaultAlpha * CurrentAlpha;
return Color;
}
FSlateColor SFlareWeaponStatus::GetIconColor() const
{
FLinearColor NormalColor = FLinearColor::White;
NormalColor.A *= CurrentAlpha;
return NormalColor;
}
FSlateColor SFlareWeaponStatus::GetTextColor() const
{
const FFlareStyleCatalog& Theme = FFlareStyleSet::GetDefaultTheme();
FLinearColor NormalColor = Theme.NeutralColor;
NormalColor.A *= Theme.DefaultAlpha * CurrentAlpha;
return NormalColor;
}
FLinearColor SFlareWeaponStatus::GetShadowColor() const
{
const FFlareStyleCatalog& Theme = FFlareStyleSet::GetDefaultTheme();
FLinearColor NormalColor = Theme.InvertedColor;
NormalColor.A *= Theme.DefaultAlpha * CurrentAlpha;
return NormalColor;
}
#undef LOCTEXT_NAMESPACE
<|endoftext|>
|
<commit_before>/*************************************************************************
* UrBackup - Client/Server backup system
* Copyright (C) 2011 Martin Raiber
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
**************************************************************************/
#ifndef CLIENT_ONLY
#include "server.h"
#include "../Interface/Server.h"
#include "../Interface/Database.h"
#include "../Interface/ThreadPool.h"
#include "server_get.h"
#include "database.h"
#include "../Interface/SettingsReader.h"
#include "server_status.h"
#include "../stringtools.h"
#include "os_functions.h"
#include <memory.h>
const unsigned int waittime=50*1000; //1 min
const int max_offline=5;
BackupServer::BackupServer(IPipe *pExitpipe)
{
exitpipe=pExitpipe;
}
void BackupServer::operator()(void)
{
IDatabase *db=Server->getDatabase(Server->getThreadID(),URBACKUPDB_SERVER);
ISettingsReader *settings=Server->createDBSettingsReader(Server->getDatabase(Server->getThreadID(),URBACKUPDB_SERVER), "settings");
#ifdef _WIN32
std::wstring tmpdir;
if(settings->getValue(L"tmpdir", &tmpdir) && !tmpdir.empty())
{
os_remove_nonempty_dir(tmpdir+os_file_sep()+L"urbackup_tmp");
os_create_dir(tmpdir+os_file_sep()+L"urbackup_tmp");
Server->setTemporaryDirectory(tmpdir+os_file_sep()+L"urbackup_tmp");
}
else
{
wchar_t tmpp[MAX_PATH];
DWORD l;
if((l=GetTempPathW(MAX_PATH, tmpp))==0 || l>MAX_PATH )
{
wcscpy_s(tmpp,L"C:\\");
}
std::wstring w_tmp=tmpp;
if(!w_tmp.empty() && w_tmp[w_tmp.size()-1]=='\\')
{
w_tmp.erase(w_tmp.size()-1, 1); }
os_remove_nonempty_dir(w_tmp+os_file_sep()+L"urbackup_tmp");
os_create_dir(w_tmp+os_file_sep()+L"urbackup_tmp");
Server->setTemporaryDirectory(w_tmp+os_file_sep()+L"urbackup_tmp");
}
#endif
q_get_extra_hostnames=db->Prepare("SELECT id,hostname FROM extra_clients");
q_update_extra_ip=db->Prepare("UPDATE extra_clients SET lastip=? WHERE id=?");
FileClient fc;
while(true)
{
findClients(fc);
startClients(fc);
if(!ServerStatus::isActive() && settings->getValue("autoshutdown", "false")=="true")
{
writestring("true", "urbackup/shutdown_now");
#ifdef _WIN32
ExitWindowsEx(EWX_POWEROFF|EWX_FORCEIFHUNG, SHTDN_REASON_MAJOR_APPLICATION|SHTDN_REASON_MINOR_OTHER );
#endif
}
std::string r;
exitpipe->Read(&r, waittime);
if(r=="exit")
{
removeAllClients();
exitpipe->Write("ok");
Server->destroy(settings);
db->destroyAllQueries();
delete this;
return;
}
}
}
void BackupServer::findClients(FileClient &fc)
{
db_results res=q_get_extra_hostnames->Read();
q_get_extra_hostnames->Reset();
std::vector<in_addr> addr_hints;
for(size_t i=0;i<res.size();++i)
{
unsigned int dest;
bool b=os_lookuphostname(Server->ConvertToUTF8(res[i][L"hostname"]), &dest);
if(b)
{
q_update_extra_ip->Bind((_i64)dest);
q_update_extra_ip->Bind(res[i][L"id"]);
q_update_extra_ip->Write();
q_update_extra_ip->Reset();
in_addr tmp;
tmp.s_addr=dest;
addr_hints.push_back(tmp);
}
}
_u32 rc=fc.GetServers(true, addr_hints);
while(rc==ERR_CONTINUE)
{
Server->wait(50);
rc=fc.GetServers(false, addr_hints);
}
if(rc==ERR_ERROR)
{
Server->Log("Error in BackupServer::findClients rc==ERR_ERROR",LL_ERROR);
}
}
void BackupServer::startClients(FileClient &fc)
{
std::vector<std::wstring> names=fc.getServerNames();
std::vector<sockaddr_in> servers=fc.getServers();
for(size_t i=0;i<names.size();++i)
{
std::map<std::wstring, SClient>::iterator it=clients.find(names[i]);
if( it==clients.end() )
{
Server->Log(L"New Backupclient: "+names[i]);
ServerStatus::setOnline(names[i], true);
IPipe *np=Server->createMemoryPipe();
BackupServerGet *client=new BackupServerGet(np, servers[i], names[i]);
Server->getThreadPool()->execute(client);
SClient c;
c.pipe=np;
c.offlinecount=0;
c.addr=servers[i];
ServerStatus::setIP(names[i], c.addr.sin_addr.s_addr);
clients.insert(std::pair<std::wstring, SClient>(names[i], c) );
}
else if(it->second.offlinecount<max_offline)
{
if(it->second.addr.sin_addr.s_addr==servers[i].sin_addr.s_addr)
{
it->second.offlinecount=0;
}
else
{
bool last=true;
for(size_t j=i+1;j<names.size();++j)
{
if(names[j]==names[i])
{
last=false;
break;
}
}
if(last)
{
it->second.addr=servers[i];
std::string msg;
msg.resize(7+sizeof(sockaddr_in));
msg[0]='a'; msg[1]='d'; msg[2]='d'; msg[3]='r'; msg[4]='e'; msg[5]='s'; msg[6]='s';
memcpy(&msg[7], &it->second.addr, sizeof(sockaddr_in));
it->second.pipe->Write(msg);
char *ip=(char*)it->second.addr.sin_addr.s_addr;
Server->Log("New client address: "+nconvert(ip[3])+"."+nconvert(ip[2])+"."+nconvert(ip[1])+"."+nconvert(ip[0]), LL_INFO);
ServerStatus::setIP(names[i], it->second.addr.sin_addr.s_addr);
}
}
}
}
bool c=true;
size_t maxi=0;
while(c && !clients.empty())
{
c=false;
size_t i_c=0;
for(std::map<std::wstring, SClient>::iterator it=clients.begin();it!=clients.end();++it)
{
bool found=false;
for(size_t i=0;i<names.size();++i)
{
if( it->first==names[i] )
{
found=true;
break;
}
}
if( found==false || it->second.offlinecount>max_offline)
{
if(it->second.offlinecount==max_offline)
{
Server->Log(L"Client exitet: "+it->first);
it->second.pipe->Write("exit");
++it->second.offlinecount;
ServerStatus::setOnline(it->first, false);
}
else if(it->second.offlinecount>max_offline)
{
std::string msg;
std::vector<std::string> msgs;
while(it->second.pipe->Read(&msg,0)>0)
{
if(msg!="ok")
{
msgs.push_back(msg);
}
else
{
Server->Log(L"Client finished: "+it->first);
ServerStatus::setDone(it->first, true);
Server->destroy(it->second.pipe);
clients.erase(it);
maxi=i_c;
c=true;
break;
}
}
if( c==false )
{
for(size_t i=0;i<msgs.size();++i)
{
it->second.pipe->Write(msgs[i]);
}
}
else
{
break;
}
}
else if(i_c>=maxi)
{
++it->second.offlinecount;
}
}
++i_c;
}
}
}
void BackupServer::removeAllClients(void)
{
for(std::map<std::wstring, SClient>::iterator it=clients.begin();it!=clients.end();++it)
{
it->second.pipe->Write("exitnow");
std::string msg;
while(msg!="ok")
{
it->second.pipe->Read(&msg);
it->second.pipe->Write(msg);
Server->wait(500);
}
Server->destroy(it->second.pipe);
}
}
#endif //CLIENT_ONLY<commit_msg>Fixed memory access bug<commit_after>/*************************************************************************
* UrBackup - Client/Server backup system
* Copyright (C) 2011 Martin Raiber
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
**************************************************************************/
#ifndef CLIENT_ONLY
#include "server.h"
#include "../Interface/Server.h"
#include "../Interface/Database.h"
#include "../Interface/ThreadPool.h"
#include "server_get.h"
#include "database.h"
#include "../Interface/SettingsReader.h"
#include "server_status.h"
#include "../stringtools.h"
#include "os_functions.h"
#include <memory.h>
const unsigned int waittime=50*1000; //1 min
const int max_offline=5;
BackupServer::BackupServer(IPipe *pExitpipe)
{
exitpipe=pExitpipe;
}
void BackupServer::operator()(void)
{
IDatabase *db=Server->getDatabase(Server->getThreadID(),URBACKUPDB_SERVER);
ISettingsReader *settings=Server->createDBSettingsReader(Server->getDatabase(Server->getThreadID(),URBACKUPDB_SERVER), "settings");
#ifdef _WIN32
std::wstring tmpdir;
if(settings->getValue(L"tmpdir", &tmpdir) && !tmpdir.empty())
{
os_remove_nonempty_dir(tmpdir+os_file_sep()+L"urbackup_tmp");
os_create_dir(tmpdir+os_file_sep()+L"urbackup_tmp");
Server->setTemporaryDirectory(tmpdir+os_file_sep()+L"urbackup_tmp");
}
else
{
wchar_t tmpp[MAX_PATH];
DWORD l;
if((l=GetTempPathW(MAX_PATH, tmpp))==0 || l>MAX_PATH )
{
wcscpy_s(tmpp,L"C:\\");
}
std::wstring w_tmp=tmpp;
if(!w_tmp.empty() && w_tmp[w_tmp.size()-1]=='\\')
{
w_tmp.erase(w_tmp.size()-1, 1); }
os_remove_nonempty_dir(w_tmp+os_file_sep()+L"urbackup_tmp");
os_create_dir(w_tmp+os_file_sep()+L"urbackup_tmp");
Server->setTemporaryDirectory(w_tmp+os_file_sep()+L"urbackup_tmp");
}
#endif
q_get_extra_hostnames=db->Prepare("SELECT id,hostname FROM extra_clients");
q_update_extra_ip=db->Prepare("UPDATE extra_clients SET lastip=? WHERE id=?");
FileClient fc;
while(true)
{
findClients(fc);
startClients(fc);
if(!ServerStatus::isActive() && settings->getValue("autoshutdown", "false")=="true")
{
writestring("true", "urbackup/shutdown_now");
#ifdef _WIN32
ExitWindowsEx(EWX_POWEROFF|EWX_FORCEIFHUNG, SHTDN_REASON_MAJOR_APPLICATION|SHTDN_REASON_MINOR_OTHER );
#endif
}
std::string r;
exitpipe->Read(&r, waittime);
if(r=="exit")
{
removeAllClients();
exitpipe->Write("ok");
Server->destroy(settings);
db->destroyAllQueries();
delete this;
return;
}
}
}
void BackupServer::findClients(FileClient &fc)
{
db_results res=q_get_extra_hostnames->Read();
q_get_extra_hostnames->Reset();
std::vector<in_addr> addr_hints;
for(size_t i=0;i<res.size();++i)
{
unsigned int dest;
bool b=os_lookuphostname(Server->ConvertToUTF8(res[i][L"hostname"]), &dest);
if(b)
{
q_update_extra_ip->Bind((_i64)dest);
q_update_extra_ip->Bind(res[i][L"id"]);
q_update_extra_ip->Write();
q_update_extra_ip->Reset();
in_addr tmp;
tmp.s_addr=dest;
addr_hints.push_back(tmp);
}
}
_u32 rc=fc.GetServers(true, addr_hints);
while(rc==ERR_CONTINUE)
{
Server->wait(50);
rc=fc.GetServers(false, addr_hints);
}
if(rc==ERR_ERROR)
{
Server->Log("Error in BackupServer::findClients rc==ERR_ERROR",LL_ERROR);
}
}
void BackupServer::startClients(FileClient &fc)
{
std::vector<std::wstring> names=fc.getServerNames();
std::vector<sockaddr_in> servers=fc.getServers();
for(size_t i=0;i<names.size();++i)
{
std::map<std::wstring, SClient>::iterator it=clients.find(names[i]);
if( it==clients.end() )
{
Server->Log(L"New Backupclient: "+names[i]);
ServerStatus::setOnline(names[i], true);
IPipe *np=Server->createMemoryPipe();
BackupServerGet *client=new BackupServerGet(np, servers[i], names[i]);
Server->getThreadPool()->execute(client);
SClient c;
c.pipe=np;
c.offlinecount=0;
c.addr=servers[i];
ServerStatus::setIP(names[i], c.addr.sin_addr.s_addr);
clients.insert(std::pair<std::wstring, SClient>(names[i], c) );
}
else if(it->second.offlinecount<max_offline)
{
if(it->second.addr.sin_addr.s_addr==servers[i].sin_addr.s_addr)
{
it->second.offlinecount=0;
}
else
{
bool last=true;
for(size_t j=i+1;j<names.size();++j)
{
if(names[j]==names[i])
{
last=false;
break;
}
}
if(last)
{
it->second.addr=servers[i];
std::string msg;
msg.resize(7+sizeof(sockaddr_in));
msg[0]='a'; msg[1]='d'; msg[2]='d'; msg[3]='r'; msg[4]='e'; msg[5]='s'; msg[6]='s';
memcpy(&msg[7], &it->second.addr, sizeof(sockaddr_in));
it->second.pipe->Write(msg);
char *ip=(char*)&it->second.addr.sin_addr.s_addr;
Server->Log("New client address: "+nconvert(ip[3])+"."+nconvert(ip[2])+"."+nconvert(ip[1])+"."+nconvert(ip[0]), LL_INFO);
ServerStatus::setIP(names[i], it->second.addr.sin_addr.s_addr);
}
}
}
}
bool c=true;
size_t maxi=0;
while(c && !clients.empty())
{
c=false;
size_t i_c=0;
for(std::map<std::wstring, SClient>::iterator it=clients.begin();it!=clients.end();++it)
{
bool found=false;
for(size_t i=0;i<names.size();++i)
{
if( it->first==names[i] )
{
found=true;
break;
}
}
if( found==false || it->second.offlinecount>max_offline)
{
if(it->second.offlinecount==max_offline)
{
Server->Log(L"Client exitet: "+it->first);
it->second.pipe->Write("exit");
++it->second.offlinecount;
ServerStatus::setOnline(it->first, false);
}
else if(it->second.offlinecount>max_offline)
{
std::string msg;
std::vector<std::string> msgs;
while(it->second.pipe->Read(&msg,0)>0)
{
if(msg!="ok")
{
msgs.push_back(msg);
}
else
{
Server->Log(L"Client finished: "+it->first);
ServerStatus::setDone(it->first, true);
Server->destroy(it->second.pipe);
clients.erase(it);
maxi=i_c;
c=true;
break;
}
}
if( c==false )
{
for(size_t i=0;i<msgs.size();++i)
{
it->second.pipe->Write(msgs[i]);
}
}
else
{
break;
}
}
else if(i_c>=maxi)
{
++it->second.offlinecount;
}
}
++i_c;
}
}
}
void BackupServer::removeAllClients(void)
{
for(std::map<std::wstring, SClient>::iterator it=clients.begin();it!=clients.end();++it)
{
it->second.pipe->Write("exitnow");
std::string msg;
while(msg!="ok")
{
it->second.pipe->Read(&msg);
it->second.pipe->Write(msg);
Server->wait(500);
}
Server->destroy(it->second.pipe);
}
}
#endif //CLIENT_ONLY<|endoftext|>
|
<commit_before>#include "Camera.h"
#include "../../Window.h"
#include "../GameObject.h"
#include "../../graphics/Skybox.h"
#include "../../graphics/TextRender.h"
#include "Transform.h"
#include "../../graphics/Renderer.h"
#include <algorithm>
#include "../../Input.h"
#include "../../editor/gizmos/Gizmos.h"
namespace thomas
{
namespace object
{
namespace component
{
std::vector<Camera*> Camera::s_allCameras;
void Camera::UpdateProjMatrix()
{
m_projMatrix = math::Matrix::CreatePerspectiveFieldOfView(math::DegreesToRadians(m_fov), GetViewport().AspectRatio(), m_near, m_far);
m_frustrum = math::BoundingFrustum(m_projMatrix);
}
Camera::Camera(bool dontAddTolist)
{
m_fov = 70;
m_near = 0.1;
m_far = 10000;
m_viewport = math::Viewport(0, 0, 1, 1);
m_targetDisplay = -1;
UpdateProjMatrix();
}
Camera::Camera()
{
m_fov = 70;
m_near = 0.5;
m_far = 10000;
m_viewport = math::Viewport(0, 0, 1,1);
m_targetDisplay = 0;
UpdateProjMatrix();
s_allCameras.push_back(this);
std::sort(s_allCameras.begin(), s_allCameras.end(), [](Camera* a, Camera* b)
{
return a->GetTargetDisplayIndex() < b->GetTargetDisplayIndex();
});
}
Camera::~Camera()
{
for (int i = 0; i < s_allCameras.size(); i++)
{
if (s_allCameras[i] == this)
{
s_allCameras.erase(s_allCameras.begin() + i);
break;
}
}
}
math::Matrix Camera::GetProjMatrix()
{
return m_projMatrix;
}
math::Matrix Camera::GetViewMatrix()
{
math::Matrix viewMatrix = m_gameObject->m_transform->GetWorldMatrix();
return viewMatrix.Invert();
}
math::Matrix Camera::GetViewProjMatrix()
{
return GetViewMatrix() * m_projMatrix;
}
math::Vector3 Camera::GetPosition()
{
return m_gameObject->m_transform->GetPosition();
}
math::Ray Camera::ScreenPointToRay(math::Vector2 point)
{
// Move the mouse cursor coordinates into the -1 to +1 range.
Window* window = Window::GetWindow(m_targetDisplay);
float pointX = ((2.0f * (float)point.x) / (float)window->GetWidth()) - 1.0f;
float pointY = (((2.0f * (float)point.y) / (float)window->GetHeight()) - 1.0f) * -1.0f;
// Adjust the points using the projection matrix to account for the aspect ratio of the viewport.
pointX /= m_projMatrix._11;
pointY /= m_projMatrix.Transpose()._22;
// Get the inverse of the view matrix.
math::Matrix inverseViewMatrix = GetViewMatrix().Invert();
math::Vector3 direction(pointX, pointY, -1.0f);
// Calculate the direction of the picking ray in view space.
direction = math::Vector3::TransformNormal(direction, inverseViewMatrix);
// Get the origin of the picking ray which is the position of the camera
math::Vector3 origin = GetPosition();
direction.Normalize();
return math::Ray(origin, direction);
}
float Camera::GetFov()
{
return m_fov;
}
float Camera::GetNear()
{
return m_near;
}
float Camera::GetFar()
{
return m_far;
}
void Camera::SetFov(float fov)
{
m_fov = fov;
UpdateProjMatrix();
}
void Camera::SetNear(float viewNear)
{
if (viewNear > 0)
m_near = viewNear;
UpdateProjMatrix();
}
void Camera::SetFar(float viewFar)
{
if (viewFar > 0)
m_far = viewFar;
UpdateProjMatrix();
}
math::Viewport Camera::GetViewport()
{
Window* window = Window::GetWindow(m_targetDisplay);
if (window)
return math::Viewport(m_viewport.x, m_viewport.y, m_viewport.width * window->GetWidth(), m_viewport.height * window->GetHeight());
else
return m_viewport;
}
void Camera::SetViewport(math::Viewport viewport)
{
m_viewport = viewport;
UpdateProjMatrix();
}
void Camera::SetViewport(float x, float y, float width, float height)
{
SetViewport(math::Viewport(x, y, width, height));
}
float Camera::GetAspectRatio()
{
return m_viewport.AspectRatio();
}
void Camera::Render()
{
graphics::Renderer::BindCamera(this);
graphics::Renderer::Render();
}
void Camera::OnDrawGizmos()
{
}
void Camera::OnDrawGizmosSelected()
{
//editor::Gizmos::SetMatrix(m_gameObject->m_transform->GetWorldMatrix().Transpose());
editor::Gizmos::SetColor(math::Color(0.6, 0.6, 0.6));
editor::Gizmos::DrawFrustum(GetFrustrum());
}
void Camera::SetTargetDisplay(int index)
{
if (Window::GetWindows().size() < index)
{
m_targetDisplay = index;
UpdateProjMatrix();
}
}
int Camera::GetTargetDisplayIndex()
{
return m_targetDisplay;
}
math::BoundingFrustum Camera::GetFrustrum()
{
math::BoundingFrustum frustrum;
m_frustrum.Transform(frustrum, m_gameObject->m_transform->GetWorldMatrix());
return frustrum;
}
}
}
}<commit_msg>Fixed aspect ratio bug<commit_after>#include "Camera.h"
#include "../../Window.h"
#include "../GameObject.h"
#include "../../graphics/Skybox.h"
#include "../../graphics/TextRender.h"
#include "Transform.h"
#include "../../graphics/Renderer.h"
#include <algorithm>
#include "../../Input.h"
#include "../../editor/gizmos/Gizmos.h"
namespace thomas
{
namespace object
{
namespace component
{
std::vector<Camera*> Camera::s_allCameras;
void Camera::UpdateProjMatrix()
{
m_projMatrix = math::Matrix::CreatePerspectiveFieldOfView(math::DegreesToRadians(m_fov), GetViewport().AspectRatio(), m_near, m_far);
m_frustrum = math::BoundingFrustum(m_projMatrix);
}
Camera::Camera(bool dontAddTolist)
{
m_fov = 70;
m_near = 0.1;
m_far = 10000;
m_viewport = math::Viewport(0, 0, 1, 1);
m_targetDisplay = -1;
UpdateProjMatrix();
}
Camera::Camera()
{
m_fov = 70;
m_near = 0.5;
m_far = 10000;
m_viewport = math::Viewport(0, 0, 1,1);
m_targetDisplay = 0;
UpdateProjMatrix();
s_allCameras.push_back(this);
std::sort(s_allCameras.begin(), s_allCameras.end(), [](Camera* a, Camera* b)
{
return a->GetTargetDisplayIndex() < b->GetTargetDisplayIndex();
});
}
Camera::~Camera()
{
for (int i = 0; i < s_allCameras.size(); i++)
{
if (s_allCameras[i] == this)
{
s_allCameras.erase(s_allCameras.begin() + i);
break;
}
}
}
math::Matrix Camera::GetProjMatrix()
{
UpdateProjMatrix();
return m_projMatrix;
}
math::Matrix Camera::GetViewMatrix()
{
math::Matrix viewMatrix = m_gameObject->m_transform->GetWorldMatrix();
return viewMatrix.Invert();
}
math::Matrix Camera::GetViewProjMatrix()
{
return GetViewMatrix() * m_projMatrix;
}
math::Vector3 Camera::GetPosition()
{
return m_gameObject->m_transform->GetPosition();
}
math::Ray Camera::ScreenPointToRay(math::Vector2 point)
{
// Move the mouse cursor coordinates into the -1 to +1 range.
Window* window = Window::GetWindow(m_targetDisplay);
float pointX = ((2.0f * (float)point.x) / (float)window->GetWidth()) - 1.0f;
float pointY = (((2.0f * (float)point.y) / (float)window->GetHeight()) - 1.0f) * -1.0f;
// Adjust the points using the projection matrix to account for the aspect ratio of the viewport.
pointX /= m_projMatrix._11;
pointY /= m_projMatrix.Transpose()._22;
// Get the inverse of the view matrix.
math::Matrix inverseViewMatrix = GetViewMatrix().Invert();
math::Vector3 direction(pointX, pointY, -1.0f);
// Calculate the direction of the picking ray in view space.
direction = math::Vector3::TransformNormal(direction, inverseViewMatrix);
// Get the origin of the picking ray which is the position of the camera
math::Vector3 origin = GetPosition();
direction.Normalize();
return math::Ray(origin, direction);
}
float Camera::GetFov()
{
return m_fov;
}
float Camera::GetNear()
{
return m_near;
}
float Camera::GetFar()
{
return m_far;
}
void Camera::SetFov(float fov)
{
m_fov = fov;
UpdateProjMatrix();
}
void Camera::SetNear(float viewNear)
{
if (viewNear > 0)
m_near = viewNear;
UpdateProjMatrix();
}
void Camera::SetFar(float viewFar)
{
if (viewFar > 0)
m_far = viewFar;
UpdateProjMatrix();
}
math::Viewport Camera::GetViewport()
{
Window* window = Window::GetWindow(m_targetDisplay);
if (window)
return math::Viewport(m_viewport.x, m_viewport.y, m_viewport.width * window->GetWidth(), m_viewport.height * window->GetHeight());
else
return m_viewport;
}
void Camera::SetViewport(math::Viewport viewport)
{
m_viewport = viewport;
UpdateProjMatrix();
}
void Camera::SetViewport(float x, float y, float width, float height)
{
SetViewport(math::Viewport(x, y, width, height));
}
float Camera::GetAspectRatio()
{
return m_viewport.AspectRatio();
}
void Camera::Render()
{
graphics::Renderer::BindCamera(this);
graphics::Renderer::Render();
}
void Camera::OnDrawGizmos()
{
}
void Camera::OnDrawGizmosSelected()
{
//editor::Gizmos::SetMatrix(m_gameObject->m_transform->GetWorldMatrix().Transpose());
editor::Gizmos::SetColor(math::Color(0.6, 0.6, 0.6));
editor::Gizmos::DrawFrustum(GetFrustrum());
}
void Camera::SetTargetDisplay(int index)
{
if (Window::GetWindows().size() < index)
{
m_targetDisplay = index;
UpdateProjMatrix();
}
}
int Camera::GetTargetDisplayIndex()
{
return m_targetDisplay;
}
math::BoundingFrustum Camera::GetFrustrum()
{
math::BoundingFrustum frustrum;
m_frustrum.Transform(frustrum, m_gameObject->m_transform->GetWorldMatrix());
return frustrum;
}
}
}
}<|endoftext|>
|
<commit_before>/*=========================================================================
Program: ORFEO Toolbox
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.
See OTBCopyright.txt for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
=========================================================================*/
#include "otbMacro.h"
#include "otbImage.h"
#include "otbMapProjections.h"
//TODO add control baseline
int otbMapProjection( int argc, char* argv[] )
{
const char * outFileName = argv[1];
std::ofstream file;
file.open(outFileName);
otb::UtmInverseProjection::Pointer lUtmProjection = otb::UtmInverseProjection::New();
file << lUtmProjection->GetWkt() << std::endl << std::endl;
otb::UtmForwardProjection::Pointer lUtmProjection2 = otb::UtmForwardProjection::New();
file << lUtmProjection2->GetWkt() << std::endl << std::endl;
otb::Lambert2EtenduInverseProjection::Pointer lLambert2Etendu = otb::Lambert2EtenduInverseProjection::New();
file << lLambert2Etendu->GetWkt() << std::endl << std::endl;
otb::Lambert2EtenduForwardProjection::Pointer lLambert2Etendu2 = otb::Lambert2EtenduForwardProjection::New();
file << lLambert2Etendu2->GetWkt() << std::endl << std::endl;
otb::Lambert93InverseProjection::Pointer lLambert93 = otb::Lambert93InverseProjection::New();
file << lLambert93->GetWkt() << std::endl << std::endl;
otb::Lambert93ForwardProjection::Pointer lLambert93_2 = otb::Lambert93ForwardProjection::New();
file << lLambert93_2->GetWkt() << std::endl << std::endl;
otb::MercatorInverseProjection::Pointer lMercatorProjection = otb::MercatorInverseProjection::New();
file << lMercatorProjection->GetWkt() << std::endl << std::endl;
otb::MercatorForwardProjection::Pointer lMercatorProjection2 = otb::MercatorForwardProjection::New();
file << lMercatorProjection2->GetWkt() << std::endl << std::endl;
file.close();
return EXIT_SUCCESS;
}<commit_msg>WRG : add a new line at the end of otbMapProjection.cxx<commit_after>/*=========================================================================
Program: ORFEO Toolbox
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.
See OTBCopyright.txt for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
=========================================================================*/
#include "otbMacro.h"
#include "otbImage.h"
#include "otbMapProjections.h"
//TODO add control baseline
int otbMapProjection( int argc, char* argv[] )
{
const char * outFileName = argv[1];
std::ofstream file;
file.open(outFileName);
otb::UtmInverseProjection::Pointer lUtmProjection = otb::UtmInverseProjection::New();
file << lUtmProjection->GetWkt() << std::endl << std::endl;
otb::UtmForwardProjection::Pointer lUtmProjection2 = otb::UtmForwardProjection::New();
file << lUtmProjection2->GetWkt() << std::endl << std::endl;
otb::Lambert2EtenduInverseProjection::Pointer lLambert2Etendu = otb::Lambert2EtenduInverseProjection::New();
file << lLambert2Etendu->GetWkt() << std::endl << std::endl;
otb::Lambert2EtenduForwardProjection::Pointer lLambert2Etendu2 = otb::Lambert2EtenduForwardProjection::New();
file << lLambert2Etendu2->GetWkt() << std::endl << std::endl;
otb::Lambert93InverseProjection::Pointer lLambert93 = otb::Lambert93InverseProjection::New();
file << lLambert93->GetWkt() << std::endl << std::endl;
otb::Lambert93ForwardProjection::Pointer lLambert93_2 = otb::Lambert93ForwardProjection::New();
file << lLambert93_2->GetWkt() << std::endl << std::endl;
otb::MercatorInverseProjection::Pointer lMercatorProjection = otb::MercatorInverseProjection::New();
file << lMercatorProjection->GetWkt() << std::endl << std::endl;
otb::MercatorForwardProjection::Pointer lMercatorProjection2 = otb::MercatorForwardProjection::New();
file << lMercatorProjection2->GetWkt() << std::endl << std::endl;
file.close();
return EXIT_SUCCESS;
}
<|endoftext|>
|
<commit_before>#include <iostream>
#include <iomanip>
using namespace std;
int main() {
// Declara as variavéis A B MEDIA
double A, B, MEDIA;
// Leiura das var A e B
cin >> A;
cin >> B;
// Produto dos pesos e cálcula a média e armazenada na var MEDIA
MEDIA = ((A*3.5)+(B*7.5))/11;
// Setar a precisao para 5 casas
cout << fixed << setprecision(5);
// Mostra o resultado em MEDIA
cout << "MEDIA = " << MEDIA << endl;
return 0;
}<commit_msg>Delete 1005.cpp<commit_after><|endoftext|>
|
<commit_before>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/sync_socket.h"
#include <errno.h>
#include <limits.h>
#include <stdio.h>
#include <sys/types.h>
#include "base/logging.h"
namespace base {
const SyncSocket::Handle SyncSocket::kInvalidHandle = -1;
SyncSocket::SyncSocket() : handle_(kInvalidHandle) {
}
SyncSocket::~SyncSocket() {
}
// static
bool SyncSocket::CreatePair(SyncSocket* socket_a, SyncSocket* socket_b) {
return false;
}
bool SyncSocket::Close() {
if (handle_ != kInvalidHandle) {
if (close(handle_) < 0)
DPLOG(ERROR) << "close";
handle_ = -1;
}
return true;
}
size_t SyncSocket::Send(const void* buffer, size_t length) {
// Not implemented since it's not needed by any client code yet.
return -1;
}
size_t SyncSocket::Receive(void* buffer, size_t length) {
return read(handle_, buffer, length);
}
size_t SyncSocket::ReceiveWithTimeout(void* buffer, size_t length, TimeDelta) {
NOTIMPLEMENTED();
return 0;
}
size_t SyncSocket::Peek() {
return -1;
}
CancelableSyncSocket::CancelableSyncSocket() {
}
CancelableSyncSocket::CancelableSyncSocket(Handle handle)
: SyncSocket(handle) {
}
size_t CancelableSyncSocket::Send(const void* buffer, size_t length) {
return -1;
}
bool CancelableSyncSocket::Shutdown() {
return false;
}
// static
bool CancelableSyncSocket::CreatePair(CancelableSyncSocket* socket_a,
CancelableSyncSocket* socket_b) {
return SyncSocket::CreatePair(socket_a, socket_b);
}
} // namespace base
<commit_msg>Add write() impl to SyncSocket for NaCl. Fix shutdown leaks.<commit_after>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/sync_socket.h"
#include <errno.h>
#include <limits.h>
#include <stdio.h>
#include <sys/types.h>
#include "base/logging.h"
namespace base {
const SyncSocket::Handle SyncSocket::kInvalidHandle = -1;
SyncSocket::SyncSocket() : handle_(kInvalidHandle) {
}
SyncSocket::~SyncSocket() {
Close();
}
// static
bool SyncSocket::CreatePair(SyncSocket* socket_a, SyncSocket* socket_b) {
return false;
}
bool SyncSocket::Close() {
if (handle_ != kInvalidHandle) {
if (close(handle_) < 0)
DPLOG(ERROR) << "close";
handle_ = kInvalidHandle;
}
return true;
}
size_t SyncSocket::Send(const void* buffer, size_t length) {
const ssize_t bytes_written = write(handle_, buffer, length);
return bytes_written > 0 ? bytes_written : 0;
}
size_t SyncSocket::Receive(void* buffer, size_t length) {
const ssize_t bytes_read = read(handle_, buffer, length);
return bytes_read > 0 ? bytes_read : 0;
}
size_t SyncSocket::ReceiveWithTimeout(void* buffer, size_t length, TimeDelta) {
NOTIMPLEMENTED();
return 0;
}
size_t SyncSocket::Peek() {
NOTIMPLEMENTED();
return 0;
}
CancelableSyncSocket::CancelableSyncSocket() {
}
CancelableSyncSocket::CancelableSyncSocket(Handle handle)
: SyncSocket(handle) {
}
size_t CancelableSyncSocket::Send(const void* buffer, size_t length) {
return Send(buffer, length);
}
bool CancelableSyncSocket::Shutdown() {
return Close();
}
// static
bool CancelableSyncSocket::CreatePair(CancelableSyncSocket* socket_a,
CancelableSyncSocket* socket_b) {
return SyncSocket::CreatePair(socket_a, socket_b);
}
} // namespace base
<|endoftext|>
|
<commit_before>/// @file
/// @version 3.5
///
/// @section LICENSE
///
/// This program is free software; you can redistribute it and/or modify it under
/// the terms of the BSD license: http://opensource.org/licenses/BSD-3-Clause
#ifdef _ANDROID
#include <jni.h>
#include <hltypes/harray.h>
#include <hltypes/hlog.h>
#include <hltypes/hltypesUtil.h>
#include <hltypes/hresource.h>
#include <hltypes/hstring.h>
#define __NATIVE_INTERFACE_CLASS "com/april/NativeInterface"
#include "androidUtilJNI.h"
#include "april.h"
#include "Keys.h"
#include "main_base.h"
#include "Platform.h"
#include "RenderSystem.h"
#include "Window.h"
#include "AndroidJNI_Keys.h"
#define PROTECTED_WINDOW_CALL(methodCall) \
if (april::window != NULL) \
{ \
april::window->methodCall; \
}
#define PROTECTED_RENDERSYS_CALL(methodCall) \
if (april::rendersys != NULL) \
{ \
april::rendersys->methodCall; \
}
namespace april
{
extern void* javaVM;
extern void (*dialogCallback)(MessageBoxButton);
void (*aprilInit)(const harray<hstr>&) = NULL;
void (*aprilDestroy)() = NULL;
extern jobject classLoader;
void JNICALL _JNI_setVariables(JNIEnv* env, jclass classe, jstring jDataPath, jstring jForcedArchivePath)
{
hstr dataPath = _JSTR_TO_HSTR(jDataPath);
hstr archivePath = _JSTR_TO_HSTR(jForcedArchivePath);
hlog::write(april::logTag, "System path: " + april::getUserDataPath());
if (!hresource::hasZip()) // if not using APK as data file archive
{
#ifndef _OPENKODE
// set the resources CWD
hresource::setCwd(dataPath + "/Android/data/" + april::getPackageName());
hresource::setArchive(""); // not used anyway when hasZip() returns false
hlog::write(april::logTag, "Using no-zip: " + hresource::getCwd());
#else
hlog::write(april::logTag, "Using KD file system: " + hresource::getCwd());
#endif
}
else if (archivePath != "")
{
// using APK file as archive
hresource::setCwd("assets");
hresource::setArchive(archivePath);
hlog::write(april::logTag, "Using assets: " + hresource::getArchive());
}
else
{
// using OBB file as archive
hresource::setCwd(".");
// using Google Play's "Expansion File" system
hresource::setArchive(dataPath);
hlog::write(april::logTag, "Using obb: " + hresource::getArchive());
}
}
void JNICALL _JNI_init(JNIEnv* env, jclass classe, jobjectArray _args)
{
harray<hstr> args;
int length = env->GetArrayLength(_args);
jstring jStr;
for_iter (i, 0, length)
{
args += _JSTR_TO_HSTR((jstring)env->GetObjectArrayElement(_args, i));
}
hlog::debug(april::logTag, "Got args:");
foreach (hstr, it, args)
{
hlog::debug(april::logTag, " " + (*it));
}
(*aprilInit)(args);
}
void JNICALL _JNI_destroy(JNIEnv* env, jclass classe)
{
(*aprilDestroy)();
}
bool JNICALL _JNI_render(JNIEnv* env, jclass classe)
{
bool result = true;
if (april::window != NULL)
{
try
{
result = april::window->updateOneFrame();
}
catch (hltypes::exception& e)
{
hlog::error("FATAL", e.getMessage());
throw e;
}
}
return true;
}
void JNICALL _JNI_onKeyDown(JNIEnv* env, jclass classe, jint keyCode, jint charCode)
{
PROTECTED_WINDOW_CALL(queueKeyEvent(april::Window::KEY_DOWN, android2april((int)keyCode), (unsigned int)charCode));
}
void JNICALL _JNI_onKeyUp(JNIEnv* env, jclass classe, jint keyCode)
{
PROTECTED_WINDOW_CALL(queueKeyEvent(april::Window::KEY_UP, android2april((int)keyCode), 0));
}
void JNICALL _JNI_onTouch(JNIEnv* env, jclass classe, jint type, jfloat x, jfloat y, jint index)
{
PROTECTED_WINDOW_CALL(queueTouchEvent((april::Window::MouseEventType)type, gvec2((float)x, (float)y), (int)index));
}
void JNICALL _JNI_onButtonDown(JNIEnv* env, jclass classe, jint keyCode, jint charCode)
{
PROTECTED_WINDOW_CALL(queueControllerEvent(april::Window::CONTROLLER_DOWN, (Button)(int)keyCode));
}
void JNICALL _JNI_onButtonUp(JNIEnv* env, jclass classe, jint keyCode)
{
PROTECTED_WINDOW_CALL(queueControllerEvent(april::Window::CONTROLLER_UP, (Button)(int)keyCode));
}
void JNICALL _JNI_onControllerAxis(JNIEnv* env, jclass classe, jint keyCode, jfloat axisValue)
{
PROTECTED_WINDOW_CALL(queueControllerAxisEvent(april::Window::CONTROLLER_AXIS, (Button)(int)keyCode, (float) axisValue));
}
void JNICALL _JNI_onWindowFocusChanged(JNIEnv* env, jclass classe, jboolean jFocused)
{
bool focused = (jFocused != JNI_FALSE);
hlog::write(april::logTag, "onWindowFocusChanged(" + hstr(focused) + ")");
PROTECTED_WINDOW_CALL(handleFocusChangeEvent(focused));
}
void JNICALL _JNI_onVirtualKeyboardChanged(JNIEnv* env, jclass classe, jboolean jVisible, jfloat jHeightRatio)
{
bool visible = (jVisible != JNI_FALSE);
float heightRatio = (float)jHeightRatio;
hlog::write(april::logTag, "onVirtualKeyboardChanged(" + hstr(visible) + "," + hstr(heightRatio) + ")");
PROTECTED_WINDOW_CALL(handleVirtualKeyboardChangeEvent(visible, heightRatio));
}
void JNICALL _JNI_onLowMemory(JNIEnv* env, jclass classe)
{
hlog::write(april::logTag, "onLowMemoryWarning()");
PROTECTED_WINDOW_CALL(handleLowMemoryWarning());
}
void JNICALL _JNI_onSurfaceCreated(JNIEnv* env, jclass classe)
{
hlog::write(april::logTag, "Android View::onSurfaceCreated()");
PROTECTED_RENDERSYS_CALL(reset());
}
void JNICALL _JNI_activityOnCreate(JNIEnv* env, jclass classe)
{
hlog::write(april::logTag, "Android Activity::onCreate()");
}
void JNICALL _JNI_activityOnStart(JNIEnv* env, jclass classe)
{
hlog::write(april::logTag, "Android Activity::onStart()");
}
void JNICALL _JNI_activityOnResume(JNIEnv* env, jclass classe)
{
hlog::write(april::logTag, "Android Activity::onResume()");
PROTECTED_WINDOW_CALL(handleActivityChangeEvent(true));
}
void JNICALL _JNI_activityOnPause(JNIEnv* env, jclass classe)
{
hlog::write(april::logTag, "Android Activity::onPause()");
PROTECTED_WINDOW_CALL(handleActivityChangeEvent(false));
PROTECTED_RENDERSYS_CALL(unloadTextures());
}
void JNICALL _JNI_activityOnStop(JNIEnv* env, jclass classe)
{
hlog::write(april::logTag, "Android Activity::onStop()");
}
void JNICALL _JNI_activityOnDestroy(JNIEnv* env, jclass classe)
{
hlog::write(april::logTag, "Android Activity::onDestroy()");
if (april::classLoader != NULL)
{
env->DeleteGlobalRef(april::classLoader);
april::classLoader = NULL;
}
}
void JNICALL _JNI_activityOnRestart(JNIEnv* env, jclass classe)
{
hlog::write(april::logTag, "Android Activity::onRestart()");
}
void JNICALL _JNI_onDialogOk(JNIEnv* env, jclass classe)
{
if (dialogCallback != NULL)
{
(*dialogCallback)(MESSAGE_BUTTON_OK);
}
}
void JNICALL _JNI_onDialogYes(JNIEnv* env, jclass classe)
{
if (dialogCallback != NULL)
{
(*dialogCallback)(MESSAGE_BUTTON_YES);
}
}
void JNICALL _JNI_onDialogNo(JNIEnv* env, jclass classe)
{
if (dialogCallback != NULL)
{
(*dialogCallback)(MESSAGE_BUTTON_NO);
}
}
void JNICALL _JNI_onDialogCancel(JNIEnv* env, jclass classe)
{
if (dialogCallback != NULL)
{
(*dialogCallback)(MESSAGE_BUTTON_CANCEL);
}
}
#define METHOD_COUNT 25 // make sure this fits
static JNINativeMethod methods[METHOD_COUNT] =
{
{"setVariables", _JARGS(_JVOID, _JSTR _JSTR), (void*)&april::_JNI_setVariables },
{"init", _JARGS(_JVOID, _JARR(_JSTR)), (void*)&april::_JNI_init },
{"destroy", _JARGS(_JVOID, ), (void*)&april::_JNI_destroy },
{"render", _JARGS(_JBOOL, ), (void*)&april::_JNI_render },
{"onKeyDown", _JARGS(_JVOID, _JINT _JINT), (bool*)&april::_JNI_onKeyDown },
{"onKeyUp", _JARGS(_JVOID, _JINT), (bool*)&april::_JNI_onKeyUp },
{"onTouch", _JARGS(_JVOID, _JINT _JFLOAT _JFLOAT _JINT), (void*)&april::_JNI_onTouch },
{"onButtonDown", _JARGS(_JVOID, _JINT), (bool*)&april::_JNI_onButtonDown },
{"onButtonUp", _JARGS(_JVOID, _JINT), (bool*)&april::_JNI_onButtonUp },
{"onControllerAxis", _JARGS(_JVOID, _JINT _JFLOAT), (bool*)&april::_JNI_onControllerAxis },
{"onWindowFocusChanged", _JARGS(_JVOID, _JBOOL), (void*)&april::_JNI_onWindowFocusChanged },
{"onVirtualKeyboardChanged", _JARGS(_JVOID, _JBOOL _JFLOAT), (void*)&april::_JNI_onVirtualKeyboardChanged },
{"onLowMemory", _JARGS(_JVOID, ), (void*)&april::_JNI_onLowMemory },
{"onSurfaceCreated", _JARGS(_JVOID, ), (void*)&april::_JNI_onSurfaceCreated },
{"activityOnCreate", _JARGS(_JVOID, ), (void*)&april::_JNI_activityOnCreate },
{"activityOnStart", _JARGS(_JVOID, ), (void*)&april::_JNI_activityOnStart },
{"activityOnResume", _JARGS(_JVOID, ), (void*)&april::_JNI_activityOnResume },
{"activityOnPause", _JARGS(_JVOID, ), (void*)&april::_JNI_activityOnPause },
{"activityOnStop", _JARGS(_JVOID, ), (void*)&april::_JNI_activityOnStop },
{"activityOnDestroy", _JARGS(_JVOID, ), (void*)&april::_JNI_activityOnDestroy },
{"activityOnRestart", _JARGS(_JVOID, ), (void*)&april::_JNI_activityOnRestart },
{"onDialogOk", _JARGS(_JVOID, ), (void*)&april::_JNI_onDialogOk },
{"onDialogYes", _JARGS(_JVOID, ), (void*)&april::_JNI_onDialogYes },
{"onDialogNo", _JARGS(_JVOID, ), (void*)&april::_JNI_onDialogNo },
{"onDialogCancel", _JARGS(_JVOID, ), (void*)&april::_JNI_onDialogCancel }
};
jint JNI_OnLoad(void (*anAprilInit)(const harray<hstr>&), void (*anAprilDestroy)(), JavaVM* vm, void* reserved)
{
april::javaVM = (void*)vm;
april::aprilInit = anAprilInit;
april::aprilDestroy = anAprilDestroy;
JNIEnv* env = NULL;
if (vm->GetEnv(reinterpret_cast<void**>(&env), JNI_VERSION_1_6) != JNI_OK)
{
return -1;
}
jclass classNativeInterface = env->FindClass(__NATIVE_INTERFACE_CLASS);
if (env->RegisterNatives(classNativeInterface, methods, METHOD_COUNT) != 0)
{
return -1;
}
#ifdef _OPENKODE // not really needed when OpenKODE isn't used
jclass classClass = env->FindClass("java/lang/Class");
jmethodID methodGetClassLoader = env->GetMethodID(classClass, "getClassLoader", _JARGS(_JCLASS("java/lang/ClassLoader"), ));
jobject classLoader = env->CallObjectMethod(classNativeInterface, methodGetClassLoader);
april::classLoader = env->NewGlobalRef(classLoader);
#endif
return JNI_VERSION_1_6;
}
}
#endif
<commit_msg>android update terminate fix<commit_after>/// @file
/// @version 3.5
///
/// @section LICENSE
///
/// This program is free software; you can redistribute it and/or modify it under
/// the terms of the BSD license: http://opensource.org/licenses/BSD-3-Clause
#ifdef _ANDROID
#include <jni.h>
#include <hltypes/harray.h>
#include <hltypes/hlog.h>
#include <hltypes/hltypesUtil.h>
#include <hltypes/hresource.h>
#include <hltypes/hstring.h>
#define __NATIVE_INTERFACE_CLASS "com/april/NativeInterface"
#include "androidUtilJNI.h"
#include "april.h"
#include "Keys.h"
#include "main_base.h"
#include "Platform.h"
#include "RenderSystem.h"
#include "Window.h"
#include "AndroidJNI_Keys.h"
#define PROTECTED_WINDOW_CALL(methodCall) \
if (april::window != NULL) \
{ \
april::window->methodCall; \
}
#define PROTECTED_RENDERSYS_CALL(methodCall) \
if (april::rendersys != NULL) \
{ \
april::rendersys->methodCall; \
}
namespace april
{
extern void* javaVM;
extern void (*dialogCallback)(MessageBoxButton);
void (*aprilInit)(const harray<hstr>&) = NULL;
void (*aprilDestroy)() = NULL;
extern jobject classLoader;
void JNICALL _JNI_setVariables(JNIEnv* env, jclass classe, jstring jDataPath, jstring jForcedArchivePath)
{
hstr dataPath = _JSTR_TO_HSTR(jDataPath);
hstr archivePath = _JSTR_TO_HSTR(jForcedArchivePath);
hlog::write(april::logTag, "System path: " + april::getUserDataPath());
if (!hresource::hasZip()) // if not using APK as data file archive
{
#ifndef _OPENKODE
// set the resources CWD
hresource::setCwd(dataPath + "/Android/data/" + april::getPackageName());
hresource::setArchive(""); // not used anyway when hasZip() returns false
hlog::write(april::logTag, "Using no-zip: " + hresource::getCwd());
#else
hlog::write(april::logTag, "Using KD file system: " + hresource::getCwd());
#endif
}
else if (archivePath != "")
{
// using APK file as archive
hresource::setCwd("assets");
hresource::setArchive(archivePath);
hlog::write(april::logTag, "Using assets: " + hresource::getArchive());
}
else
{
// using OBB file as archive
hresource::setCwd(".");
// using Google Play's "Expansion File" system
hresource::setArchive(dataPath);
hlog::write(april::logTag, "Using obb: " + hresource::getArchive());
}
}
void JNICALL _JNI_init(JNIEnv* env, jclass classe, jobjectArray _args)
{
harray<hstr> args;
int length = env->GetArrayLength(_args);
jstring jStr;
for_iter (i, 0, length)
{
args += _JSTR_TO_HSTR((jstring)env->GetObjectArrayElement(_args, i));
}
hlog::debug(april::logTag, "Got args:");
foreach (hstr, it, args)
{
hlog::debug(april::logTag, " " + (*it));
}
(*aprilInit)(args);
}
void JNICALL _JNI_destroy(JNIEnv* env, jclass classe)
{
(*aprilDestroy)();
}
bool JNICALL _JNI_render(JNIEnv* env, jclass classe)
{
bool result = true;
if (april::window != NULL)
{
try
{
result = april::window->updateOneFrame();
}
catch (hltypes::exception& e)
{
hlog::error("FATAL", e.getMessage());
throw e;
}
}
return result;
}
void JNICALL _JNI_onKeyDown(JNIEnv* env, jclass classe, jint keyCode, jint charCode)
{
PROTECTED_WINDOW_CALL(queueKeyEvent(april::Window::KEY_DOWN, android2april((int)keyCode), (unsigned int)charCode));
}
void JNICALL _JNI_onKeyUp(JNIEnv* env, jclass classe, jint keyCode)
{
PROTECTED_WINDOW_CALL(queueKeyEvent(april::Window::KEY_UP, android2april((int)keyCode), 0));
}
void JNICALL _JNI_onTouch(JNIEnv* env, jclass classe, jint type, jfloat x, jfloat y, jint index)
{
PROTECTED_WINDOW_CALL(queueTouchEvent((april::Window::MouseEventType)type, gvec2((float)x, (float)y), (int)index));
}
void JNICALL _JNI_onButtonDown(JNIEnv* env, jclass classe, jint keyCode, jint charCode)
{
PROTECTED_WINDOW_CALL(queueControllerEvent(april::Window::CONTROLLER_DOWN, (Button)(int)keyCode));
}
void JNICALL _JNI_onButtonUp(JNIEnv* env, jclass classe, jint keyCode)
{
PROTECTED_WINDOW_CALL(queueControllerEvent(april::Window::CONTROLLER_UP, (Button)(int)keyCode));
}
void JNICALL _JNI_onControllerAxis(JNIEnv* env, jclass classe, jint keyCode, jfloat axisValue)
{
PROTECTED_WINDOW_CALL(queueControllerAxisEvent(april::Window::CONTROLLER_AXIS, (Button)(int)keyCode, (float) axisValue));
}
void JNICALL _JNI_onWindowFocusChanged(JNIEnv* env, jclass classe, jboolean jFocused)
{
bool focused = (jFocused != JNI_FALSE);
hlog::write(april::logTag, "onWindowFocusChanged(" + hstr(focused) + ")");
PROTECTED_WINDOW_CALL(handleFocusChangeEvent(focused));
}
void JNICALL _JNI_onVirtualKeyboardChanged(JNIEnv* env, jclass classe, jboolean jVisible, jfloat jHeightRatio)
{
bool visible = (jVisible != JNI_FALSE);
float heightRatio = (float)jHeightRatio;
hlog::write(april::logTag, "onVirtualKeyboardChanged(" + hstr(visible) + "," + hstr(heightRatio) + ")");
PROTECTED_WINDOW_CALL(handleVirtualKeyboardChangeEvent(visible, heightRatio));
}
void JNICALL _JNI_onLowMemory(JNIEnv* env, jclass classe)
{
hlog::write(april::logTag, "onLowMemoryWarning()");
PROTECTED_WINDOW_CALL(handleLowMemoryWarning());
}
void JNICALL _JNI_onSurfaceCreated(JNIEnv* env, jclass classe)
{
hlog::write(april::logTag, "Android View::onSurfaceCreated()");
PROTECTED_RENDERSYS_CALL(reset());
}
void JNICALL _JNI_activityOnCreate(JNIEnv* env, jclass classe)
{
hlog::write(april::logTag, "Android Activity::onCreate()");
}
void JNICALL _JNI_activityOnStart(JNIEnv* env, jclass classe)
{
hlog::write(april::logTag, "Android Activity::onStart()");
}
void JNICALL _JNI_activityOnResume(JNIEnv* env, jclass classe)
{
hlog::write(april::logTag, "Android Activity::onResume()");
PROTECTED_WINDOW_CALL(handleActivityChangeEvent(true));
}
void JNICALL _JNI_activityOnPause(JNIEnv* env, jclass classe)
{
hlog::write(april::logTag, "Android Activity::onPause()");
PROTECTED_WINDOW_CALL(handleActivityChangeEvent(false));
PROTECTED_RENDERSYS_CALL(unloadTextures());
}
void JNICALL _JNI_activityOnStop(JNIEnv* env, jclass classe)
{
hlog::write(april::logTag, "Android Activity::onStop()");
}
void JNICALL _JNI_activityOnDestroy(JNIEnv* env, jclass classe)
{
hlog::write(april::logTag, "Android Activity::onDestroy()");
if (april::classLoader != NULL)
{
env->DeleteGlobalRef(april::classLoader);
april::classLoader = NULL;
}
}
void JNICALL _JNI_activityOnRestart(JNIEnv* env, jclass classe)
{
hlog::write(april::logTag, "Android Activity::onRestart()");
}
void JNICALL _JNI_onDialogOk(JNIEnv* env, jclass classe)
{
if (dialogCallback != NULL)
{
(*dialogCallback)(MESSAGE_BUTTON_OK);
}
}
void JNICALL _JNI_onDialogYes(JNIEnv* env, jclass classe)
{
if (dialogCallback != NULL)
{
(*dialogCallback)(MESSAGE_BUTTON_YES);
}
}
void JNICALL _JNI_onDialogNo(JNIEnv* env, jclass classe)
{
if (dialogCallback != NULL)
{
(*dialogCallback)(MESSAGE_BUTTON_NO);
}
}
void JNICALL _JNI_onDialogCancel(JNIEnv* env, jclass classe)
{
if (dialogCallback != NULL)
{
(*dialogCallback)(MESSAGE_BUTTON_CANCEL);
}
}
#define METHOD_COUNT 25 // make sure this fits
static JNINativeMethod methods[METHOD_COUNT] =
{
{"setVariables", _JARGS(_JVOID, _JSTR _JSTR), (void*)&april::_JNI_setVariables },
{"init", _JARGS(_JVOID, _JARR(_JSTR)), (void*)&april::_JNI_init },
{"destroy", _JARGS(_JVOID, ), (void*)&april::_JNI_destroy },
{"render", _JARGS(_JBOOL, ), (void*)&april::_JNI_render },
{"onKeyDown", _JARGS(_JVOID, _JINT _JINT), (bool*)&april::_JNI_onKeyDown },
{"onKeyUp", _JARGS(_JVOID, _JINT), (bool*)&april::_JNI_onKeyUp },
{"onTouch", _JARGS(_JVOID, _JINT _JFLOAT _JFLOAT _JINT), (void*)&april::_JNI_onTouch },
{"onButtonDown", _JARGS(_JVOID, _JINT), (bool*)&april::_JNI_onButtonDown },
{"onButtonUp", _JARGS(_JVOID, _JINT), (bool*)&april::_JNI_onButtonUp },
{"onControllerAxis", _JARGS(_JVOID, _JINT _JFLOAT), (bool*)&april::_JNI_onControllerAxis },
{"onWindowFocusChanged", _JARGS(_JVOID, _JBOOL), (void*)&april::_JNI_onWindowFocusChanged },
{"onVirtualKeyboardChanged", _JARGS(_JVOID, _JBOOL _JFLOAT), (void*)&april::_JNI_onVirtualKeyboardChanged },
{"onLowMemory", _JARGS(_JVOID, ), (void*)&april::_JNI_onLowMemory },
{"onSurfaceCreated", _JARGS(_JVOID, ), (void*)&april::_JNI_onSurfaceCreated },
{"activityOnCreate", _JARGS(_JVOID, ), (void*)&april::_JNI_activityOnCreate },
{"activityOnStart", _JARGS(_JVOID, ), (void*)&april::_JNI_activityOnStart },
{"activityOnResume", _JARGS(_JVOID, ), (void*)&april::_JNI_activityOnResume },
{"activityOnPause", _JARGS(_JVOID, ), (void*)&april::_JNI_activityOnPause },
{"activityOnStop", _JARGS(_JVOID, ), (void*)&april::_JNI_activityOnStop },
{"activityOnDestroy", _JARGS(_JVOID, ), (void*)&april::_JNI_activityOnDestroy },
{"activityOnRestart", _JARGS(_JVOID, ), (void*)&april::_JNI_activityOnRestart },
{"onDialogOk", _JARGS(_JVOID, ), (void*)&april::_JNI_onDialogOk },
{"onDialogYes", _JARGS(_JVOID, ), (void*)&april::_JNI_onDialogYes },
{"onDialogNo", _JARGS(_JVOID, ), (void*)&april::_JNI_onDialogNo },
{"onDialogCancel", _JARGS(_JVOID, ), (void*)&april::_JNI_onDialogCancel }
};
jint JNI_OnLoad(void (*anAprilInit)(const harray<hstr>&), void (*anAprilDestroy)(), JavaVM* vm, void* reserved)
{
april::javaVM = (void*)vm;
april::aprilInit = anAprilInit;
april::aprilDestroy = anAprilDestroy;
JNIEnv* env = NULL;
if (vm->GetEnv(reinterpret_cast<void**>(&env), JNI_VERSION_1_6) != JNI_OK)
{
return -1;
}
jclass classNativeInterface = env->FindClass(__NATIVE_INTERFACE_CLASS);
if (env->RegisterNatives(classNativeInterface, methods, METHOD_COUNT) != 0)
{
return -1;
}
#ifdef _OPENKODE // not really needed when OpenKODE isn't used
jclass classClass = env->FindClass("java/lang/Class");
jmethodID methodGetClassLoader = env->GetMethodID(classClass, "getClassLoader", _JARGS(_JCLASS("java/lang/ClassLoader"), ));
jobject classLoader = env->CallObjectMethod(classNativeInterface, methodGetClassLoader);
april::classLoader = env->NewGlobalRef(classLoader);
#endif
return JNI_VERSION_1_6;
}
}
#endif
<|endoftext|>
|
<commit_before>/* FLAC input plugin for Winamp3
* Copyright (C) 2000,2001,2002 Josh Coalson
*
* 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.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*
* NOTE: this code is derived from the 'rawpcm' example by
* Nullsoft; the original license for the 'rawpcm' example follows.
*/
/*
Nullsoft WASABI Source File License
Copyright 1999-2001 Nullsoft, Inc.
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
Brennan Underwood
brennan@nullsoft.com
*/
#include "flacpcm.h"
extern "C" {
#include "FLAC/utility.h"
};
struct id3v1_struct {
FLAC__byte raw[128];
char title[31];
char artist[31];
char album[31];
char comment[31];
unsigned year;
unsigned track; /* may be 0 if v1 (not v1.1) tag */
unsigned genre;
char description[1024]; /* the formatted description passed to the gui */
};
static bool get_id3v1_tag_(const char *filename, id3v1_struct *tag);
FlacPcm::FlacPcm():
needs_seek(false),
seek_sample(0),
samples_in_reservoir(0),
abort_flag(false),
reader(0),
decoder(0)
{
}
FlacPcm::~FlacPcm()
{
cleanup();
}
int FlacPcm::getInfos(MediaInfo *infos)
{
reader = infos->getReader();
if(!reader) return 0;
//@@@ to be really "clean" we should go through the reader instead of directly to the file...
if(!FLAC__utility_get_streaminfo(infos->getFilename(), &stream_info))
return 1;
id3v1_struct tag;
//@@@ ditto here...
bool has_tag = get_id3v1_tag_(infos->getFilename(), &tag);
infos->setLength(lengthInMsec());
//@@@ infos->setTitle(Std::filename(infos->getFilename()));
infos->setTitle(tag.description);
infos->setInfo(StringPrintf("FLAC:<%ihz:%ibps:%dch>", stream_info.sample_rate, stream_info.bits_per_sample, stream_info.channels)); //@@@ fix later
if(has_tag) {
infos->setData("Title", tag.title);
infos->setData("Artist", tag.artist);
infos->setData("Album", tag.album);
}
return 0;
}
int FlacPcm::processData(MediaInfo *infos, ChunkList *chunk_list, bool *killswitch)
{
reader = infos->getReader();
if(reader == 0)
return 0;
if(decoder == 0) {
decoder = FLAC__seekable_stream_decoder_new();
if(decoder == 0)
return 0;
FLAC__seekable_stream_decoder_set_md5_checking(decoder, false);
FLAC__seekable_stream_decoder_set_read_callback(decoder, readCallback_);
FLAC__seekable_stream_decoder_set_seek_callback(decoder, seekCallback_);
FLAC__seekable_stream_decoder_set_tell_callback(decoder, tellCallback_);
FLAC__seekable_stream_decoder_set_length_callback(decoder, lengthCallback_);
FLAC__seekable_stream_decoder_set_eof_callback(decoder, eofCallback_);
FLAC__seekable_stream_decoder_set_write_callback(decoder, writeCallback_);
FLAC__seekable_stream_decoder_set_metadata_callback(decoder, metadataCallback_);
FLAC__seekable_stream_decoder_set_error_callback(decoder, errorCallback_);
FLAC__seekable_stream_decoder_set_client_data(decoder, this);
if(FLAC__seekable_stream_decoder_init(decoder) != FLAC__SEEKABLE_STREAM_DECODER_OK) {
cleanup();
return 0;
}
if(!FLAC__seekable_stream_decoder_process_metadata(decoder)) {
cleanup();
return 0;
}
}
if(needs_seek) {
FLAC__seekable_stream_decoder_seek_absolute(decoder, seek_sample);
needs_seek = false;
}
bool eof = false;
while(samples_in_reservoir < 576) {
if(FLAC__seekable_stream_decoder_get_state(decoder) == FLAC__SEEKABLE_STREAM_DECODER_END_OF_STREAM) {
eof = true;
break;
}
else if(!FLAC__seekable_stream_decoder_process_one_frame(decoder))
break;
}
if(samples_in_reservoir == 0) {
eof = true;
}
else {
const unsigned channels = stream_info.channels;
const unsigned bits_per_sample = stream_info.bits_per_sample;
const unsigned bytes_per_sample = (bits_per_sample+7)/8;
const unsigned sample_rate = stream_info.sample_rate;
unsigned i, n = min(samples_in_reservoir, 576), delta;
signed short *ssbuffer = (signed short*)output;
for(i = 0; i < n*channels; i++)
ssbuffer[i] = reservoir[i];
delta = i;
for( ; i < samples_in_reservoir*channels; i++)
reservoir[i-delta] = reservoir[i];
samples_in_reservoir -= n;
const int bytes = n * channels * bytes_per_sample;
ChunkInfosI *ci=new ChunkInfosI();
ci->addInfo("srate", sample_rate);
ci->addInfo("bps", bits_per_sample);
ci->addInfo("nch", channels);
chunk_list->setChunk("PCM", output, bytes, ci);
}
if(eof)
return 0;
return 1;
}
int FlacPcm::corecb_onSeeked(int newpos)
{
if(stream_info.total_samples == 0 || newpos < 0)
return 1;
needs_seek = true;
seek_sample = (FLAC__uint64)((double)newpos / (double)lengthInMsec() * (double)(FLAC__int64)stream_info.total_samples);
return 0;
}
void FlacPcm::cleanup()
{
if(decoder) {
FLAC__seekable_stream_decoder_finish(decoder);
FLAC__seekable_stream_decoder_delete(decoder);
decoder = 0;
}
}
FLAC__SeekableStreamDecoderReadStatus FlacPcm::readCallback_(const FLAC__SeekableStreamDecoder *decoder, FLAC__byte buffer[], unsigned *bytes, void *client_data)
{
FlacPcm *instance = (FlacPcm*)client_data;
*bytes = instance->reader->read((char*)buffer, *bytes);
return FLAC__SEEKABLE_STREAM_DECODER_READ_STATUS_OK;
}
FLAC__SeekableStreamDecoderSeekStatus FlacPcm::seekCallback_(const FLAC__SeekableStreamDecoder *decoder, FLAC__uint64 absolute_byte_offset, void *client_data)
{
FlacPcm *instance = (FlacPcm*)client_data;
if(instance->reader->seek((int)absolute_byte_offset) < 0)
return FLAC__SEEKABLE_STREAM_DECODER_SEEK_STATUS_ERROR;
else
return FLAC__SEEKABLE_STREAM_DECODER_SEEK_STATUS_OK;
}
FLAC__SeekableStreamDecoderTellStatus FlacPcm::tellCallback_(const FLAC__SeekableStreamDecoder *decoder, FLAC__uint64 *absolute_byte_offset, void *client_data)
{
FlacPcm *instance = (FlacPcm*)client_data;
int pos = instance->reader->getPos();
if(pos < 0)
return FLAC__SEEKABLE_STREAM_DECODER_TELL_STATUS_ERROR;
else {
*absolute_byte_offset = pos;
return FLAC__SEEKABLE_STREAM_DECODER_TELL_STATUS_OK;
}
}
FLAC__SeekableStreamDecoderLengthStatus FlacPcm::lengthCallback_(const FLAC__SeekableStreamDecoder *decoder, FLAC__uint64 *stream_length, void *client_data)
{
FlacPcm *instance = (FlacPcm*)client_data;
int length = instance->reader->getPos();
if(length < 0)
return FLAC__SEEKABLE_STREAM_DECODER_LENGTH_STATUS_ERROR;
else {
*stream_length = length;
return FLAC__SEEKABLE_STREAM_DECODER_LENGTH_STATUS_OK;
}
}
FLAC__bool FlacPcm::eofCallback_(const FLAC__SeekableStreamDecoder *decoder, void *client_data)
{
FlacPcm *instance = (FlacPcm*)client_data;
return instance->reader->getPos() == instance->reader->getLength();
}
FLAC__StreamDecoderWriteStatus FlacPcm::writeCallback_(const FLAC__SeekableStreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 *buffer[], void *client_data)
{
FlacPcm *instance = (FlacPcm*)client_data;
const unsigned bps = instance->stream_info.bits_per_sample, channels = instance->stream_info.channels, wide_samples = frame->header.blocksize;
unsigned wide_sample, sample, channel;
(void)decoder;
if(instance->abort_flag)
return FLAC__STREAM_DECODER_WRITE_ABORT;
for(sample = instance->samples_in_reservoir*channels, wide_sample = 0; wide_sample < wide_samples; wide_sample++)
for(channel = 0; channel < channels; channel++, sample++)
instance->reservoir[sample] = (FLAC__int16)buffer[channel][wide_sample];
instance->samples_in_reservoir += wide_samples;
return FLAC__STREAM_DECODER_WRITE_CONTINUE;
}
void FlacPcm::metadataCallback_(const FLAC__SeekableStreamDecoder *decoder, const FLAC__StreamMetaData *metadata, void *client_data)
{
FlacPcm *instance = (FlacPcm*)client_data;
(void)decoder;
if(metadata->type == FLAC__METADATA_TYPE_STREAMINFO) {
instance->stream_info = metadata->data.stream_info;
if(instance->stream_info.bits_per_sample != 16) {
//@@@ how to do this? MessageBox(mod.hMainWindow, "ERROR: plugin can only handle 16-bit samples\n", "ERROR: plugin can only handle 16-bit samples", 0);
instance->abort_flag = true;
return;
}
}
}
void FlacPcm::errorCallback_(const FLAC__SeekableStreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status, void *client_data)
{
FlacPcm *instance = (FlacPcm*)client_data;
(void)decoder;
if(status != FLAC__STREAM_DECODER_ERROR_LOST_SYNC)
instance->abort_flag = true;
}
/***********************************************************************
* local routines
**********************************************************************/
bool get_id3v1_tag_(const char *filename, id3v1_struct *tag)
{
const char *temp;
FILE *f = fopen(filename, "rb");
memset(tag, 0, sizeof(id3v1_struct));
strcpy(tag->title,"Sonata K.42");
strcpy(tag->artist,"Domenico Scarlatti");
strcpy(tag->album,"Narcisso Yepes Plays Scarlatti");
sprintf(tag->description, "%s - %s", tag->artist, tag->title);
/* set the title and description to the filename by default */
temp = strrchr(filename, '/');
if(!temp)
temp = filename;
else
temp++;
strcpy(tag->description, temp);
*strrchr(tag->description, '.') = '\0';
strncpy(tag->title, tag->description, 30); tag->title[30] = '\0';
if(0 == f)
return false;
if(-1 == fseek(f, -128, SEEK_END)) {
fclose(f);
return false;
}
if(fread(tag->raw, 1, 128, f) < 128) {
fclose(f);
return false;
}
fclose(f);
if(strncmp((const char*)tag->raw, "TAG", 3))
return false;
else {
char year_str[5];
memcpy(tag->title, tag->raw+3, 30);
memcpy(tag->artist, tag->raw+33, 30);
memcpy(tag->album, tag->raw+63, 30);
memcpy(year_str, tag->raw+93, 4); year_str[4] = '\0'; tag->year = atoi(year_str);
memcpy(tag->comment, tag->raw+97, 30);
tag->genre = (unsigned)((FLAC__byte)tag->raw[127]);
tag->track = (unsigned)((FLAC__byte)tag->raw[126]);
sprintf(tag->description, "%s - %s", tag->artist, tag->title);
return true;
}
}
<commit_msg>update to use new metadata interface<commit_after>/* FLAC input plugin for Winamp3
* Copyright (C) 2000,2001,2002 Josh Coalson
*
* 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.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*
* NOTE: this code is derived from the 'rawpcm' example by
* Nullsoft; the original license for the 'rawpcm' example follows.
*/
/*
Nullsoft WASABI Source File License
Copyright 1999-2001 Nullsoft, Inc.
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
Brennan Underwood
brennan@nullsoft.com
*/
#include "flacpcm.h"
extern "C" {
#include "FLAC/metadata.h"
};
struct id3v1_struct {
FLAC__byte raw[128];
char title[31];
char artist[31];
char album[31];
char comment[31];
unsigned year;
unsigned track; /* may be 0 if v1 (not v1.1) tag */
unsigned genre;
char description[1024]; /* the formatted description passed to the gui */
};
static bool get_id3v1_tag_(const char *filename, id3v1_struct *tag);
FlacPcm::FlacPcm():
needs_seek(false),
seek_sample(0),
samples_in_reservoir(0),
abort_flag(false),
reader(0),
decoder(0)
{
}
FlacPcm::~FlacPcm()
{
cleanup();
}
int FlacPcm::getInfos(MediaInfo *infos)
{
reader = infos->getReader();
if(!reader) return 0;
//@@@ to be really "clean" we should go through the reader instead of directly to the file...
if(!FLAC__metadata_get_streaminfo(infos->getFilename(), &stream_info))
return 1;
id3v1_struct tag;
//@@@ ditto here...
bool has_tag = get_id3v1_tag_(infos->getFilename(), &tag);
infos->setLength(lengthInMsec());
//@@@ infos->setTitle(Std::filename(infos->getFilename()));
infos->setTitle(tag.description);
infos->setInfo(StringPrintf("FLAC:<%ihz:%ibps:%dch>", stream_info.sample_rate, stream_info.bits_per_sample, stream_info.channels)); //@@@ fix later
if(has_tag) {
infos->setData("Title", tag.title);
infos->setData("Artist", tag.artist);
infos->setData("Album", tag.album);
}
return 0;
}
int FlacPcm::processData(MediaInfo *infos, ChunkList *chunk_list, bool *killswitch)
{
reader = infos->getReader();
if(reader == 0)
return 0;
if(decoder == 0) {
decoder = FLAC__seekable_stream_decoder_new();
if(decoder == 0)
return 0;
FLAC__seekable_stream_decoder_set_md5_checking(decoder, false);
FLAC__seekable_stream_decoder_set_read_callback(decoder, readCallback_);
FLAC__seekable_stream_decoder_set_seek_callback(decoder, seekCallback_);
FLAC__seekable_stream_decoder_set_tell_callback(decoder, tellCallback_);
FLAC__seekable_stream_decoder_set_length_callback(decoder, lengthCallback_);
FLAC__seekable_stream_decoder_set_eof_callback(decoder, eofCallback_);
FLAC__seekable_stream_decoder_set_write_callback(decoder, writeCallback_);
FLAC__seekable_stream_decoder_set_metadata_callback(decoder, metadataCallback_);
FLAC__seekable_stream_decoder_set_error_callback(decoder, errorCallback_);
FLAC__seekable_stream_decoder_set_client_data(decoder, this);
if(FLAC__seekable_stream_decoder_init(decoder) != FLAC__SEEKABLE_STREAM_DECODER_OK) {
cleanup();
return 0;
}
if(!FLAC__seekable_stream_decoder_process_metadata(decoder)) {
cleanup();
return 0;
}
}
if(needs_seek) {
FLAC__seekable_stream_decoder_seek_absolute(decoder, seek_sample);
needs_seek = false;
}
bool eof = false;
while(samples_in_reservoir < 576) {
if(FLAC__seekable_stream_decoder_get_state(decoder) == FLAC__SEEKABLE_STREAM_DECODER_END_OF_STREAM) {
eof = true;
break;
}
else if(!FLAC__seekable_stream_decoder_process_one_frame(decoder))
break;
}
if(samples_in_reservoir == 0) {
eof = true;
}
else {
const unsigned channels = stream_info.channels;
const unsigned bits_per_sample = stream_info.bits_per_sample;
const unsigned bytes_per_sample = (bits_per_sample+7)/8;
const unsigned sample_rate = stream_info.sample_rate;
unsigned i, n = min(samples_in_reservoir, 576), delta;
signed short *ssbuffer = (signed short*)output;
for(i = 0; i < n*channels; i++)
ssbuffer[i] = reservoir[i];
delta = i;
for( ; i < samples_in_reservoir*channels; i++)
reservoir[i-delta] = reservoir[i];
samples_in_reservoir -= n;
const int bytes = n * channels * bytes_per_sample;
ChunkInfosI *ci=new ChunkInfosI();
ci->addInfo("srate", sample_rate);
ci->addInfo("bps", bits_per_sample);
ci->addInfo("nch", channels);
chunk_list->setChunk("PCM", output, bytes, ci);
}
if(eof)
return 0;
return 1;
}
int FlacPcm::corecb_onSeeked(int newpos)
{
if(stream_info.total_samples == 0 || newpos < 0)
return 1;
needs_seek = true;
seek_sample = (FLAC__uint64)((double)newpos / (double)lengthInMsec() * (double)(FLAC__int64)stream_info.total_samples);
return 0;
}
void FlacPcm::cleanup()
{
if(decoder) {
FLAC__seekable_stream_decoder_finish(decoder);
FLAC__seekable_stream_decoder_delete(decoder);
decoder = 0;
}
}
FLAC__SeekableStreamDecoderReadStatus FlacPcm::readCallback_(const FLAC__SeekableStreamDecoder *decoder, FLAC__byte buffer[], unsigned *bytes, void *client_data)
{
FlacPcm *instance = (FlacPcm*)client_data;
*bytes = instance->reader->read((char*)buffer, *bytes);
return FLAC__SEEKABLE_STREAM_DECODER_READ_STATUS_OK;
}
FLAC__SeekableStreamDecoderSeekStatus FlacPcm::seekCallback_(const FLAC__SeekableStreamDecoder *decoder, FLAC__uint64 absolute_byte_offset, void *client_data)
{
FlacPcm *instance = (FlacPcm*)client_data;
if(instance->reader->seek((int)absolute_byte_offset) < 0)
return FLAC__SEEKABLE_STREAM_DECODER_SEEK_STATUS_ERROR;
else
return FLAC__SEEKABLE_STREAM_DECODER_SEEK_STATUS_OK;
}
FLAC__SeekableStreamDecoderTellStatus FlacPcm::tellCallback_(const FLAC__SeekableStreamDecoder *decoder, FLAC__uint64 *absolute_byte_offset, void *client_data)
{
FlacPcm *instance = (FlacPcm*)client_data;
int pos = instance->reader->getPos();
if(pos < 0)
return FLAC__SEEKABLE_STREAM_DECODER_TELL_STATUS_ERROR;
else {
*absolute_byte_offset = pos;
return FLAC__SEEKABLE_STREAM_DECODER_TELL_STATUS_OK;
}
}
FLAC__SeekableStreamDecoderLengthStatus FlacPcm::lengthCallback_(const FLAC__SeekableStreamDecoder *decoder, FLAC__uint64 *stream_length, void *client_data)
{
FlacPcm *instance = (FlacPcm*)client_data;
int length = instance->reader->getPos();
if(length < 0)
return FLAC__SEEKABLE_STREAM_DECODER_LENGTH_STATUS_ERROR;
else {
*stream_length = length;
return FLAC__SEEKABLE_STREAM_DECODER_LENGTH_STATUS_OK;
}
}
FLAC__bool FlacPcm::eofCallback_(const FLAC__SeekableStreamDecoder *decoder, void *client_data)
{
FlacPcm *instance = (FlacPcm*)client_data;
return instance->reader->getPos() == instance->reader->getLength();
}
FLAC__StreamDecoderWriteStatus FlacPcm::writeCallback_(const FLAC__SeekableStreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 *buffer[], void *client_data)
{
FlacPcm *instance = (FlacPcm*)client_data;
const unsigned bps = instance->stream_info.bits_per_sample, channels = instance->stream_info.channels, wide_samples = frame->header.blocksize;
unsigned wide_sample, sample, channel;
(void)decoder;
if(instance->abort_flag)
return FLAC__STREAM_DECODER_WRITE_ABORT;
for(sample = instance->samples_in_reservoir*channels, wide_sample = 0; wide_sample < wide_samples; wide_sample++)
for(channel = 0; channel < channels; channel++, sample++)
instance->reservoir[sample] = (FLAC__int16)buffer[channel][wide_sample];
instance->samples_in_reservoir += wide_samples;
return FLAC__STREAM_DECODER_WRITE_CONTINUE;
}
void FlacPcm::metadataCallback_(const FLAC__SeekableStreamDecoder *decoder, const FLAC__StreamMetaData *metadata, void *client_data)
{
FlacPcm *instance = (FlacPcm*)client_data;
(void)decoder;
if(metadata->type == FLAC__METADATA_TYPE_STREAMINFO) {
instance->stream_info = metadata->data.stream_info;
if(instance->stream_info.bits_per_sample != 16) {
//@@@ how to do this? MessageBox(mod.hMainWindow, "ERROR: plugin can only handle 16-bit samples\n", "ERROR: plugin can only handle 16-bit samples", 0);
instance->abort_flag = true;
return;
}
}
}
void FlacPcm::errorCallback_(const FLAC__SeekableStreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status, void *client_data)
{
FlacPcm *instance = (FlacPcm*)client_data;
(void)decoder;
if(status != FLAC__STREAM_DECODER_ERROR_LOST_SYNC)
instance->abort_flag = true;
}
/***********************************************************************
* local routines
**********************************************************************/
bool get_id3v1_tag_(const char *filename, id3v1_struct *tag)
{
const char *temp;
FILE *f = fopen(filename, "rb");
memset(tag, 0, sizeof(id3v1_struct));
strcpy(tag->title,"Sonata K.42");
strcpy(tag->artist,"Domenico Scarlatti");
strcpy(tag->album,"Narcisso Yepes Plays Scarlatti");
sprintf(tag->description, "%s - %s", tag->artist, tag->title);
/* set the title and description to the filename by default */
temp = strrchr(filename, '/');
if(!temp)
temp = filename;
else
temp++;
strcpy(tag->description, temp);
*strrchr(tag->description, '.') = '\0';
strncpy(tag->title, tag->description, 30); tag->title[30] = '\0';
if(0 == f)
return false;
if(-1 == fseek(f, -128, SEEK_END)) {
fclose(f);
return false;
}
if(fread(tag->raw, 1, 128, f) < 128) {
fclose(f);
return false;
}
fclose(f);
if(strncmp((const char*)tag->raw, "TAG", 3))
return false;
else {
char year_str[5];
memcpy(tag->title, tag->raw+3, 30);
memcpy(tag->artist, tag->raw+33, 30);
memcpy(tag->album, tag->raw+63, 30);
memcpy(year_str, tag->raw+93, 4); year_str[4] = '\0'; tag->year = atoi(year_str);
memcpy(tag->comment, tag->raw+97, 30);
tag->genre = (unsigned)((FLAC__byte)tag->raw[127]);
tag->track = (unsigned)((FLAC__byte)tag->raw[126]);
sprintf(tag->description, "%s - %s", tag->artist, tag->title);
return true;
}
}
<|endoftext|>
|
<commit_before>/*
* Copyright (c) 2011, Peter Thorson. 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 WebSocket++ Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL PETER THORSON 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.
*
*/
#ifndef WEBSOCKET_PROCESSOR_HYBI_LEGACY_HPP
#define WEBSOCKET_PROCESSOR_HYBI_LEGACY_HPP
#include "processor.hpp"
#include "../md5/md5.hpp"
#include "../network_utilities.hpp"
namespace websocketpp {
namespace processor {
namespace hybi_legacy_state {
enum value {
INIT = 0,
READ = 1,
DONE = 2
};
}
template <class connection_type>
class hybi_legacy : public processor_base {
public:
hybi_legacy(connection_type &connection)
: m_connection(connection),
m_state(hybi_legacy_state::INIT)
{
reset();
}
void validate_handshake(const http::parser::request& headers) const {
}
void handshake_response(const http::parser::request& request,http::parser::response& response) {
char key_final[16];
// copy key1 into final key
*reinterpret_cast<uint32_t*>(&key_final[0]) =
decode_client_key(request.header("Sec-WebSocket-Key1"));
// copy key2 into final key
*reinterpret_cast<uint32_t*>(&key_final[4]) =
decode_client_key(request.header("Sec-WebSocket-Key2"));
// copy key3 into final key
memcpy(&key_final[8],request.header("Sec-WebSocket-Key3").c_str(),8);
m_key3 = md5_hash_string(std::string(key_final,16));
response.add_header("Upgrade","websocket");
response.add_header("Connection","Upgrade");
// TODO: require headers that need application specific information?
// Echo back client's origin unless our local application set a
// more restrictive one.
if (response.header("Sec-WebSocket-Origin") == "") {
response.add_header("Sec-WebSocket-Origin",request.header("Origin"));
}
// Echo back the client's request host unless our local application
// set a different one.
if (response.header("Sec-WebSocket-Location") == "") {
// TODO: extract from host header rather than hard code
uri_ptr uri = get_uri(request);
response.add_header("Sec-WebSocket-Location",uri->str());
}
}
std::string get_origin(const http::parser::request& request) const {
return request.header("Origin");
}
uri_ptr get_uri(const http::parser::request& request) const {
std::string h = request.header("Host");
size_t last_colon = h.rfind(":");
size_t last_sbrace = h.rfind("]");
// no : = hostname with no port
// last : before ] = ipv6 literal with no port
// : with no ] = hostname with port
// : after ] = ipv6 literal with port
if (last_colon == std::string::npos ||
(last_sbrace != std::string::npos && last_sbrace > last_colon))
{
return uri_ptr(new uri(m_connection.is_secure(),h,request.uri()));
} else {
return uri_ptr(new uri(m_connection.is_secure(),
h.substr(0,last_colon),
h.substr(last_colon+1),
request.uri()));
}
// TODO: check if get_uri is a full uri
}
void consume(std::istream& s) {
//unsigned char c;
while (s.good() && m_state != hybi_legacy_state::DONE) {
//c = s.get();
//if (s.good()) {
process(s);
//}
}
}
bool ready() const {
return m_state == hybi_legacy_state::DONE;
}
// legacy hybi has no control messages.
bool is_control() const {
return false;
}
message::data_ptr get_data_message() {
message::data_ptr p = m_data_message;
m_data_message.reset();
return p;
}
message::control_ptr get_control_message() {
throw "Hybi legacy has no control messages.";
}
void process(std::istream& input) {
if (m_state == hybi_legacy_state::INIT) {
// we are looking for a 0x00
if (input.peek() == 0x00) {
// start a message
input.ignore();
m_state = hybi_legacy_state::READ;
m_data_message = m_connection.get_data_message();
if (!m_data_message) {
throw processor::exception("Out of data messages",processor::error::OUT_OF_MESSAGES);
}
m_data_message->reset(frame::opcode::TEXT);
} else {
input.ignore();
// TODO: ignore or error
//std::stringstream foo;
//foo << "invalid character read: |" << input.peek() << "|";
std::cout << "invalid character read: |" << input.peek() << "|" << std::endl;
//throw processor::exception(foo.str(),processor::error::PROTOCOL_VIOLATION);
}
} else if (m_state == hybi_legacy_state::READ) {
if (input.peek() == 0xFF) {
// end
input.ignore();
m_state = hybi_legacy_state::DONE;
} else {
if (m_data_message) {
m_data_message->process_payload(input,1);
}
}
}
}
void reset() {
m_state = hybi_legacy_state::INIT;
m_data_message.reset();
}
uint64_t get_bytes_needed() const {
return 1;
}
std::string get_key3() const {
return m_key3;
}
// TODO: to factor away
binary_string_ptr prepare_frame(frame::opcode::value opcode,
bool mask,
const binary_string& payload) {
if (opcode != frame::opcode::TEXT) {
// TODO: hybi_legacy doesn't allow non-text frames.
throw;
}
// TODO: mask = ignore?
// TODO: utf8 validation on payload.
binary_string_ptr response(new binary_string(payload.size()+2));
(*response)[0] = 0x00;
std::copy(payload.begin(),payload.end(),response->begin()+1);
(*response)[response->size()-1] = 0xFF;
return response;
}
binary_string_ptr prepare_frame(frame::opcode::value opcode,
bool mask,
const utf8_string& payload) {
if (opcode != frame::opcode::TEXT) {
// TODO: hybi_legacy doesn't allow non-text frames.
throw;
}
// TODO: mask = ignore?
// TODO: utf8 validation on payload.
binary_string_ptr response(new binary_string(payload.size()+2));
(*response)[0] = 0x00;
std::copy(payload.begin(),payload.end(),response->begin()+1);
(*response)[response->size()-1] = 0xFF;
return response;
}
binary_string_ptr prepare_close_frame(close::status::value code,
bool mask,
const std::string& reason) {
binary_string_ptr response(new binary_string(2));
(*response)[0] = 0xFF;
(*response)[1] = 0x00;
return response;
}
void prepare_frame(message::data_ptr msg) {
assert(msg);
if (msg->get_prepared()) {
return;
}
msg->set_header(std::string(0x00));
msg->append_payload(std::string(1,0xFF));
msg->set_prepared(true);
}
void prepare_close_frame(message::data_ptr msg,
close::status::value code,
const std::string& reason)
{
assert(msg);
if (msg->get_prepared()) {
return;
}
msg->set_header(std::string());
std::string val;
val.append(1,0xFF);
val.append(1,0x00);
msg->set_payload(val);
msg->set_prepared(true);
}
private:
uint32_t decode_client_key(const std::string& key) {
int spaces = 0;
std::string digits = "";
uint32_t num;
// key2
for (size_t i = 0; i < key.size(); i++) {
if (key[i] == ' ') {
spaces++;
} else if (key[i] >= '0' && key[i] <= '9') {
digits += key[i];
}
}
num = atoi(digits.c_str());
if (spaces > 0 && num > 0) {
return htonl(num/spaces);
} else {
return 0;
}
}
connection_type& m_connection;
hybi_legacy_state::value m_state;
message::data_ptr m_data_message;
std::string m_key3;
};
} // processor
} // websocketpp
#endif // WEBSOCKET_PROCESSOR_HYBI_LEGACY_HPP
<commit_msg>fixes a crash when sending messages to hybi00 clients<commit_after>/*
* Copyright (c) 2011, Peter Thorson. 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 WebSocket++ Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL PETER THORSON 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.
*
*/
#ifndef WEBSOCKET_PROCESSOR_HYBI_LEGACY_HPP
#define WEBSOCKET_PROCESSOR_HYBI_LEGACY_HPP
#include "processor.hpp"
#include "../md5/md5.hpp"
#include "../network_utilities.hpp"
namespace websocketpp {
namespace processor {
namespace hybi_legacy_state {
enum value {
INIT = 0,
READ = 1,
DONE = 2
};
}
template <class connection_type>
class hybi_legacy : public processor_base {
public:
hybi_legacy(connection_type &connection)
: m_connection(connection),
m_state(hybi_legacy_state::INIT)
{
reset();
}
void validate_handshake(const http::parser::request& headers) const {
}
void handshake_response(const http::parser::request& request,http::parser::response& response) {
char key_final[16];
// copy key1 into final key
*reinterpret_cast<uint32_t*>(&key_final[0]) =
decode_client_key(request.header("Sec-WebSocket-Key1"));
// copy key2 into final key
*reinterpret_cast<uint32_t*>(&key_final[4]) =
decode_client_key(request.header("Sec-WebSocket-Key2"));
// copy key3 into final key
memcpy(&key_final[8],request.header("Sec-WebSocket-Key3").c_str(),8);
m_key3 = md5_hash_string(std::string(key_final,16));
response.add_header("Upgrade","websocket");
response.add_header("Connection","Upgrade");
// TODO: require headers that need application specific information?
// Echo back client's origin unless our local application set a
// more restrictive one.
if (response.header("Sec-WebSocket-Origin") == "") {
response.add_header("Sec-WebSocket-Origin",request.header("Origin"));
}
// Echo back the client's request host unless our local application
// set a different one.
if (response.header("Sec-WebSocket-Location") == "") {
// TODO: extract from host header rather than hard code
uri_ptr uri = get_uri(request);
response.add_header("Sec-WebSocket-Location",uri->str());
}
}
std::string get_origin(const http::parser::request& request) const {
return request.header("Origin");
}
uri_ptr get_uri(const http::parser::request& request) const {
std::string h = request.header("Host");
size_t last_colon = h.rfind(":");
size_t last_sbrace = h.rfind("]");
// no : = hostname with no port
// last : before ] = ipv6 literal with no port
// : with no ] = hostname with port
// : after ] = ipv6 literal with port
if (last_colon == std::string::npos ||
(last_sbrace != std::string::npos && last_sbrace > last_colon))
{
return uri_ptr(new uri(m_connection.is_secure(),h,request.uri()));
} else {
return uri_ptr(new uri(m_connection.is_secure(),
h.substr(0,last_colon),
h.substr(last_colon+1),
request.uri()));
}
// TODO: check if get_uri is a full uri
}
void consume(std::istream& s) {
//unsigned char c;
while (s.good() && m_state != hybi_legacy_state::DONE) {
//c = s.get();
//if (s.good()) {
process(s);
//}
}
}
bool ready() const {
return m_state == hybi_legacy_state::DONE;
}
// legacy hybi has no control messages.
bool is_control() const {
return false;
}
message::data_ptr get_data_message() {
message::data_ptr p = m_data_message;
m_data_message.reset();
return p;
}
message::control_ptr get_control_message() {
throw "Hybi legacy has no control messages.";
}
void process(std::istream& input) {
if (m_state == hybi_legacy_state::INIT) {
// we are looking for a 0x00
if (input.peek() == 0x00) {
// start a message
input.ignore();
m_state = hybi_legacy_state::READ;
m_data_message = m_connection.get_data_message();
if (!m_data_message) {
throw processor::exception("Out of data messages",processor::error::OUT_OF_MESSAGES);
}
m_data_message->reset(frame::opcode::TEXT);
} else {
input.ignore();
// TODO: ignore or error
//std::stringstream foo;
//foo << "invalid character read: |" << input.peek() << "|";
std::cout << "invalid character read: |" << input.peek() << "|" << std::endl;
//throw processor::exception(foo.str(),processor::error::PROTOCOL_VIOLATION);
}
} else if (m_state == hybi_legacy_state::READ) {
if (input.peek() == 0xFF) {
// end
input.ignore();
m_state = hybi_legacy_state::DONE;
} else {
if (m_data_message) {
m_data_message->process_payload(input,1);
}
}
}
}
void reset() {
m_state = hybi_legacy_state::INIT;
m_data_message.reset();
}
uint64_t get_bytes_needed() const {
return 1;
}
std::string get_key3() const {
return m_key3;
}
// TODO: to factor away
binary_string_ptr prepare_frame(frame::opcode::value opcode,
bool mask,
const binary_string& payload) {
if (opcode != frame::opcode::TEXT) {
// TODO: hybi_legacy doesn't allow non-text frames.
throw;
}
// TODO: mask = ignore?
// TODO: utf8 validation on payload.
binary_string_ptr response(new binary_string(payload.size()+2));
(*response)[0] = 0x00;
std::copy(payload.begin(),payload.end(),response->begin()+1);
(*response)[response->size()-1] = 0xFF;
return response;
}
binary_string_ptr prepare_frame(frame::opcode::value opcode,
bool mask,
const utf8_string& payload) {
if (opcode != frame::opcode::TEXT) {
// TODO: hybi_legacy doesn't allow non-text frames.
throw;
}
// TODO: mask = ignore?
// TODO: utf8 validation on payload.
binary_string_ptr response(new binary_string(payload.size()+2));
(*response)[0] = 0x00;
std::copy(payload.begin(),payload.end(),response->begin()+1);
(*response)[response->size()-1] = 0xFF;
return response;
}
binary_string_ptr prepare_close_frame(close::status::value code,
bool mask,
const std::string& reason) {
binary_string_ptr response(new binary_string(2));
(*response)[0] = 0xFF;
(*response)[1] = 0x00;
return response;
}
void prepare_frame(message::data_ptr msg) {
assert(msg);
if (msg->get_prepared()) {
return;
}
msg->set_header(std::string(1,0x00));
msg->append_payload(std::string(1,0xFF));
msg->set_prepared(true);
}
void prepare_close_frame(message::data_ptr msg,
close::status::value code,
const std::string& reason)
{
assert(msg);
if (msg->get_prepared()) {
return;
}
msg->set_header(std::string());
std::string val;
val.append(1,0xFF);
val.append(1,0x00);
msg->set_payload(val);
msg->set_prepared(true);
}
private:
uint32_t decode_client_key(const std::string& key) {
int spaces = 0;
std::string digits = "";
uint32_t num;
// key2
for (size_t i = 0; i < key.size(); i++) {
if (key[i] == ' ') {
spaces++;
} else if (key[i] >= '0' && key[i] <= '9') {
digits += key[i];
}
}
num = atoi(digits.c_str());
if (spaces > 0 && num > 0) {
return htonl(num/spaces);
} else {
return 0;
}
}
connection_type& m_connection;
hybi_legacy_state::value m_state;
message::data_ptr m_data_message;
std::string m_key3;
};
} // processor
} // websocketpp
#endif // WEBSOCKET_PROCESSOR_HYBI_LEGACY_HPP
<|endoftext|>
|
<commit_before>/*
* Copyright (C) 2018 The Android Open Source Project
*
* 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 "src/profiling/memory/client.h"
#include <inttypes.h>
#include <sys/prctl.h>
#include <sys/syscall.h>
#include <unistd.h>
#include <atomic>
#include <new>
#include <unwindstack/MachineArm.h>
#include <unwindstack/MachineArm64.h>
#include <unwindstack/MachineMips.h>
#include <unwindstack/MachineMips64.h>
#include <unwindstack/MachineX86.h>
#include <unwindstack/MachineX86_64.h>
#include <unwindstack/Regs.h>
#include <unwindstack/RegsGetLocal.h>
#include "perfetto/base/logging.h"
#include "perfetto/base/scoped_file.h"
#include "perfetto/base/thread_utils.h"
#include "perfetto/base/unix_socket.h"
#include "perfetto/base/utils.h"
#include "src/profiling/memory/sampler.h"
#include "src/profiling/memory/scoped_spinlock.h"
#include "src/profiling/memory/wire_protocol.h"
namespace perfetto {
namespace profiling {
namespace {
const char kSingleByte[1] = {'x'};
constexpr std::chrono::seconds kLockTimeout{1};
base::Optional<base::UnixSocketRaw> Connect(const std::string& sock_name) {
auto sock = base::UnixSocketRaw::CreateMayFail(base::SockType::kStream);
if (!sock || !sock.Connect(sock_name)) {
PERFETTO_PLOG("Failed to connect to %s", sock_name.c_str());
return base::nullopt;
}
if (!sock.SetTxTimeout(kClientSockTimeoutMs)) {
PERFETTO_PLOG("Failed to set send timeout for %s", sock_name.c_str());
return base::nullopt;
}
if (!sock.SetRxTimeout(kClientSockTimeoutMs)) {
PERFETTO_PLOG("Failed to set receive timeout for %s", sock_name.c_str());
return base::nullopt;
}
return std::move(sock);
}
inline bool IsMainThread() {
return getpid() == base::GetThreadId();
}
// TODO(b/117203899): Remove this after making bionic implementation safe to
// use.
char* FindMainThreadStack() {
base::ScopedFstream maps(fopen("/proc/self/maps", "r"));
if (!maps) {
return nullptr;
}
while (!feof(*maps)) {
char line[1024];
char* data = fgets(line, sizeof(line), *maps);
if (data != nullptr && strstr(data, "[stack]")) {
char* sep = strstr(data, "-");
if (sep == nullptr)
continue;
sep++;
return reinterpret_cast<char*>(strtoll(sep, nullptr, 16));
}
}
return nullptr;
}
int UnsetDumpable(int) {
prctl(PR_SET_DUMPABLE, 0);
return 0;
}
} // namespace
bool FreePage::Add(const uint64_t addr,
const uint64_t sequence_number,
Client* client) {
std::unique_lock<std::timed_mutex> l(mutex_, kLockTimeout);
if (!l.owns_lock())
return false;
if (free_page_.num_entries == kFreePageSize) {
if (!client->FlushFrees(&free_page_))
return false;
// Now that we have flushed, reset to after the header.
free_page_.num_entries = 0;
}
FreePageEntry& current_entry = free_page_.entries[free_page_.num_entries++];
current_entry.sequence_number = sequence_number;
current_entry.addr = addr;
return true;
}
bool Client::FlushFrees(FreeMetadata* free_metadata) {
WireMessage msg = {};
msg.record_type = RecordType::Free;
msg.free_header = free_metadata;
if (!SendWireMessage(&shmem_, msg)) {
PERFETTO_PLOG("Failed to send wire message");
Shutdown();
return false;
}
if (!sock_.Send(kSingleByte, sizeof(kSingleByte))) {
Shutdown();
return false;
}
return true;
}
const char* GetThreadStackBase() {
pthread_attr_t attr;
if (pthread_getattr_np(pthread_self(), &attr) != 0)
return nullptr;
base::ScopedResource<pthread_attr_t*, pthread_attr_destroy, nullptr> cleanup(
&attr);
char* stackaddr;
size_t stacksize;
if (pthread_attr_getstack(&attr, reinterpret_cast<void**>(&stackaddr),
&stacksize) != 0)
return nullptr;
return stackaddr + stacksize;
}
Client::Client(base::Optional<base::UnixSocketRaw> sock)
: sampler_(8192), // placeholder until we receive the config (within ctor)
main_thread_stack_base_(FindMainThreadStack()) {
if (!sock || !sock.value()) {
PERFETTO_DFATAL("Socket not connected.");
return;
}
sock_ = std::move(sock.value());
// We might be running in a process that is not dumpable (such as app
// processes on user builds), in which case the /proc/self/mem will be chown'd
// to root:root, and will not be accessible even to the process itself (see
// man 5 proc). In such situations, temporarily mark the process dumpable to
// be able to open the files, unsetting dumpability immediately afterwards.
int orig_dumpable = prctl(PR_GET_DUMPABLE);
enum { kNop, kDoUnset };
base::ScopedResource<int, UnsetDumpable, kNop, false> unset_dumpable(kNop);
if (orig_dumpable == 0) {
unset_dumpable.reset(kDoUnset);
prctl(PR_SET_DUMPABLE, 1);
}
base::ScopedFile maps(base::OpenFile("/proc/self/maps", O_RDONLY));
if (!maps) {
PERFETTO_DFATAL("Failed to open /proc/self/maps");
return;
}
base::ScopedFile mem(base::OpenFile("/proc/self/mem", O_RDONLY));
if (!mem) {
PERFETTO_DFATAL("Failed to open /proc/self/mem");
return;
}
// Restore original dumpability value if we overrode it.
unset_dumpable.reset();
int fds[kHandshakeSize];
fds[kHandshakeMaps] = *maps;
fds[kHandshakeMem] = *mem;
// Send an empty record to transfer fds for /proc/self/maps and
// /proc/self/mem.
if (sock_.Send(kSingleByte, sizeof(kSingleByte), fds, kHandshakeSize) !=
sizeof(kSingleByte)) {
PERFETTO_DFATAL("Failed to send file descriptors.");
return;
}
base::ScopedFile shmem_fd;
if (sock_.Receive(&client_config_, sizeof(client_config_), &shmem_fd, 1) !=
sizeof(client_config_)) {
PERFETTO_DFATAL("Failed to receive client config.");
return;
}
auto shmem = SharedRingBuffer::Attach(std::move(shmem_fd));
if (!shmem || !shmem->is_valid()) {
PERFETTO_DFATAL("Failed to attach to shmem.");
return;
}
shmem_ = std::move(shmem.value());
PERFETTO_DCHECK(client_config_.interval >= 1);
sampler_ = Sampler(client_config_.interval);
PERFETTO_DLOG("Initialized client.");
inited_.store(true, std::memory_order_release);
}
Client::Client(const std::string& sock_name) : Client(Connect(sock_name)) {}
const char* Client::GetStackBase() {
if (IsMainThread()) {
if (!main_thread_stack_base_)
// Because pthread_attr_getstack reads and parses /proc/self/maps and
// /proc/self/stat, we have to cache the result here.
main_thread_stack_base_ = GetThreadStackBase();
return main_thread_stack_base_;
}
return GetThreadStackBase();
}
// The stack grows towards numerically smaller addresses, so the stack layout
// of main calling malloc is as follows.
//
// +------------+
// |SendWireMsg |
// stacktop +--> +------------+ 0x1000
// |RecordMalloc| +
// +------------+ |
// | malloc | |
// +------------+ |
// | main | v
// stackbase +-> +------------+ 0xffff
bool Client::RecordMalloc(uint64_t alloc_size,
uint64_t total_size,
uint64_t alloc_address) {
if (!inited_.load(std::memory_order_acquire)) {
return false;
}
AllocMetadata metadata;
const char* stackbase = GetStackBase();
const char* stacktop = reinterpret_cast<char*>(__builtin_frame_address(0));
unwindstack::AsmGetRegs(metadata.register_data);
if (stackbase < stacktop) {
PERFETTO_DFATAL("Stackbase >= stacktop.");
Shutdown();
return false;
}
uint64_t stack_size = static_cast<uint64_t>(stackbase - stacktop);
metadata.total_size = total_size;
metadata.alloc_size = alloc_size;
metadata.alloc_address = alloc_address;
metadata.stack_pointer = reinterpret_cast<uint64_t>(stacktop);
metadata.stack_pointer_offset = sizeof(AllocMetadata);
metadata.arch = unwindstack::Regs::CurrentArch();
metadata.sequence_number =
1 + sequence_number_.fetch_add(1, std::memory_order_acq_rel);
WireMessage msg{};
msg.record_type = RecordType::Malloc;
msg.alloc_header = &metadata;
msg.payload = const_cast<char*>(stacktop);
msg.payload_size = static_cast<size_t>(stack_size);
if (!SendWireMessage(&shmem_, msg)) {
PERFETTO_PLOG("Failed to send wire message.");
Shutdown();
return false;
}
if (sock_.Send(kSingleByte, sizeof(kSingleByte)) == -1) {
PERFETTO_PLOG("Failed to send wire message.");
Shutdown();
return false;
}
return true;
}
bool Client::RecordFree(uint64_t alloc_address) {
if (!inited_.load(std::memory_order_acquire))
return false;
bool success = free_page_.Add(
alloc_address,
1 + sequence_number_.fetch_add(1, std::memory_order_acq_rel), this);
if (!success)
Shutdown();
return success;
}
void Client::Shutdown() {
inited_.store(false, std::memory_order_release);
}
} // namespace profiling
} // namespace perfetto
<commit_msg>heapprofd client control sock: correct err checking on free batch flush<commit_after>/*
* Copyright (C) 2018 The Android Open Source Project
*
* 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 "src/profiling/memory/client.h"
#include <inttypes.h>
#include <sys/prctl.h>
#include <sys/syscall.h>
#include <unistd.h>
#include <atomic>
#include <new>
#include <unwindstack/MachineArm.h>
#include <unwindstack/MachineArm64.h>
#include <unwindstack/MachineMips.h>
#include <unwindstack/MachineMips64.h>
#include <unwindstack/MachineX86.h>
#include <unwindstack/MachineX86_64.h>
#include <unwindstack/Regs.h>
#include <unwindstack/RegsGetLocal.h>
#include "perfetto/base/logging.h"
#include "perfetto/base/scoped_file.h"
#include "perfetto/base/thread_utils.h"
#include "perfetto/base/unix_socket.h"
#include "perfetto/base/utils.h"
#include "src/profiling/memory/sampler.h"
#include "src/profiling/memory/scoped_spinlock.h"
#include "src/profiling/memory/wire_protocol.h"
namespace perfetto {
namespace profiling {
namespace {
const char kSingleByte[1] = {'x'};
constexpr std::chrono::seconds kLockTimeout{1};
base::Optional<base::UnixSocketRaw> Connect(const std::string& sock_name) {
auto sock = base::UnixSocketRaw::CreateMayFail(base::SockType::kStream);
if (!sock || !sock.Connect(sock_name)) {
PERFETTO_PLOG("Failed to connect to %s", sock_name.c_str());
return base::nullopt;
}
if (!sock.SetTxTimeout(kClientSockTimeoutMs)) {
PERFETTO_PLOG("Failed to set send timeout for %s", sock_name.c_str());
return base::nullopt;
}
if (!sock.SetRxTimeout(kClientSockTimeoutMs)) {
PERFETTO_PLOG("Failed to set receive timeout for %s", sock_name.c_str());
return base::nullopt;
}
return std::move(sock);
}
inline bool IsMainThread() {
return getpid() == base::GetThreadId();
}
// TODO(b/117203899): Remove this after making bionic implementation safe to
// use.
char* FindMainThreadStack() {
base::ScopedFstream maps(fopen("/proc/self/maps", "r"));
if (!maps) {
return nullptr;
}
while (!feof(*maps)) {
char line[1024];
char* data = fgets(line, sizeof(line), *maps);
if (data != nullptr && strstr(data, "[stack]")) {
char* sep = strstr(data, "-");
if (sep == nullptr)
continue;
sep++;
return reinterpret_cast<char*>(strtoll(sep, nullptr, 16));
}
}
return nullptr;
}
int UnsetDumpable(int) {
prctl(PR_SET_DUMPABLE, 0);
return 0;
}
} // namespace
bool FreePage::Add(const uint64_t addr,
const uint64_t sequence_number,
Client* client) {
std::unique_lock<std::timed_mutex> l(mutex_, kLockTimeout);
if (!l.owns_lock())
return false;
if (free_page_.num_entries == kFreePageSize) {
if (!client->FlushFrees(&free_page_))
return false;
// Now that we have flushed, reset to after the header.
free_page_.num_entries = 0;
}
FreePageEntry& current_entry = free_page_.entries[free_page_.num_entries++];
current_entry.sequence_number = sequence_number;
current_entry.addr = addr;
return true;
}
bool Client::FlushFrees(FreeMetadata* free_metadata) {
WireMessage msg = {};
msg.record_type = RecordType::Free;
msg.free_header = free_metadata;
if (!SendWireMessage(&shmem_, msg)) {
PERFETTO_PLOG("Failed to send wire message");
Shutdown();
return false;
}
if (sock_.Send(kSingleByte, sizeof(kSingleByte)) == -1) {
Shutdown();
return false;
}
return true;
}
const char* GetThreadStackBase() {
pthread_attr_t attr;
if (pthread_getattr_np(pthread_self(), &attr) != 0)
return nullptr;
base::ScopedResource<pthread_attr_t*, pthread_attr_destroy, nullptr> cleanup(
&attr);
char* stackaddr;
size_t stacksize;
if (pthread_attr_getstack(&attr, reinterpret_cast<void**>(&stackaddr),
&stacksize) != 0)
return nullptr;
return stackaddr + stacksize;
}
Client::Client(base::Optional<base::UnixSocketRaw> sock)
: sampler_(8192), // placeholder until we receive the config (within ctor)
main_thread_stack_base_(FindMainThreadStack()) {
if (!sock || !sock.value()) {
PERFETTO_DFATAL("Socket not connected.");
return;
}
sock_ = std::move(sock.value());
// We might be running in a process that is not dumpable (such as app
// processes on user builds), in which case the /proc/self/mem will be chown'd
// to root:root, and will not be accessible even to the process itself (see
// man 5 proc). In such situations, temporarily mark the process dumpable to
// be able to open the files, unsetting dumpability immediately afterwards.
int orig_dumpable = prctl(PR_GET_DUMPABLE);
enum { kNop, kDoUnset };
base::ScopedResource<int, UnsetDumpable, kNop, false> unset_dumpable(kNop);
if (orig_dumpable == 0) {
unset_dumpable.reset(kDoUnset);
prctl(PR_SET_DUMPABLE, 1);
}
base::ScopedFile maps(base::OpenFile("/proc/self/maps", O_RDONLY));
if (!maps) {
PERFETTO_DFATAL("Failed to open /proc/self/maps");
return;
}
base::ScopedFile mem(base::OpenFile("/proc/self/mem", O_RDONLY));
if (!mem) {
PERFETTO_DFATAL("Failed to open /proc/self/mem");
return;
}
// Restore original dumpability value if we overrode it.
unset_dumpable.reset();
int fds[kHandshakeSize];
fds[kHandshakeMaps] = *maps;
fds[kHandshakeMem] = *mem;
// Send an empty record to transfer fds for /proc/self/maps and
// /proc/self/mem.
if (sock_.Send(kSingleByte, sizeof(kSingleByte), fds, kHandshakeSize) !=
sizeof(kSingleByte)) {
PERFETTO_DFATAL("Failed to send file descriptors.");
return;
}
base::ScopedFile shmem_fd;
if (sock_.Receive(&client_config_, sizeof(client_config_), &shmem_fd, 1) !=
sizeof(client_config_)) {
PERFETTO_DFATAL("Failed to receive client config.");
return;
}
auto shmem = SharedRingBuffer::Attach(std::move(shmem_fd));
if (!shmem || !shmem->is_valid()) {
PERFETTO_DFATAL("Failed to attach to shmem.");
return;
}
shmem_ = std::move(shmem.value());
PERFETTO_DCHECK(client_config_.interval >= 1);
sampler_ = Sampler(client_config_.interval);
PERFETTO_DLOG("Initialized client.");
inited_.store(true, std::memory_order_release);
}
Client::Client(const std::string& sock_name) : Client(Connect(sock_name)) {}
const char* Client::GetStackBase() {
if (IsMainThread()) {
if (!main_thread_stack_base_)
// Because pthread_attr_getstack reads and parses /proc/self/maps and
// /proc/self/stat, we have to cache the result here.
main_thread_stack_base_ = GetThreadStackBase();
return main_thread_stack_base_;
}
return GetThreadStackBase();
}
// The stack grows towards numerically smaller addresses, so the stack layout
// of main calling malloc is as follows.
//
// +------------+
// |SendWireMsg |
// stacktop +--> +------------+ 0x1000
// |RecordMalloc| +
// +------------+ |
// | malloc | |
// +------------+ |
// | main | v
// stackbase +-> +------------+ 0xffff
bool Client::RecordMalloc(uint64_t alloc_size,
uint64_t total_size,
uint64_t alloc_address) {
if (!inited_.load(std::memory_order_acquire)) {
return false;
}
AllocMetadata metadata;
const char* stackbase = GetStackBase();
const char* stacktop = reinterpret_cast<char*>(__builtin_frame_address(0));
unwindstack::AsmGetRegs(metadata.register_data);
if (stackbase < stacktop) {
PERFETTO_DFATAL("Stackbase >= stacktop.");
Shutdown();
return false;
}
uint64_t stack_size = static_cast<uint64_t>(stackbase - stacktop);
metadata.total_size = total_size;
metadata.alloc_size = alloc_size;
metadata.alloc_address = alloc_address;
metadata.stack_pointer = reinterpret_cast<uint64_t>(stacktop);
metadata.stack_pointer_offset = sizeof(AllocMetadata);
metadata.arch = unwindstack::Regs::CurrentArch();
metadata.sequence_number =
1 + sequence_number_.fetch_add(1, std::memory_order_acq_rel);
WireMessage msg{};
msg.record_type = RecordType::Malloc;
msg.alloc_header = &metadata;
msg.payload = const_cast<char*>(stacktop);
msg.payload_size = static_cast<size_t>(stack_size);
if (!SendWireMessage(&shmem_, msg)) {
PERFETTO_PLOG("Failed to send wire message.");
Shutdown();
return false;
}
if (sock_.Send(kSingleByte, sizeof(kSingleByte)) == -1) {
PERFETTO_PLOG("Failed to send wire message.");
Shutdown();
return false;
}
return true;
}
bool Client::RecordFree(uint64_t alloc_address) {
if (!inited_.load(std::memory_order_acquire))
return false;
bool success = free_page_.Add(
alloc_address,
1 + sequence_number_.fetch_add(1, std::memory_order_acq_rel), this);
if (!success)
Shutdown();
return success;
}
void Client::Shutdown() {
inited_.store(false, std::memory_order_release);
}
} // namespace profiling
} // namespace perfetto
<|endoftext|>
|
<commit_before>#include "askpassphrasedialog.h"
#include "ui_askpassphrasedialog.h"
#include "guiconstants.h"
#include "walletmodel.h"
#include <QMessageBox>
#include <QPushButton>
#include <QKeyEvent>
extern bool fWalletUnlockStakingOnly;
AskPassphraseDialog::AskPassphraseDialog(Mode mode, QWidget *parent) :
QDialog(parent),
ui(new Ui::AskPassphraseDialog),
mode(mode),
model(0),
fCapsLock(false)
{
ui->setupUi(this);
ui->passEdit1->setMaxLength(MAX_PASSPHRASE_SIZE);
ui->passEdit2->setMaxLength(MAX_PASSPHRASE_SIZE);
ui->passEdit3->setMaxLength(MAX_PASSPHRASE_SIZE);
// Setup Caps Lock detection.
ui->passEdit1->installEventFilter(this);
ui->passEdit2->installEventFilter(this);
ui->passEdit3->installEventFilter(this);
ui->stakingCheckBox->setChecked(fWalletUnlockStakingOnly);
switch(mode)
{
case Encrypt: // Ask passphrase x2
ui->passLabel1->hide();
ui->passEdit1->hide();
ui->warningLabel->setText(tr("Enter the new passphrase to the wallet.<br/>Please use a passphrase of <b>10 or more random characters</b>, or <b>eight or more words</b>."));
setWindowTitle(tr("Encrypt wallet"));
break;
case UnlockStaking:
ui->stakingCheckBox->setChecked(true);
ui->stakingCheckBox->show();
// fallthru
case Unlock: // Ask passphrase
ui->warningLabel->setText(tr("This operation needs your wallet passphrase to unlock the wallet."));
ui->passLabel2->hide();
ui->passEdit2->hide();
ui->passLabel3->hide();
ui->passEdit3->hide();
setWindowTitle(tr("Unlock wallet"));
break;
case Decrypt: // Ask passphrase
ui->warningLabel->setText(tr("This operation needs your wallet passphrase to decrypt the wallet."));
ui->passLabel2->hide();
ui->passEdit2->hide();
ui->passLabel3->hide();
ui->passEdit3->hide();
setWindowTitle(tr("Decrypt wallet"));
break;
case ChangePass: // Ask old passphrase + new passphrase x2
setWindowTitle(tr("Change passphrase"));
ui->warningLabel->setText(tr("Enter the old and new passphrase to the wallet."));
break;
}
textChanged();
connect(ui->passEdit1, SIGNAL(textChanged(QString)), this, SLOT(textChanged()));
connect(ui->passEdit2, SIGNAL(textChanged(QString)), this, SLOT(textChanged()));
connect(ui->passEdit3, SIGNAL(textChanged(QString)), this, SLOT(textChanged()));
}
AskPassphraseDialog::~AskPassphraseDialog()
{
secureClearPassFields();
delete ui;
}
void AskPassphraseDialog::setModel(WalletModel *model)
{
this->model = model;
}
void AskPassphraseDialog::accept()
{
SecureString oldpass, newpass1, newpass2;
if(!model)
return;
oldpass.reserve(MAX_PASSPHRASE_SIZE);
newpass1.reserve(MAX_PASSPHRASE_SIZE);
newpass2.reserve(MAX_PASSPHRASE_SIZE);
// TODO: get rid of this .c_str() by implementing SecureString::operator=(std::string)
// Alternately, find a way to make this input mlock()'d to begin with.
oldpass.assign(ui->passEdit1->text().toStdString().c_str());
newpass1.assign(ui->passEdit2->text().toStdString().c_str());
newpass2.assign(ui->passEdit3->text().toStdString().c_str());
secureClearPassFields();
switch(mode)
{
case Encrypt: {
if(newpass1.empty() || newpass2.empty())
{
// Cannot encrypt with empty passphrase
break;
}
QMessageBox::StandardButton retval = QMessageBox::question(this, tr("Confirm wallet encryption"),
tr("Warning: If you encrypt your wallet and lose your passphrase, you will <b>LOSE ALL OF YOUR COINS</b>!") + "<br><br>" + tr("Are you sure you wish to encrypt your wallet?"),
QMessageBox::Yes|QMessageBox::Cancel,
QMessageBox::Cancel);
if(retval == QMessageBox::Yes)
{
if(newpass1 == newpass2)
{
if(model->setWalletEncrypted(true, newpass1))
{
QMessageBox::warning(this, tr("Wallet encrypted"),
"<qt>" +
tr("Okcash will close now to finish the encryption process. "
"Remember that encrypting your wallet cannot fully protect "
"your coins from being stolen by malware infecting your computer.") +
"<br><br><b>" +
tr("IMPORTANT: Any previous backups you have made of your wallet file "
"should be replaced with the newly generated, encrypted wallet file. "
"For security reasons, previous backups of the unencrypted wallet file "
"will become useless as soon as you start using the new, encrypted wallet.") +
"</b></qt>");
QApplication::quit();
}
else
{
QMessageBox::critical(this, tr("Wallet encryption failed"),
tr("Wallet encryption failed due to an internal error. Your wallet was not encrypted."));
}
QDialog::accept(); // Success
}
else
{
QMessageBox::critical(this, tr("Wallet encryption failed"),
tr("The supplied passphrases do not match."));
}
}
else
{
QDialog::reject(); // Cancelled
}
} break;
case UnlockStaking:
case Unlock:
if(!model->setWalletLocked(false, oldpass))
{
QMessageBox::critical(this, tr("Wallet unlock failed"),
tr("The passphrase entered for the wallet decryption was incorrect."));
}
else
{
fWalletUnlockStakingOnly = ui->stakingCheckBox->isChecked();
QDialog::accept(); // Success
}
break;
case Decrypt:
if(!model->setWalletEncrypted(false, oldpass))
{
QMessageBox::critical(this, tr("Wallet decryption failed"),
tr("The passphrase entered for the wallet decryption was incorrect."));
}
else
{
QDialog::accept(); // Success
}
break;
case ChangePass:
if(newpass1 == newpass2)
{
if(model->changePassphrase(oldpass, newpass1))
{
QMessageBox::information(this, tr("Wallet encrypted"),
tr("Wallet passphrase was successfully changed."));
QDialog::accept(); // Success
}
else
{
QMessageBox::critical(this, tr("Wallet encryption failed"),
tr("The passphrase entered for the wallet decryption was incorrect."));
}
}
else
{
QMessageBox::critical(this, tr("Wallet encryption failed"),
tr("The supplied passphrases do not match."));
}
break;
}
}
void AskPassphraseDialog::textChanged()
{
// Validate input, set Ok button to enabled when acceptable
bool acceptable = false;
switch(mode)
{
case Encrypt: // New passphrase x2
acceptable = !ui->passEdit2->text().isEmpty() && !ui->passEdit3->text().isEmpty();
break;
case UnlockStaking:
case Unlock: // Old passphrase x1
case Decrypt:
acceptable = !ui->passEdit1->text().isEmpty();
break;
case ChangePass: // Old passphrase x1, new passphrase x2
acceptable = !ui->passEdit1->text().isEmpty() && !ui->passEdit2->text().isEmpty() && !ui->passEdit3->text().isEmpty();
break;
}
ui->buttonBox->button(QDialogButtonBox::Ok)->setEnabled(acceptable);
}
bool AskPassphraseDialog::event(QEvent *event)
{
// Detect Caps Lock key press.
if (event->type() == QEvent::KeyPress) {
QKeyEvent *ke = static_cast<QKeyEvent *>(event);
if (ke->key() == Qt::Key_CapsLock) {
fCapsLock = !fCapsLock;
}
if (fCapsLock) {
ui->capsLabel->setText(tr("Warning: The Caps Lock key is on!"));
} else {
ui->capsLabel->clear();
}
}
return QWidget::event(event);
}
bool AskPassphraseDialog::eventFilter(QObject *object, QEvent *event)
{
/* Detect Caps Lock.
* There is no good OS-independent way to check a key state in Qt, but we
* can detect Caps Lock by checking for the following condition:
* Shift key is down and the result is a lower case character, or
* Shift key is not down and the result is an upper case character.
*/
if (event->type() == QEvent::KeyPress) {
QKeyEvent *ke = static_cast<QKeyEvent *>(event);
QString str = ke->text();
if (str.length() != 0) {
const QChar *psz = str.unicode();
bool fShift = (ke->modifiers() & Qt::ShiftModifier) != 0;
if ((fShift && psz->isLower()) || (!fShift && psz->isUpper())) {
fCapsLock = true;
ui->capsLabel->setText(tr("Warning: The Caps Lock key is on!"));
} else if (psz->isLetter()) {
fCapsLock = false;
ui->capsLabel->clear();
}
}
}
return QDialog::eventFilter(object, event);
}
void AskPassphraseDialog::secureClearPassFields()
{
// Attempt to overwrite text so that they do not linger around in memory
ui->passEdit1->setText(QString(" ").repeated(ui->passEdit1->text().size()));
ui->passEdit2->setText(QString(" ").repeated(ui->passEdit2->text().size()));
ui->passEdit3->setText(QString(" ").repeated(ui->passEdit3->text().size()));
ui->passEdit1->clear();
ui->passEdit2->clear();
ui->passEdit3->clear();
}
<commit_msg>unlock for okcashv2 upgrd<commit_after>#include "askpassphrasedialog.h"
#include "ui_askpassphrasedialog.h"
#include "guiconstants.h"
#include "walletmodel.h"
#include <QMessageBox>
#include <QPushButton>
#include <QKeyEvent>
extern bool fWalletUnlockStakingOnly;
extern bool fWalletUnlockMessagingEnabled;
AskPassphraseDialog::AskPassphraseDialog(Mode mode, QWidget *parent) :
QDialog(parent),
ui(new Ui::AskPassphraseDialog),
mode(mode),
model(0),
fCapsLock(false)
{
ui->setupUi(this);
ui->passEdit1->setMaxLength(MAX_PASSPHRASE_SIZE);
ui->passEdit2->setMaxLength(MAX_PASSPHRASE_SIZE);
ui->passEdit3->setMaxLength(MAX_PASSPHRASE_SIZE);
// Setup Caps Lock detection.
ui->passEdit1->installEventFilter(this);
ui->passEdit2->installEventFilter(this);
ui->passEdit3->installEventFilter(this);
ui->stakingCheckBox->setChecked(fWalletUnlockStakingOnly);
ui->messagingCheckBox->setChecked(fWalletUnlockMessagingEnabled);
switch(mode)
{
case Encrypt: // Ask passphrase x2
ui->passLabel1->hide();
ui->passEdit1->hide();
ui->warningLabel->setText(tr("Enter the new passphrase to the wallet.<br/>Please use a passphrase of <b>10 or more random characters</b>, or <b>eight or more words</b>."));
setWindowTitle(tr("Encrypt wallet"));
break;
case UnlockStaking:
ui->stakingCheckBox->setChecked(true);
ui->stakingCheckBox->show();
// fallthru
case UnlockMessaging:
ui->messagingCheckBox->setChecked(true);
ui->messagingCheckBox->show();
case Unlock: // Ask passphrase
ui->warningLabel->setText(tr("This operation needs your wallet passphrase to unlock the wallet."));
ui->passLabel2->hide();
ui->passEdit2->hide();
ui->passLabel3->hide();
ui->passEdit3->hide();
setWindowTitle(tr("Unlock wallet"));
break;
case Decrypt: // Ask passphrase
ui->warningLabel->setText(tr("This operation needs your wallet passphrase to decrypt the wallet."));
ui->passLabel2->hide();
ui->passEdit2->hide();
ui->passLabel3->hide();
ui->passEdit3->hide();
setWindowTitle(tr("Decrypt wallet"));
break;
case ChangePass: // Ask old passphrase + new passphrase x2
setWindowTitle(tr("Change passphrase"));
ui->warningLabel->setText(tr("Enter the old and new passphrase to the wallet."));
break;
}
textChanged();
connect(ui->passEdit1, SIGNAL(textChanged(QString)), this, SLOT(textChanged()));
connect(ui->passEdit2, SIGNAL(textChanged(QString)), this, SLOT(textChanged()));
connect(ui->passEdit3, SIGNAL(textChanged(QString)), this, SLOT(textChanged()));
}
AskPassphraseDialog::~AskPassphraseDialog()
{
secureClearPassFields();
delete ui;
}
void AskPassphraseDialog::setModel(WalletModel *model)
{
this->model = model;
}
void AskPassphraseDialog::accept()
{
SecureString oldpass, newpass1, newpass2;
if(!model)
return;
oldpass.reserve(MAX_PASSPHRASE_SIZE);
newpass1.reserve(MAX_PASSPHRASE_SIZE);
newpass2.reserve(MAX_PASSPHRASE_SIZE);
// TODO: get rid of this .c_str() by implementing SecureString::operator=(std::string)
// Alternately, find a way to make this input mlock()'d to begin with.
oldpass.assign(ui->passEdit1->text().toStdString().c_str());
newpass1.assign(ui->passEdit2->text().toStdString().c_str());
newpass2.assign(ui->passEdit3->text().toStdString().c_str());
secureClearPassFields();
switch(mode)
{
case Encrypt: {
if(newpass1.empty() || newpass2.empty())
{
// Cannot encrypt with empty passphrase
break;
}
QMessageBox::StandardButton retval = QMessageBox::question(this, tr("Confirm wallet encryption"),
tr("Warning: If you encrypt your wallet and lose your passphrase, you will <b>LOSE ALL OF YOUR COINS</b>!") + "<br><br>" + tr("Are you sure you wish to encrypt your wallet?"),
QMessageBox::Yes|QMessageBox::Cancel,
QMessageBox::Cancel);
if(retval == QMessageBox::Yes)
{
if(newpass1 == newpass2)
{
if(model->setWalletEncrypted(true, newpass1))
{
QMessageBox::warning(this, tr("Wallet encrypted"),
"<qt>" +
tr("Okcash will close now to finish the encryption process. "
"Remember that encrypting your wallet cannot fully protect "
"your coins from being stolen by malware infecting your computer.") +
"<br><br><b>" +
tr("IMPORTANT: Any previous backups you have made of your wallet file "
"should be replaced with the newly generated, encrypted wallet file. "
"For security reasons, previous backups of the unencrypted wallet file "
"will become useless as soon as you start using the new, encrypted wallet.") +
"</b></qt>");
QApplication::quit();
}
else
{
QMessageBox::critical(this, tr("Wallet encryption failed"),
tr("Wallet encryption failed due to an internal error. Your wallet was not encrypted."));
}
QDialog::accept(); // Success
}
else
{
QMessageBox::critical(this, tr("Wallet encryption failed"),
tr("The supplied passphrases do not match."));
}
}
else
{
QDialog::reject(); // Cancelled
}
} break;
case UnlockStaking:
case Unlock:
if(!model->setWalletLocked(false, oldpass))
{
QMessageBox::critical(this, tr("Wallet unlock failed"),
tr("The passphrase entered for the wallet decryption was incorrect."));
}
else
{
fWalletUnlockStakingOnly = ui->stakingCheckBox->isChecked();
fWalletUnlockMessagingEnabled = ui->messagingCheckBox->isChecked();
QDialog::accept(); // Success
}
break;
case Decrypt:
if(!model->setWalletEncrypted(false, oldpass))
{
QMessageBox::critical(this, tr("Wallet decryption failed"),
tr("The passphrase entered for the wallet decryption was incorrect."));
}
else
{
QDialog::accept(); // Success
}
break;
case ChangePass:
if(newpass1 == newpass2)
{
if(model->changePassphrase(oldpass, newpass1))
{
QMessageBox::information(this, tr("Wallet encrypted"),
tr("Wallet passphrase was successfully changed."));
QDialog::accept(); // Success
}
else
{
QMessageBox::critical(this, tr("Wallet encryption failed"),
tr("The passphrase entered for the wallet decryption was incorrect."));
}
}
else
{
QMessageBox::critical(this, tr("Wallet encryption failed"),
tr("The supplied passphrases do not match."));
}
break;
}
}
void AskPassphraseDialog::textChanged()
{
// Validate input, set Ok button to enabled when acceptable
bool acceptable = false;
switch(mode)
{
case Encrypt: // New passphrase x2
acceptable = !ui->passEdit2->text().isEmpty() && !ui->passEdit3->text().isEmpty();
break;
case UnlockStaking:
case Unlock: // Old passphrase x1
case Decrypt:
acceptable = !ui->passEdit1->text().isEmpty();
break;
case ChangePass: // Old passphrase x1, new passphrase x2
acceptable = !ui->passEdit1->text().isEmpty() && !ui->passEdit2->text().isEmpty() && !ui->passEdit3->text().isEmpty();
break;
}
ui->buttonBox->button(QDialogButtonBox::Ok)->setEnabled(acceptable);
}
bool AskPassphraseDialog::event(QEvent *event)
{
// Detect Caps Lock key press.
if (event->type() == QEvent::KeyPress) {
QKeyEvent *ke = static_cast<QKeyEvent *>(event);
if (ke->key() == Qt::Key_CapsLock) {
fCapsLock = !fCapsLock;
}
if (fCapsLock) {
ui->capsLabel->setText(tr("Warning: The Caps Lock key is on!"));
} else {
ui->capsLabel->clear();
}
}
return QWidget::event(event);
}
bool AskPassphraseDialog::eventFilter(QObject *object, QEvent *event)
{
/* Detect Caps Lock.
* There is no good OS-independent way to check a key state in Qt, but we
* can detect Caps Lock by checking for the following condition:
* Shift key is down and the result is a lower case character, or
* Shift key is not down and the result is an upper case character.
*/
if (event->type() == QEvent::KeyPress) {
QKeyEvent *ke = static_cast<QKeyEvent *>(event);
QString str = ke->text();
if (str.length() != 0) {
const QChar *psz = str.unicode();
bool fShift = (ke->modifiers() & Qt::ShiftModifier) != 0;
if ((fShift && psz->isLower()) || (!fShift && psz->isUpper())) {
fCapsLock = true;
ui->capsLabel->setText(tr("Warning: The Caps Lock key is on!"));
} else if (psz->isLetter()) {
fCapsLock = false;
ui->capsLabel->clear();
}
}
}
return QDialog::eventFilter(object, event);
}
void AskPassphraseDialog::secureClearPassFields()
{
// Attempt to overwrite text so that they do not linger around in memory
ui->passEdit1->setText(QString(" ").repeated(ui->passEdit1->text().size()));
ui->passEdit2->setText(QString(" ").repeated(ui->passEdit2->text().size()));
ui->passEdit3->setText(QString(" ").repeated(ui->passEdit3->text().size()));
ui->passEdit1->clear();
ui->passEdit2->clear();
ui->passEdit3->clear();
}
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* REALM CONFIDENTIAL
* __________________
*
* [2011] - [2015] Realm Inc
* All Rights Reserved.
*
* NOTICE: All information contained herein is, and remains
* the property of Realm Incorporated and its suppliers,
* if any. The intellectual and technical concepts contained
* herein are proprietary to Realm Incorporated
* and its suppliers and may be covered by U.S. and Foreign Patents,
* patents in process, and are protected by trade secret or copyright law.
* Dissemination of this information or reproduction of this material
* is strictly forbidden unless prior written permission is obtained
* from Realm Incorporated.
*
**************************************************************************/
#ifndef REALM_COLUMN_TIMESTAMP_HPP
#define REALM_COLUMN_TIMESTAMP_HPP
#include <realm/column.hpp>
namespace realm {
struct Timestamp {
Timestamp(int64_t seconds, uint32_t nanoseconds) : m_seconds(seconds), m_nanoseconds(nanoseconds), m_is_null(false)
{
REALM_ASSERT_3(nanoseconds, <, nanoseconds_per_second);
}
Timestamp() : m_is_null(true) { }
bool is_null() const { return m_is_null; }
// Note that nullability is handled by query system. These operators are only invoked for non-null dates.
bool operator==(const Timestamp& rhs) const { return m_seconds == rhs.m_seconds && m_nanoseconds == rhs.m_nanoseconds; }
bool operator!=(const Timestamp& rhs) const { return m_seconds != rhs.m_seconds || m_nanoseconds != rhs.m_nanoseconds; }
bool operator>(const Timestamp& rhs) const { return (m_seconds > rhs.m_seconds) || (m_seconds == rhs.m_seconds && m_nanoseconds > rhs.m_nanoseconds); }
bool operator<(const Timestamp& rhs) const { return (m_seconds < rhs.m_seconds) || (m_seconds == rhs.m_seconds && m_nanoseconds < rhs.m_nanoseconds); }
bool operator<=(const Timestamp& rhs) const { return *this < rhs || *this == rhs; }
bool operator>=(const Timestamp& rhs) const { return *this > rhs || *this == rhs; }
Timestamp& operator=(const Timestamp& rhs) = default;
template<class Ch, class Tr>
friend std::basic_ostream<Ch, Tr>& operator<<(std::basic_ostream<Ch, Tr>& out, const Timestamp&);
int64_t m_seconds;
uint32_t m_nanoseconds;
bool m_is_null;
static constexpr uint32_t nanoseconds_per_second = 1000000000;
};
template<class C, class T>
inline std::basic_ostream<C, T>& operator<<(std::basic_ostream<C, T>& out, const Timestamp& d)
{
out << "Timestamp(" << d.m_seconds << ", " << d.m_nanoseconds << ")";
return out;
}
// Inherits from ColumnTemplate to get a compare_values() that can be called without knowing the
// column type
class TimestampColumn : public ColumnBaseSimple, public ColumnTemplate<Timestamp> {
public:
TimestampColumn(Allocator& alloc, ref_type ref);
~TimestampColumn() noexcept override;
static ref_type create(Allocator& alloc, size_t size = 0);
/// Get the number of entries in this column. This operation is relatively
/// slow.
size_t size() const noexcept override;
/// Whether or not this column is nullable.
bool is_nullable() const noexcept override;
/// Whether or not the value at \a row_ndx is NULL. If the column is not
/// nullable, always returns false.
bool is_null(size_t row_ndx) const noexcept override;
/// Sets the value at \a row_ndx to be NULL.
/// \throw LogicError Thrown if this column is not nullable.
void set_null(size_t row_ndx) override;
void insert_rows(size_t row_ndx, size_t num_rows_to_insert, size_t prior_num_rows, bool nullable) override;
void erase_rows(size_t row_ndx, size_t num_rows_to_erase, size_t prior_num_rows,
bool broken_reciprocal_backlinks) override;
void move_last_row_over(size_t row_ndx, size_t prior_num_rows,
bool broken_reciprocal_backlinks) override;
void clear(size_t num_rows, bool broken_reciprocal_backlinks) override;
void swap_rows(size_t row_ndx_1, size_t row_ndx_2) override;
void destroy() noexcept override;
bool has_search_index() const noexcept final { return bool(m_search_index); }
StringIndex* get_search_index() noexcept final { return m_search_index.get(); }
void destroy_search_index() noexcept override;
void set_search_index_ref(ref_type ref, ArrayParent* parent, size_t ndx_in_parent,
bool allow_duplicate_values) final;
void populate_search_index();
StringIndex* create_search_index() override;
StringData get_index_data(size_t, StringIndex::StringConversionBuffer& buffer) const noexcept override;
ref_type write(size_t slice_offset, size_t slice_size, size_t table_size, _impl::OutputStream&) const override;
void update_from_parent(size_t old_baseline) noexcept override;
void set_ndx_in_parent(size_t ndx) noexcept override;
void refresh_accessor_tree(size_t new_col_ndx, const Spec&) override;
#ifdef REALM_DEBUG
void verify() const override;
void to_dot(std::ostream&, StringData title = StringData()) const override;
void do_dump_node_structure(std::ostream&, int level) const override;
void leaf_to_dot(MemRef, ArrayParent*, size_t ndx_in_parent, std::ostream&) const override;
#endif
void add(const Timestamp& ts = Timestamp{});
Timestamp get(size_t row_ndx) const noexcept;
Timestamp get_val(size_t row_ndx) const noexcept override { return get(row_ndx); }
void set(size_t row_ndx, const Timestamp& ts);
bool compare(const TimestampColumn& c) const noexcept;
Timestamp maximum(size_t& result_index) const;
Timestamp minimum(size_t& result_index) const;
size_t count(Timestamp) const;
void erase(size_t row_ndx, bool is_last);
template <class Condition>
size_t find(Timestamp value, size_t begin, size_t end) const noexcept
{
// FIXME: Here we can do all sorts of clever optimizations. Use bithack-search on seconds, then for each match check
// nanoseconds, etc, etc, etc. Lots of possibilities. Below code is naive and slow but works.
Condition cond;
for (size_t t = begin; t < end; t++) {
Timestamp ts = get(t);
if (cond(ts, value, ts.is_null(), value.is_null()))
return t;
}
return npos;
}
typedef Timestamp value_type;
private:
std::unique_ptr<BpTree<util::Optional<int64_t>>> m_seconds;
std::unique_ptr<BpTree<int64_t>> m_nanoseconds;
std::unique_ptr<StringIndex> m_search_index;
template<class BT>
class CreateHandler;
template <class Condition>
Timestamp minmax(size_t& result_index) const noexcept
{
// Condition is realm::Greater for maximum and realm::Less for minimum.
Timestamp best;
result_index = npos;
if (size() > 0) {
best = get(0);
result_index = 0;
}
for (size_t i = 0; i < size(); ++i) {
if (Condition()(get(i), best, get(i).is_null(), best.is_null())) {
best = get(i);
result_index = i;
}
}
return best;
}
};
} // namespace realm
#endif // REALM_COLUMN_TIMESTAMP_HPP
<commit_msg>Simplified TimestampColumn::minmax()<commit_after>/*************************************************************************
*
* REALM CONFIDENTIAL
* __________________
*
* [2011] - [2015] Realm Inc
* All Rights Reserved.
*
* NOTICE: All information contained herein is, and remains
* the property of Realm Incorporated and its suppliers,
* if any. The intellectual and technical concepts contained
* herein are proprietary to Realm Incorporated
* and its suppliers and may be covered by U.S. and Foreign Patents,
* patents in process, and are protected by trade secret or copyright law.
* Dissemination of this information or reproduction of this material
* is strictly forbidden unless prior written permission is obtained
* from Realm Incorporated.
*
**************************************************************************/
#ifndef REALM_COLUMN_TIMESTAMP_HPP
#define REALM_COLUMN_TIMESTAMP_HPP
#include <realm/column.hpp>
namespace realm {
struct Timestamp {
Timestamp(int64_t seconds, uint32_t nanoseconds) : m_seconds(seconds), m_nanoseconds(nanoseconds), m_is_null(false)
{
REALM_ASSERT_3(nanoseconds, <, nanoseconds_per_second);
}
Timestamp() : m_is_null(true) { }
bool is_null() const { return m_is_null; }
// Note that nullability is handled by query system. These operators are only invoked for non-null dates.
bool operator==(const Timestamp& rhs) const { return m_seconds == rhs.m_seconds && m_nanoseconds == rhs.m_nanoseconds; }
bool operator!=(const Timestamp& rhs) const { return m_seconds != rhs.m_seconds || m_nanoseconds != rhs.m_nanoseconds; }
bool operator>(const Timestamp& rhs) const { return (m_seconds > rhs.m_seconds) || (m_seconds == rhs.m_seconds && m_nanoseconds > rhs.m_nanoseconds); }
bool operator<(const Timestamp& rhs) const { return (m_seconds < rhs.m_seconds) || (m_seconds == rhs.m_seconds && m_nanoseconds < rhs.m_nanoseconds); }
bool operator<=(const Timestamp& rhs) const { return *this < rhs || *this == rhs; }
bool operator>=(const Timestamp& rhs) const { return *this > rhs || *this == rhs; }
Timestamp& operator=(const Timestamp& rhs) = default;
template<class Ch, class Tr>
friend std::basic_ostream<Ch, Tr>& operator<<(std::basic_ostream<Ch, Tr>& out, const Timestamp&);
int64_t m_seconds;
uint32_t m_nanoseconds;
bool m_is_null;
static constexpr uint32_t nanoseconds_per_second = 1000000000;
};
template<class C, class T>
inline std::basic_ostream<C, T>& operator<<(std::basic_ostream<C, T>& out, const Timestamp& d)
{
out << "Timestamp(" << d.m_seconds << ", " << d.m_nanoseconds << ")";
return out;
}
// Inherits from ColumnTemplate to get a compare_values() that can be called without knowing the
// column type
class TimestampColumn : public ColumnBaseSimple, public ColumnTemplate<Timestamp> {
public:
TimestampColumn(Allocator& alloc, ref_type ref);
~TimestampColumn() noexcept override;
static ref_type create(Allocator& alloc, size_t size = 0);
/// Get the number of entries in this column. This operation is relatively
/// slow.
size_t size() const noexcept override;
/// Whether or not this column is nullable.
bool is_nullable() const noexcept override;
/// Whether or not the value at \a row_ndx is NULL. If the column is not
/// nullable, always returns false.
bool is_null(size_t row_ndx) const noexcept override;
/// Sets the value at \a row_ndx to be NULL.
/// \throw LogicError Thrown if this column is not nullable.
void set_null(size_t row_ndx) override;
void insert_rows(size_t row_ndx, size_t num_rows_to_insert, size_t prior_num_rows, bool nullable) override;
void erase_rows(size_t row_ndx, size_t num_rows_to_erase, size_t prior_num_rows,
bool broken_reciprocal_backlinks) override;
void move_last_row_over(size_t row_ndx, size_t prior_num_rows,
bool broken_reciprocal_backlinks) override;
void clear(size_t num_rows, bool broken_reciprocal_backlinks) override;
void swap_rows(size_t row_ndx_1, size_t row_ndx_2) override;
void destroy() noexcept override;
bool has_search_index() const noexcept final { return bool(m_search_index); }
StringIndex* get_search_index() noexcept final { return m_search_index.get(); }
void destroy_search_index() noexcept override;
void set_search_index_ref(ref_type ref, ArrayParent* parent, size_t ndx_in_parent,
bool allow_duplicate_values) final;
void populate_search_index();
StringIndex* create_search_index() override;
StringData get_index_data(size_t, StringIndex::StringConversionBuffer& buffer) const noexcept override;
ref_type write(size_t slice_offset, size_t slice_size, size_t table_size, _impl::OutputStream&) const override;
void update_from_parent(size_t old_baseline) noexcept override;
void set_ndx_in_parent(size_t ndx) noexcept override;
void refresh_accessor_tree(size_t new_col_ndx, const Spec&) override;
#ifdef REALM_DEBUG
void verify() const override;
void to_dot(std::ostream&, StringData title = StringData()) const override;
void do_dump_node_structure(std::ostream&, int level) const override;
void leaf_to_dot(MemRef, ArrayParent*, size_t ndx_in_parent, std::ostream&) const override;
#endif
void add(const Timestamp& ts = Timestamp{});
Timestamp get(size_t row_ndx) const noexcept;
Timestamp get_val(size_t row_ndx) const noexcept override { return get(row_ndx); }
void set(size_t row_ndx, const Timestamp& ts);
bool compare(const TimestampColumn& c) const noexcept;
Timestamp maximum(size_t& result_index) const;
Timestamp minimum(size_t& result_index) const;
size_t count(Timestamp) const;
void erase(size_t row_ndx, bool is_last);
template <class Condition>
size_t find(Timestamp value, size_t begin, size_t end) const noexcept
{
// FIXME: Here we can do all sorts of clever optimizations. Use bithack-search on seconds, then for each match check
// nanoseconds, etc, etc, etc. Lots of possibilities. Below code is naive and slow but works.
Condition cond;
for (size_t t = begin; t < end; t++) {
Timestamp ts = get(t);
if (cond(ts, value, ts.is_null(), value.is_null()))
return t;
}
return npos;
}
typedef Timestamp value_type;
private:
std::unique_ptr<BpTree<util::Optional<int64_t>>> m_seconds;
std::unique_ptr<BpTree<int64_t>> m_nanoseconds;
std::unique_ptr<StringIndex> m_search_index;
template<class BT>
class CreateHandler;
template <class Condition>
Timestamp minmax(size_t& result_index) const noexcept
{
// Condition is realm::Greater for maximum and realm::Less for minimum.
if (size() == 0) {
result_index = npos;
return Timestamp();
}
Timestamp best = get(0);
result_index = 0;
for (size_t i = 1; i < size(); ++i) {
if (Condition()(get(i), best, get(i).is_null(), best.is_null())) {
best = get(i);
result_index = i;
}
}
return best;
}
};
} // namespace realm
#endif // REALM_COLUMN_TIMESTAMP_HPP
<|endoftext|>
|
<commit_before>/*
I actually got tricked into working hard and ended up wasting half a day
when a such a naive solution works.
:<
*/
#include <iostream>
#include <vector>
#include <cmath>
#include <numeric>
#include <unordered_set>
#include "prime_util.h"
#include "number_util.h"
void search(
int N,
std::vector<int> &primes,
std::vector<std::vector<int>> &powers,
std::vector<int> &solution,
int sum_solution,
int index,
std::unordered_set<int> &results)
{
if (solution.size() == powers.size())
{
results.emplace(sum_solution);
return;
}
for (int &power : powers[index])
{
if (sum_solution + power >= N)
break;
std::vector<int> _solution(solution);
_solution.emplace_back(power);
search(N, primes, powers, _solution, sum_solution + power, index + 1, results);
}
}
int main()
{
int N = 50000000;
std::vector<int> primes = util::get_primes(int(std::sqrt(N)));
std::vector<std::vector<int>> powers = { { }, { }, { } };
for (int e = 2; e < 5; e++)
{
for (int &prime : primes)
{
int power = util::mpz_to<int>(util::pow(prime, e));
if (power > N)
break;
powers[e - 2].emplace_back(power);
}
}
std::unordered_set<int> results;
std::vector<int> solution;
search(N, primes, powers, solution, 0, 0, results);
std::cout << results.size();
}
<commit_msg>Enforce const correctness.<commit_after>/*
I actually got tricked into working hard and ended up wasting half a day
when a such a naive solution works.
:<
*/
#include <iostream>
#include <vector>
#include <cmath>
#include <numeric>
#include <unordered_set>
#include "prime_util.h"
#include "number_util.h"
void search(
int N,
std::vector<int> const &primes,
std::vector<std::vector<int>> const &powers,
std::vector<int> const &solution,
int sum_solution,
int index,
std::unordered_set<int> &results)
{
if (solution.size() == powers.size())
{
results.emplace(sum_solution);
return;
}
for (int const &power : powers[index])
{
if (sum_solution + power >= N)
break;
std::vector<int> _solution(solution);
_solution.emplace_back(power);
search(N, primes, powers, _solution, sum_solution + power, index + 1, results);
}
}
int main()
{
int N = 50000000;
std::vector<int> primes = util::get_primes(int(std::sqrt(N)));
std::vector<std::vector<int>> powers = { { }, { }, { } };
for (int e = 2; e < 5; e++)
{
for (int &prime : primes)
{
int power = util::mpz_to<int>(util::pow(prime, e));
if (power > N)
break;
powers[e - 2].emplace_back(power);
}
}
std::unordered_set<int> results;
std::vector<int> solution;
search(N, primes, powers, solution, 0, 0, results);
std::cout << results.size();
}
<|endoftext|>
|
<commit_before>class Solution {
public:
int titleToNumber(string s) {
int ans=0,mul=1;
for(int i=s.size()-1;i>=0;i--){
ans+=(s[i]-'A'+1)*mul;
mul*=26;
}
return ans;
}
};
<commit_msg>Excel Sheet Column Number<commit_after>class Solution {
public:
int titleToNumber(string s) {
int ans=0,mul=1;
for(int i=s.size()-1;i>=0;i--){
ans+=(s[i]-'A'+1)*mul;
mul*=26;
}
return ans;
}
};
<|endoftext|>
|
<commit_before>#include "Zookeeper.hpp"
Gpu::Gpu() {
box->cpu->map_io(0xFD000000, PAGE_SIZE, (MMIOReceiver *) this); // 16MB address space
}
uint32_t Gpu::read(uint32_t addr) {
cout << format("Gpu::read(0x%08x)") % addr << endl;
switch(addr) {
case 0xfd100200:
return 3;
default:
return addr;
}
}
void Gpu::write(uint32_t addr, uint32_t value) {
if(addr > 0xfd700000 && addr <= 0xfd705000)
return;
cout << format("Gpu::write(0x%08x, 0x%08x)") % addr % value << endl;
}
<commit_msg>Reverted constant in Gpu case.<commit_after>#include "Zookeeper.hpp"
Gpu::Gpu() {
box->cpu->map_io(0xFD000000, 4096, (MMIOReceiver *) this); // 4096 pages * 4KB == 16MB address space
}
uint32_t Gpu::read(uint32_t addr) {
cout << format("Gpu::read(0x%08x)") % addr << endl;
switch(addr) {
case 0xfd100200:
return 3;
default:
return addr;
}
}
void Gpu::write(uint32_t addr, uint32_t value) {
if(addr > 0xfd700000 && addr <= 0xfd705000)
return;
cout << format("Gpu::write(0x%08x, 0x%08x)") % addr % value << endl;
}
<|endoftext|>
|
<commit_before>// BUG: this whole thing depends on the specifics of how the clang version I
// am using emits llvm bitcode for the hacky RMC protocol.
// We rely on how basic blocks get named, on the labels forcing things
// into their own basic blocks, and probably will rely on this block
// having one predecessor and one successor. We could probably even
// force those to be empty without too much work by adding more labels...
#include <llvm/Pass.h>
#include <llvm/IR/Function.h>
#include <llvm/IR/Module.h>
#include <llvm/IR/Constants.h>
#include <llvm/IR/Instructions.h>
#include <llvm/IR/InlineAsm.h>
#include <llvm/IR/CFG.h>
#include <llvm/IR/InstIterator.h>
#include <llvm/Transforms/Scalar.h>
#include <llvm/ADT/ArrayRef.h>
#include <llvm/Transforms/Utils/BasicBlockUtils.h>
#include <llvm/Support/raw_ostream.h>
#include <ostream>
#include <fstream>
#include <iostream>
#include <map>
#include <set>
using namespace llvm;
namespace {
#if 0 // I hate you, emacs. Is there a better way to work around this?
}
#endif
/* To do bogus data dependencies, we will emit inline assembly
instructions. This is sort of tasteless; we should add an intrinsic;
but it means we don't need to modify llvm. This is what the
instruction should look like (probably the constraints aren't
right?):
%2 = call i32 asm sideeffect "eor $0, $0;", "=r,0"(i32 %1) #2, !srcloc !11
Also for ctrlisb we do:
call void asm sideeffect "cmp $0, $0;beq 1f;1: isb", "r,~{memory}"(i32 %1) #2, !srcloc !4
And for dmb:
call void asm sideeffect "dmb", "~{memory}"() #2, !srcloc !5
We can probably do a bogus inline asm on x86 to prevent reordering:
%2 = call i32 asm sideeffect "", "=r,r,0,~{dirflag},~{fpsr},~{flags}"(i32 %1, i32 %0) #3, !srcloc !9
What about this makes the right value come out:
=r specifies an output parameter and the 0 says that that input parameter
is paired with param 0.
Hm. Does this *actually* work?? What does "sideeffect" actually mean
for asm and do we need it.
--
Should we emit dmb directly, or try to use llvm's fences?
*/
//// Some auxillary data structures
enum RMCEdgeType {
VisbilityEdge,
ExecutionEdge
};
raw_ostream& operator<<(raw_ostream& os, const RMCEdgeType& t) {
switch (t) {
case VisbilityEdge:
os << "v";
break;
case ExecutionEdge:
os << "x";
break;
default:
os << "?";
break;
}
return os;
}
// Info about an RMC edge
struct RMCEdge {
RMCEdgeType edgeType;
BasicBlock *src;
BasicBlock *dst;
bool operator<(const RMCEdge& rhs) const {
return std::tie(edgeType, src, dst)
< std::tie(rhs.edgeType, rhs.src, rhs.dst);
}
void print(raw_ostream &os) const {
// substr(5) is to drop "_rmc_" from the front
os << src->getName().substr(5) << " -" << edgeType <<
"-> " << dst->getName().substr(5);
}
};
raw_ostream& operator<<(raw_ostream& os, const RMCEdge& e) {
e.print(os);
return os;
}
///////////////////////////////////////////////////////////////////////////
// Information for a node in the RMC graph.
enum ActionType {
ActionComplex,
ActionSimpleRead,
ActionSimpleWrites, // needs to be paired with a dep
ActionSimpleRMW
};
struct Action {
Action(BasicBlock *p_bb) :
bb(p_bb),
type(ActionComplex),
stores(0), loads(0), RMWs(0), calls(0), soleLoad(nullptr) {}
void operator=(const Action &) LLVM_DELETED_FUNCTION;
Action(const Action &) LLVM_DELETED_FUNCTION;
Action(Action &&) = default; // move constructor!
BasicBlock *bb;
// Some basic info about what sort of instructions live in the action
ActionType type;
int stores;
int loads;
int RMWs;
int calls;
LoadInst *soleLoad;
// Edges in the graph.
// XXX: Would we be better off storing this some other way?
// a <ptr, type> pair?
// And should we store v edges in x
SmallPtrSet<Action *, 2> execEdges;
SmallPtrSet<Action *, 2> visEdges;
};
enum CutType {
CutNone,
CutCtrlIsync, // needs to be paired with a dep
CutLwsync,
CutSync
};
struct EdgeCut {
EdgeCut() : type(CutNone), front(false), read(nullptr) {}
CutType type;
bool front;
Value *read;
};
///////////////////////////////////////////////////////////////////////////
// Code to find all simple paths between two basic blocks.
// Could generalize more to graphs if we wanted, but I don't right
// now.
typedef std::vector<BasicBlock *> Path;
typedef SmallVector<Path, 2> PathList;
typedef SmallPtrSet<BasicBlock *, 8> GreySet;
PathList findAllSimplePaths_(GreySet *grey, BasicBlock *src, BasicBlock *dst) {
PathList paths;
if (grey->count(src)) return paths;
if (src == dst) {
Path path;
path.push_back(dst);
paths.push_back(std::move(path));
return paths;
}
grey->insert(src);
// Go search all the successors
for (auto i = succ_begin(src), e = succ_end(src); i != e; i++) {
PathList subpaths = findAllSimplePaths_(grey, *i, dst);
std::move(subpaths.begin(), subpaths.end(), back_inserter(paths));
}
// Add our step to all of the vectors
for (auto & path : paths) {
path.push_back(src);
}
// Remove it from the set of things we've seen. We might come
// through here again.
// We can't really do any sort of memoization, since in a cyclic
// graph the possible simple paths depend not just on what node we
// are on, but our previous path (to avoid looping).
grey->erase(src);
return paths;
}
PathList findAllSimplePaths(BasicBlock *src, BasicBlock *dst) {
GreySet grey;
return findAllSimplePaths_(&grey, src, dst);
}
void dumpPaths(const PathList &paths) {
for (auto & path : paths) {
for (auto block : path) {
errs() << block->getName() << " <- ";
}
errs() << "\n";
}
}
///////////////////////////////////////////////////////////////////////////
// XXX: This is the wrong way to do this!
bool targetARM = true;
bool targetx86 = false;
// Some llvm nonsense. I should probably find a way to clean this up.
// do we put ~{dirflag},~{fpsr},~{flags} for the x86 ones? don't think so.
Instruction *makeSync(Value *dummy) {
LLVMContext &C = dummy->getContext();
FunctionType *f_ty = FunctionType::get(FunctionType::getVoidTy(C), false);
InlineAsm *a;
if (targetARM) {
a = InlineAsm::get(f_ty, "dmb", "~{memory}", true);
} else if (targetx86) {
a = InlineAsm::get(f_ty, "msync", "~{memory}", true);
} else {
assert(false && "invalid target");
}
return CallInst::Create(a, None, "sync");
}
Instruction *makeLwsync(Value *dummy) {
LLVMContext &C = dummy->getContext();
FunctionType *f_ty = FunctionType::get(FunctionType::getVoidTy(C), false);
InlineAsm *a;
if (targetARM) {
a = InlineAsm::get(f_ty, "dmb", "~{memory}", true);
} else if (targetx86) {
a = InlineAsm::get(f_ty, "", "~{memory}", true);
} else {
assert(false && "invalid target");
}
return CallInst::Create(a, None, "lwsync");
}
Instruction *makeCtrlIsync(Value *v) {
LLVMContext &C = v->getContext();
FunctionType *f_ty =
FunctionType::get(FunctionType::getVoidTy(C), v->getType(), false);
InlineAsm *a;
if (targetARM) {
a = InlineAsm::get(f_ty, "cmp $0, $0;beq 1f;1: isb", "r,~{memory}", true);
} else if (targetx86) {
a = InlineAsm::get(f_ty, "", "r,~{memory}", true);
} else {
assert(false && "invalid target");
}
return CallInst::Create(a, None, "ctrlisync");
}
// We also need to add a thing for fake data deps, which is more annoying.
///////////////////////////////////////////////////////////////////////////
//// Actual code for the pass
class RMCPass : public FunctionPass {
private:
std::vector<Action> actions_;
DenseMap<BasicBlock *, Action *> bb2action_;
DenseMap<BasicBlock *, EdgeCut> cuts_;
public:
static char ID;
RMCPass() : FunctionPass(ID) {
}
~RMCPass() { }
std::vector<RMCEdge> findEdges(Function &F);
void buildGraph(std::vector<RMCEdge> &edges, Function &F);
virtual bool runOnFunction(Function &F);
void getAnalysisUsage(AnalysisUsage &AU) const override {
AU.addRequiredID(BreakCriticalEdgesID);
AU.setPreservesCFG();
}
};
bool nameMatches(StringRef blockName, StringRef target) {
StringRef name = "_rmc_" + target.str() + "_";
if (!blockName.startswith(name)) return false;
// Now make sure the rest is an int
APInt dummy;
return !blockName.drop_front(name.size()).getAsInteger(10, dummy);
}
StringRef getStringArg(Value *v) {
const Value *g = cast<Constant>(v)->stripPointerCasts();
const Constant *ptr = cast<GlobalVariable>(g)->getInitializer();
StringRef str = cast<ConstantDataSequential>(ptr)->getAsString();
// Drop the '\0' at the end
return str.drop_back();
}
std::vector<RMCEdge> RMCPass::findEdges(Function &F) {
std::vector<RMCEdge> edges;
for (inst_iterator is = inst_begin(F), ie = inst_end(F); is != ie;) {
// Grab the instruction and advance the iterator at the start, since
// we might delete the instruction.
Instruction *i = &*is;
is++;
CallInst *load = dyn_cast<CallInst>(i);
if (!load) continue;
Function *target = load->getCalledFunction();
// We look for calls to the bogus function
// __rmc_edge_register, pull out the information about them,
// and delete the calls.
if (!target || target->getName() != "__rmc_edge_register") continue;
// Pull out what the operands have to be.
// We just assert if something is wrong, which is not great UX.
bool isVisibility = cast<ConstantInt>(load->getOperand(0))
->getValue().getBoolValue();
RMCEdgeType edgeType = isVisibility ? VisbilityEdge : ExecutionEdge;
StringRef srcName = getStringArg(load->getOperand(1));
StringRef dstName = getStringArg(load->getOperand(2));
// Since multiple blocks can have the same tag, we search for
// them by name.
// We could make this more efficient by building maps but I don't think
// it is going to matter.
for (auto & src : F) {
if (!nameMatches(src.getName(), srcName)) continue;
for (auto & dst : F) {
if (!nameMatches(dst.getName(), dstName)) continue;
edges.push_back({edgeType, &src, &dst});
}
}
// Delete the bogus call.
i->eraseFromParent();
}
return edges;
}
void analyzeAction(Action &info) {
LoadInst *soleLoad = nullptr;
for (auto & i : *info.bb) {
if (LoadInst *load = dyn_cast<LoadInst>(&i)) {
info.loads++;
soleLoad = load;
} else if (isa<StoreInst>(i)) {
info.stores++;
// What else counts as a call? I'm counting fences I guess.
} else if (isa<CallInst>(i) || isa<FenceInst>(i)) {
info.calls++;
} else if (isa<AtomicCmpXchgInst>(i) || isa<AtomicRMWInst>(i)) {
info.RMWs++;
}
}
// Try to characterize what this action does.
// These categories might not be the best.
if (info.loads == 1 && info.stores+info.calls+info.RMWs == 0) {
info.soleLoad = soleLoad;
info.type = ActionSimpleRead;
} else if (info.stores >= 1 && info.loads+info.calls+info.RMWs == 0) {
info.type = ActionSimpleWrites;
} else if (info.RMWs == 1 && info.stores+info.loads+info.calls == 0) {
info.type = ActionSimpleRMW;
} else {
info.type = ActionComplex;
}
}
void RMCPass::buildGraph(std::vector<RMCEdge> &edges, Function &F) {
// First, collect all the basic blocks with edges attached to them
SmallPtrSet<BasicBlock *, 8> basicBlocks;
for (auto & edge : edges) {
basicBlocks.insert(edge.src);
basicBlocks.insert(edge.dst);
}
// Now, make the vector of actions and a mapping from BasicBlock *.
actions_.reserve(basicBlocks.size());
for (auto bb : basicBlocks) {
actions_.emplace_back(bb);
bb2action_[bb] = &actions_.back();
}
// Analyze the instructions in actions to see what they do.
for (auto & action : actions_) {
analyzeAction(action);
}
// Build our list of edges into a more explicit graph
for (auto & edge : edges) {
Action *src = bb2action_[edge.src];
Action *dst = bb2action_[edge.dst];
if (edge.edgeType == VisbilityEdge) {
src->visEdges.insert(dst);
} else {
src->execEdges.insert(dst);
}
}
}
bool RMCPass::runOnFunction(Function &F) {
auto edges = findEdges(F);
if (edges.empty()) return false;
for (auto & edge : edges) {
errs() << "Found an edge: " << edge << "\n";
}
buildGraph(edges, F);
// Clear our data structures to save memory, make things clean for
// future runs.
actions_.clear();
bb2action_.clear();
cuts_.clear();
return true;
}
char RMCPass::ID = 0;
RegisterPass<RMCPass> X("rmc-pass", "RMC");
}
<commit_msg>Refactor clearing of data structures.<commit_after>// BUG: this whole thing depends on the specifics of how the clang version I
// am using emits llvm bitcode for the hacky RMC protocol.
// We rely on how basic blocks get named, on the labels forcing things
// into their own basic blocks, and probably will rely on this block
// having one predecessor and one successor. We could probably even
// force those to be empty without too much work by adding more labels...
#include <llvm/Pass.h>
#include <llvm/IR/Function.h>
#include <llvm/IR/Module.h>
#include <llvm/IR/Constants.h>
#include <llvm/IR/Instructions.h>
#include <llvm/IR/InlineAsm.h>
#include <llvm/IR/CFG.h>
#include <llvm/IR/InstIterator.h>
#include <llvm/Transforms/Scalar.h>
#include <llvm/ADT/ArrayRef.h>
#include <llvm/Transforms/Utils/BasicBlockUtils.h>
#include <llvm/Support/raw_ostream.h>
#include <ostream>
#include <fstream>
#include <iostream>
#include <map>
#include <set>
using namespace llvm;
namespace {
#if 0 // I hate you, emacs. Is there a better way to work around this?
}
#endif
/* To do bogus data dependencies, we will emit inline assembly
instructions. This is sort of tasteless; we should add an intrinsic;
but it means we don't need to modify llvm. This is what the
instruction should look like (probably the constraints aren't
right?):
%2 = call i32 asm sideeffect "eor $0, $0;", "=r,0"(i32 %1) #2, !srcloc !11
Also for ctrlisb we do:
call void asm sideeffect "cmp $0, $0;beq 1f;1: isb", "r,~{memory}"(i32 %1) #2, !srcloc !4
And for dmb:
call void asm sideeffect "dmb", "~{memory}"() #2, !srcloc !5
We can probably do a bogus inline asm on x86 to prevent reordering:
%2 = call i32 asm sideeffect "", "=r,r,0,~{dirflag},~{fpsr},~{flags}"(i32 %1, i32 %0) #3, !srcloc !9
What about this makes the right value come out:
=r specifies an output parameter and the 0 says that that input parameter
is paired with param 0.
Hm. Does this *actually* work?? What does "sideeffect" actually mean
for asm and do we need it.
--
Should we emit dmb directly, or try to use llvm's fences?
*/
//// Some auxillary data structures
enum RMCEdgeType {
VisbilityEdge,
ExecutionEdge
};
raw_ostream& operator<<(raw_ostream& os, const RMCEdgeType& t) {
switch (t) {
case VisbilityEdge:
os << "v";
break;
case ExecutionEdge:
os << "x";
break;
default:
os << "?";
break;
}
return os;
}
// Info about an RMC edge
struct RMCEdge {
RMCEdgeType edgeType;
BasicBlock *src;
BasicBlock *dst;
bool operator<(const RMCEdge& rhs) const {
return std::tie(edgeType, src, dst)
< std::tie(rhs.edgeType, rhs.src, rhs.dst);
}
void print(raw_ostream &os) const {
// substr(5) is to drop "_rmc_" from the front
os << src->getName().substr(5) << " -" << edgeType <<
"-> " << dst->getName().substr(5);
}
};
raw_ostream& operator<<(raw_ostream& os, const RMCEdge& e) {
e.print(os);
return os;
}
///////////////////////////////////////////////////////////////////////////
// Information for a node in the RMC graph.
enum ActionType {
ActionComplex,
ActionSimpleRead,
ActionSimpleWrites, // needs to be paired with a dep
ActionSimpleRMW
};
struct Action {
Action(BasicBlock *p_bb) :
bb(p_bb),
type(ActionComplex),
stores(0), loads(0), RMWs(0), calls(0), soleLoad(nullptr) {}
void operator=(const Action &) LLVM_DELETED_FUNCTION;
Action(const Action &) LLVM_DELETED_FUNCTION;
Action(Action &&) = default; // move constructor!
BasicBlock *bb;
// Some basic info about what sort of instructions live in the action
ActionType type;
int stores;
int loads;
int RMWs;
int calls;
LoadInst *soleLoad;
// Edges in the graph.
// XXX: Would we be better off storing this some other way?
// a <ptr, type> pair?
// And should we store v edges in x
SmallPtrSet<Action *, 2> execEdges;
SmallPtrSet<Action *, 2> visEdges;
};
enum CutType {
CutNone,
CutCtrlIsync, // needs to be paired with a dep
CutLwsync,
CutSync
};
struct EdgeCut {
EdgeCut() : type(CutNone), front(false), read(nullptr) {}
CutType type;
bool front;
Value *read;
};
///////////////////////////////////////////////////////////////////////////
// Code to find all simple paths between two basic blocks.
// Could generalize more to graphs if we wanted, but I don't right
// now.
typedef std::vector<BasicBlock *> Path;
typedef SmallVector<Path, 2> PathList;
typedef SmallPtrSet<BasicBlock *, 8> GreySet;
PathList findAllSimplePaths_(GreySet *grey, BasicBlock *src, BasicBlock *dst) {
PathList paths;
if (grey->count(src)) return paths;
if (src == dst) {
Path path;
path.push_back(dst);
paths.push_back(std::move(path));
return paths;
}
grey->insert(src);
// Go search all the successors
for (auto i = succ_begin(src), e = succ_end(src); i != e; i++) {
PathList subpaths = findAllSimplePaths_(grey, *i, dst);
std::move(subpaths.begin(), subpaths.end(), back_inserter(paths));
}
// Add our step to all of the vectors
for (auto & path : paths) {
path.push_back(src);
}
// Remove it from the set of things we've seen. We might come
// through here again.
// We can't really do any sort of memoization, since in a cyclic
// graph the possible simple paths depend not just on what node we
// are on, but our previous path (to avoid looping).
grey->erase(src);
return paths;
}
PathList findAllSimplePaths(BasicBlock *src, BasicBlock *dst) {
GreySet grey;
return findAllSimplePaths_(&grey, src, dst);
}
void dumpPaths(const PathList &paths) {
for (auto & path : paths) {
for (auto block : path) {
errs() << block->getName() << " <- ";
}
errs() << "\n";
}
}
///////////////////////////////////////////////////////////////////////////
// XXX: This is the wrong way to do this!
bool targetARM = true;
bool targetx86 = false;
// Some llvm nonsense. I should probably find a way to clean this up.
// do we put ~{dirflag},~{fpsr},~{flags} for the x86 ones? don't think so.
Instruction *makeSync(Value *dummy) {
LLVMContext &C = dummy->getContext();
FunctionType *f_ty = FunctionType::get(FunctionType::getVoidTy(C), false);
InlineAsm *a;
if (targetARM) {
a = InlineAsm::get(f_ty, "dmb", "~{memory}", true);
} else if (targetx86) {
a = InlineAsm::get(f_ty, "msync", "~{memory}", true);
} else {
assert(false && "invalid target");
}
return CallInst::Create(a, None, "sync");
}
Instruction *makeLwsync(Value *dummy) {
LLVMContext &C = dummy->getContext();
FunctionType *f_ty = FunctionType::get(FunctionType::getVoidTy(C), false);
InlineAsm *a;
if (targetARM) {
a = InlineAsm::get(f_ty, "dmb", "~{memory}", true);
} else if (targetx86) {
a = InlineAsm::get(f_ty, "", "~{memory}", true);
} else {
assert(false && "invalid target");
}
return CallInst::Create(a, None, "lwsync");
}
Instruction *makeCtrlIsync(Value *v) {
LLVMContext &C = v->getContext();
FunctionType *f_ty =
FunctionType::get(FunctionType::getVoidTy(C), v->getType(), false);
InlineAsm *a;
if (targetARM) {
a = InlineAsm::get(f_ty, "cmp $0, $0;beq 1f;1: isb", "r,~{memory}", true);
} else if (targetx86) {
a = InlineAsm::get(f_ty, "", "r,~{memory}", true);
} else {
assert(false && "invalid target");
}
return CallInst::Create(a, None, "ctrlisync");
}
// We also need to add a thing for fake data deps, which is more annoying.
///////////////////////////////////////////////////////////////////////////
//// Actual code for the pass
class RMCPass : public FunctionPass {
private:
std::vector<Action> actions_;
DenseMap<BasicBlock *, Action *> bb2action_;
DenseMap<BasicBlock *, EdgeCut> cuts_;
public:
static char ID;
RMCPass() : FunctionPass(ID) {
}
~RMCPass() { }
std::vector<RMCEdge> findEdges(Function &F);
void buildGraph(std::vector<RMCEdge> &edges, Function &F);
virtual bool runOnFunction(Function &F);
void getAnalysisUsage(AnalysisUsage &AU) const override {
AU.addRequiredID(BreakCriticalEdgesID);
AU.setPreservesCFG();
}
// Clear our data structures to save memory, make things clean for
// future runs.
void clear() {
actions_.clear();
bb2action_.clear();
cuts_.clear();
}
};
bool nameMatches(StringRef blockName, StringRef target) {
StringRef name = "_rmc_" + target.str() + "_";
if (!blockName.startswith(name)) return false;
// Now make sure the rest is an int
APInt dummy;
return !blockName.drop_front(name.size()).getAsInteger(10, dummy);
}
StringRef getStringArg(Value *v) {
const Value *g = cast<Constant>(v)->stripPointerCasts();
const Constant *ptr = cast<GlobalVariable>(g)->getInitializer();
StringRef str = cast<ConstantDataSequential>(ptr)->getAsString();
// Drop the '\0' at the end
return str.drop_back();
}
std::vector<RMCEdge> RMCPass::findEdges(Function &F) {
std::vector<RMCEdge> edges;
for (inst_iterator is = inst_begin(F), ie = inst_end(F); is != ie;) {
// Grab the instruction and advance the iterator at the start, since
// we might delete the instruction.
Instruction *i = &*is;
is++;
CallInst *load = dyn_cast<CallInst>(i);
if (!load) continue;
Function *target = load->getCalledFunction();
// We look for calls to the bogus function
// __rmc_edge_register, pull out the information about them,
// and delete the calls.
if (!target || target->getName() != "__rmc_edge_register") continue;
// Pull out what the operands have to be.
// We just assert if something is wrong, which is not great UX.
bool isVisibility = cast<ConstantInt>(load->getOperand(0))
->getValue().getBoolValue();
RMCEdgeType edgeType = isVisibility ? VisbilityEdge : ExecutionEdge;
StringRef srcName = getStringArg(load->getOperand(1));
StringRef dstName = getStringArg(load->getOperand(2));
// Since multiple blocks can have the same tag, we search for
// them by name.
// We could make this more efficient by building maps but I don't think
// it is going to matter.
for (auto & src : F) {
if (!nameMatches(src.getName(), srcName)) continue;
for (auto & dst : F) {
if (!nameMatches(dst.getName(), dstName)) continue;
edges.push_back({edgeType, &src, &dst});
}
}
// Delete the bogus call.
i->eraseFromParent();
}
return edges;
}
void analyzeAction(Action &info) {
LoadInst *soleLoad = nullptr;
for (auto & i : *info.bb) {
if (LoadInst *load = dyn_cast<LoadInst>(&i)) {
info.loads++;
soleLoad = load;
} else if (isa<StoreInst>(i)) {
info.stores++;
// What else counts as a call? I'm counting fences I guess.
} else if (isa<CallInst>(i) || isa<FenceInst>(i)) {
info.calls++;
} else if (isa<AtomicCmpXchgInst>(i) || isa<AtomicRMWInst>(i)) {
info.RMWs++;
}
}
// Try to characterize what this action does.
// These categories might not be the best.
if (info.loads == 1 && info.stores+info.calls+info.RMWs == 0) {
info.soleLoad = soleLoad;
info.type = ActionSimpleRead;
} else if (info.stores >= 1 && info.loads+info.calls+info.RMWs == 0) {
info.type = ActionSimpleWrites;
} else if (info.RMWs == 1 && info.stores+info.loads+info.calls == 0) {
info.type = ActionSimpleRMW;
} else {
info.type = ActionComplex;
}
}
void RMCPass::buildGraph(std::vector<RMCEdge> &edges, Function &F) {
// First, collect all the basic blocks with edges attached to them
SmallPtrSet<BasicBlock *, 8> basicBlocks;
for (auto & edge : edges) {
basicBlocks.insert(edge.src);
basicBlocks.insert(edge.dst);
}
// Now, make the vector of actions and a mapping from BasicBlock *.
actions_.reserve(basicBlocks.size());
for (auto bb : basicBlocks) {
actions_.emplace_back(bb);
bb2action_[bb] = &actions_.back();
}
// Analyze the instructions in actions to see what they do.
for (auto & action : actions_) {
analyzeAction(action);
}
// Build our list of edges into a more explicit graph
for (auto & edge : edges) {
Action *src = bb2action_[edge.src];
Action *dst = bb2action_[edge.dst];
if (edge.edgeType == VisbilityEdge) {
src->visEdges.insert(dst);
} else {
src->execEdges.insert(dst);
}
}
}
bool RMCPass::runOnFunction(Function &F) {
auto edges = findEdges(F);
if (edges.empty()) return false;
for (auto & edge : edges) {
errs() << "Found an edge: " << edge << "\n";
}
buildGraph(edges, F);
clear();
return true;
}
char RMCPass::ID = 0;
RegisterPass<RMCPass> X("rmc-pass", "RMC");
}
<|endoftext|>
|
<commit_before>#include "mn101.hpp"
#include <srarea.hpp>
typedef enum {
OPG_NONE = 0,
OPG_D_SRC,
OPG_D_DST,
OPG_DW_SRC,
OPG_DW_DST,
OPG_D0_DW_DST, //#
OPG_D1_DW_DST, //#
OPG_A_8, //#
OPG_A_SRC, //#
OPG_A_DST, //#
OPG_IMM4,
OPG_IMM4_S,
OPG_IMM8, //#
OPG_IMM8_S, //#
OPG_IMM12, //#
OPG_IMM16, //#
OPG_IO8, //#
OPG_BRANCH4,
OPG_BRANCH7,
OPG_BRANCH11,
OPG_BRANCH18, //#
OPG_BRANCH20, //#
OPG_CALL12, //#
OPG_CALL16, //#
OPG_CALL18, //#
OPG_CALL20, //#
OPG_CALLTBL4, //#
OPG_REG_SP,
OPG_REG_PSW, //#
OPG_REG_HA, //#
OPG_BITPOS, //#
OPG_REP3, //#
OPGF_RELATIVE = 0x100,//#
OPGF_LOAD = 0X200,//#
OPGF_SHOWAT_0 = 0x1000, //#
OPGF_SHOWAT_1 = 0x2000,
OPGF_SHOWAT_2 = 0x3000,
OPGF_SHOWAT_MASK = 0x7000
} opgen_t;
#define FLAG_SRCOFF_SP 0x01
#define FLAG_DSTOFF_SP 0x02
typedef struct
{
uchar code;
uchar mask;
ins_enum_t mnemonic;
uint32 op[3];
} parseinfo_t;
static parseinfo_t parseTable[] = {
#include "parsetable0.gen.c"
};
static parseinfo_t parseTableExtension2[] = {
#include "parsetable1.gen.c"
};
static parseinfo_t parseTableExtension3[] = {
#include "parsetable2.gen.c"
};
static struct parseState_t
{
ea_t pc;
ea_t ptr;
uint32 code;
uchar sz;
uchar insbyte;
void reset()
{
code = 0;
sz = 0;
uchar H = get_segreg(cmd.ea, rVh);
ptr = pc = (cmd.ea << 1) + H;
}
uint32 fetchNibble()
{
uchar nibble;
if (ptr & 1)
nibble = get_byte(ptr >> 1) >> 4;
else
nibble = get_byte(ptr >> 1) & 0xF;
QASSERT(256, nibble <= 0xF);
code = (code << 4) | nibble;
sz++;
ptr++;
return nibble;
}
// This is unaligned byte fetch. Note it is not the same as 2x fetchNibble()
uint32 fetchByte()
{
uchar byte;
if (ptr & 1)
byte = (get_byte(ptr >> 1) >> 4) | (get_byte((ptr >> 1)+1) << 4);
else
byte = get_byte(ptr >> 1);
code = (code << 8) | byte;
sz += 2;
ptr += 2;
return byte;
}
bool compareMask(const parseinfo_t *pi)
{
if ((code & pi->mask) == pi->code)
{
// Save the first two nibbles for operands parsing
insbyte = code;
return true;
}
return false;
}
} parseState;
static void setCodeAddrValue(op_t &op, ea_t addr)
{
op.addr = addr >> 1;
op.value = addr;
}
#define IOTOP 0x3F00
#define SRVT 0x4080
#define SIGN_EXTEND(nbits, val) (((val) << (32 - (nbits))) >> (32 - (nbits)))
static bool parseOperand(op_t &op, int type)
{
uchar v;
signed int imm;
signed char imm8;
switch (type)
{
case OPG_NONE:
break;
case OPG_D_SRC:
v = (parseState.insbyte & 0xC) >> 2;
op.type = o_reg;
op.reg = OP_REG_D + v;
break;
case OPG_D_DST:
v = parseState.insbyte & 0x3;
op.type = o_reg;
op.reg = OP_REG_D + v;
break;
case OPG_DW_SRC:
v = (parseState.insbyte & 0x2) >> 1;
op.type = o_reg;
op.reg = OP_REG_DW + v;
break;
case OPG_DW_DST:
v = parseState.insbyte & 0x1;
op.type = o_reg;
op.reg = OP_REG_DW + v;
break;
case OPG_D0_DW_DST:
case OPG_D1_DW_DST:
v = parseState.insbyte & 0x1;
op.type = o_reg;
op.reg = OP_REG_D + v * 2;
if (type == OPG_D1_DW_DST)
op.reg++;
break;
case OPG_A_8:
v = (parseState.insbyte & 0x4) >> 2;
op.type = o_reg;
op.reg = OP_REG_A + v;
break;
case OPG_A_SRC:
v = (parseState.insbyte & 0x2) >> 1;
op.type = o_reg;
op.reg = OP_REG_A + v;
break;
case OPG_A_DST:
v = parseState.insbyte & 0x1;
op.type = o_reg;
op.reg = OP_REG_A + v;
break;
case OPG_IMM4:
case OPG_IMM4_S:
imm = parseState.fetchNibble();
if (type == OPG_IMM4_S)
{
imm = SIGN_EXTEND(4, imm);
op.flags |= OF_NUMBER;
}
op.addr = op.value = imm;
op.type = o_imm;
op.dtyp = dt_byte;
break;
case OPG_IMM8:
case OPG_IMM8_S:
imm = parseState.fetchByte();
if (type == OPG_IMM8_S)
{
imm = SIGN_EXTEND(8, imm);
op.flags |= OF_NUMBER;
}
op.addr = op.value = imm;
op.type = o_imm;
op.dtyp = dt_byte;
break;
case OPG_IMM12:
imm = parseState.fetchByte();
imm |= parseState.fetchNibble() << 8;
op.addr = op.value = imm;
op.type = o_imm;
op.dtyp = dt_word;
break;
case OPG_IMM16:
imm = parseState.fetchByte();
imm |= parseState.fetchByte() << 8;
op.addr = op.value = imm;
op.type = o_imm;
op.dtyp = dt_word;
//op.flags |= OF_NUMBER;
break;
case OPG_IO8:
imm = parseState.fetchByte();
op.addr = op.value = IOTOP + imm;
op.type = o_mem;
op.dtyp = dt_byte;
break;
case OPG_BRANCH4:
imm = parseState.fetchNibble();
imm = SIGN_EXTEND(4, imm);
imm = (imm << 1) | (parseState.insbyte & 1); // Extract H
setCodeAddrValue(op, parseState.pc + imm + parseState.sz);
op.type = o_near;
break;
case OPG_BRANCH7:
imm8 = parseState.fetchByte(); //Signed imm#8
setCodeAddrValue(op, parseState.pc + imm8 + parseState.sz);
op.type = o_near;
break;
case OPG_BRANCH11:
imm = parseState.fetchByte() | (parseState.fetchNibble() << 8); //Signed imm#12
imm = SIGN_EXTEND(12, imm);
setCodeAddrValue(op, parseState.pc + imm + parseState.sz);
op.type = o_near;
break;
case OPG_BRANCH18:
case OPG_CALL18:
imm = parseState.fetchByte() | (parseState.fetchByte() << 8);
imm |= (parseState.insbyte & 0x6) << 15; //aa
imm = (imm << 1) | (parseState.insbyte & 0x1); //H
setCodeAddrValue(op, imm);
op.type = o_near;
break;
case OPG_BRANCH20:
case OPG_CALL20:
v = parseState.fetchByte();
imm = parseState.fetchByte() | (parseState.fetchByte() << 8);
imm |= (v & 0x1E) << 15; //Bbbb
imm = (imm << 1) | (v & 0x1); //H
setCodeAddrValue(op, imm);
op.type = o_near;
break;
case OPG_CALL12:
imm = parseState.fetchByte() | (parseState.fetchNibble() << 8);
imm = SIGN_EXTEND(12, imm);
imm = (imm << 1) | (parseState.insbyte & 0x1); //H
setCodeAddrValue(op, parseState.pc + imm + parseState.sz);
op.type = o_near;
break;
case OPG_CALL16:
imm = parseState.fetchByte() | (parseState.fetchByte() << 8);
imm = SIGN_EXTEND(16, imm);
imm = (imm << 1) | (parseState.insbyte & 0x1); //H
setCodeAddrValue(op, parseState.pc + imm + parseState.sz);
op.type = o_near;
break;
case OPG_CALLTBL4:
imm = parseState.fetchNibble();
setCodeAddrValue(op, SRVT + (imm << 2));
op.type = o_mem;
break;
case OPG_REG_SP:
op.type = o_reg;
op.reg = OP_REG_SP;
break;
case OPG_REG_PSW:
op.type = o_reg;
op.reg = OP_REG_PSW;
break;
case OPG_REG_HA:
op.type = o_reg;
op.reg = OP_REG_HA;
break;
case OPG_BITPOS:
case OPG_REP3:
imm = parseState.insbyte & 0x7;
if (type == OPG_BITPOS)
op.type = o_bitpos;
else
op.type = o_imm;
op.value = imm;
break;
default:
QASSERT(257, 0);
}
return true;
}
static void mergeOps(op_t &src, op_t &dst)
{
QASSERT(258, &src != &dst);
dst.type = src.type;
QASSERT(258, dst.reg == OP_REG_NONE);
dst.reg = src.reg;
dst.addr += src.addr;
dst.value += src.value;
dst.flags |= src.flags;
dst.dtyp = src.dtyp;
src.type = 0;
src.reg = 0;
src.addr = 0;
src.value = 0;
src.flags = 0;
src.dtyp = 0;
}
static bool parseInstruction(const parseinfo_t *pTable, size_t tblSize)
{
const parseinfo_t *ins;
for (size_t i = 0; i < tblSize; i++)
{
ins = &pTable[i];
if (parseState.compareMask(ins))
{
cmd.itype = ins->mnemonic;
int opidx = -1;
for (int j = 0; j < 3; j++)
{
opidx = (ins->op[j] & OPGF_SHOWAT_MASK) >> 12;
if (opidx != 0)
opidx--;
else
opidx = j;
parseOperand(cmd.Operands[opidx], ins->op[j] & 0xFF);
if ((ins->op[j] & OPGF_LOAD) != 0)
{
if (cmd.Operands[opidx].type == o_reg)
cmd.Operands[opidx].type = o_phrase;
else if (cmd.Operands[opidx].type == o_imm)
cmd.Operands[opidx].type = o_mem;
}
if ((ins->op[j] & OPGF_RELATIVE) != 0)
{
cmd.Operands[opidx].type = o_displ;
cmd.Operands[opidx].addr = cmd.Operands[opidx].value;
}
}
// Merge displacement ops
int dstidx = 0;
for (int srcidx = 0; srcidx < 3; srcidx++)
{
if (cmd.Operands[srcidx].type == o_displ)
{
dstidx--;
}
if (srcidx != dstidx)
{
mergeOps(cmd.Operands[srcidx], cmd.Operands[dstidx]);
}
dstidx++;
}
return true;
}
}
return false;
}
int idaapi mn101_ana(void)
{
bool decoded;
parseState.reset();
// Get the first byte of instruction
uchar extension = parseState.fetchNibble();
// Handle extension codes
switch (extension)
{
case 0x3:
parseState.fetchNibble();
parseState.fetchNibble();
decoded = parseInstruction(parseTableExtension3, qnumber(parseTableExtension3));
break;
case 0x2:
parseState.fetchNibble();
parseState.fetchNibble();
decoded = parseInstruction(parseTableExtension2, qnumber(parseTableExtension2));
break;
default:
parseState.fetchNibble();
decoded = parseInstruction(parseTable, qnumber(parseTable));
break;
}
if (!decoded)
return 0;
// Compiler generally aligns the size of return instructions by a byte
//TODO: maybe add a user option for this
if (cmd.itype == INS_RTS || cmd.itype == INS_RTI)
{
if ((parseState.sz + parseState.pc) & 1) ++parseState.sz;
cmd.segpref = 0;
}
else
{
// cmd.segpref would hold 1 if the last byte was only partially consumed
cmd.segpref = parseState.ptr & 1;
}
// Update the command size
cmd.size = (parseState.sz + (parseState.pc & 1)) / 2;
return(cmd.size);
}
<commit_msg>Added an assert and fixed MSVC warning<commit_after>#include "mn101.hpp"
#include <srarea.hpp>
typedef enum {
OPG_NONE = 0,
OPG_D_SRC,
OPG_D_DST,
OPG_DW_SRC,
OPG_DW_DST,
OPG_D0_DW_DST, //#
OPG_D1_DW_DST, //#
OPG_A_8, //#
OPG_A_SRC, //#
OPG_A_DST, //#
OPG_IMM4,
OPG_IMM4_S,
OPG_IMM8, //#
OPG_IMM8_S, //#
OPG_IMM12, //#
OPG_IMM16, //#
OPG_IO8, //#
OPG_BRANCH4,
OPG_BRANCH7,
OPG_BRANCH11,
OPG_BRANCH18, //#
OPG_BRANCH20, //#
OPG_CALL12, //#
OPG_CALL16, //#
OPG_CALL18, //#
OPG_CALL20, //#
OPG_CALLTBL4, //#
OPG_REG_SP,
OPG_REG_PSW, //#
OPG_REG_HA, //#
OPG_BITPOS, //#
OPG_REP3, //#
OPGF_RELATIVE = 0x100,//#
OPGF_LOAD = 0X200,//#
OPGF_SHOWAT_0 = 0x1000, //#
OPGF_SHOWAT_1 = 0x2000,
OPGF_SHOWAT_2 = 0x3000,
OPGF_SHOWAT_MASK = 0x7000
} opgen_t;
#define FLAG_SRCOFF_SP 0x01
#define FLAG_DSTOFF_SP 0x02
typedef struct
{
uchar code;
uchar mask;
ins_enum_t mnemonic;
uint32 op[3];
} parseinfo_t;
static parseinfo_t parseTable[] = {
#include "parsetable0.gen.c"
};
static parseinfo_t parseTableExtension2[] = {
#include "parsetable1.gen.c"
};
static parseinfo_t parseTableExtension3[] = {
#include "parsetable2.gen.c"
};
static struct parseState_t
{
ea_t pc;
ea_t ptr;
uint32 code;
uchar sz;
uchar insbyte;
void reset()
{
code = 0;
sz = 0;
uchar H = get_segreg(cmd.ea, rVh);
ptr = pc = (cmd.ea << 1) + H;
}
uint32 fetchNibble()
{
uchar nibble;
if (ptr & 1)
nibble = get_byte(ptr >> 1) >> 4;
else
nibble = get_byte(ptr >> 1) & 0xF;
QASSERT(256, nibble <= 0xF);
code = (code << 4) | nibble;
sz++;
ptr++;
return nibble;
}
// This is unaligned byte fetch. Note it is not the same as 2x fetchNibble()
uint32 fetchByte()
{
uchar byte;
if (ptr & 1)
byte = (get_byte(ptr >> 1) >> 4) | (get_byte((ptr >> 1)+1) << 4);
else
byte = get_byte(ptr >> 1);
code = (code << 8) | byte;
sz += 2;
ptr += 2;
return byte;
}
bool compareMask(const parseinfo_t *pi)
{
if ((code & pi->mask) == pi->code)
{
// Save the first two nibbles for operands parsing
insbyte = code;
return true;
}
return false;
}
} parseState;
static void setCodeAddrValue(op_t &op, ea_t addr)
{
op.addr = addr >> 1;
op.value = addr;
}
#define IOTOP 0x3F00
#define SRVT 0x4080
#define SIGN_EXTEND(nbits, val) (((val) << (32 - (nbits))) >> (32 - (nbits)))
static bool parseOperand(op_t &op, int type)
{
uchar v;
signed int imm;
signed char imm8;
switch (type)
{
case OPG_NONE:
break;
case OPG_D_SRC:
v = (parseState.insbyte & 0xC) >> 2;
op.type = o_reg;
op.reg = OP_REG_D + v;
break;
case OPG_D_DST:
v = parseState.insbyte & 0x3;
op.type = o_reg;
op.reg = OP_REG_D + v;
break;
case OPG_DW_SRC:
v = (parseState.insbyte & 0x2) >> 1;
op.type = o_reg;
op.reg = OP_REG_DW + v;
break;
case OPG_DW_DST:
v = parseState.insbyte & 0x1;
op.type = o_reg;
op.reg = OP_REG_DW + v;
break;
case OPG_D0_DW_DST:
case OPG_D1_DW_DST:
v = parseState.insbyte & 0x1;
op.type = o_reg;
op.reg = OP_REG_D + v * 2;
if (type == OPG_D1_DW_DST)
op.reg++;
break;
case OPG_A_8:
v = (parseState.insbyte & 0x4) >> 2;
op.type = o_reg;
op.reg = OP_REG_A + v;
break;
case OPG_A_SRC:
v = (parseState.insbyte & 0x2) >> 1;
op.type = o_reg;
op.reg = OP_REG_A + v;
break;
case OPG_A_DST:
v = parseState.insbyte & 0x1;
op.type = o_reg;
op.reg = OP_REG_A + v;
break;
case OPG_IMM4:
case OPG_IMM4_S:
imm = parseState.fetchNibble();
if (type == OPG_IMM4_S)
{
imm = SIGN_EXTEND(4, imm);
op.flags |= OF_NUMBER;
}
op.addr = op.value = imm;
op.type = o_imm;
op.dtyp = dt_byte;
break;
case OPG_IMM8:
case OPG_IMM8_S:
imm = parseState.fetchByte();
if (type == OPG_IMM8_S)
{
imm = SIGN_EXTEND(8, imm);
op.flags |= OF_NUMBER;
}
op.addr = op.value = imm;
op.type = o_imm;
op.dtyp = dt_byte;
break;
case OPG_IMM12:
imm = parseState.fetchByte();
imm |= parseState.fetchNibble() << 8;
op.addr = op.value = imm;
op.type = o_imm;
op.dtyp = dt_word;
break;
case OPG_IMM16:
imm = parseState.fetchByte();
imm |= parseState.fetchByte() << 8;
op.addr = op.value = imm;
op.type = o_imm;
op.dtyp = dt_word;
//op.flags |= OF_NUMBER;
break;
case OPG_IO8:
imm = parseState.fetchByte();
op.addr = op.value = IOTOP + imm;
op.type = o_mem;
op.dtyp = dt_byte;
break;
case OPG_BRANCH4:
imm = parseState.fetchNibble();
imm = SIGN_EXTEND(4, imm);
imm = (imm << 1) | (parseState.insbyte & 1); // Extract H
setCodeAddrValue(op, parseState.pc + imm + parseState.sz);
op.type = o_near;
break;
case OPG_BRANCH7:
imm8 = parseState.fetchByte(); //Signed imm#8
setCodeAddrValue(op, parseState.pc + imm8 + parseState.sz);
op.type = o_near;
break;
case OPG_BRANCH11:
imm = parseState.fetchByte() | (parseState.fetchNibble() << 8); //Signed imm#12
imm = SIGN_EXTEND(12, imm);
setCodeAddrValue(op, parseState.pc + imm + parseState.sz);
op.type = o_near;
break;
case OPG_BRANCH18:
case OPG_CALL18:
imm = parseState.fetchByte() | (parseState.fetchByte() << 8);
imm |= (parseState.insbyte & 0x6) << 15; //aa
imm = (imm << 1) | (parseState.insbyte & 0x1); //H
setCodeAddrValue(op, imm);
op.type = o_near;
break;
case OPG_BRANCH20:
case OPG_CALL20:
v = parseState.fetchByte();
imm = parseState.fetchByte() | (parseState.fetchByte() << 8);
imm |= (v & 0x1E) << 15; //Bbbb
imm = (imm << 1) | (v & 0x1); //H
setCodeAddrValue(op, imm);
op.type = o_near;
break;
case OPG_CALL12:
imm = parseState.fetchByte() | (parseState.fetchNibble() << 8);
imm = SIGN_EXTEND(12, imm);
imm = (imm << 1) | (parseState.insbyte & 0x1); //H
setCodeAddrValue(op, parseState.pc + imm + parseState.sz);
op.type = o_near;
break;
case OPG_CALL16:
imm = parseState.fetchByte() | (parseState.fetchByte() << 8);
imm = SIGN_EXTEND(16, imm);
imm = (imm << 1) | (parseState.insbyte & 0x1); //H
setCodeAddrValue(op, parseState.pc + imm + parseState.sz);
op.type = o_near;
break;
case OPG_CALLTBL4:
imm = parseState.fetchNibble();
setCodeAddrValue(op, SRVT + (imm << 2));
op.type = o_mem;
break;
case OPG_REG_SP:
op.type = o_reg;
op.reg = OP_REG_SP;
break;
case OPG_REG_PSW:
op.type = o_reg;
op.reg = OP_REG_PSW;
break;
case OPG_REG_HA:
op.type = o_reg;
op.reg = OP_REG_HA;
break;
case OPG_BITPOS:
case OPG_REP3:
imm = parseState.insbyte & 0x7;
if (type == OPG_BITPOS)
op.type = o_bitpos;
else
op.type = o_imm;
op.value = imm;
break;
default:
QASSERT(257, 0);
}
return true;
}
static void mergeOps(op_t &src, op_t &dst)
{
QASSERT(258, &src != &dst);
dst.type = src.type;
QASSERT(258, dst.reg == OP_REG_NONE);
dst.reg = src.reg;
dst.addr += src.addr;
dst.value += src.value;
dst.flags |= src.flags;
dst.dtyp = src.dtyp;
src.type = 0;
src.reg = 0;
src.addr = 0;
src.value = 0;
src.flags = 0;
src.dtyp = 0;
}
static bool parseInstruction(const parseinfo_t *pTable, size_t tblSize)
{
const parseinfo_t *ins;
for (size_t i = 0; i < tblSize; i++)
{
ins = &pTable[i];
if (parseState.compareMask(ins))
{
cmd.itype = ins->mnemonic;
int opidx = -1;
for (int j = 0; j < 3; j++)
{
opidx = (ins->op[j] & OPGF_SHOWAT_MASK) >> 12;
if (opidx != 0)
opidx--;
else
opidx = j;
parseOperand(cmd.Operands[opidx], ins->op[j] & 0xFF);
if ((ins->op[j] & OPGF_LOAD) != 0)
{
if (cmd.Operands[opidx].type == o_reg)
cmd.Operands[opidx].type = o_phrase;
else if (cmd.Operands[opidx].type == o_imm)
cmd.Operands[opidx].type = o_mem;
}
if ((ins->op[j] & OPGF_RELATIVE) != 0)
{
cmd.Operands[opidx].type = o_displ;
cmd.Operands[opidx].addr = cmd.Operands[opidx].value;
}
}
// Merge displacement ops
int dstidx = 0;
for (int srcidx = 0; srcidx < 3; srcidx++)
{
if (cmd.Operands[srcidx].type == o_displ)
{
QASSERT(258, dstidx > 0);
dstidx--;
}
if (srcidx != dstidx)
{
mergeOps(cmd.Operands[srcidx], cmd.Operands[dstidx]);
}
dstidx++;
}
return true;
}
}
return false;
}
int idaapi mn101_ana(void)
{
bool decoded;
parseState.reset();
// Get the first byte of instruction
uchar extension = parseState.fetchNibble();
// Handle extension codes
switch (extension)
{
case 0x3:
parseState.fetchNibble();
parseState.fetchNibble();
decoded = parseInstruction(parseTableExtension3, qnumber(parseTableExtension3));
break;
case 0x2:
parseState.fetchNibble();
parseState.fetchNibble();
decoded = parseInstruction(parseTableExtension2, qnumber(parseTableExtension2));
break;
default:
parseState.fetchNibble();
decoded = parseInstruction(parseTable, qnumber(parseTable));
break;
}
if (!decoded)
return 0;
// Compiler generally aligns the size of return instructions by a byte
//TODO: maybe add a user option for this
if (cmd.itype == INS_RTS || cmd.itype == INS_RTI)
{
if ((parseState.sz + parseState.pc) & 1) ++parseState.sz;
cmd.segpref = 0;
}
else
{
// cmd.segpref would hold 1 if the last byte was only partially consumed
cmd.segpref = parseState.ptr & 1;
}
// Update the command size
cmd.size = (parseState.sz + (parseState.pc & 1)) / 2;
return(cmd.size);
}
<|endoftext|>
|
<commit_before>#ifndef ANY_HPP
# define ANY_HPP
# pragma once
#include <cassert>
#include <cstdint>
#include <stdexcept>
#include <typeinfo>
#include <type_traits>
#include <utility>
namespace generic
{
class any
{
public:
template <typename T>
using remove_cvr = ::std::remove_cv<
typename ::std::remove_reference<T>::type
>;
using typeid_t = void const*;
template <typename T>
static typeid_t type_id() noexcept
{
static char const type_id{};
return &type_id;
}
any() = default;
any(any const& other) :
content(other.content ? other.content->cloner_(other.content) : nullptr)
{
}
any(any&& other) noexcept { *this = ::std::move(other); }
template<typename ValueType,
typename = typename ::std::enable_if<
!::std::is_same<any, typename ::std::decay<ValueType>::type>{}
>::type
>
any(ValueType&& value) :
content(new holder<typename remove_cvr<ValueType>::type>(
::std::forward<ValueType>(value)))
{
}
~any() { delete content; }
public: // modifiers
void clear() { swap(any()); }
bool empty() const noexcept { return !*this; }
void swap(any& other) noexcept { ::std::swap(content, other.content); }
void swap(any&& other) noexcept { ::std::swap(content, other.content); }
any& operator=(any const& rhs) { return *this = any(rhs); }
any& operator=(any&& rhs) noexcept { swap(rhs); return *this; }
template<typename ValueType,
typename = typename ::std::enable_if<
!::std::is_same<any, typename remove_cvr<ValueType>::type>{}
>::type
>
any& operator=(ValueType&& rhs)
{
return *this = any(::std::forward<ValueType>(rhs));
}
public: // queries
explicit operator bool() const noexcept { return content; }
typeid_t type() const noexcept { return type_id(); }
typeid_t type_id() const noexcept
{
return content ? content->type_id_ : type_id<void>();
}
public: // get
template <typename ValueType>
ValueType cget() const
{
return get<ValueType>();
}
template <typename ValueType>
ValueType get() const
{
using nonref = typename ::std::remove_reference<ValueType>::type;
return const_cast<any*>(this)->get<nonref const&>();
}
template <typename ValueType>
ValueType get()
{
using nonref = typename ::std::remove_reference<ValueType>::type;
#ifndef NDEBUG
if (content && (type_id() ==
any::type_id<typename any::remove_cvr<ValueType>::type>()))
{
return static_cast<any::holder<nonref>*>(content)->held;
}
else
{
throw ::std::bad_typeid();
}
#else
return static_cast<any::holder<nonref>*>(content)->held;
#endif // NDEBUG
}
private: // types
template <typename T>
static constexpr T* begin(T& value) noexcept
{
return &value;
}
template <typename T, ::std::size_t N>
static constexpr typename ::std::remove_all_extents<T>::type*
begin(T (&array)[N]) noexcept
{
return begin(*array);
}
template <typename T>
static constexpr T* end(T& value) noexcept
{
return &value + 1;
}
template <typename T, ::std::size_t N>
static constexpr typename ::std::remove_all_extents<T>::type*
end(T (&array)[N]) noexcept
{
return end(array[N - 1]);
}
struct placeholder
{
typeid_t const type_id_;
placeholder* (* const cloner_)(placeholder*);
virtual ~placeholder() = default;
protected:
placeholder(typeid_t const ti, decltype(cloner_) const c) noexcept :
type_id_(ti),
cloner_(c)
{
}
};
template <typename ValueType>
struct holder : public placeholder
{
public: // constructor
template <class T, typename U = ValueType>
holder(T&& value,
typename ::std::enable_if<
!::std::is_array<U>{} &&
!::std::is_copy_constructible<U>{}
>::type* = nullptr) :
placeholder(type_id<ValueType>(), throwing_cloner),
held(::std::forward<T>(value))
{
}
template <class T, typename U = ValueType>
holder(T&& value,
typename ::std::enable_if<
!::std::is_array<U>{} &&
::std::is_copy_constructible<U>{}
>::type* = nullptr) :
placeholder(type_id<ValueType>(), cloner),
held(::std::forward<T>(value))
{
}
template <class T, typename U = ValueType>
holder(T&& value,
typename ::std::enable_if<
::std::is_array<U>{} &&
!::std::is_copy_assignable<
typename ::std::remove_all_extents<U>::type
>{} &&
::std::is_move_assignable<
typename ::std::remove_all_extents<U>::type
>{}
>::type* = nullptr) :
placeholder(type_id<ValueType>(), throwing_cloner)
{
::std::copy(::std::make_move_iterator(begin(value)),
::std::make_move_iterator(end(value)),
begin(held));
}
template <class T, typename U = ValueType>
holder(T&& value,
typename ::std::enable_if<
::std::is_array<U>{} &&
::std::is_copy_assignable<
typename ::std::remove_all_extents<U>::type
>{}
>::type* = nullptr) :
placeholder(type_id<ValueType>(), cloner)
{
::std::copy(begin(value), end(value), begin(held));
}
holder& operator=(holder const&) = delete;
static placeholder* cloner(placeholder* const base)
{
return new holder<ValueType>(static_cast<holder*>(base)->held);
}
static placeholder* throwing_cloner(placeholder* const)
{
throw ::std::logic_error("");
}
public:
ValueType held;
};
private: // representation
template<typename ValueType>
friend ValueType* any_cast(any*) noexcept;
template<typename ValueType>
friend ValueType* unsafe_any_cast(any*) noexcept;
placeholder* content{};
};
template<typename ValueType>
inline ValueType* unsafe_any_cast(any* const operand) noexcept
{
return &static_cast<any::holder<ValueType>*>(operand->content)->held;
}
template<typename ValueType>
inline ValueType const* unsafe_any_cast(any const* const operand) noexcept
{
return unsafe_any_cast<ValueType>(const_cast<any*>(operand));
}
template<typename ValueType>
inline ValueType* any_cast(any* const operand) noexcept
{
return operand &&
(operand->type_id() ==
any::type_id<typename any::remove_cvr<ValueType>::type>()) ?
&static_cast<any::holder<ValueType>*>(operand->content)->held :
nullptr;
}
template<typename ValueType>
inline ValueType const* any_cast(any const* const operand) noexcept
{
return any_cast<ValueType>(const_cast<any*>(operand));
}
template<typename ValueType>
inline ValueType any_cast(any& operand)
{
using nonref = typename ::std::remove_reference<ValueType>::type;
#ifndef NDEBUG
auto const result(any_cast<nonref>(&operand));
if (result)
{
return *result;
}
else
{
throw ::std::bad_cast();
}
#else
return *unsafe_any_cast<nonref>(&operand);
#endif // NDEBUG
}
template<typename ValueType>
inline ValueType any_cast(any const& operand)
{
using nonref = typename ::std::remove_reference<ValueType>::type;
return any_cast<nonref const&>(const_cast<any&>(operand));
}
}
#endif // ANY_HPP
<commit_msg>some fixes<commit_after>#ifndef ANY_HPP
# define ANY_HPP
# pragma once
#include <cassert>
#include <cstdint>
#include <stdexcept>
#include <typeinfo>
#include <type_traits>
#include <utility>
namespace generic
{
class any
{
public:
template <typename T>
using remove_cvr = ::std::remove_cv<
typename ::std::remove_reference<T>::type
>;
using typeid_t = void const*;
template <typename T>
static typeid_t type_id() noexcept
{
static char const type_id{};
return &type_id;
}
any() = default;
any(any const& other) :
content(other.content ? other.content->cloner_(other.content) : nullptr)
{
}
any(any&& other) noexcept { *this = ::std::move(other); }
template<typename ValueType,
typename = typename ::std::enable_if<
!::std::is_same<any, typename ::std::decay<ValueType>::type>{}
>::type
>
any(ValueType&& value) :
content(new holder<typename remove_cvr<ValueType>::type>(
::std::forward<ValueType>(value)))
{
}
~any() { delete content; }
public: // modifiers
void clear() { swap(any()); }
bool empty() const noexcept { return !*this; }
void swap(any& other) noexcept { ::std::swap(content, other.content); }
void swap(any&& other) noexcept { ::std::swap(content, other.content); }
any& operator=(any const& rhs) { return content == rhs.content ? *this : *this = any(rhs); }
any& operator=(any&& rhs) noexcept { swap(rhs); return *this; }
template<typename ValueType,
typename = typename ::std::enable_if<
!::std::is_same<any, typename remove_cvr<ValueType>::type>{}
>::type
>
any& operator=(ValueType&& rhs)
{
return *this = any(::std::forward<ValueType>(rhs));
}
public: // queries
explicit operator bool() const noexcept { return content; }
typeid_t type() const noexcept { return type_id(); }
typeid_t type_id() const noexcept
{
return content ? content->type_id_ : type_id<void>();
}
public: // get
template <typename ValueType>
ValueType cget() const
{
return get<ValueType>();
}
template <typename ValueType>
ValueType get() const
{
using nonref = typename ::std::remove_reference<ValueType>::type;
return const_cast<any*>(this)->get<nonref const&>();
}
template <typename ValueType>
ValueType get()
{
using nonref = typename ::std::remove_reference<ValueType>::type;
#ifndef NDEBUG
if (content && (type_id() ==
any::type_id<typename any::remove_cvr<ValueType>::type>()))
{
return static_cast<any::holder<nonref>*>(content)->held;
}
else
{
throw ::std::bad_typeid();
}
#else
return static_cast<any::holder<nonref>*>(content)->held;
#endif // NDEBUG
}
private: // types
template <typename T>
static constexpr T* begin(T& value) noexcept
{
return &value;
}
template <typename T, ::std::size_t N>
static constexpr typename ::std::remove_all_extents<T>::type*
begin(T (&array)[N]) noexcept
{
return begin(*array);
}
template <typename T>
static constexpr T* end(T& value) noexcept
{
return &value + 1;
}
template <typename T, ::std::size_t N>
static constexpr typename ::std::remove_all_extents<T>::type*
end(T (&array)[N]) noexcept
{
return end(array[N - 1]);
}
struct placeholder
{
typeid_t const type_id_;
placeholder* (* const cloner_)(placeholder*);
virtual ~placeholder() = default;
protected:
placeholder(typeid_t const ti, decltype(cloner_) const c) noexcept :
type_id_(ti),
cloner_(c)
{
}
};
template <typename ValueType>
struct holder : public placeholder
{
public: // constructor
template <class T, typename U = ValueType>
holder(T&& value,
typename ::std::enable_if<
!::std::is_array<U>{} &&
!::std::is_copy_constructible<U>{}
>::type* = nullptr) :
placeholder(type_id<ValueType>(), throwing_cloner),
held(::std::forward<T>(value))
{
}
template <class T, typename U = ValueType>
holder(T&& value,
typename ::std::enable_if<
!::std::is_array<U>{} &&
::std::is_copy_constructible<U>{}
>::type* = nullptr) :
placeholder(type_id<ValueType>(), cloner),
held(::std::forward<T>(value))
{
}
template <class T, typename U = ValueType>
holder(T&& value,
typename ::std::enable_if<
::std::is_array<U>{} &&
!::std::is_copy_assignable<
typename ::std::remove_all_extents<U>::type
>{} &&
::std::is_move_assignable<
typename ::std::remove_all_extents<U>::type
>{}
>::type* = nullptr) :
placeholder(type_id<ValueType>(), throwing_cloner)
{
::std::copy(::std::make_move_iterator(begin(value)),
::std::make_move_iterator(end(value)),
begin(held));
}
template <class T, typename U = ValueType>
holder(T&& value,
typename ::std::enable_if<
::std::is_array<U>{} &&
::std::is_copy_assignable<
typename ::std::remove_all_extents<U>::type
>{}
>::type* = nullptr) :
placeholder(type_id<ValueType>(), cloner)
{
::std::copy(begin(value), end(value), begin(held));
}
holder& operator=(holder const&) = delete;
static placeholder* cloner(placeholder* const base)
{
return new holder<ValueType>(static_cast<holder*>(base)->held);
}
static placeholder* throwing_cloner(placeholder* const)
{
throw ::std::logic_error("");
}
public:
ValueType held;
};
private: // representation
template<typename ValueType>
friend ValueType* any_cast(any*) noexcept;
template<typename ValueType>
friend ValueType* unsafe_any_cast(any*) noexcept;
placeholder* content{};
};
template<typename ValueType>
inline ValueType* unsafe_any_cast(any* const operand) noexcept
{
return &static_cast<any::holder<ValueType>*>(operand->content)->held;
}
template<typename ValueType>
inline ValueType const* unsafe_any_cast(any const* const operand) noexcept
{
return unsafe_any_cast<ValueType>(const_cast<any*>(operand));
}
template<typename ValueType>
inline ValueType* any_cast(any* const operand) noexcept
{
return operand &&
(operand->type_id() ==
any::type_id<typename any::remove_cvr<ValueType>::type>()) ?
&static_cast<any::holder<ValueType>*>(operand->content)->held :
nullptr;
}
template<typename ValueType>
inline ValueType const* any_cast(any const* const operand) noexcept
{
return any_cast<ValueType>(const_cast<any*>(operand));
}
template<typename ValueType>
inline ValueType any_cast(any& operand)
{
using nonref = typename ::std::remove_reference<ValueType>::type;
#ifndef NDEBUG
auto const result(any_cast<nonref>(&operand));
if (result)
{
return *result;
}
else
{
throw ::std::bad_cast();
}
#else
return *unsafe_any_cast<nonref>(&operand);
#endif // NDEBUG
}
template<typename ValueType>
inline ValueType any_cast(any const& operand)
{
using nonref = typename ::std::remove_reference<ValueType>::type;
return any_cast<nonref const&>(const_cast<any&>(operand));
}
}
#endif // ANY_HPP
<|endoftext|>
|
<commit_before>namespace bmi {
const int BMI_SUCCESS = 0;
const int BMI_FAILURE = 1;
const int MAX_COMPONENT_NAME = 2048;
const int MAX_VAR_NAME = 2048;
const int MAX_UNITS_NAME = 2048;
const int MAX_TYPE_NAME = 2048;
class Bmi {
public:
// Model control functions.
virtual void Initialize(std::string config_file) = 0;
virtual void Update() = 0;
virtual void UpdateUntil(double time) = 0;
virtual void Finalize() = 0;
// Model information functions.
virtual std::string GetComponentName() = 0;
virtual int GetInputItemCount() = 0;
virtual int GetOutputItemCount() = 0;
virtual void GetInputVarNames(std::vector<std::string>&) = 0;
virtual void GetOutputVarNames(std::vector<std::string>&) = 0;
// Variable information functions
virtual int GetVarGrid(std::string name) = 0;
virtual std::string GetVarType(std::string name) = 0;
virtual std::string GetVarUnits(std::string name) = 0;
virtual int GetVarItemsize(std::string name) = 0;
virtual int GetVarNbytes(std::string name) = 0;
virtual std::string GetVarLocation(std::string name) = 0;
virtual double GetCurrentTime() = 0;
virtual double GetStartTime() = 0;
virtual double GetEndTime() = 0;
virtual std::string GetTimeUnits() = 0;
virtual double GetTimeStep() = 0;
// Variable getters
virtual void GetValue(std::string name, void *dest) = 0;
virtual void *GetValuePtr(std::string name) = 0;
virtual void GetValueAtIndices(std::string name, void *dest, int *inds, int count) = 0;
// Variable setters
virtual void SetValue(std::string name, void *src) = 0;
virtual void SetValueAtIndices(std::string name, int *inds, int count, void *src) = 0;
// Grid information functions
virtual int GetGridRank(const int grid) = 0;
virtual int GetGridSize(const int grid) = 0;
virtual std::string GetGridType(const int grid) = 0;
virtual void GetGridShape(const int grid, int *shape) = 0;
virtual void GetGridSpacing(const int grid, double *spacing) = 0;
virtual void GetGridOrigin(const int grid, double *origin) = 0;
virtual void GetGridX(const int grid, double *x) = 0;
virtual void GetGridY(const int grid, double *y) = 0;
virtual void GetGridZ(const int grid, double *z) = 0;
virtual int GetGridNodeCount(const int grid) = 0;
virtual int GetGridEdgeCount(const int grid) = 0;
virtual int GetGridFaceCount(const int grid) = 0;
virtual void GetGridEdgeNodes(const int grid, int *edge_nodes) = 0;
virtual void GetGridFaceEdges(const int grid, int *face_edges) = 0;
virtual void GetGridFaceNodes(const int grid, int *face_nodes) = 0;
virtual void GetGridNodesPerFace(const int grid, int *nodes_per_face) = 0;
};
}
<commit_msg>Eliminate parameter, instead returning vector of strings<commit_after>namespace bmi {
const int BMI_SUCCESS = 0;
const int BMI_FAILURE = 1;
const int MAX_COMPONENT_NAME = 2048;
const int MAX_VAR_NAME = 2048;
const int MAX_UNITS_NAME = 2048;
const int MAX_TYPE_NAME = 2048;
class Bmi {
public:
// Model control functions.
virtual void Initialize(std::string config_file) = 0;
virtual void Update() = 0;
virtual void UpdateUntil(double time) = 0;
virtual void Finalize() = 0;
// Model information functions.
virtual std::string GetComponentName() = 0;
virtual int GetInputItemCount() = 0;
virtual int GetOutputItemCount() = 0;
virtual std::vector<std::string> GetInputVarNames() = 0;
virtual std::vector<std::string> GetOutputVarNames() = 0;
// Variable information functions
virtual int GetVarGrid(std::string name) = 0;
virtual std::string GetVarType(std::string name) = 0;
virtual std::string GetVarUnits(std::string name) = 0;
virtual int GetVarItemsize(std::string name) = 0;
virtual int GetVarNbytes(std::string name) = 0;
virtual std::string GetVarLocation(std::string name) = 0;
virtual double GetCurrentTime() = 0;
virtual double GetStartTime() = 0;
virtual double GetEndTime() = 0;
virtual std::string GetTimeUnits() = 0;
virtual double GetTimeStep() = 0;
// Variable getters
virtual void GetValue(std::string name, void *dest) = 0;
virtual void *GetValuePtr(std::string name) = 0;
virtual void GetValueAtIndices(std::string name, void *dest, int *inds, int count) = 0;
// Variable setters
virtual void SetValue(std::string name, void *src) = 0;
virtual void SetValueAtIndices(std::string name, int *inds, int count, void *src) = 0;
// Grid information functions
virtual int GetGridRank(const int grid) = 0;
virtual int GetGridSize(const int grid) = 0;
virtual std::string GetGridType(const int grid) = 0;
virtual void GetGridShape(const int grid, int *shape) = 0;
virtual void GetGridSpacing(const int grid, double *spacing) = 0;
virtual void GetGridOrigin(const int grid, double *origin) = 0;
virtual void GetGridX(const int grid, double *x) = 0;
virtual void GetGridY(const int grid, double *y) = 0;
virtual void GetGridZ(const int grid, double *z) = 0;
virtual int GetGridNodeCount(const int grid) = 0;
virtual int GetGridEdgeCount(const int grid) = 0;
virtual int GetGridFaceCount(const int grid) = 0;
virtual void GetGridEdgeNodes(const int grid, int *edge_nodes) = 0;
virtual void GetGridFaceEdges(const int grid, int *face_edges) = 0;
virtual void GetGridFaceNodes(const int grid, int *face_nodes) = 0;
virtual void GetGridNodesPerFace(const int grid, int *nodes_per_face) = 0;
};
}
<|endoftext|>
|
<commit_before>// Calculates the size of a C-style array
int a[5];
std::cout << "Size: " << sizeof(a)/sizeof(*a) << std::endl;
<commit_msg>-Fast sigmoid is added<commit_after>// Calculates the size of a C-style array
int a[5];
std::cout << "Size: " << sizeof(a)/sizeof(*a) << std::endl;
// Fast sigmoid f(x) = x / (1 + abs(x))
double fastSigmoid(double in){
return in / (1.0 + (in < 0.0 ? -in : in));
}
<|endoftext|>
|
<commit_before>/***************************************************************************
* Copyright (c) 2013 Jan Rheinländer *
* <jrheinlaender@users.sourceforge.net> *
* *
* This file is part of the FreeCAD CAx development system. *
* *
* This library is free software; you can redistribute it and/or *
* modify it under the terms of the GNU Library General Public *
* License as published by the Free Software Foundation; either *
* version 2 of the License, or (at your option) any later version. *
* *
* This library is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU Library General Public License for more details. *
* *
* You should have received a copy of the GNU Library General Public *
* License along with this library; see the file COPYING.LIB. If not, *
* write to the Free Software Foundation, Inc., 59 Temple Place, *
* Suite 330, Boston, MA 02111-1307, USA *
* *
***************************************************************************/
#include "PreCompiled.h"
#ifndef _PreComp_
# include <sstream>
# include <QRegExp>
# include <QTextStream>
# include <Precision.hxx>
#endif
#include <Base/Console.h>
#include <App/Application.h>
#include <App/Document.h>
#include <App/Origin.h>
#include <App/OriginFeature.h>
#include <Gui/Application.h>
#include <Gui/Document.h>
#include <Gui/BitmapFactory.h>
#include <Gui/ViewProvider.h>
#include <Gui/WaitCursor.h>
#include <Gui/Selection.h>
#include <Gui/Command.h>
#include <Mod/Part/App/DatumFeature.h>
#include <Mod/PartDesign/App/FeatureSketchBased.h>
#include <Mod/Sketcher/App/SketchObject.h>
#include <Mod/PartDesign/App/Body.h>
#include "Utils.h"
#include "ReferenceSelection.h"
#include "TaskSketchBasedParameters.h"
using namespace PartDesignGui;
using namespace Gui;
/* TRANSLATOR PartDesignGui::TaskSketchBasedParameters */
TaskSketchBasedParameters::TaskSketchBasedParameters(PartDesignGui::ViewProvider *vp, QWidget *parent,
const std::string& pixmapname, const QString& parname)
: TaskFeatureParameters(vp, parent, pixmapname, parname)
{
}
const QString TaskSketchBasedParameters::onAddSelection(const Gui::SelectionChanges& msg)
{
// Note: The validity checking has already been done in ReferenceSelection.cpp
PartDesign::ProfileBased* pcSketchBased = static_cast<PartDesign::ProfileBased*>(vp->getObject());
App::DocumentObject* selObj = pcSketchBased->getDocument()->getObject(msg.pObjectName);
if (selObj == pcSketchBased)
return QString();
std::string subname = msg.pSubName;
QString refStr;
// Remove subname for planes and datum features
if (PartDesign::Feature::isDatum(selObj)) {
subname = "";
refStr = QString::fromLatin1(selObj->getNameInDocument());
} else if (subname.size() > 4) {
int faceId = std::atoi(&subname[4]);
refStr = QString::fromLatin1(selObj->getNameInDocument()) + QString::fromLatin1(":") + QObject::tr("Face") + QString::number(faceId);
}
std::vector<std::string> upToFaces(1,subname);
pcSketchBased->UpToFace.setValue(selObj, upToFaces);
recomputeFeature();
return refStr;
}
void TaskSketchBasedParameters::onSelectReference(const bool pressed, const bool edge, const bool face, const bool planar) {
// Note: Even if there is no solid, App::Plane and Part::Datum can still be selected
PartDesign::ProfileBased* pcSketchBased = dynamic_cast<PartDesign::ProfileBased*>(vp->getObject());
if (pcSketchBased) {
// The solid this feature will be fused to
App::DocumentObject* prevSolid = pcSketchBased->getBaseObject( /* silent =*/ true );
if (pressed) {
Gui::Document* doc = vp->getDocument();
if (doc) {
doc->setHide(pcSketchBased->getNameInDocument());
if (prevSolid)
doc->setShow(prevSolid->getNameInDocument());
}
Gui::Selection().clearSelection();
Gui::Selection().addSelectionGate
(new ReferenceSelection(prevSolid, edge, face, planar));
} else {
Gui::Selection().rmvSelectionGate();
Gui::Document* doc = vp->getDocument();
if (doc) {
doc->setShow(pcSketchBased->getNameInDocument());
if (prevSolid)
doc->setHide(prevSolid->getNameInDocument());
}
}
}
}
void TaskSketchBasedParameters::exitSelectionMode()
{
onSelectReference(false, false, false, false);
}
QVariant TaskSketchBasedParameters::setUpToFace(const QString& text)
{
if (text.isEmpty())
return QVariant();
QStringList parts = text.split(QChar::fromLatin1(':'));
if (parts.length() < 2)
parts.push_back(QString::fromLatin1(""));
// Check whether this is the name of an App::Plane or Part::Datum feature
App::DocumentObject* obj = vp->getObject()->getDocument()->getObject(parts[0].toLatin1());
if (obj == NULL)
return QVariant();
if (obj->getTypeId().isDerivedFrom(App::Plane::getClassTypeId())) {
// everything is OK (we assume a Part can only have exactly 3 App::Plane objects located at the base of the feature tree)
return QVariant();
}
else if (obj->getTypeId().isDerivedFrom(Part::Datum::getClassTypeId())) {
// it's up to the document to check that the datum plane is in the same body
return QVariant();
}
else {
// We must expect that "parts[1]" is the translation of "Face" followed by an ID.
QString name;
QTextStream str(&name);
str << "^" << tr("Face") << "(\\d+)$";
QRegExp rx(name);
if (parts[1].indexOf(rx) < 0) {
return QVariant();
}
int faceId = rx.cap(1).toInt();
std::stringstream ss;
ss << "Face" << faceId;
std::vector<std::string> upToFaces(1,ss.str());
PartDesign::ProfileBased* pcSketchBased = static_cast<PartDesign::ProfileBased*>(vp->getObject());
pcSketchBased->UpToFace.setValue(obj, upToFaces);
recomputeFeature();
return QByteArray(ss.str().c_str());
}
}
QVariant TaskSketchBasedParameters::objectNameByLabel(const QString& label,
const QVariant& suggest) const
{
// search for an object with the given label
App::Document* doc = this->vp->getObject()->getDocument();
// for faster access try the suggestion
if (suggest.isValid()) {
App::DocumentObject* obj = doc->getObject(suggest.toByteArray());
if (obj && QString::fromUtf8(obj->Label.getValue()) == label) {
return QVariant(QByteArray(obj->getNameInDocument()));
}
}
// go through all objects and check the labels
std::string name = label.toUtf8().data();
std::vector<App::DocumentObject*> objs = doc->getObjects();
for (std::vector<App::DocumentObject*>::iterator it = objs.begin(); it != objs.end(); ++it) {
if (name == (*it)->Label.getValue()) {
return QVariant(QByteArray((*it)->getNameInDocument()));
}
}
return QVariant(); // no such feature found
}
QString TaskSketchBasedParameters::getFaceReference(const QString& obj, const QString& sub) const
{
App::Document* doc = this->vp->getObject()->getDocument();
QString o = obj.left(obj.indexOf(QString::fromLatin1(":")));
if (o.isEmpty())
return QString();
return QString::fromLatin1("(App.getDocument(\"%1\").%2, [\"%3\"])")
.arg(QString::fromLatin1(doc->getName()), o, sub);
}
TaskSketchBasedParameters::~TaskSketchBasedParameters()
{
}
//**************************************************************************
//**************************************************************************
// TaskDialog
//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
TaskDlgSketchBasedParameters::TaskDlgSketchBasedParameters(PartDesignGui::ViewProvider *vp)
: TaskDlgFeatureParameters(vp)
{
}
TaskDlgSketchBasedParameters::~TaskDlgSketchBasedParameters()
{
}
//==== calls from the TaskView ===============================================================
bool TaskDlgSketchBasedParameters::accept() {
App::DocumentObject* feature = vp->getObject();
// Make sure the feature is what we are expecting
// Should be fine but you never know...
if ( !feature->getTypeId().isDerivedFrom(PartDesign::ProfileBased::getClassTypeId()) ) {
throw Base::TypeError("Bad object processed in the sketch based dialog.");
}
App::DocumentObject* sketch = static_cast<PartDesign::ProfileBased*>(feature)->Profile.getValue();
FCMD_OBJ_HIDE(sketch);
return TaskDlgFeatureParameters::accept();
}
bool TaskDlgSketchBasedParameters::reject()
{
PartDesign::ProfileBased* pcSketchBased = static_cast<PartDesign::ProfileBased*>(vp->getObject());
// get the Sketch
Sketcher::SketchObject *pcSketch = static_cast<Sketcher::SketchObject*>(pcSketchBased->Profile.getValue());
bool rv;
// rv should be true anyway but to be on the safe side due to further changes better respect it.
rv = TaskDlgFeatureParameters::reject();
// if abort command deleted the object the sketch is visible again.
// The previous one feature already should be made visible
if (!Gui::Application::Instance->getViewProvider(pcSketchBased)) {
// Make the sketch visible
if (pcSketch && Gui::Application::Instance->getViewProvider(pcSketch))
Gui::Application::Instance->getViewProvider(pcSketch)->show();
}
return rv;
}
#include "moc_TaskSketchBasedParameters.cpp"
<commit_msg>PartDesign: make sure to remove selection gate when closing task panel<commit_after>/***************************************************************************
* Copyright (c) 2013 Jan Rheinländer *
* <jrheinlaender@users.sourceforge.net> *
* *
* This file is part of the FreeCAD CAx development system. *
* *
* This library is free software; you can redistribute it and/or *
* modify it under the terms of the GNU Library General Public *
* License as published by the Free Software Foundation; either *
* version 2 of the License, or (at your option) any later version. *
* *
* This library is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU Library General Public License for more details. *
* *
* You should have received a copy of the GNU Library General Public *
* License along with this library; see the file COPYING.LIB. If not, *
* write to the Free Software Foundation, Inc., 59 Temple Place, *
* Suite 330, Boston, MA 02111-1307, USA *
* *
***************************************************************************/
#include "PreCompiled.h"
#ifndef _PreComp_
# include <sstream>
# include <QRegExp>
# include <QTextStream>
# include <Precision.hxx>
#endif
#include <Base/Console.h>
#include <App/Application.h>
#include <App/Document.h>
#include <App/Origin.h>
#include <App/OriginFeature.h>
#include <Gui/Application.h>
#include <Gui/Document.h>
#include <Gui/BitmapFactory.h>
#include <Gui/ViewProvider.h>
#include <Gui/WaitCursor.h>
#include <Gui/Selection.h>
#include <Gui/Command.h>
#include <Mod/Part/App/DatumFeature.h>
#include <Mod/PartDesign/App/FeatureSketchBased.h>
#include <Mod/Sketcher/App/SketchObject.h>
#include <Mod/PartDesign/App/Body.h>
#include "Utils.h"
#include "ReferenceSelection.h"
#include "TaskSketchBasedParameters.h"
using namespace PartDesignGui;
using namespace Gui;
/* TRANSLATOR PartDesignGui::TaskSketchBasedParameters */
TaskSketchBasedParameters::TaskSketchBasedParameters(PartDesignGui::ViewProvider *vp, QWidget *parent,
const std::string& pixmapname, const QString& parname)
: TaskFeatureParameters(vp, parent, pixmapname, parname)
{
}
const QString TaskSketchBasedParameters::onAddSelection(const Gui::SelectionChanges& msg)
{
// Note: The validity checking has already been done in ReferenceSelection.cpp
PartDesign::ProfileBased* pcSketchBased = static_cast<PartDesign::ProfileBased*>(vp->getObject());
App::DocumentObject* selObj = pcSketchBased->getDocument()->getObject(msg.pObjectName);
if (selObj == pcSketchBased)
return QString();
std::string subname = msg.pSubName;
QString refStr;
// Remove subname for planes and datum features
if (PartDesign::Feature::isDatum(selObj)) {
subname = "";
refStr = QString::fromLatin1(selObj->getNameInDocument());
} else if (subname.size() > 4) {
int faceId = std::atoi(&subname[4]);
refStr = QString::fromLatin1(selObj->getNameInDocument()) + QString::fromLatin1(":") + QObject::tr("Face") + QString::number(faceId);
}
std::vector<std::string> upToFaces(1,subname);
pcSketchBased->UpToFace.setValue(selObj, upToFaces);
recomputeFeature();
return refStr;
}
void TaskSketchBasedParameters::onSelectReference(const bool pressed, const bool edge, const bool face, const bool planar) {
// Note: Even if there is no solid, App::Plane and Part::Datum can still be selected
PartDesign::ProfileBased* pcSketchBased = dynamic_cast<PartDesign::ProfileBased*>(vp->getObject());
if (pcSketchBased) {
// The solid this feature will be fused to
App::DocumentObject* prevSolid = pcSketchBased->getBaseObject( /* silent =*/ true );
if (pressed) {
Gui::Document* doc = vp->getDocument();
if (doc) {
doc->setHide(pcSketchBased->getNameInDocument());
if (prevSolid)
doc->setShow(prevSolid->getNameInDocument());
}
Gui::Selection().clearSelection();
Gui::Selection().addSelectionGate
(new ReferenceSelection(prevSolid, edge, face, planar));
} else {
Gui::Selection().rmvSelectionGate();
Gui::Document* doc = vp->getDocument();
if (doc) {
doc->setShow(pcSketchBased->getNameInDocument());
if (prevSolid)
doc->setHide(prevSolid->getNameInDocument());
}
}
}
}
void TaskSketchBasedParameters::exitSelectionMode()
{
onSelectReference(false, false, false, false);
}
QVariant TaskSketchBasedParameters::setUpToFace(const QString& text)
{
if (text.isEmpty())
return QVariant();
QStringList parts = text.split(QChar::fromLatin1(':'));
if (parts.length() < 2)
parts.push_back(QString::fromLatin1(""));
// Check whether this is the name of an App::Plane or Part::Datum feature
App::DocumentObject* obj = vp->getObject()->getDocument()->getObject(parts[0].toLatin1());
if (obj == NULL)
return QVariant();
if (obj->getTypeId().isDerivedFrom(App::Plane::getClassTypeId())) {
// everything is OK (we assume a Part can only have exactly 3 App::Plane objects located at the base of the feature tree)
return QVariant();
}
else if (obj->getTypeId().isDerivedFrom(Part::Datum::getClassTypeId())) {
// it's up to the document to check that the datum plane is in the same body
return QVariant();
}
else {
// We must expect that "parts[1]" is the translation of "Face" followed by an ID.
QString name;
QTextStream str(&name);
str << "^" << tr("Face") << "(\\d+)$";
QRegExp rx(name);
if (parts[1].indexOf(rx) < 0) {
return QVariant();
}
int faceId = rx.cap(1).toInt();
std::stringstream ss;
ss << "Face" << faceId;
std::vector<std::string> upToFaces(1,ss.str());
PartDesign::ProfileBased* pcSketchBased = static_cast<PartDesign::ProfileBased*>(vp->getObject());
pcSketchBased->UpToFace.setValue(obj, upToFaces);
recomputeFeature();
return QByteArray(ss.str().c_str());
}
}
QVariant TaskSketchBasedParameters::objectNameByLabel(const QString& label,
const QVariant& suggest) const
{
// search for an object with the given label
App::Document* doc = this->vp->getObject()->getDocument();
// for faster access try the suggestion
if (suggest.isValid()) {
App::DocumentObject* obj = doc->getObject(suggest.toByteArray());
if (obj && QString::fromUtf8(obj->Label.getValue()) == label) {
return QVariant(QByteArray(obj->getNameInDocument()));
}
}
// go through all objects and check the labels
std::string name = label.toUtf8().data();
std::vector<App::DocumentObject*> objs = doc->getObjects();
for (std::vector<App::DocumentObject*>::iterator it = objs.begin(); it != objs.end(); ++it) {
if (name == (*it)->Label.getValue()) {
return QVariant(QByteArray((*it)->getNameInDocument()));
}
}
return QVariant(); // no such feature found
}
QString TaskSketchBasedParameters::getFaceReference(const QString& obj, const QString& sub) const
{
App::Document* doc = this->vp->getObject()->getDocument();
QString o = obj.left(obj.indexOf(QString::fromLatin1(":")));
if (o.isEmpty())
return QString();
return QString::fromLatin1("(App.getDocument(\"%1\").%2, [\"%3\"])")
.arg(QString::fromLatin1(doc->getName()), o, sub);
}
TaskSketchBasedParameters::~TaskSketchBasedParameters()
{
Gui::Selection().rmvSelectionGate();
}
//**************************************************************************
//**************************************************************************
// TaskDialog
//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
TaskDlgSketchBasedParameters::TaskDlgSketchBasedParameters(PartDesignGui::ViewProvider *vp)
: TaskDlgFeatureParameters(vp)
{
}
TaskDlgSketchBasedParameters::~TaskDlgSketchBasedParameters()
{
}
//==== calls from the TaskView ===============================================================
bool TaskDlgSketchBasedParameters::accept() {
App::DocumentObject* feature = vp->getObject();
// Make sure the feature is what we are expecting
// Should be fine but you never know...
if ( !feature->getTypeId().isDerivedFrom(PartDesign::ProfileBased::getClassTypeId()) ) {
throw Base::TypeError("Bad object processed in the sketch based dialog.");
}
App::DocumentObject* sketch = static_cast<PartDesign::ProfileBased*>(feature)->Profile.getValue();
FCMD_OBJ_HIDE(sketch);
return TaskDlgFeatureParameters::accept();
}
bool TaskDlgSketchBasedParameters::reject()
{
PartDesign::ProfileBased* pcSketchBased = static_cast<PartDesign::ProfileBased*>(vp->getObject());
// get the Sketch
Sketcher::SketchObject *pcSketch = static_cast<Sketcher::SketchObject*>(pcSketchBased->Profile.getValue());
bool rv;
// rv should be true anyway but to be on the safe side due to further changes better respect it.
rv = TaskDlgFeatureParameters::reject();
// if abort command deleted the object the sketch is visible again.
// The previous one feature already should be made visible
if (!Gui::Application::Instance->getViewProvider(pcSketchBased)) {
// Make the sketch visible
if (pcSketch && Gui::Application::Instance->getViewProvider(pcSketch))
Gui::Application::Instance->getViewProvider(pcSketch)->show();
}
return rv;
}
#include "moc_TaskSketchBasedParameters.cpp"
<|endoftext|>
|
<commit_before>// returns success if stdin or the argument is a complete datafile
#include "rdb.hpp"
#include "../utils/utils.hpp"
#include <cerrno>
// from datafile.cc
extern const char *start4;
extern const char *end4;
int main(int argc, char *argv[]) {
FILE *in = stdin;
if (argc == 2) {
if (!fileexists(argv[1]))
return 1;
in = fopen(argv[1], "r");
if (!in)
fatalx(errno, "failed to open %s for reading", argv[1]);
}
boost::optional<std::string> l = readline(in);
if (l && *l != start4)
return 1;
std::string prev;
while (l) {
prev = *l;
l = readline(in);
}
if (prev != end4)
return 1;
return 0;
}<commit_msg>rdb: fix bug in dfcmplt.<commit_after>// returns success if stdin or the argument is a complete datafile
#include "rdb.hpp"
#include "../utils/utils.hpp"
#include <cerrno>
// from datafile.cc
extern const char *start4;
extern const char *end4;
int main(int argc, char *argv[]) {
FILE *in = stdin;
if (argc == 2) {
if (!fileexists(argv[1]))
return 1;
in = fopen(argv[1], "r");
if (!in)
fatalx(errno, "failed to open %s for reading", argv[1]);
}
boost::optional<std::string> l = readline(in);
if (!l)
return 1;
l->push_back('\n');
if (*l != start4)
return 1;
std::string prev;
while (l) {
prev = *l;
l = readline(in);
}
prev.push_back('\n');
if (prev != end4)
return 1;
return 0;
}<|endoftext|>
|
<commit_before>#include "stdafx.h"
#include "Formula.h"
#include "Actions.h"
#include "Parser.h"
#include "PropertyBag.h"
#include "TokenPool.h"
#include "EventHandler.h"
#include "Scriptable.h"
#include "ScriptWorld.h"
#include "DeserializerFactory.h"
#include "../GameEngine/Map.h"
#include "../GameEngine/Unit.h"
#include "../GameEngine/SubMap.h"
namespace Simulation {
void SimulationRunKingdomWar() {
const unsigned worldWidth = 20;
const unsigned worldHeight = 20;
const unsigned cellWidth = 20;
const unsigned cellHeight = 20;
Map worldMap(worldWidth, worldHeight);
for(unsigned x = 0; x < worldWidth; ++x) {
for(unsigned y = 0; y < worldHeight; ++y) {
SubMap * cell = new SubMap(cellWidth, cellHeight, x, y);
worldMap.AddUnit(cell);
}
}
ScriptWorld world;
DeserializerFactory factory;
factory.LoadFileIntoScriptWorld("Data\\KingdomWar.json", &world);
world.QueueBroadcastEvent("OnCreate");
while(world.DispatchEvents());
world.DumpOverview();
}
}
<commit_msg>Fix build break<commit_after>#include "stdafx.h"
#include "Formula.h"
#include "Actions.h"
#include "Parser.h"
#include "PropertyBag.h"
#include "TokenPool.h"
#include "EventHandler.h"
#include "Scriptable.h"
#include "ScriptWorld.h"
#include "DeserializerFactory.h"
#include "../GameEngine/Map.h"
#include "../GameEngine/Unit.h"
#include "../GameEngine/SubMap.h"
namespace Simulation {
void RunKingdomWar() {
const unsigned worldWidth = 20;
const unsigned worldHeight = 20;
const unsigned cellWidth = 20;
const unsigned cellHeight = 20;
Map worldMap(worldWidth, worldHeight);
for(unsigned x = 0; x < worldWidth; ++x) {
for(unsigned y = 0; y < worldHeight; ++y) {
SubMap * cell = new SubMap(cellWidth, cellHeight, x, y);
worldMap.AddUnit(cell);
}
}
ScriptWorld world;
DeserializerFactory factory;
factory.LoadFileIntoScriptWorld("Data\\KingdomWar.json", &world);
world.QueueBroadcastEvent("OnCreate");
while(world.DispatchEvents());
world.DumpOverview();
}
}
<|endoftext|>
|
<commit_before>#include "cartrige.h"
struct rom_header
{
u8 start_vector[4];
u8 nintendo_logo[48];
u8 game_title[11];
u8 manufacturer_code[4];
u8 cgb_flag;
u8 new_license_code[2];
u8 sgb_flag;
u8 cartrige_type;
u8 rom_size;
u8 ram_size;
u8 destination_code;
u8 old_license_code;
u8 rom_version;
u8 checksum;
u8 global_checksum[2];
};
bool in_range(u32 value, u32 begin, u32 end)
{
return (value >= begin) && (value <= end);
}
void Cartrige::attach_rom(const u8* rom_ptr, u32 size)
{
rom2 = std::make_pair(rom_ptr, size);
}
void Cartrige::attach_ram(u8* ram_ptr, u32 size)
{
ram2 = std::make_pair(ram_ptr, size);
}
void Cartrige::attach_rtc(u8* rtc_ptr, u32 size)
{
rtc2 = std::make_pair(rtc_ptr, size);
}
bool Cartrige::has_battery_ram() const
{
if (std::get<0>(rom2) == nullptr)
return false;
const rom_header* header = reinterpret_cast<const rom_header*>(&std::get<0>(rom2)[0x100]);
switch (header->cartrige_type)
{
case 0x03:
case 0x06:
case 0x09:
case 0x0D:
case 0x0F:
case 0x10:
case 0x13:
case 0x1B:
case 0x1E:
return true;
default:
return false;
}
}
u32 Cartrige::get_declared_ram_size() const
{
static const u32 sizes[] = { 0, 0x800, 0x2000, 0x8000, 0x20000, 0x10000 };
if (std::get<0>(rom2) == nullptr)
return 0;
const rom_header* header = reinterpret_cast<const rom_header*>(&std::get<0>(rom2)[0x100]);
//MBC2 has always header->ram_size == 0, but it has 512 bytes actually!
if (in_range(header->cartrige_type, 0x05, 0x06))
return 512;
else
return (header->ram_size > 5) ? 0 : sizes[header->ram_size];
}
bool Cartrige::has_rtc() const
{
if (std::get<0>(rom2) == nullptr)
return false;
const rom_header* header = reinterpret_cast<const rom_header*>(&std::get<0>(rom2)[0x100]);
return in_range(header->cartrige_type, 0xF, 0x10);
}
Cartrige::~Cartrige()
{
const rom_header* header = reinterpret_cast<rom_header*>(&rom[0x100]);
if (battery_ram)
save_ram_callback(ram.get(), ram_size);
if (in_range(header->cartrige_type, 0x0F, 0x10))
{
memory_interface.reset(); //make sure that MBC3 update rtc_regs
auto epoch = std::chrono::system_clock::now().time_since_epoch();
auto cur_timestamp = std::chrono::duration_cast<std::chrono::seconds>(epoch);
save_rtc_callback(cur_timestamp, rtc_regs, 5);
}
}
bool Cartrige::load_cartrige(std::ifstream& cart, std::ifstream& ram, std::ifstream& rtc)
{
if (!cart.is_open())
return false;
cart.seekg(0, std::ios_base::end);
size_t size = cart.tellg();
cart.seekg(0, std::ios_base::beg);
rom = std::make_unique<u8[]>(size);
cart.read(reinterpret_cast<char*>(rom.get()), size);
attach_rom(rom.get(), size);
load_or_create_ram(ram);
load_rtc(rtc);
dispatch();
return true;
}
std::string Cartrige::get_name() const
{
const rom_header* header = reinterpret_cast<rom_header*>(&rom[0x100]);
return std::string(std::begin(header->game_title), std::end(header->game_title));
}
void Cartrige::attach_endpoints(function<void(const u8*, u32)> ram_save, function<void(std::chrono::seconds, const u8*, u32)> rtc_save)
{
save_ram_callback = ram_save;
save_rtc_callback = rtc_save;
}
void Cartrige::load_or_create_ram(std::ifstream& ram_file)
{
ram_size = get_declared_ram_size();
ram = ram_size ? std::make_unique<u8[]>(ram_size) : nullptr;
battery_ram = has_battery_ram();
if (battery_ram && ram_file.is_open())
ram_file.read(reinterpret_cast<char*>(ram.get()), ram_size);
}
void Cartrige::load_rtc(std::ifstream& rtc_file)
{
if (has_rtc() && rtc_file.is_open())
{
i64 saved_timestamp;
rtc_file >> saved_timestamp;
rtc_file.read(reinterpret_cast<char*>(rtc_regs), sizeof(u8) * 5);
auto epoch = std::chrono::system_clock::now().time_since_epoch();
auto cur_timestamp = std::chrono::duration_cast<std::chrono::seconds>(epoch);
auto delta = cur_timestamp.count() - saved_timestamp;
if (delta <= 0 || check_bit(rtc_regs[4], 6))
return;
auto ns = rtc_regs[0] + delta;
auto nm = rtc_regs[1] + ns / 60;
auto nh = rtc_regs[2] + nm / 60;
auto nd = (((rtc_regs[4] & 1) << 8) | rtc_regs[3]) + nh / 24;
rtc_regs[0] = ns % 60;
rtc_regs[1] = nm % 60;
rtc_regs[2] = nh % 24;
rtc_regs[3] = (nd % 512) & 0xFF;
rtc_regs[4] = change_bit(rtc_regs[4], (nd % 512) > 255, 0);
rtc_regs[4] = change_bit(rtc_regs[4], nd > 511, 7);
}
}
IMemory* Cartrige::get_memory_controller() const
{
return memory_interface.get();
}
IDmaMemory* Cartrige::get_dma_controller() const
{
return dma_interface;
}
bool Cartrige::is_cgb_ready() const
{
const rom_header* header = reinterpret_cast<rom_header*>(&rom[0x100]);
return (header->cgb_flag == 0x80) || (header->cgb_flag == 0xC0);
}
void Cartrige::serialize(std::ostream& stream)
{
//TODO: update rtc regs before serialization
stream << battery_ram << ram_size;
stream.write(reinterpret_cast<char*>(ram.get()), sizeof(u8) * ram_size);
stream.write(reinterpret_cast<char*>(rtc_regs), sizeof(u8) * 5);
}
void Cartrige::deserialize(std::istream & stream)
{
stream >> battery_ram >> ram_size;
stream.read(reinterpret_cast<char*>(ram.get()), sizeof(u8) * ram_size);
stream.read(reinterpret_cast<char*>(rtc_regs), sizeof(u8) * 5);
}
void Cartrige::dispatch()
{
rom_header* header = reinterpret_cast<rom_header*>(&rom[0x100]);
const u8 type = header->cartrige_type;
const u32 rom_banks = 2 << header->rom_size;
if (type == 0x00 || type == 0x08 || type == 0x09)
{
auto tmp = std::make_unique<NoMBC>(NoMBC(rom.get(), ram.get(), ram_size));
dma_interface = tmp.get();
memory_interface = std::move(tmp);
}
else if (in_range(type, 0x01, 0x03))
{
auto tmp = std::make_unique<MBC1>(MBC1(rom.get(), ram.get(), rom_banks, ram_size));
dma_interface = tmp.get();
memory_interface = std::move(tmp);
}
else if (in_range(type, 0x05, 0x06))
{
auto tmp = std::make_unique<MBC2>(MBC2(rom.get(), ram.get(), rom_banks, ram_size));
dma_interface = tmp.get();
memory_interface = std::move(tmp);
}
else if (in_range(type, 0x0F, 0x13))
{
auto tmp = std::make_unique<MBC3>(MBC3(rom.get(), ram.get(), (type <= 0x10 ? rtc_regs : nullptr), rom_banks, ram_size));
dma_interface = tmp.get();
memory_interface = std::move(tmp);
}
else if (in_range(type, 0x19, 0x1E))
{
auto tmp = std::make_unique<MBC5>(MBC5(rom.get(), ram.get(), rom_banks, ram_size));
dma_interface = tmp.get();
memory_interface = std::move(tmp);
}
else
memory_interface = nullptr;
//TODO: inform somehow that there is some unknown MBC
}
<commit_msg>changed mbc dispatching<commit_after>#include "cartrige.h"
struct rom_header
{
u8 start_vector[4];
u8 nintendo_logo[48];
u8 game_title[11];
u8 manufacturer_code[4];
u8 cgb_flag;
u8 new_license_code[2];
u8 sgb_flag;
u8 cartrige_type;
u8 rom_size;
u8 ram_size;
u8 destination_code;
u8 old_license_code;
u8 rom_version;
u8 checksum;
u8 global_checksum[2];
};
bool in_range(u32 value, u32 begin, u32 end)
{
return (value >= begin) && (value <= end);
}
void Cartrige::attach_rom(const u8* rom_ptr, u32 size)
{
rom2 = std::make_pair(rom_ptr, size);
}
void Cartrige::attach_ram(u8* ram_ptr, u32 size)
{
ram2 = std::make_pair(ram_ptr, size);
}
void Cartrige::attach_rtc(u8* rtc_ptr, u32 size)
{
rtc2 = std::make_pair(rtc_ptr, size);
}
bool Cartrige::has_battery_ram() const
{
if (std::get<0>(rom2) == nullptr)
return false;
const rom_header* header = reinterpret_cast<const rom_header*>(&std::get<0>(rom2)[0x100]);
switch (header->cartrige_type)
{
case 0x03:
case 0x06:
case 0x09:
case 0x0D:
case 0x0F:
case 0x10:
case 0x13:
case 0x1B:
case 0x1E:
return true;
default:
return false;
}
}
u32 Cartrige::get_declared_ram_size() const
{
static const u32 sizes[] = { 0, 0x800, 0x2000, 0x8000, 0x20000, 0x10000 };
if (std::get<0>(rom2) == nullptr)
return 0;
const rom_header* header = reinterpret_cast<const rom_header*>(&std::get<0>(rom2)[0x100]);
//MBC2 has always header->ram_size == 0, but it has 512 bytes actually!
if (in_range(header->cartrige_type, 0x05, 0x06))
return 512;
else
return (header->ram_size > 5) ? 0 : sizes[header->ram_size];
}
bool Cartrige::has_rtc() const
{
if (std::get<0>(rom2) == nullptr)
return false;
const rom_header* header = reinterpret_cast<const rom_header*>(&std::get<0>(rom2)[0x100]);
return in_range(header->cartrige_type, 0xF, 0x10);
}
Cartrige::~Cartrige()
{
const rom_header* header = reinterpret_cast<rom_header*>(&rom[0x100]);
if (battery_ram)
save_ram_callback(ram.get(), ram_size);
if (in_range(header->cartrige_type, 0x0F, 0x10))
{
memory_interface.reset(); //make sure that MBC3 update rtc_regs
auto epoch = std::chrono::system_clock::now().time_since_epoch();
auto cur_timestamp = std::chrono::duration_cast<std::chrono::seconds>(epoch);
save_rtc_callback(cur_timestamp, rtc_regs, 5);
}
}
bool Cartrige::load_cartrige(std::ifstream& cart, std::ifstream& ram, std::ifstream& rtc)
{
if (!cart.is_open())
return false;
cart.seekg(0, std::ios_base::end);
size_t size = cart.tellg();
cart.seekg(0, std::ios_base::beg);
rom = std::make_unique<u8[]>(size);
cart.read(reinterpret_cast<char*>(rom.get()), size);
attach_rom(rom.get(), size);
load_or_create_ram(ram);
load_rtc(rtc);
dispatch();
return true;
}
std::string Cartrige::get_name() const
{
const rom_header* header = reinterpret_cast<rom_header*>(&rom[0x100]);
return std::string(std::begin(header->game_title), std::end(header->game_title));
}
void Cartrige::attach_endpoints(function<void(const u8*, u32)> ram_save, function<void(std::chrono::seconds, const u8*, u32)> rtc_save)
{
save_ram_callback = ram_save;
save_rtc_callback = rtc_save;
}
void Cartrige::load_or_create_ram(std::ifstream& ram_file)
{
ram_size = get_declared_ram_size();
ram = ram_size ? std::make_unique<u8[]>(ram_size) : nullptr;
battery_ram = has_battery_ram();
if (battery_ram && ram_file.is_open())
ram_file.read(reinterpret_cast<char*>(ram.get()), ram_size);
}
void Cartrige::load_rtc(std::ifstream& rtc_file)
{
if (has_rtc() && rtc_file.is_open())
{
i64 saved_timestamp;
rtc_file >> saved_timestamp;
rtc_file.read(reinterpret_cast<char*>(rtc_regs), sizeof(u8) * 5);
auto epoch = std::chrono::system_clock::now().time_since_epoch();
auto cur_timestamp = std::chrono::duration_cast<std::chrono::seconds>(epoch);
auto delta = cur_timestamp.count() - saved_timestamp;
if (delta <= 0 || check_bit(rtc_regs[4], 6))
return;
auto ns = rtc_regs[0] + delta;
auto nm = rtc_regs[1] + ns / 60;
auto nh = rtc_regs[2] + nm / 60;
auto nd = (((rtc_regs[4] & 1) << 8) | rtc_regs[3]) + nh / 24;
rtc_regs[0] = ns % 60;
rtc_regs[1] = nm % 60;
rtc_regs[2] = nh % 24;
rtc_regs[3] = (nd % 512) & 0xFF;
rtc_regs[4] = change_bit(rtc_regs[4], (nd % 512) > 255, 0);
rtc_regs[4] = change_bit(rtc_regs[4], nd > 511, 7);
}
}
IMemory* Cartrige::get_memory_controller() const
{
return memory_interface.get();
}
IDmaMemory* Cartrige::get_dma_controller() const
{
return dma_interface;
}
bool Cartrige::is_cgb_ready() const
{
const rom_header* header = reinterpret_cast<rom_header*>(&rom[0x100]);
return (header->cgb_flag == 0x80) || (header->cgb_flag == 0xC0);
}
void Cartrige::serialize(std::ostream& stream)
{
//TODO: update rtc regs before serialization
stream << battery_ram << ram_size;
stream.write(reinterpret_cast<char*>(ram.get()), sizeof(u8) * ram_size);
stream.write(reinterpret_cast<char*>(rtc_regs), sizeof(u8) * 5);
}
void Cartrige::deserialize(std::istream & stream)
{
stream >> battery_ram >> ram_size;
stream.read(reinterpret_cast<char*>(ram.get()), sizeof(u8) * ram_size);
stream.read(reinterpret_cast<char*>(rtc_regs), sizeof(u8) * 5);
}
void Cartrige::dispatch()
{
const u8* rom_ptr = std::get<0>(rom2);
const rom_header* header = reinterpret_cast<const rom_header*>(&rom_ptr[0x100]);
const u8 type = header->cartrige_type;
const u32 rom_banks = 2 << header->rom_size;
if (type == 0x00 || type == 0x08 || type == 0x09)
{
auto tmp = std::make_unique<NoMBC>(NoMBC(rom_ptr, ram.get(), ram_size));
dma_interface = tmp.get();
memory_interface = std::move(tmp);
}
else if (in_range(type, 0x01, 0x03))
{
auto tmp = std::make_unique<MBC1>(MBC1(rom_ptr, ram.get(), rom_banks, ram_size));
dma_interface = tmp.get();
memory_interface = std::move(tmp);
}
else if (in_range(type, 0x05, 0x06))
{
auto tmp = std::make_unique<MBC2>(MBC2(rom_ptr, ram.get(), rom_banks, ram_size));
dma_interface = tmp.get();
memory_interface = std::move(tmp);
}
else if (in_range(type, 0x0F, 0x13))
{
auto tmp = std::make_unique<MBC3>(MBC3(rom_ptr, ram.get(), (type <= 0x10 ? rtc_regs : nullptr), rom_banks, ram_size));
dma_interface = tmp.get();
memory_interface = std::move(tmp);
}
else if (in_range(type, 0x19, 0x1E))
{
auto tmp = std::make_unique<MBC5>(MBC5(rom_ptr, ram.get(), rom_banks, ram_size));
dma_interface = tmp.get();
memory_interface = std::move(tmp);
}
else
memory_interface = nullptr;
//TODO: inform somehow that there is some unknown MBC
}
<|endoftext|>
|
<commit_before><commit_msg>Added _absoluteRotation attribute<commit_after><|endoftext|>
|
<commit_before>/*************************************************************************
*
* $RCSfile: fumeasur.cxx,v $
*
* $Revision: 1.4 $
*
* last change: $Author: rt $ $Date: 2004-08-04 08:54:17 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#pragma hdrstop
#include "fumeasur.hxx"
//CHINA001 #include <svx/measure.hxx>
#ifndef _SV_MSGBOX_HXX //autogen
#include <vcl/msgbox.hxx>
#endif
#ifndef _SFXREQUEST_HXX //autogen
#include <sfx2/request.hxx>
#endif
#ifndef SD_VIEW_HXX
#include "View.hxx"
#endif
#ifndef SD_VIEW_SHELL_HXX
#include "ViewShell.hxx"
#endif
#include "drawdoc.hxx"
#include <svx/svxdlg.hxx> //CHINA001
#include <svx/dialogs.hrc> //CHINA001
namespace sd {
TYPEINIT1( FuMeasureDlg, FuPoor );
/*************************************************************************
|*
|* Konstruktor
|*
\************************************************************************/
FuMeasureDlg::FuMeasureDlg (
ViewShell* pViewSh,
::sd::Window* pWin,
::sd::View* pView,
SdDrawDocument* pDoc,
SfxRequest& rReq)
: FuPoor(pViewSh, pWin, pView, pDoc, rReq)
{
SfxItemSet aNewAttr( pDoc->GetPool() );
pView->GetAttributes( aNewAttr );
const SfxItemSet* pArgs = rReq.GetArgs();
::std::auto_ptr<AbstractSfxSingleTabDialog> pDlg (NULL);
if( !pArgs )
{
//CHINA001 SvxMeasureDialog* pDlg = new SvxMeasureDialog( NULL, aNewAttr, pView );
SvxAbstractDialogFactory* pFact = SvxAbstractDialogFactory::Create();
DBG_ASSERT(pFact, "Dialogdiet Factory fail!");//CHINA001
pDlg.reset (pFact->CreateSfxSingleTabDialog( NULL,
aNewAttr,
pView,
ResId(RID_SVXPAGE_MEASURE)));
DBG_ASSERT(pDlg.get()!=NULL, "Dialogdiet fail!");//CHINA001
USHORT nResult = pDlg->Execute();
switch( nResult )
{
case RET_OK:
{
pArgs = pDlg->GetOutputItemSet();
rReq.Done( *pArgs );
}
break;
default:
return; // Abbruch
}
}
pView->SetAttributes( *pArgs );
}
} // end of namespace sd
<commit_msg>INTEGRATION: CWS ooo19126 (1.4.394); FILE MERGED 2005/09/05 13:22:18 rt 1.4.394.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: fumeasur.cxx,v $
*
* $Revision: 1.5 $
*
* last change: $Author: rt $ $Date: 2005-09-09 04:44:37 $
*
* 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
*
************************************************************************/
#pragma hdrstop
#include "fumeasur.hxx"
//CHINA001 #include <svx/measure.hxx>
#ifndef _SV_MSGBOX_HXX //autogen
#include <vcl/msgbox.hxx>
#endif
#ifndef _SFXREQUEST_HXX //autogen
#include <sfx2/request.hxx>
#endif
#ifndef SD_VIEW_HXX
#include "View.hxx"
#endif
#ifndef SD_VIEW_SHELL_HXX
#include "ViewShell.hxx"
#endif
#include "drawdoc.hxx"
#include <svx/svxdlg.hxx> //CHINA001
#include <svx/dialogs.hrc> //CHINA001
namespace sd {
TYPEINIT1( FuMeasureDlg, FuPoor );
/*************************************************************************
|*
|* Konstruktor
|*
\************************************************************************/
FuMeasureDlg::FuMeasureDlg (
ViewShell* pViewSh,
::sd::Window* pWin,
::sd::View* pView,
SdDrawDocument* pDoc,
SfxRequest& rReq)
: FuPoor(pViewSh, pWin, pView, pDoc, rReq)
{
SfxItemSet aNewAttr( pDoc->GetPool() );
pView->GetAttributes( aNewAttr );
const SfxItemSet* pArgs = rReq.GetArgs();
::std::auto_ptr<AbstractSfxSingleTabDialog> pDlg (NULL);
if( !pArgs )
{
//CHINA001 SvxMeasureDialog* pDlg = new SvxMeasureDialog( NULL, aNewAttr, pView );
SvxAbstractDialogFactory* pFact = SvxAbstractDialogFactory::Create();
DBG_ASSERT(pFact, "Dialogdiet Factory fail!");//CHINA001
pDlg.reset (pFact->CreateSfxSingleTabDialog( NULL,
aNewAttr,
pView,
ResId(RID_SVXPAGE_MEASURE)));
DBG_ASSERT(pDlg.get()!=NULL, "Dialogdiet fail!");//CHINA001
USHORT nResult = pDlg->Execute();
switch( nResult )
{
case RET_OK:
{
pArgs = pDlg->GetOutputItemSet();
rReq.Done( *pArgs );
}
break;
default:
return; // Abbruch
}
}
pView->SetAttributes( *pArgs );
}
} // end of namespace sd
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* $RCSfile: fuprlout.cxx,v $
*
* $Revision: 1.9 $
*
* last change: $Author: kz $ $Date: 2004-10-04 18:33:21 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#pragma hdrstop
#include "fuprlout.hxx"
#ifndef _SV_WRKWIN_HXX
#include <vcl/wrkwin.hxx>
#endif
#ifndef _SFXDISPATCH_HXX //autogen
#include <sfx2/dispatch.hxx>
#endif
#ifndef _SFXSMPLHINT_HXX //autogen
#include <svtools/smplhint.hxx>
#endif
#ifndef _SFXITEMPOOL_HXX //autogen
#include <svtools/itempool.hxx>
#endif
#include <sot/storage.hxx>
#ifndef _SV_MSGBOX_HXX //autogen
#include <vcl/msgbox.hxx>
#endif
#ifndef _SVDUNDO_HXX //autogen
#include <svx/svdundo.hxx>
#endif
#include <sfx2/viewfrm.hxx>
#include "drawdoc.hxx"
#include "sdpage.hxx"
#include "pres.hxx"
#ifndef SD_DRAW_VIEW_SHELL_HXX
#include "DrawViewShell.hxx"
#endif
#ifndef SD_FRAMW_VIEW_HXX
#include "FrameView.hxx"
#endif
#include "stlpool.hxx"
#ifndef SD_VIEW_HXX
#include "View.hxx"
#endif
#include "glob.hrc"
#include "glob.hxx"
#include "strings.hrc"
#include "strmname.h"
#include "app.hrc"
#include "DrawDocShell.hxx"
#include "unprlout.hxx"
#include "unchss.hxx"
#include "unmovss.hxx"
#include "sdattr.hxx"
#include "sdresid.hxx"
//CHINA001 #include "sdpreslt.hxx"
#ifndef SD_DRAW_VIEW_HXX
#include "drawview.hxx"
#endif
#include "eetext.hxx"
#include <svx/editdata.hxx>
#include "sdabstdlg.hxx" //CHINA001
#include "sdpreslt.hrc" //CHINA001
namespace sd {
#ifndef SO2_DECL_SVSTORAGE_DEFINED
#define SO2_DECL_SVSTORAGE_DEFINED
SO2_DECL_REF(SvStorage)
#endif
TYPEINIT1( FuPresentationLayout, FuPoor );
#define POOL_BUFFER_SIZE (USHORT)32768
#define DOCUMENT_BUFFER_SIZE (USHORT)32768
#define DOCUMENT_TOKEN (sal_Unicode('#'))
/*************************************************************************
|*
|* Konstruktor
|*
\************************************************************************/
FuPresentationLayout::FuPresentationLayout (
ViewShell* pViewSh,
::sd::Window* pWin,
::sd::View* pView,
SdDrawDocument* pDoc,
SfxRequest& rReq)
: FuPoor(pViewSh, pWin, pView, pDoc, rReq)
{
// damit nicht Objekte, die gerade editiert werden oder selektiert
// sind , verschwinden
pView->EndTextEdit();
USHORT nPgViewCount = pView->GetPageViewCount();
for (USHORT nPgView = 0; nPgView < nPgViewCount; nPgView++)
{
pView->UnmarkAll();
}
BOOL bError = FALSE;
// die aktive Seite ermitteln
USHORT nSelectedPage = SDRPAGE_NOTFOUND;
for (USHORT nPage = 0; nPage < pDoc->GetSdPageCount(PK_STANDARD); nPage++)
{
if (pDoc->GetSdPage(nPage, PK_STANDARD)->IsSelected())
{
nSelectedPage = nPage;
break;
}
}
DBG_ASSERT(nSelectedPage != SDRPAGE_NOTFOUND, "keine selektierte Seite");
SdPage* pSelectedPage = pDoc->GetSdPage(nSelectedPage, PK_STANDARD);
String aOldPageLayoutName(pSelectedPage->GetLayoutName());
String aOldLayoutName(aOldPageLayoutName);
aOldLayoutName.Erase(aOldLayoutName.SearchAscii(SD_LT_SEPARATOR));
// wenn wir auf einer Masterpage sind, gelten die Aenderungen fuer alle
// Seiten und Notizseiten, die das betreffende Layout benutzen
BOOL bOnMaster = FALSE;
if (pViewSh->ISA(DrawViewShell))
{
EditMode eEditMode =
static_cast<DrawViewShell*>(pViewSh)->GetEditMode();
if (eEditMode == EM_MASTERPAGE)
bOnMaster = TRUE;
}
BOOL bMasterPage = bOnMaster;
BOOL bCheckMasters = FALSE;
// Dialog aufrufen
BOOL bLoad = FALSE; // tauchen neue Masterpages auf?
String aFile;
SfxItemSet aSet(pDoc->GetPool(), ATTR_PRESLAYOUT_START, ATTR_PRESLAYOUT_END);
aSet.Put( SfxBoolItem( ATTR_PRESLAYOUT_LOAD, bLoad));
aSet.Put( SfxBoolItem( ATTR_PRESLAYOUT_MASTER_PAGE, bMasterPage ) );
aSet.Put( SfxBoolItem( ATTR_PRESLAYOUT_CHECK_MASTERS, bCheckMasters ) );
aSet.Put( SfxStringItem( ATTR_PRESLAYOUT_NAME, aOldLayoutName));
//CHINA001 SdPresLayoutDlg* pDlg = new SdPresLayoutDlg( pDocSh, pViewSh, NULL, aSet);
SdAbstractDialogFactory* pFact = SdAbstractDialogFactory::Create();//CHINA001
DBG_ASSERT(pFact, "SdAbstractDialogFactory fail!");//CHINA001
AbstractSdPresLayoutDlg* pDlg = pFact->CreateSdPresLayoutDlg(ResId( DLG_PRESLT ), pDocSh, pViewSh, NULL, aSet );
DBG_ASSERT(pDlg, "Dialogdiet fail!");//CHINA001
USHORT nResult = pDlg->Execute();
switch (nResult)
{
case RET_OK:
{
pDlg->GetAttr(aSet);
if (aSet.GetItemState(ATTR_PRESLAYOUT_LOAD) == SFX_ITEM_SET)
bLoad = ((SfxBoolItem&)aSet.Get(ATTR_PRESLAYOUT_LOAD)).GetValue();
if( aSet.GetItemState( ATTR_PRESLAYOUT_MASTER_PAGE ) == SFX_ITEM_SET )
bMasterPage = ( (SfxBoolItem&) aSet.Get( ATTR_PRESLAYOUT_MASTER_PAGE ) ).GetValue();
if( aSet.GetItemState( ATTR_PRESLAYOUT_CHECK_MASTERS ) == SFX_ITEM_SET )
bCheckMasters = ( (SfxBoolItem&) aSet.Get( ATTR_PRESLAYOUT_CHECK_MASTERS ) ).GetValue();
if (aSet.GetItemState(ATTR_PRESLAYOUT_NAME) == SFX_ITEM_SET)
aFile = ((SfxStringItem&)aSet.Get(ATTR_PRESLAYOUT_NAME)).GetValue();
}
break;
default:
bError = TRUE;
}
delete pDlg;
if (!bError)
{
pDocSh->SetWaitCursor( TRUE );
// Hier werden nur Masterpages ausgewechselt, d.h. die aktuelle Seite
// bleibt aktuell. Damit beim Ein- und Ausfuegen der Masterpages nicht
// dauernd via PageOrderChangedHint die Methode ResetActualPage gerufen
// wird, wird jetzt blockiert.
// That isn't quitely right. If the masterpageview is active and you are
// removing a masterpage, it's possible that you are removing the
// current masterpage. So you have to call ResetActualPage !
if( pViewShell->ISA(DrawViewShell) && !bCheckMasters )
static_cast<DrawView*>(pView)->BlockPageOrderChangedHint(TRUE);
if (bLoad)
{
String aFileName = aFile.GetToken( 0, DOCUMENT_TOKEN );
SdDrawDocument* pTempDoc = pDoc->OpenBookmarkDoc( aFileName );
// #69581: If I chosed the standard-template I got no filename and so I get no
// SdDrawDocument-Pointer. But the method SetMasterPage is able to handle
// a NULL-pointer as a Standard-template ( look at SdDrawDocument::SetMasterPage )
String aLayoutName;
if( pTempDoc )
aLayoutName = aFile.GetToken( 1, DOCUMENT_TOKEN );
pDoc->SetMasterPage(nSelectedPage, aLayoutName, pTempDoc, bMasterPage, bCheckMasters);
pDoc->CloseBookmarkDoc();
}
else
{
// MasterPage mit dem LayoutNamen aFile aus aktuellem Doc verwenden
pDoc->SetMasterPage(nSelectedPage, aFile, pDoc, bMasterPage, bCheckMasters);
}
// Blockade wieder aufheben
if (pViewShell->ISA(DrawViewShell) && !bCheckMasters )
static_cast<DrawView*>(pView)->BlockPageOrderChangedHint(FALSE);
/*************************************************************************
|* Falls dargestellte Masterpage sichtbar war, neu darstellen
\************************************************************************/
if (!bError && nSelectedPage != SDRPAGE_NOTFOUND)
{
if (bOnMaster)
{
if (pViewShell->ISA(DrawViewShell))
{
::sd::View* pView =
static_cast<DrawViewShell*>(pViewShell)->GetView();
USHORT nPgNum = pSelectedPage->TRG_GetMasterPage().GetPageNum();
if (static_cast<DrawViewShell*>(pViewShell)->GetPageKind() == PK_NOTES)
nPgNum++;
pView->HideAllPages();
pView->ShowMasterPagePgNum(nPgNum, Point());
}
// damit TabBar aktualisiert wird
pViewShell->GetViewFrame()->GetDispatcher()->Execute(SID_MASTERPAGE, SFX_CALLMODE_ASYNCHRON | SFX_CALLMODE_RECORD);
}
else
{
pSelectedPage->SetAutoLayout(pSelectedPage->GetAutoLayout());
}
}
// fake a mode change to repaint the page tab bar
if( pViewShell && pViewShell->ISA( DrawViewShell ) )
{
DrawViewShell* pDrawViewSh =
static_cast<DrawViewShell*>(pViewShell);
EditMode eMode = pDrawViewSh->GetEditMode();
BOOL bLayer = pDrawViewSh->IsLayerModeActive();
pDrawViewSh->ChangeEditMode( eMode, !bLayer );
pDrawViewSh->ChangeEditMode( eMode, bLayer );
}
pDocSh->SetWaitCursor( FALSE );
}
}
/*************************************************************************
|*
|* Destruktor
|*
\************************************************************************/
FuPresentationLayout::~FuPresentationLayout()
{
}
/*************************************************************************
|*
|* Layoutvorlage von einem StyleSheetPool in einen anderen uebertragen
|*
\************************************************************************/
void FuPresentationLayout::TransferLayoutTemplate(String aFromName,
String aToName,
SfxStyleSheetBasePool* pFrom,
SfxStyleSheetBasePool* pTo)
{
SfxStyleSheetBase* pHis = pFrom->Find(aFromName,SD_LT_FAMILY);
SfxStyleSheetBase* pMy = pTo->Find(aToName, SD_LT_FAMILY);
DBG_ASSERT(pHis, "neue Layoutvorlage nicht gefunden");
// gibt's noch nicht: neu anlegen
if (!pMy)
{
pMy = &(pTo->Make(aToName, SD_LT_FAMILY));
}
// Inhalte neu setzen
if (pHis)
pMy->GetItemSet().Set(pHis->GetItemSet());
}
} // end of namespace sd
<commit_msg>INTEGRATION: CWS ooo19126 (1.9.362); FILE MERGED 2005/09/05 13:22:22 rt 1.9.362.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: fuprlout.cxx,v $
*
* $Revision: 1.10 $
*
* last change: $Author: rt $ $Date: 2005-09-09 04:49:20 $
*
* 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
*
************************************************************************/
#pragma hdrstop
#include "fuprlout.hxx"
#ifndef _SV_WRKWIN_HXX
#include <vcl/wrkwin.hxx>
#endif
#ifndef _SFXDISPATCH_HXX //autogen
#include <sfx2/dispatch.hxx>
#endif
#ifndef _SFXSMPLHINT_HXX //autogen
#include <svtools/smplhint.hxx>
#endif
#ifndef _SFXITEMPOOL_HXX //autogen
#include <svtools/itempool.hxx>
#endif
#include <sot/storage.hxx>
#ifndef _SV_MSGBOX_HXX //autogen
#include <vcl/msgbox.hxx>
#endif
#ifndef _SVDUNDO_HXX //autogen
#include <svx/svdundo.hxx>
#endif
#include <sfx2/viewfrm.hxx>
#include "drawdoc.hxx"
#include "sdpage.hxx"
#include "pres.hxx"
#ifndef SD_DRAW_VIEW_SHELL_HXX
#include "DrawViewShell.hxx"
#endif
#ifndef SD_FRAMW_VIEW_HXX
#include "FrameView.hxx"
#endif
#include "stlpool.hxx"
#ifndef SD_VIEW_HXX
#include "View.hxx"
#endif
#include "glob.hrc"
#include "glob.hxx"
#include "strings.hrc"
#include "strmname.h"
#include "app.hrc"
#include "DrawDocShell.hxx"
#include "unprlout.hxx"
#include "unchss.hxx"
#include "unmovss.hxx"
#include "sdattr.hxx"
#include "sdresid.hxx"
//CHINA001 #include "sdpreslt.hxx"
#ifndef SD_DRAW_VIEW_HXX
#include "drawview.hxx"
#endif
#include "eetext.hxx"
#include <svx/editdata.hxx>
#include "sdabstdlg.hxx" //CHINA001
#include "sdpreslt.hrc" //CHINA001
namespace sd {
#ifndef SO2_DECL_SVSTORAGE_DEFINED
#define SO2_DECL_SVSTORAGE_DEFINED
SO2_DECL_REF(SvStorage)
#endif
TYPEINIT1( FuPresentationLayout, FuPoor );
#define POOL_BUFFER_SIZE (USHORT)32768
#define DOCUMENT_BUFFER_SIZE (USHORT)32768
#define DOCUMENT_TOKEN (sal_Unicode('#'))
/*************************************************************************
|*
|* Konstruktor
|*
\************************************************************************/
FuPresentationLayout::FuPresentationLayout (
ViewShell* pViewSh,
::sd::Window* pWin,
::sd::View* pView,
SdDrawDocument* pDoc,
SfxRequest& rReq)
: FuPoor(pViewSh, pWin, pView, pDoc, rReq)
{
// damit nicht Objekte, die gerade editiert werden oder selektiert
// sind , verschwinden
pView->EndTextEdit();
USHORT nPgViewCount = pView->GetPageViewCount();
for (USHORT nPgView = 0; nPgView < nPgViewCount; nPgView++)
{
pView->UnmarkAll();
}
BOOL bError = FALSE;
// die aktive Seite ermitteln
USHORT nSelectedPage = SDRPAGE_NOTFOUND;
for (USHORT nPage = 0; nPage < pDoc->GetSdPageCount(PK_STANDARD); nPage++)
{
if (pDoc->GetSdPage(nPage, PK_STANDARD)->IsSelected())
{
nSelectedPage = nPage;
break;
}
}
DBG_ASSERT(nSelectedPage != SDRPAGE_NOTFOUND, "keine selektierte Seite");
SdPage* pSelectedPage = pDoc->GetSdPage(nSelectedPage, PK_STANDARD);
String aOldPageLayoutName(pSelectedPage->GetLayoutName());
String aOldLayoutName(aOldPageLayoutName);
aOldLayoutName.Erase(aOldLayoutName.SearchAscii(SD_LT_SEPARATOR));
// wenn wir auf einer Masterpage sind, gelten die Aenderungen fuer alle
// Seiten und Notizseiten, die das betreffende Layout benutzen
BOOL bOnMaster = FALSE;
if (pViewSh->ISA(DrawViewShell))
{
EditMode eEditMode =
static_cast<DrawViewShell*>(pViewSh)->GetEditMode();
if (eEditMode == EM_MASTERPAGE)
bOnMaster = TRUE;
}
BOOL bMasterPage = bOnMaster;
BOOL bCheckMasters = FALSE;
// Dialog aufrufen
BOOL bLoad = FALSE; // tauchen neue Masterpages auf?
String aFile;
SfxItemSet aSet(pDoc->GetPool(), ATTR_PRESLAYOUT_START, ATTR_PRESLAYOUT_END);
aSet.Put( SfxBoolItem( ATTR_PRESLAYOUT_LOAD, bLoad));
aSet.Put( SfxBoolItem( ATTR_PRESLAYOUT_MASTER_PAGE, bMasterPage ) );
aSet.Put( SfxBoolItem( ATTR_PRESLAYOUT_CHECK_MASTERS, bCheckMasters ) );
aSet.Put( SfxStringItem( ATTR_PRESLAYOUT_NAME, aOldLayoutName));
//CHINA001 SdPresLayoutDlg* pDlg = new SdPresLayoutDlg( pDocSh, pViewSh, NULL, aSet);
SdAbstractDialogFactory* pFact = SdAbstractDialogFactory::Create();//CHINA001
DBG_ASSERT(pFact, "SdAbstractDialogFactory fail!");//CHINA001
AbstractSdPresLayoutDlg* pDlg = pFact->CreateSdPresLayoutDlg(ResId( DLG_PRESLT ), pDocSh, pViewSh, NULL, aSet );
DBG_ASSERT(pDlg, "Dialogdiet fail!");//CHINA001
USHORT nResult = pDlg->Execute();
switch (nResult)
{
case RET_OK:
{
pDlg->GetAttr(aSet);
if (aSet.GetItemState(ATTR_PRESLAYOUT_LOAD) == SFX_ITEM_SET)
bLoad = ((SfxBoolItem&)aSet.Get(ATTR_PRESLAYOUT_LOAD)).GetValue();
if( aSet.GetItemState( ATTR_PRESLAYOUT_MASTER_PAGE ) == SFX_ITEM_SET )
bMasterPage = ( (SfxBoolItem&) aSet.Get( ATTR_PRESLAYOUT_MASTER_PAGE ) ).GetValue();
if( aSet.GetItemState( ATTR_PRESLAYOUT_CHECK_MASTERS ) == SFX_ITEM_SET )
bCheckMasters = ( (SfxBoolItem&) aSet.Get( ATTR_PRESLAYOUT_CHECK_MASTERS ) ).GetValue();
if (aSet.GetItemState(ATTR_PRESLAYOUT_NAME) == SFX_ITEM_SET)
aFile = ((SfxStringItem&)aSet.Get(ATTR_PRESLAYOUT_NAME)).GetValue();
}
break;
default:
bError = TRUE;
}
delete pDlg;
if (!bError)
{
pDocSh->SetWaitCursor( TRUE );
// Hier werden nur Masterpages ausgewechselt, d.h. die aktuelle Seite
// bleibt aktuell. Damit beim Ein- und Ausfuegen der Masterpages nicht
// dauernd via PageOrderChangedHint die Methode ResetActualPage gerufen
// wird, wird jetzt blockiert.
// That isn't quitely right. If the masterpageview is active and you are
// removing a masterpage, it's possible that you are removing the
// current masterpage. So you have to call ResetActualPage !
if( pViewShell->ISA(DrawViewShell) && !bCheckMasters )
static_cast<DrawView*>(pView)->BlockPageOrderChangedHint(TRUE);
if (bLoad)
{
String aFileName = aFile.GetToken( 0, DOCUMENT_TOKEN );
SdDrawDocument* pTempDoc = pDoc->OpenBookmarkDoc( aFileName );
// #69581: If I chosed the standard-template I got no filename and so I get no
// SdDrawDocument-Pointer. But the method SetMasterPage is able to handle
// a NULL-pointer as a Standard-template ( look at SdDrawDocument::SetMasterPage )
String aLayoutName;
if( pTempDoc )
aLayoutName = aFile.GetToken( 1, DOCUMENT_TOKEN );
pDoc->SetMasterPage(nSelectedPage, aLayoutName, pTempDoc, bMasterPage, bCheckMasters);
pDoc->CloseBookmarkDoc();
}
else
{
// MasterPage mit dem LayoutNamen aFile aus aktuellem Doc verwenden
pDoc->SetMasterPage(nSelectedPage, aFile, pDoc, bMasterPage, bCheckMasters);
}
// Blockade wieder aufheben
if (pViewShell->ISA(DrawViewShell) && !bCheckMasters )
static_cast<DrawView*>(pView)->BlockPageOrderChangedHint(FALSE);
/*************************************************************************
|* Falls dargestellte Masterpage sichtbar war, neu darstellen
\************************************************************************/
if (!bError && nSelectedPage != SDRPAGE_NOTFOUND)
{
if (bOnMaster)
{
if (pViewShell->ISA(DrawViewShell))
{
::sd::View* pView =
static_cast<DrawViewShell*>(pViewShell)->GetView();
USHORT nPgNum = pSelectedPage->TRG_GetMasterPage().GetPageNum();
if (static_cast<DrawViewShell*>(pViewShell)->GetPageKind() == PK_NOTES)
nPgNum++;
pView->HideAllPages();
pView->ShowMasterPagePgNum(nPgNum, Point());
}
// damit TabBar aktualisiert wird
pViewShell->GetViewFrame()->GetDispatcher()->Execute(SID_MASTERPAGE, SFX_CALLMODE_ASYNCHRON | SFX_CALLMODE_RECORD);
}
else
{
pSelectedPage->SetAutoLayout(pSelectedPage->GetAutoLayout());
}
}
// fake a mode change to repaint the page tab bar
if( pViewShell && pViewShell->ISA( DrawViewShell ) )
{
DrawViewShell* pDrawViewSh =
static_cast<DrawViewShell*>(pViewShell);
EditMode eMode = pDrawViewSh->GetEditMode();
BOOL bLayer = pDrawViewSh->IsLayerModeActive();
pDrawViewSh->ChangeEditMode( eMode, !bLayer );
pDrawViewSh->ChangeEditMode( eMode, bLayer );
}
pDocSh->SetWaitCursor( FALSE );
}
}
/*************************************************************************
|*
|* Destruktor
|*
\************************************************************************/
FuPresentationLayout::~FuPresentationLayout()
{
}
/*************************************************************************
|*
|* Layoutvorlage von einem StyleSheetPool in einen anderen uebertragen
|*
\************************************************************************/
void FuPresentationLayout::TransferLayoutTemplate(String aFromName,
String aToName,
SfxStyleSheetBasePool* pFrom,
SfxStyleSheetBasePool* pTo)
{
SfxStyleSheetBase* pHis = pFrom->Find(aFromName,SD_LT_FAMILY);
SfxStyleSheetBase* pMy = pTo->Find(aToName, SD_LT_FAMILY);
DBG_ASSERT(pHis, "neue Layoutvorlage nicht gefunden");
// gibt's noch nicht: neu anlegen
if (!pMy)
{
pMy = &(pTo->Make(aToName, SD_LT_FAMILY));
}
// Inhalte neu setzen
if (pHis)
pMy->GetItemSet().Set(pHis->GetItemSet());
}
} // end of namespace sd
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* $RCSfile: fuprobjs.cxx,v $
*
* $Revision: 1.1.1.1 $
*
* last change: $Author: hr $ $Date: 2000-09-18 16:48: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 _MSGBOX_HXX //autogen
#include <vcl/msgbox.hxx>
#endif
#ifndef _SFXSTYLE_HXX //autogen
#include <svtools/style.hxx>
#endif
#ifndef _OUTLINER_HXX
#include <svx/outliner.hxx>
#endif
#ifndef _SFXSMPLHINT_HXX //autogen
#include <svtools/smplhint.hxx>
#endif
#pragma hdrstop
#include "app.hrc"
#include "res_bmp.hrc"
#include "strings.hrc"
#include "glob.hrc"
#include "prltempl.hrc"
#include "sdresid.hxx"
#include "fuprobjs.hxx"
#include "drawdoc.hxx"
#include "outlnvsh.hxx"
#include "viewshel.hxx"
#include "glob.hxx"
#include "prlayout.hxx"
#include "prltempl.hxx"
#include "unchss.hxx"
TYPEINIT1( FuPresentationObjects, FuPoor );
/*************************************************************************
|*
|* Konstruktor
|*
\************************************************************************/
FuPresentationObjects::FuPresentationObjects(SdViewShell* pViewSh,
SdWindow* pWin, SdView* pView,
SdDrawDocument* pDoc,
SfxRequest& rReq)
: FuPoor(pViewSh, pWin, pView, pDoc, rReq)
{
// ergibt die Selektion ein eindeutiges Praesentationslayout?
// wenn nicht, duerfen die Vorlagen nicht bearbeitet werden
SfxItemSet aSet(pDoc->GetItemPool(), SID_STATUS_LAYOUT, SID_STATUS_LAYOUT);
( (SdOutlineViewShell*) pViewSh )->GetStatusBarState( aSet );
String aLayoutName = (((SfxStringItem&)aSet.Get(SID_STATUS_LAYOUT)).GetValue());
DBG_ASSERT(aLayoutName.Len(), "Layout unbestimmt");
BOOL bUnique = FALSE;
USHORT nDepth, nTmp;
SdOutlineView* pOlView = (SdOutlineView*)( (SdOutlineViewShell*) pViewSh )->GetView();
OutlinerView* pOutlinerView = pOlView->GetViewByWindow( (Window*) pWin );
Outliner* pOutl = pOutlinerView->GetOutliner();
List* pList = pOutlinerView->CreateSelectionList();
Paragraph* pPara = (Paragraph*)pList->First();
nDepth = pOutl->GetDepth( pOutl->GetAbsPos( pPara ) );
while( pPara )
{
nTmp = pOutl->GetDepth( pOutl->GetAbsPos( pPara ) );
if( nDepth != nTmp )
{
bUnique = FALSE;
break;
}
bUnique = TRUE;
pPara = (Paragraph*) pList->Next();
}
if( bUnique )
{
String aStyleName = aLayoutName;
aStyleName.AppendAscii( RTL_CONSTASCII_STRINGPARAM( SD_LT_SEPARATOR ) );
USHORT nDlgId = TAB_PRES_LAYOUT_TEMPLATE_3;
PresentationObjects ePO;
if( nDepth == 0 )
{
ePO = PO_TITLE;
String aStr(SdResId( STR_LAYOUT_TITLE ));
aStyleName.Append( aStr );
}
else
{
ePO = (PresentationObjects) ( PO_OUTLINE_1 + nDepth - 1 );
String aStr(SdResId( STR_LAYOUT_OUTLINE ));
aStyleName.Append( aStr );
aStyleName.Append( sal_Unicode(' ') );
aStyleName.Append( UniString::CreateFromInt32( nDepth ) );
}
SfxStyleSheetBasePool* pStyleSheetPool = pDocSh->GetStyleSheetPool();
SfxStyleSheetBase* pStyleSheet = pStyleSheetPool->Find( aStyleName,
(SfxStyleFamily) SD_LT_FAMILY );
DBG_ASSERT(pStyleSheet, "StyleSheet nicht gefunden");
if( pStyleSheet )
{
SfxStyleSheetBase& rStyleSheet = *pStyleSheet;
SdPresLayoutTemplateDlg* pDlg = new SdPresLayoutTemplateDlg( pDocSh, NULL,
SdResId( nDlgId ), rStyleSheet, ePO, pStyleSheetPool );
if( pDlg->Execute() == RET_OK )
{
// Undo-Action
StyleSheetUndoAction* pAction = new StyleSheetUndoAction
(pDoc, (SfxStyleSheet*)pStyleSheet,
pDlg->GetOutputItemSet());
pDocSh->GetUndoManager()->AddUndoAction(pAction);
pStyleSheet->GetItemSet().Put( *( pDlg->GetOutputItemSet() ) );
( (SfxStyleSheet*) pStyleSheet )->Broadcast( SfxSimpleHint( SFX_HINT_DATACHANGED ) );
}
delete( pDlg );
}
}
}
/*************************************************************************
|*
|* Destruktor
|*
\************************************************************************/
FuPresentationObjects::~FuPresentationObjects()
{
}
<commit_msg>#77245# call getoutputset only once!<commit_after>/*************************************************************************
*
* $RCSfile: fuprobjs.cxx,v $
*
* $Revision: 1.2 $
*
* last change: $Author: cl $ $Date: 2000-11-15 13:34:21 $
*
* 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 _MSGBOX_HXX //autogen
#include <vcl/msgbox.hxx>
#endif
#ifndef _SFXSTYLE_HXX //autogen
#include <svtools/style.hxx>
#endif
#ifndef _OUTLINER_HXX
#include <svx/outliner.hxx>
#endif
#ifndef _SFXSMPLHINT_HXX //autogen
#include <svtools/smplhint.hxx>
#endif
#pragma hdrstop
#include "app.hrc"
#include "res_bmp.hrc"
#include "strings.hrc"
#include "glob.hrc"
#include "prltempl.hrc"
#include "sdresid.hxx"
#include "fuprobjs.hxx"
#include "drawdoc.hxx"
#include "outlnvsh.hxx"
#include "viewshel.hxx"
#include "glob.hxx"
#include "prlayout.hxx"
#include "prltempl.hxx"
#include "unchss.hxx"
TYPEINIT1( FuPresentationObjects, FuPoor );
/*************************************************************************
|*
|* Konstruktor
|*
\************************************************************************/
FuPresentationObjects::FuPresentationObjects(SdViewShell* pViewSh,
SdWindow* pWin, SdView* pView,
SdDrawDocument* pDoc,
SfxRequest& rReq)
: FuPoor(pViewSh, pWin, pView, pDoc, rReq)
{
// ergibt die Selektion ein eindeutiges Praesentationslayout?
// wenn nicht, duerfen die Vorlagen nicht bearbeitet werden
SfxItemSet aSet(pDoc->GetItemPool(), SID_STATUS_LAYOUT, SID_STATUS_LAYOUT);
( (SdOutlineViewShell*) pViewSh )->GetStatusBarState( aSet );
String aLayoutName = (((SfxStringItem&)aSet.Get(SID_STATUS_LAYOUT)).GetValue());
DBG_ASSERT(aLayoutName.Len(), "Layout unbestimmt");
BOOL bUnique = FALSE;
USHORT nDepth, nTmp;
SdOutlineView* pOlView = (SdOutlineView*)( (SdOutlineViewShell*) pViewSh )->GetView();
OutlinerView* pOutlinerView = pOlView->GetViewByWindow( (Window*) pWin );
Outliner* pOutl = pOutlinerView->GetOutliner();
List* pList = pOutlinerView->CreateSelectionList();
Paragraph* pPara = (Paragraph*)pList->First();
nDepth = pOutl->GetDepth( pOutl->GetAbsPos( pPara ) );
while( pPara )
{
nTmp = pOutl->GetDepth( pOutl->GetAbsPos( pPara ) );
if( nDepth != nTmp )
{
bUnique = FALSE;
break;
}
bUnique = TRUE;
pPara = (Paragraph*) pList->Next();
}
if( bUnique )
{
String aStyleName = aLayoutName;
aStyleName.AppendAscii( RTL_CONSTASCII_STRINGPARAM( SD_LT_SEPARATOR ) );
USHORT nDlgId = TAB_PRES_LAYOUT_TEMPLATE_3;
PresentationObjects ePO;
if( nDepth == 0 )
{
ePO = PO_TITLE;
String aStr(SdResId( STR_LAYOUT_TITLE ));
aStyleName.Append( aStr );
}
else
{
ePO = (PresentationObjects) ( PO_OUTLINE_1 + nDepth - 1 );
String aStr(SdResId( STR_LAYOUT_OUTLINE ));
aStyleName.Append( aStr );
aStyleName.Append( sal_Unicode(' ') );
aStyleName.Append( UniString::CreateFromInt32( nDepth ) );
}
SfxStyleSheetBasePool* pStyleSheetPool = pDocSh->GetStyleSheetPool();
SfxStyleSheetBase* pStyleSheet = pStyleSheetPool->Find( aStyleName,
(SfxStyleFamily) SD_LT_FAMILY );
DBG_ASSERT(pStyleSheet, "StyleSheet nicht gefunden");
if( pStyleSheet )
{
SfxStyleSheetBase& rStyleSheet = *pStyleSheet;
SdPresLayoutTemplateDlg* pDlg = new SdPresLayoutTemplateDlg( pDocSh, NULL,
SdResId( nDlgId ), rStyleSheet, ePO, pStyleSheetPool );
if( pDlg->Execute() == RET_OK )
{
const SfxItemSet* pOutSet = pDlg->GetOutputItemSet();
// Undo-Action
StyleSheetUndoAction* pAction = new StyleSheetUndoAction
(pDoc, (SfxStyleSheet*)pStyleSheet,
pOutSet);
pDocSh->GetUndoManager()->AddUndoAction(pAction);
pStyleSheet->GetItemSet().Put( *pOutSet );
( (SfxStyleSheet*) pStyleSheet )->Broadcast( SfxSimpleHint( SFX_HINT_DATACHANGED ) );
}
delete( pDlg );
}
}
}
/*************************************************************************
|*
|* Destruktor
|*
\************************************************************************/
FuPresentationObjects::~FuPresentationObjects()
{
}
<|endoftext|>
|
<commit_before>#include <Python.h>
#include <awd/libawd.h>
#include "AWD.h"
#include "AWDMatrix4.h"
#include "AWDAttrBlock.h"
#include "AWDSubMesh.h"
#include "AWDMeshData.h"
#include "AWDMeshInst.h"
#include "AWDSkeleton.h"
#include "AWDSkeletonPose.h"
#include "AWDSkeletonJoint.h"
#include "AWDSkeletonAnimation.h"
#if PYTHON_VERSION == 3
static PyModuleDef pyawd_mod = {
PyModuleDef_HEAD_INIT,
"pyawd",
"Module for reading/writing Away3D data format (AWD).",
-1,
NULL, NULL, NULL, NULL, NULL
};
#else // Python 2.6
static PyMethodDef pyawd_methods[] = {
{NULL, NULL, 0, NULL} /* Sentinel */
};
#endif
/*
* Python version-agnostic method to initialize pyawd module.
* Invoked in different ways depending on whether this module
* is compiled for Python 2.6 or 3.x.
*/
PyObject *_init_pyawd(PyObject *m)
{
PyObject *pyawd_ver;
PyObject *libawd_ver;
char *version_str;
version_str = (char*)malloc(64);
snprintf(version_str, 64, "PyAWD %d.%d (libawd %d.%d)",
PYAWD_MAJOR_VERSION, PYAWD_MINOR_VERSION,
AWD_MAJOR_VERSION, AWD_MINOR_VERSION);
pyawd_ver = Py_BuildValue("(i,i)", PYAWD_MAJOR_VERSION, PYAWD_MINOR_VERSION);
libawd_ver = Py_BuildValue("(i,i)", AWD_MAJOR_VERSION, AWD_MINOR_VERSION);
// Version "constants"
PyModule_AddStringConstant(m, "version", version_str);
PyModule_AddObject(m, "pyawd_version", pyawd_ver);
PyModule_AddObject(m, "libawd_version", libawd_ver);
// Enumeration constants
PyModule_AddIntConstant(m, "UNCOMPRESSED", UNCOMPRESSED);
PyModule_AddIntConstant(m, "DEFLATE", DEFLATE);
PyModule_AddIntConstant(m, "LZMA", LZMA);
PyModule_AddIntConstant(m, "VERTEX_STREAM", VERTICES);
PyModule_AddIntConstant(m, "TRIANGLE_STREAM", TRIANGLES);
PyModule_AddIntConstant(m, "UV_STREAM", UVS);
PyModule_AddIntConstant(m, "VNORMAL_STREAM", VERTEX_NORMALS);
PyModule_AddIntConstant(m, "VTANGENT_STREAM", VERTEX_TANGENTS);
PyModule_AddIntConstant(m, "FNORMAL_STREAM", FACE_NORMALS);
PyModule_AddIntConstant(m, "JINDEX_STREAM", JOINT_INDICES);
PyModule_AddIntConstant(m, "VWEIGHT_STREAM", VERTEX_WEIGHTS);
// Prepare class data types
if ((PyType_Ready(&pyawd_AWDType) < 0)
|| (PyType_Ready(&pyawd_AWDMatrix4Type) < 0)
|| (PyType_Ready(&pyawd_AWDSkeletonPoseType) < 0)
|| (PyType_Ready(&pyawd_AWDSkeletonAnimationType) < 0)
|| (PyType_Ready(&pyawd_AWDSkeletonJointType) < 0)
|| (PyType_Ready(&pyawd_AWDSkeletonType) < 0)
|| (PyType_Ready(&pyawd_AWDAttrBlockType) < 0)
|| (PyType_Ready(&pyawd_AWDMeshDataType) < 0)
|| (PyType_Ready(&pyawd_AWDMeshInstType) < 0)
|| (PyType_Ready(&pyawd_AWDSubMeshType) < 0))
return NULL;
// Add classes to module
Py_INCREF(&pyawd_AWDMatrix4Type);
PyModule_AddObject(m, "AWDMatrix4", (PyObject *)&pyawd_AWDMatrix4Type);
Py_INCREF(&pyawd_AWDType);
PyModule_AddObject(m, "AWD", (PyObject *)&pyawd_AWDType);
Py_INCREF(&pyawd_AWDAttrBlockType);
PyModule_AddObject(m, "AWDAttrBlock", (PyObject *)&pyawd_AWDAttrBlockType);
Py_INCREF(&pyawd_AWDMeshDataType);
PyModule_AddObject(m, "AWDMeshData", (PyObject *)&pyawd_AWDMeshDataType);
Py_INCREF(&pyawd_AWDSubMeshType);
PyModule_AddObject(m, "AWDSubMesh", (PyObject *)&pyawd_AWDSubMeshType);
Py_INCREF(&pyawd_AWDMeshInstType);
PyModule_AddObject(m, "AWDMeshInst", (PyObject *)&pyawd_AWDMeshInstType);
Py_INCREF(&pyawd_AWDSkeletonType);
PyModule_AddObject(m, "AWDSkeleton", (PyObject *)&pyawd_AWDSkeletonType);
Py_INCREF(&pyawd_AWDSkeletonJointType);
PyModule_AddObject(m, "AWDSkeletonJoint", (PyObject *)&pyawd_AWDSkeletonJointType);
Py_INCREF(&pyawd_AWDSkeletonPoseType);
PyModule_AddObject(m, "AWDSkeletonPose", (PyObject *)&pyawd_AWDSkeletonPoseType);
Py_INCREF(&pyawd_AWDSkeletonAnimationType);
PyModule_AddObject(m, "AWDSkeletonAnimation", (PyObject *)&pyawd_AWDSkeletonAnimationType);
return m;
}
#if PYTHON_VERSION == 3
PyMODINIT_FUNC
PyInit_pyawd(void)
{
PyObject *m;
m = PyModule_Create(&pyawd_mod);
if (m == NULL)
return NULL;
return _init_pyawd(m);
}
#else // Python 2.6
PyMODINIT_FUNC
initpyawd(void)
{
PyObject *m;
m = Py_InitModule("pyawd", pyawd_methods);
_init_pyawd(m);
}
#endif
<commit_msg>Moved constants to classes (instead of directly on the pyawd module.)<commit_after>#include <Python.h>
#include <awd/libawd.h>
#include "AWD.h"
#include "AWDMatrix4.h"
#include "AWDAttrBlock.h"
#include "AWDSubMesh.h"
#include "AWDMeshData.h"
#include "AWDMeshInst.h"
#include "AWDSkeleton.h"
#include "AWDSkeletonPose.h"
#include "AWDSkeletonJoint.h"
#include "AWDSkeletonAnimation.h"
#if PYTHON_VERSION == 3
static PyModuleDef pyawd_mod = {
PyModuleDef_HEAD_INIT,
"pyawd",
"Module for reading/writing Away3D data format (AWD).",
-1,
NULL, NULL, NULL, NULL, NULL
};
#else // Python 2.6
static PyMethodDef pyawd_methods[] = {
{NULL, NULL, 0, NULL} /* Sentinel */
};
#endif
void _add_int_const(PyTypeObject *type, const char *attr, int val)
{
PyObject *pyval;
pyval = PyInt_FromLong(val);
Py_INCREF(pyval);
PyDict_SetItemString(type->tp_dict, attr, pyval);
}
/*
* Python version-agnostic method to initialize pyawd module.
* Invoked in different ways depending on whether this module
* is compiled for Python 2.6 or 3.x.
*/
PyObject *_init_pyawd(PyObject *m)
{
PyObject *pyawd_ver;
PyObject *libawd_ver;
char *version_str;
version_str = (char*)malloc(64);
snprintf(version_str, 64, "PyAWD %d.%d (libawd %d.%d)",
PYAWD_MAJOR_VERSION, PYAWD_MINOR_VERSION,
AWD_MAJOR_VERSION, AWD_MINOR_VERSION);
pyawd_ver = Py_BuildValue("(i,i)", PYAWD_MAJOR_VERSION, PYAWD_MINOR_VERSION);
libawd_ver = Py_BuildValue("(i,i)", AWD_MAJOR_VERSION, AWD_MINOR_VERSION);
// Version "constants"
PyModule_AddStringConstant(m, "version", version_str);
PyModule_AddObject(m, "pyawd_version", pyawd_ver);
PyModule_AddObject(m, "libawd_version", libawd_ver);
// Prepare class data types
if ((PyType_Ready(&pyawd_AWDType) < 0)
|| (PyType_Ready(&pyawd_AWDMatrix4Type) < 0)
|| (PyType_Ready(&pyawd_AWDSkeletonPoseType) < 0)
|| (PyType_Ready(&pyawd_AWDSkeletonAnimationType) < 0)
|| (PyType_Ready(&pyawd_AWDSkeletonJointType) < 0)
|| (PyType_Ready(&pyawd_AWDSkeletonType) < 0)
|| (PyType_Ready(&pyawd_AWDAttrBlockType) < 0)
|| (PyType_Ready(&pyawd_AWDMeshDataType) < 0)
|| (PyType_Ready(&pyawd_AWDMeshInstType) < 0)
|| (PyType_Ready(&pyawd_AWDSubMeshType) < 0))
return NULL;
// AWD type constants
_add_int_const(&pyawd_AWDType, "UNCOMPRESSED", UNCOMPRESSED);
_add_int_const(&pyawd_AWDType, "DEFLATE", DEFLATE);
_add_int_const(&pyawd_AWDType, "LZMA", LZMA);
// SubMesh type constants
_add_int_const(&pyawd_AWDSubMeshType, "VERTICES", VERTICES);
_add_int_const(&pyawd_AWDSubMeshType, "TRIANGLES", TRIANGLES);
_add_int_const(&pyawd_AWDSubMeshType, "UVS", UVS);
_add_int_const(&pyawd_AWDSubMeshType, "VERTEX_NORMALS", VERTEX_NORMALS);
_add_int_const(&pyawd_AWDSubMeshType, "VERTEX_TANGENTS", VERTEX_TANGENTS);
_add_int_const(&pyawd_AWDSubMeshType, "FACE_NORMALS", FACE_NORMALS);
_add_int_const(&pyawd_AWDSubMeshType, "JOINT_INDICES", JOINT_INDICES);
_add_int_const(&pyawd_AWDSubMeshType, "VERTEX_WEIGHTS", VERTEX_WEIGHTS);
// Add classes to module
Py_INCREF(&pyawd_AWDMatrix4Type);
PyModule_AddObject(m, "AWDMatrix4", (PyObject *)&pyawd_AWDMatrix4Type);
Py_INCREF(&pyawd_AWDType);
PyModule_AddObject(m, "AWD", (PyObject *)&pyawd_AWDType);
Py_INCREF(&pyawd_AWDAttrBlockType);
PyModule_AddObject(m, "AWDAttrBlock", (PyObject *)&pyawd_AWDAttrBlockType);
Py_INCREF(&pyawd_AWDMeshDataType);
PyModule_AddObject(m, "AWDMeshData", (PyObject *)&pyawd_AWDMeshDataType);
Py_INCREF(&pyawd_AWDSubMeshType);
PyModule_AddObject(m, "AWDSubMesh", (PyObject *)&pyawd_AWDSubMeshType);
Py_INCREF(&pyawd_AWDMeshInstType);
PyModule_AddObject(m, "AWDMeshInst", (PyObject *)&pyawd_AWDMeshInstType);
Py_INCREF(&pyawd_AWDSkeletonType);
PyModule_AddObject(m, "AWDSkeleton", (PyObject *)&pyawd_AWDSkeletonType);
Py_INCREF(&pyawd_AWDSkeletonJointType);
PyModule_AddObject(m, "AWDSkeletonJoint", (PyObject *)&pyawd_AWDSkeletonJointType);
Py_INCREF(&pyawd_AWDSkeletonPoseType);
PyModule_AddObject(m, "AWDSkeletonPose", (PyObject *)&pyawd_AWDSkeletonPoseType);
Py_INCREF(&pyawd_AWDSkeletonAnimationType);
PyModule_AddObject(m, "AWDSkeletonAnimation", (PyObject *)&pyawd_AWDSkeletonAnimationType);
return m;
}
#if PYTHON_VERSION == 3
PyMODINIT_FUNC
PyInit_pyawd(void)
{
PyObject *m;
m = PyModule_Create(&pyawd_mod);
if (m == NULL)
return NULL;
return _init_pyawd(m);
}
#else // Python 2.6
PyMODINIT_FUNC
initpyawd(void)
{
PyObject *m;
m = Py_InitModule("pyawd", pyawd_methods);
_init_pyawd(m);
}
#endif
<|endoftext|>
|
<commit_before>// Copyright 2016 Yahoo Inc. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
#include <vespa/fastos/fastos.h>
#include <map>
#include <vespa/searchlib/features/rankingexpression/feature_name_extractor.h>
#include <vector>
#include <vespa/eval/eval/llvm/compiled_function.h>
#include <vespa/eval/eval/function.h>
#include <vespa/eval/eval/interpreted_function.h>
#include <vespa/eval/eval/basic_nodes.h>
#include <vespa/eval/eval/call_nodes.h>
#include <vespa/eval/eval/operator_nodes.h>
#include <vespa/vespalib/util/benchmark_timer.h>
#include <vespa/eval/eval/gbdt.h>
#include <vespa/eval/eval/vm_forest.h>
#include <vespa/eval/eval/llvm/deinline_forest.h>
#include <vespa/eval/tensor/default_tensor_engine.h>
#include <cmath>
//-----------------------------------------------------------------------------
using vespalib::BenchmarkTimer;
using vespalib::tensor::DefaultTensorEngine;
using namespace vespalib::eval;
using namespace vespalib::eval::nodes;
using namespace vespalib::eval::gbdt;
using namespace search::features::rankingexpression;
//-----------------------------------------------------------------------------
struct File {
int file;
char *data;
size_t size;
File(const vespalib::string &file_name)
: file(open(file_name.c_str(), O_RDONLY)), data((char*)MAP_FAILED), size(0)
{
struct stat info;
if ((file != -1) && (fstat(file, &info) == 0)) {
data = (char*)mmap(0, info.st_size, PROT_READ, MAP_SHARED, file, 0);
if (data != MAP_FAILED) {
size = info.st_size;
}
}
}
~File() {
if (valid()) {
munmap(data, size);
}
if (file != -1) {
close(file);
}
}
bool valid() const { return (data != MAP_FAILED); }
};
//-----------------------------------------------------------------------------
vespalib::string strip_name(const vespalib::string &name) {
const char *expected_ending = ".expression";
vespalib::string tmp = name;
size_t pos = tmp.rfind("/");
if (pos != tmp.npos) {
tmp = tmp.substr(pos + 1);
}
pos = tmp.rfind(expected_ending);
if (pos == tmp.size() - strlen(expected_ending)) {
tmp = tmp.substr(0, pos);
}
return tmp;
}
size_t as_percent(double value) {
return size_t(std::round(value * 100.0));
}
const char *maybe_s(size_t n) { return (n == 1) ? "" : "s"; }
//-----------------------------------------------------------------------------
size_t count_nodes(const Node &node) {
size_t count = 1;
for (size_t i = 0; i < node.num_children(); ++i) {
count += count_nodes(node.get_child(i));
}
return count;
}
//-----------------------------------------------------------------------------
struct InputInfo {
vespalib::string name;
std::vector<double> cmp_with;
explicit InputInfo(vespalib::stringref name_in)
: name(name_in), cmp_with() {}
double select_value() const {
return cmp_with.empty() ? 0.5 : cmp_with[(cmp_with.size()-1)/2];
return 0.5;
}
};
//-----------------------------------------------------------------------------
struct FunctionInfo {
typedef std::vector<const Node *> TreeList;
size_t expression_size;
bool root_is_forest;
std::vector<TreeList> forests;
std::vector<InputInfo> inputs;
std::vector<double> params;
void find_forests(const Node &node) {
if (node.is_forest()) {
forests.push_back(extract_trees(node));
} else {
for (size_t i = 0; i < node.num_children(); ++i) {
find_forests(node.get_child(i));
}
}
}
template <typename T>
void check_cmp(const T *node) {
if (node) {
auto lhs_symbol = as<Symbol>(node->lhs());
auto rhs_symbol = as<Symbol>(node->rhs());
if (lhs_symbol && node->rhs().is_const()) {
inputs[lhs_symbol->id()].cmp_with.push_back(node->rhs().get_const_value());
}
if (node->lhs().is_const() && rhs_symbol) {
inputs[rhs_symbol->id()].cmp_with.push_back(node->lhs().get_const_value());
}
}
}
void check_in(const In *node) {
if (node) {
auto lhs_symbol = as<Symbol>(node->lhs());
auto rhs_symbol = as<Symbol>(node->rhs());
if (lhs_symbol && node->rhs().is_const()) {
auto array = as<Array>(node->rhs());
if (array) {
for (size_t i = 0; i < array->size(); ++i) {
inputs[lhs_symbol->id()].cmp_with.push_back(array->get(i).get_const_value());
}
} else {
inputs[lhs_symbol->id()].cmp_with.push_back(node->rhs().get_const_value());
}
}
if (node->lhs().is_const() && rhs_symbol) {
inputs[rhs_symbol->id()].cmp_with.push_back(node->lhs().get_const_value());
}
}
}
void analyze_inputs(const Node &node) {
for (size_t i = 0; i < node.num_children(); ++i) {
analyze_inputs(node.get_child(i));
}
check_cmp(as<Equal>(node));
check_cmp(as<NotEqual>(node));
check_cmp(as<Approx>(node));
check_cmp(as<Less>(node));
check_cmp(as<LessEqual>(node));
check_cmp(as<Greater>(node));
check_cmp(as<GreaterEqual>(node));
check_in(as<In>(node));
}
FunctionInfo(const Function &function)
: expression_size(count_nodes(function.root())),
root_is_forest(function.root().is_forest()),
forests(),
inputs(),
params()
{
for (size_t i = 0; i < function.num_params(); ++i) {
inputs.emplace_back(function.param_name(i));
}
find_forests(function.root());
analyze_inputs(function.root());
for (size_t i = 0; i < function.num_params(); ++i) {
std::sort(inputs[i].cmp_with.begin(), inputs[i].cmp_with.end());
}
for (size_t i = 0; i < function.num_params(); ++i) {
params.push_back(inputs[i].select_value());
}
}
size_t get_path_len(const TreeList &trees) const {
size_t path = 0;
for (const Node *tree: trees) {
InterpretedFunction ifun(DefaultTensorEngine::ref(), *tree, params.size(), NodeTypes());
InterpretedFunction::Context ctx;
for (double param: params) {
ctx.add_param(param);
}
ifun.eval(ctx);
path += ctx.if_cnt();
}
return path;
}
void report() const {
fprintf(stderr, " number of inputs: %zu\n", inputs.size());
fprintf(stderr, " expression size (AST node count): %zu\n", expression_size);
if (root_is_forest) {
fprintf(stderr, " expression root is a sum of GBD trees\n");
}
if (!forests.empty()) {
fprintf(stderr, " expression contains %zu GBD forest%s\n",
forests.size(), maybe_s(forests.size()));
}
for (size_t i = 0; i < forests.size(); ++i) {
ForestStats forest(forests[i]);
fprintf(stderr, " GBD forest %zu:\n", i);
fprintf(stderr, " average path length: %g\n", forest.total_average_path_length);
fprintf(stderr, " expected path length: %g\n", forest.total_expected_path_length);
fprintf(stderr, " actual path with sample input: %zu\n", get_path_len(forests[i]));
if (forest.total_tuned_checks == 0) {
fprintf(stderr, " WARNING: checks are not tuned (expected path length to be ignored)\n");
}
fprintf(stderr, " largest set membership check: %zu\n", forest.max_set_size);
for (const auto &item: forest.tree_sizes) {
fprintf(stderr, " forest contains %zu GBD tree%s of size %zu\n",
item.count, maybe_s(item.count), item.size);
}
if (forest.tree_sizes.size() > 1) {
fprintf(stderr, " forest contains %zu GBD trees in total\n", forest.num_trees);
}
}
}
};
//-----------------------------------------------------------------------------
bool none_used(const std::vector<Forest::UP> &forests) {
return forests.empty();
}
bool deinline_used(const std::vector<Forest::UP> &forests) {
if (forests.empty()) {
return false;
}
for (const Forest::UP &forest: forests) {
if (dynamic_cast<DeinlineForest*>(forest.get()) == nullptr) {
return false;
}
}
return true;
}
bool vmforest_used(const std::vector<Forest::UP> &forests) {
if (forests.empty()) {
return false;
}
for (const Forest::UP &forest: forests) {
if (dynamic_cast<VMForest*>(forest.get()) == nullptr) {
return false;
}
}
return true;
}
//-----------------------------------------------------------------------------
struct State {
vespalib::string name;
vespalib::string expression;
Function function;
FunctionInfo fun_info;
CompiledFunction::UP compiled_function;
double llvm_compile_s = 0.0;
double llvm_execute_us = 0.0;
std::vector<vespalib::string> options;
std::vector<double> options_us;
explicit State(const vespalib::string &file_name,
vespalib::stringref expression_in)
: name(strip_name(file_name)),
expression(expression_in),
function(Function::parse(expression, FeatureNameExtractor())),
fun_info(function),
compiled_function(),
llvm_compile_s(0.0),
llvm_execute_us(0.0),
options(),
options_us()
{
}
void benchmark_llvm_compile() {
BenchmarkTimer timer(1.0);
while (timer.has_budget()) {
timer.before();
CompiledFunction::UP new_cf(new CompiledFunction(function, PassParams::ARRAY));
timer.after();
compiled_function = std::move(new_cf);
}
llvm_compile_s = timer.min_time();
}
void benchmark_option(const vespalib::string &opt_name, Optimize::Chain optimizer_chain) {
options.push_back(opt_name);
options_us.push_back(CompiledFunction(function, PassParams::ARRAY, optimizer_chain).estimate_cost_us(fun_info.params));
fprintf(stderr, " LLVM(%s) execute time: %g us\n", opt_name.c_str(), options_us.back());
}
void report() {
fun_info.report();
benchmark_llvm_compile();
fprintf(stderr, " LLVM compile time: %g s\n", llvm_compile_s);
llvm_execute_us = compiled_function->estimate_cost_us(fun_info.params);
fprintf(stderr, " LLVM(default) execute time: %g us\n", llvm_execute_us);
if (!none_used(compiled_function->get_forests())) {
benchmark_option("none", Optimize::none);
}
if (!deinline_used(compiled_function->get_forests()) && !fun_info.forests.empty()) {
benchmark_option("deinline", DeinlineForest::optimize_chain);
}
if (!vmforest_used(compiled_function->get_forests()) && !fun_info.forests.empty()) {
benchmark_option("vmforest", VMForest::optimize_chain);
}
fprintf(stdout, "[compile: %.3fs][execute: %.3fus]", llvm_compile_s, llvm_execute_us);
for (size_t i = 0; i < options.size(); ++i) {
double rel_speed = (llvm_execute_us / options_us[i]);
fprintf(stdout, "[%s: %zu%%]", options[i].c_str(), as_percent(rel_speed));
if (rel_speed >= 1.1) {
fprintf(stderr, " WARNING: LLVM(%s) faster than default choice\n",
options[i].c_str());
}
}
fprintf(stdout, "[name: %s]\n", name.c_str());
fflush(stdout);
}
};
//-----------------------------------------------------------------------------
struct MyApp : public FastOS_Application {
int Main();
int usage();
virtual bool useProcessStarter() const { return false; }
};
int
MyApp::usage() {
fprintf(stderr, "usage: %s <expression-file>\n", _argv[0]);
fprintf(stderr, " analyze/benchmark vespa ranking expression\n");
return 1;
}
int
MyApp::Main()
{
if (_argc != 2) {
return usage();
}
vespalib::string file_name(_argv[1]);
File file(file_name);
if (!file.valid()) {
fprintf(stderr, "could not read input file: '%s'\n",
file_name.c_str());
return 1;
}
State state(file_name, vespalib::stringref(file.data, file.size));
if (state.function.has_error()) {
vespalib::string error_message = state.function.get_error();
fprintf(stderr, "input file (%s) contains an illegal expression:\n%s\n",
file_name.c_str(), error_message.c_str());
return 1;
}
fprintf(stderr, "analyzing expression file: '%s'\n",
file_name.c_str());
state.report();
return 0;
}
int main(int argc, char **argv) {
MyApp my_app;
return my_app.Entry(argc, argv);
}
//-----------------------------------------------------------------------------
<commit_msg>use mapped input file<commit_after>// Copyright 2016 Yahoo Inc. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
#include <vespa/fastos/fastos.h>
#include <map>
#include <vespa/searchlib/features/rankingexpression/feature_name_extractor.h>
#include <vector>
#include <vespa/eval/eval/llvm/compiled_function.h>
#include <vespa/eval/eval/function.h>
#include <vespa/eval/eval/interpreted_function.h>
#include <vespa/eval/eval/basic_nodes.h>
#include <vespa/eval/eval/call_nodes.h>
#include <vespa/eval/eval/operator_nodes.h>
#include <vespa/vespalib/util/benchmark_timer.h>
#include <vespa/eval/eval/gbdt.h>
#include <vespa/eval/eval/vm_forest.h>
#include <vespa/eval/eval/llvm/deinline_forest.h>
#include <vespa/eval/tensor/default_tensor_engine.h>
#include <vespa/vespalib/io/mapped_file_input.h>
#include <cmath>
//-----------------------------------------------------------------------------
using vespalib::BenchmarkTimer;
using vespalib::tensor::DefaultTensorEngine;
using namespace vespalib::eval;
using namespace vespalib::eval::nodes;
using namespace vespalib::eval::gbdt;
using namespace search::features::rankingexpression;
//-----------------------------------------------------------------------------
vespalib::string strip_name(const vespalib::string &name) {
const char *expected_ending = ".expression";
vespalib::string tmp = name;
size_t pos = tmp.rfind("/");
if (pos != tmp.npos) {
tmp = tmp.substr(pos + 1);
}
pos = tmp.rfind(expected_ending);
if (pos == tmp.size() - strlen(expected_ending)) {
tmp = tmp.substr(0, pos);
}
return tmp;
}
size_t as_percent(double value) {
return size_t(std::round(value * 100.0));
}
const char *maybe_s(size_t n) { return (n == 1) ? "" : "s"; }
//-----------------------------------------------------------------------------
size_t count_nodes(const Node &node) {
size_t count = 1;
for (size_t i = 0; i < node.num_children(); ++i) {
count += count_nodes(node.get_child(i));
}
return count;
}
//-----------------------------------------------------------------------------
struct InputInfo {
vespalib::string name;
std::vector<double> cmp_with;
explicit InputInfo(vespalib::stringref name_in)
: name(name_in), cmp_with() {}
double select_value() const {
return cmp_with.empty() ? 0.5 : cmp_with[(cmp_with.size()-1)/2];
return 0.5;
}
};
//-----------------------------------------------------------------------------
struct FunctionInfo {
typedef std::vector<const Node *> TreeList;
size_t expression_size;
bool root_is_forest;
std::vector<TreeList> forests;
std::vector<InputInfo> inputs;
std::vector<double> params;
void find_forests(const Node &node) {
if (node.is_forest()) {
forests.push_back(extract_trees(node));
} else {
for (size_t i = 0; i < node.num_children(); ++i) {
find_forests(node.get_child(i));
}
}
}
template <typename T>
void check_cmp(const T *node) {
if (node) {
auto lhs_symbol = as<Symbol>(node->lhs());
auto rhs_symbol = as<Symbol>(node->rhs());
if (lhs_symbol && node->rhs().is_const()) {
inputs[lhs_symbol->id()].cmp_with.push_back(node->rhs().get_const_value());
}
if (node->lhs().is_const() && rhs_symbol) {
inputs[rhs_symbol->id()].cmp_with.push_back(node->lhs().get_const_value());
}
}
}
void check_in(const In *node) {
if (node) {
auto lhs_symbol = as<Symbol>(node->lhs());
auto rhs_symbol = as<Symbol>(node->rhs());
if (lhs_symbol && node->rhs().is_const()) {
auto array = as<Array>(node->rhs());
if (array) {
for (size_t i = 0; i < array->size(); ++i) {
inputs[lhs_symbol->id()].cmp_with.push_back(array->get(i).get_const_value());
}
} else {
inputs[lhs_symbol->id()].cmp_with.push_back(node->rhs().get_const_value());
}
}
if (node->lhs().is_const() && rhs_symbol) {
inputs[rhs_symbol->id()].cmp_with.push_back(node->lhs().get_const_value());
}
}
}
void analyze_inputs(const Node &node) {
for (size_t i = 0; i < node.num_children(); ++i) {
analyze_inputs(node.get_child(i));
}
check_cmp(as<Equal>(node));
check_cmp(as<NotEqual>(node));
check_cmp(as<Approx>(node));
check_cmp(as<Less>(node));
check_cmp(as<LessEqual>(node));
check_cmp(as<Greater>(node));
check_cmp(as<GreaterEqual>(node));
check_in(as<In>(node));
}
FunctionInfo(const Function &function)
: expression_size(count_nodes(function.root())),
root_is_forest(function.root().is_forest()),
forests(),
inputs(),
params()
{
for (size_t i = 0; i < function.num_params(); ++i) {
inputs.emplace_back(function.param_name(i));
}
find_forests(function.root());
analyze_inputs(function.root());
for (size_t i = 0; i < function.num_params(); ++i) {
std::sort(inputs[i].cmp_with.begin(), inputs[i].cmp_with.end());
}
for (size_t i = 0; i < function.num_params(); ++i) {
params.push_back(inputs[i].select_value());
}
}
size_t get_path_len(const TreeList &trees) const {
size_t path = 0;
for (const Node *tree: trees) {
InterpretedFunction ifun(DefaultTensorEngine::ref(), *tree, params.size(), NodeTypes());
InterpretedFunction::Context ctx;
for (double param: params) {
ctx.add_param(param);
}
ifun.eval(ctx);
path += ctx.if_cnt();
}
return path;
}
void report() const {
fprintf(stderr, " number of inputs: %zu\n", inputs.size());
fprintf(stderr, " expression size (AST node count): %zu\n", expression_size);
if (root_is_forest) {
fprintf(stderr, " expression root is a sum of GBD trees\n");
}
if (!forests.empty()) {
fprintf(stderr, " expression contains %zu GBD forest%s\n",
forests.size(), maybe_s(forests.size()));
}
for (size_t i = 0; i < forests.size(); ++i) {
ForestStats forest(forests[i]);
fprintf(stderr, " GBD forest %zu:\n", i);
fprintf(stderr, " average path length: %g\n", forest.total_average_path_length);
fprintf(stderr, " expected path length: %g\n", forest.total_expected_path_length);
fprintf(stderr, " actual path with sample input: %zu\n", get_path_len(forests[i]));
if (forest.total_tuned_checks == 0) {
fprintf(stderr, " WARNING: checks are not tuned (expected path length to be ignored)\n");
}
fprintf(stderr, " largest set membership check: %zu\n", forest.max_set_size);
for (const auto &item: forest.tree_sizes) {
fprintf(stderr, " forest contains %zu GBD tree%s of size %zu\n",
item.count, maybe_s(item.count), item.size);
}
if (forest.tree_sizes.size() > 1) {
fprintf(stderr, " forest contains %zu GBD trees in total\n", forest.num_trees);
}
}
}
};
//-----------------------------------------------------------------------------
bool none_used(const std::vector<Forest::UP> &forests) {
return forests.empty();
}
bool deinline_used(const std::vector<Forest::UP> &forests) {
if (forests.empty()) {
return false;
}
for (const Forest::UP &forest: forests) {
if (dynamic_cast<DeinlineForest*>(forest.get()) == nullptr) {
return false;
}
}
return true;
}
bool vmforest_used(const std::vector<Forest::UP> &forests) {
if (forests.empty()) {
return false;
}
for (const Forest::UP &forest: forests) {
if (dynamic_cast<VMForest*>(forest.get()) == nullptr) {
return false;
}
}
return true;
}
//-----------------------------------------------------------------------------
struct State {
vespalib::string name;
vespalib::string expression;
Function function;
FunctionInfo fun_info;
CompiledFunction::UP compiled_function;
double llvm_compile_s = 0.0;
double llvm_execute_us = 0.0;
std::vector<vespalib::string> options;
std::vector<double> options_us;
explicit State(const vespalib::string &file_name,
vespalib::string expression_in)
: name(strip_name(file_name)),
expression(std::move(expression_in)),
function(Function::parse(expression, FeatureNameExtractor())),
fun_info(function),
compiled_function(),
llvm_compile_s(0.0),
llvm_execute_us(0.0),
options(),
options_us()
{
}
void benchmark_llvm_compile() {
BenchmarkTimer timer(1.0);
while (timer.has_budget()) {
timer.before();
CompiledFunction::UP new_cf(new CompiledFunction(function, PassParams::ARRAY));
timer.after();
compiled_function = std::move(new_cf);
}
llvm_compile_s = timer.min_time();
}
void benchmark_option(const vespalib::string &opt_name, Optimize::Chain optimizer_chain) {
options.push_back(opt_name);
options_us.push_back(CompiledFunction(function, PassParams::ARRAY, optimizer_chain).estimate_cost_us(fun_info.params));
fprintf(stderr, " LLVM(%s) execute time: %g us\n", opt_name.c_str(), options_us.back());
}
void report() {
fun_info.report();
benchmark_llvm_compile();
fprintf(stderr, " LLVM compile time: %g s\n", llvm_compile_s);
llvm_execute_us = compiled_function->estimate_cost_us(fun_info.params);
fprintf(stderr, " LLVM(default) execute time: %g us\n", llvm_execute_us);
if (!none_used(compiled_function->get_forests())) {
benchmark_option("none", Optimize::none);
}
if (!deinline_used(compiled_function->get_forests()) && !fun_info.forests.empty()) {
benchmark_option("deinline", DeinlineForest::optimize_chain);
}
if (!vmforest_used(compiled_function->get_forests()) && !fun_info.forests.empty()) {
benchmark_option("vmforest", VMForest::optimize_chain);
}
fprintf(stdout, "[compile: %.3fs][execute: %.3fus]", llvm_compile_s, llvm_execute_us);
for (size_t i = 0; i < options.size(); ++i) {
double rel_speed = (llvm_execute_us / options_us[i]);
fprintf(stdout, "[%s: %zu%%]", options[i].c_str(), as_percent(rel_speed));
if (rel_speed >= 1.1) {
fprintf(stderr, " WARNING: LLVM(%s) faster than default choice\n",
options[i].c_str());
}
}
fprintf(stdout, "[name: %s]\n", name.c_str());
fflush(stdout);
}
};
//-----------------------------------------------------------------------------
struct MyApp : public FastOS_Application {
int Main();
int usage();
virtual bool useProcessStarter() const { return false; }
};
int
MyApp::usage() {
fprintf(stderr, "usage: %s <expression-file>\n", _argv[0]);
fprintf(stderr, " analyze/benchmark vespa ranking expression\n");
return 1;
}
int
MyApp::Main()
{
if (_argc != 2) {
return usage();
}
vespalib::string file_name(_argv[1]);
vespalib::MappedFileInput file(file_name);
if (!file.valid()) {
fprintf(stderr, "could not read input file: '%s'\n",
file_name.c_str());
return 1;
}
State state(file_name, file.get().make_string());
if (state.function.has_error()) {
vespalib::string error_message = state.function.get_error();
fprintf(stderr, "input file (%s) contains an illegal expression:\n%s\n",
file_name.c_str(), error_message.c_str());
return 1;
}
fprintf(stderr, "analyzing expression file: '%s'\n",
file_name.c_str());
state.report();
return 0;
}
int main(int argc, char **argv) {
MyApp my_app;
return my_app.Entry(argc, argv);
}
//-----------------------------------------------------------------------------
<|endoftext|>
|
<commit_before>// Catch
#include <catch.hpp>
// C++ Standard Library
#include <cstdlib>
#include <string>
// Armadillo
#include <armadillo>
// Mantella
#include <mantella>
extern std::string testDirectory;
TEST_CASE("bbob2013::BuecheRastriginFunction", "") {
for (const auto& numberOfDimensions : {2, 40}) {
mant::bbob2013::BuecheRastriginFunction buecheRastriginFunction(numberOfDimensions);
arma::Mat<double> parameters;
parameters.load(testDirectory + "/data/optimisationProblem/blackBoxOptimisationBenchmark/parameters,dim" + std::to_string(numberOfDimensions) +".mat");
arma::Col<double> translation;
translation.load(testDirectory + "/data/optimisationProblem/blackBoxOptimisationBenchmark/translation,dim" + std::to_string(numberOfDimensions) +".mat");
for (std::size_t n = 0; n < translation.n_elem; n += 2) {
translation(n) = std::abs(translation(n));
}
arma::Col<double> expected;
expected.load(testDirectory + "/data/optimisationProblem/blackBoxOptimisationBenchmark/expectedBuecheRastriginFunction,dim" + std::to_string(numberOfDimensions) +".mat");
buecheRastriginFunction.setObjectiveValueTranslation(0);
buecheRastriginFunction.setParameterTranslation(translation);
for (std::size_t n = 0; n < parameters.n_cols; ++n) {
CHECK(buecheRastriginFunction.getObjectiveValue(parameters.col(n)) == Approx(expected.at(n)));
}
}
SECTION("Returns the specified class name.") {
CHECK(mant::bbob2013::BuecheRastriginFunction(5).toString() == "bueche-rastigin-function");
}
}
<commit_msg>Fixed toString test<commit_after>// Catch
#include <catch.hpp>
// C++ Standard Library
#include <cstdlib>
#include <string>
// Armadillo
#include <armadillo>
// Mantella
#include <mantella>
extern std::string testDirectory;
TEST_CASE("bbob2013::BuecheRastriginFunction", "") {
for (const auto& numberOfDimensions : {2, 40}) {
mant::bbob2013::BuecheRastriginFunction buecheRastriginFunction(numberOfDimensions);
arma::Mat<double> parameters;
parameters.load(testDirectory + "/data/optimisationProblem/blackBoxOptimisationBenchmark/parameters,dim" + std::to_string(numberOfDimensions) +".mat");
arma::Col<double> translation;
translation.load(testDirectory + "/data/optimisationProblem/blackBoxOptimisationBenchmark/translation,dim" + std::to_string(numberOfDimensions) +".mat");
for (std::size_t n = 0; n < translation.n_elem; n += 2) {
translation(n) = std::abs(translation(n));
}
arma::Col<double> expected;
expected.load(testDirectory + "/data/optimisationProblem/blackBoxOptimisationBenchmark/expectedBuecheRastriginFunction,dim" + std::to_string(numberOfDimensions) +".mat");
buecheRastriginFunction.setObjectiveValueTranslation(0);
buecheRastriginFunction.setParameterTranslation(translation);
for (std::size_t n = 0; n < parameters.n_cols; ++n) {
CHECK(buecheRastriginFunction.getObjectiveValue(parameters.col(n)) == Approx(expected.at(n)));
}
}
SECTION("Returns the specified class name.") {
CHECK(mant::bbob2013::BuecheRastriginFunction(5).toString() == "bueche-rastrigin-function");
}
}
<|endoftext|>
|
<commit_before>/*
* Copyright(c) Sophist Solutions, Inc. 1990-2014. All rights reserved
*/
#include "../../StroikaPreComp.h"
#if qPlatform_Windows
#include <Windows.h>
#endif
#include "../../../Foundation/Characters/String_Constant.h"
#include "../../../Foundation/Characters/String2Float.h"
#include "../../../Foundation/Characters/Tokenize.h"
#include "../../../Foundation/Containers/Sequence.h"
#include "../../../Foundation/Debug/Assertions.h"
#include "../../../Foundation/Execution/ProcessRunner.h"
#include "../../../Foundation/Streams/BasicBinaryInputOutputStream.h"
#include "../../../Foundation/Streams/TextInputStreamBinaryAdapter.h"
#include "../CommonMeasurementTypes.h"
#include "MountedFilesystemUsage.h"
using namespace Stroika::Foundation;
using namespace Stroika::Foundation::Containers;
using namespace Stroika::Foundation::DataExchange;
using namespace Stroika::Foundation::Execution;
using namespace Stroika::Foundation::Memory;
using namespace Stroika::Frameworks;
using namespace Stroika::Frameworks::SystemPerformance;
using namespace Stroika::Frameworks::SystemPerformance::Instruments::MountedFilesystemUsage;
using Characters::String_Constant;
namespace {
Sequence<VolumeInfo> capture_ ()
{
Sequence<VolumeInfo> result;
#if qPlatform_Windows
TCHAR volumeNameBuf[1024];
for (HANDLE hVol = FindFirstVolume (volumeNameBuf, NEltsOf(volumeNameBuf)); hVol != INVALID_HANDLE_VALUE; ) {
DWORD lpMaximumComponentLength;
DWORD dwSysFlags;
TCHAR FileSysNameBuf[1024];
if (::GetVolumeInformation( volumeNameBuf, NULL, NEltsOf(volumeNameBuf), NULL, &lpMaximumComponentLength, &dwSysFlags, FileSysNameBuf, NEltsOf(FileSysNameBuf))) {
VolumeInfo v;
v.fFileSystemType = String::FromSDKString (FileSysNameBuf);
v.fVolumeID = String::FromSDKString (volumeNameBuf);
{
// @todo - use
// http://msdn.microsoft.com/en-us/library/windows/desktop/cc542456(v=vs.85).aspx
// CharCount = QueryDosDeviceW(&VolumeName[4], DeviceName, ARRAYSIZE(DeviceName));
// to get DEVICENAME
//
TCHAR volPathsBuf[1024];
DWORD retLen = 0;
DWORD x = GetVolumePathNamesForVolumeName (volumeNameBuf, volPathsBuf, NEltsOf(volPathsBuf), &retLen);
if (volPathsBuf[0] == 0) {
v.fMountedOnName.clear ();
result.push_back (v);
}
else {
for (const TCHAR* NameIdx = volPathsBuf; NameIdx[0] != L'\0'; NameIdx += wcslen(NameIdx) + 1) {
v.fMountedOnName = String::FromSDKString (NameIdx);
{
ULARGE_INTEGER freeBytesAvailable;
ULARGE_INTEGER totalNumberOfBytes;
ULARGE_INTEGER totalNumberOfFreeBytes;
memset (&freeBytesAvailable, 0, sizeof (freeBytesAvailable));
memset (&totalNumberOfBytes, 0, sizeof (totalNumberOfBytes));
memset (&totalNumberOfFreeBytes, 0, sizeof (totalNumberOfFreeBytes));
DWORD xxx = GetDiskFreeSpaceEx (v.fMountedOnName.c_str (), &freeBytesAvailable, &totalNumberOfBytes, &totalNumberOfFreeBytes);
v.fDiskSizeInBytes = static_cast<double> (totalNumberOfBytes.QuadPart);
v.fUsedSizeInBytes = *v.fDiskSizeInBytes - freeBytesAvailable.QuadPart;
}
result.push_back (v);
}
}
}
}
else {
// warning...
}
// find next
if (not ::FindNextVolume (hVol, volumeNameBuf, NEltsOf(volumeNameBuf))) {
FindVolumeClose (hVol);
hVol = INVALID_HANDLE_VALUE;
}
}
#elif qPlatform_POSIX
//
// I looked through the /proc filesystem stuff and didnt see anything obvious to retrive this info...
// run def with ProcessRunner
//
// NEW NOTE - I THINK ITS IN THERE.... RE-EXAMINE proc/filesystems proc/partitions, and http://en.wikipedia.org/wiki/Procfs
// -- LGP 2014-08-01
ProcessRunner pr (SDKSTR ("/bin/df -k -T"));
Streams::BasicBinaryInputOutputStream useStdOut;
pr.SetStdOut (useStdOut);
pr.Run ();
String out;
Streams::TextInputStreamBinaryAdapter stdOut = Streams::TextInputStreamBinaryAdapter (useStdOut);
bool skippedHeader = false;
for (String i = stdOut.ReadLine (); not i.empty (); i = stdOut.ReadLine ()) {
if (not skippedHeader) {
skippedHeader = true;
continue;
}
Sequence<String> l = Characters::Tokenize<String> (i, String_Constant (L" "));
if (l.size () < 7) {
DbgTrace ("skipping line cuz len=%d", l.size ());
continue;
}
VolumeInfo v;
v.fFileSystemType = l[1].Trim ();
v.fMountedOnName = l[6].Trim ();
{
String d = l[0].Trim ();
if (not d.empty () and d != L"none") {
v.fDeviceOrVolumeName = d;
}
}
v.fDiskSizeInBytes = Characters::String2Float<double> (l[2]) * 1024;
v.fUsedSizeInBytes = Characters::String2Float<double> (l[3]) * 1024;
result.Append (v);
}
#endif
return result;
}
}
/*
********************************************************************************
********** Instruments::MountedFilesystemUsage::GetObjectVariantMapper *********
********************************************************************************
*/
ObjectVariantMapper Instruments::MountedFilesystemUsage::GetObjectVariantMapper ()
{
using StructureFieldInfo = ObjectVariantMapper::StructureFieldInfo;
ObjectVariantMapper sMapper_ = [] () -> ObjectVariantMapper {
ObjectVariantMapper mapper;
mapper.AddCommonType<Optional<double>> ();
mapper.AddCommonType<Optional<String>> ();
DISABLE_COMPILER_CLANG_WARNING_START("clang diagnostic ignored \"-Winvalid-offsetof\""); // Really probably an issue, but not to debug here -- LGP 2014-01-04
DISABLE_COMPILER_GCC_WARNING_START("GCC diagnostic ignored \"-Winvalid-offsetof\""); // Really probably an issue, but not to debug here -- LGP 2014-01-04
mapper.AddClass<VolumeInfo> (initializer_list<StructureFieldInfo> {
{ Stroika_Foundation_DataExchange_ObjectVariantMapper_FieldInfoKey (VolumeInfo, fFileSystemType), String_Constant (L"Filesystem-Type"), StructureFieldInfo::NullFieldHandling::eOmit },
{ Stroika_Foundation_DataExchange_ObjectVariantMapper_FieldInfoKey (VolumeInfo, fDeviceOrVolumeName), String_Constant (L"Device-Name"), StructureFieldInfo::NullFieldHandling::eOmit },
{ Stroika_Foundation_DataExchange_ObjectVariantMapper_FieldInfoKey (VolumeInfo, fVolumeID), String_Constant (L"Volume-ID"), StructureFieldInfo::NullFieldHandling::eOmit },
{ Stroika_Foundation_DataExchange_ObjectVariantMapper_FieldInfoKey (VolumeInfo, fMountedOnName), String_Constant (L"Mounted-On") },
{ Stroika_Foundation_DataExchange_ObjectVariantMapper_FieldInfoKey (VolumeInfo, fDiskSizeInBytes), String_Constant (L"Disk-Size"), StructureFieldInfo::NullFieldHandling::eOmit },
{ Stroika_Foundation_DataExchange_ObjectVariantMapper_FieldInfoKey (VolumeInfo, fUsedSizeInBytes), String_Constant (L"Disk-Used-Size"), StructureFieldInfo::NullFieldHandling::eOmit },
});
DISABLE_COMPILER_GCC_WARNING_END("GCC diagnostic ignored \"-Winvalid-offsetof\"");
DISABLE_COMPILER_CLANG_WARNING_END("clang diagnostic ignored \"-Winvalid-offsetof\"");
mapper.AddCommonType<Collection<VolumeInfo>> ();
mapper.AddCommonType<Sequence<VolumeInfo>> ();
return mapper;
} ();
return sMapper_;
}
/*
********************************************************************************
************* Instruments::MountedFilesystemUsage::GetInstrument ***************
********************************************************************************
*/
Instrument SystemPerformance::Instruments::MountedFilesystemUsage::GetInstrument ()
{
static Instrument kInstrument_ = Instrument (
InstrumentNameType (String_Constant (L"Mounted-Filesystem-Usage")),
[] () -> MeasurementSet {
MeasurementSet results;
DateTime before = DateTime::Now ();
Sequence<VolumeInfo> volumes = capture_ ();
results.fMeasuredAt = DateTimeRange (before, DateTime::Now ());
Measurement m;
m.fValue = MountedFilesystemUsage::GetObjectVariantMapper ().FromObject (volumes);
m.fType = kMountedVolumeUsage;
results.fMeasurements.Add (m);
return results;
},
{kMountedVolumeUsage}
);
return kInstrument_;
}
Instrument SystemPerformance::Instruments::GetMountedFilesystemUsage ()
{
return MountedFilesystemUsage::GetInstrument ();
}
<commit_msg>minor fixes for windows narrow-A TCHAR builds<commit_after>/*
* Copyright(c) Sophist Solutions, Inc. 1990-2014. All rights reserved
*/
#include "../../StroikaPreComp.h"
#if qPlatform_Windows
#include <Windows.h>
#endif
#include "../../../Foundation/Characters/CString/Utilities.h"
#include "../../../Foundation/Characters/String_Constant.h"
#include "../../../Foundation/Characters/String2Float.h"
#include "../../../Foundation/Characters/Tokenize.h"
#include "../../../Foundation/Containers/Sequence.h"
#include "../../../Foundation/Debug/Assertions.h"
#include "../../../Foundation/Execution/ProcessRunner.h"
#include "../../../Foundation/Streams/BasicBinaryInputOutputStream.h"
#include "../../../Foundation/Streams/TextInputStreamBinaryAdapter.h"
#include "../CommonMeasurementTypes.h"
#include "MountedFilesystemUsage.h"
using namespace Stroika::Foundation;
using namespace Stroika::Foundation::Containers;
using namespace Stroika::Foundation::DataExchange;
using namespace Stroika::Foundation::Execution;
using namespace Stroika::Foundation::Memory;
using namespace Stroika::Frameworks;
using namespace Stroika::Frameworks::SystemPerformance;
using namespace Stroika::Frameworks::SystemPerformance::Instruments::MountedFilesystemUsage;
using Characters::String_Constant;
namespace {
Sequence<VolumeInfo> capture_ ()
{
Sequence<VolumeInfo> result;
#if qPlatform_Windows
TCHAR volumeNameBuf[1024];
for (HANDLE hVol = FindFirstVolume (volumeNameBuf, NEltsOf(volumeNameBuf)); hVol != INVALID_HANDLE_VALUE; ) {
DWORD lpMaximumComponentLength;
DWORD dwSysFlags;
TCHAR FileSysNameBuf[1024];
if (::GetVolumeInformation( volumeNameBuf, NULL, NEltsOf(volumeNameBuf), NULL, &lpMaximumComponentLength, &dwSysFlags, FileSysNameBuf, NEltsOf(FileSysNameBuf))) {
VolumeInfo v;
v.fFileSystemType = String::FromSDKString (FileSysNameBuf);
v.fVolumeID = String::FromSDKString (volumeNameBuf);
{
// @todo - use
// http://msdn.microsoft.com/en-us/library/windows/desktop/cc542456(v=vs.85).aspx
// CharCount = QueryDosDeviceW(&VolumeName[4], DeviceName, ARRAYSIZE(DeviceName));
// to get DEVICENAME
//
TCHAR volPathsBuf[1024];
DWORD retLen = 0;
DWORD x = GetVolumePathNamesForVolumeName (volumeNameBuf, volPathsBuf, NEltsOf(volPathsBuf), &retLen);
if (volPathsBuf[0] == 0) {
v.fMountedOnName.clear ();
result.push_back (v);
}
else {
for (const TCHAR* NameIdx = volPathsBuf; NameIdx[0] != L'\0'; NameIdx += Characters::CString::Length (NameIdx) + 1) {
v.fMountedOnName = String::FromSDKString (NameIdx);
{
ULARGE_INTEGER freeBytesAvailable;
ULARGE_INTEGER totalNumberOfBytes;
ULARGE_INTEGER totalNumberOfFreeBytes;
memset (&freeBytesAvailable, 0, sizeof (freeBytesAvailable));
memset (&totalNumberOfBytes, 0, sizeof (totalNumberOfBytes));
memset (&totalNumberOfFreeBytes, 0, sizeof (totalNumberOfFreeBytes));
DWORD xxx = GetDiskFreeSpaceEx (v.fMountedOnName.AsSDKString ().c_str (), &freeBytesAvailable, &totalNumberOfBytes, &totalNumberOfFreeBytes);
v.fDiskSizeInBytes = static_cast<double> (totalNumberOfBytes.QuadPart);
v.fUsedSizeInBytes = *v.fDiskSizeInBytes - freeBytesAvailable.QuadPart;
}
result.push_back (v);
}
}
}
}
else {
// warning...
}
// find next
if (not ::FindNextVolume (hVol, volumeNameBuf, NEltsOf(volumeNameBuf))) {
FindVolumeClose (hVol);
hVol = INVALID_HANDLE_VALUE;
}
}
#elif qPlatform_POSIX
//
// I looked through the /proc filesystem stuff and didnt see anything obvious to retrive this info...
// run def with ProcessRunner
//
// NEW NOTE - I THINK ITS IN THERE.... RE-EXAMINE proc/filesystems proc/partitions, and http://en.wikipedia.org/wiki/Procfs
// -- LGP 2014-08-01
ProcessRunner pr (SDKSTR ("/bin/df -k -T"));
Streams::BasicBinaryInputOutputStream useStdOut;
pr.SetStdOut (useStdOut);
pr.Run ();
String out;
Streams::TextInputStreamBinaryAdapter stdOut = Streams::TextInputStreamBinaryAdapter (useStdOut);
bool skippedHeader = false;
for (String i = stdOut.ReadLine (); not i.empty (); i = stdOut.ReadLine ()) {
if (not skippedHeader) {
skippedHeader = true;
continue;
}
Sequence<String> l = Characters::Tokenize<String> (i, String_Constant (L" "));
if (l.size () < 7) {
DbgTrace ("skipping line cuz len=%d", l.size ());
continue;
}
VolumeInfo v;
v.fFileSystemType = l[1].Trim ();
v.fMountedOnName = l[6].Trim ();
{
String d = l[0].Trim ();
if (not d.empty () and d != L"none") {
v.fDeviceOrVolumeName = d;
}
}
v.fDiskSizeInBytes = Characters::String2Float<double> (l[2]) * 1024;
v.fUsedSizeInBytes = Characters::String2Float<double> (l[3]) * 1024;
result.Append (v);
}
#endif
return result;
}
}
/*
********************************************************************************
********** Instruments::MountedFilesystemUsage::GetObjectVariantMapper *********
********************************************************************************
*/
ObjectVariantMapper Instruments::MountedFilesystemUsage::GetObjectVariantMapper ()
{
using StructureFieldInfo = ObjectVariantMapper::StructureFieldInfo;
ObjectVariantMapper sMapper_ = [] () -> ObjectVariantMapper {
ObjectVariantMapper mapper;
mapper.AddCommonType<Optional<double>> ();
mapper.AddCommonType<Optional<String>> ();
DISABLE_COMPILER_CLANG_WARNING_START("clang diagnostic ignored \"-Winvalid-offsetof\""); // Really probably an issue, but not to debug here -- LGP 2014-01-04
DISABLE_COMPILER_GCC_WARNING_START("GCC diagnostic ignored \"-Winvalid-offsetof\""); // Really probably an issue, but not to debug here -- LGP 2014-01-04
mapper.AddClass<VolumeInfo> (initializer_list<StructureFieldInfo> {
{ Stroika_Foundation_DataExchange_ObjectVariantMapper_FieldInfoKey (VolumeInfo, fFileSystemType), String_Constant (L"Filesystem-Type"), StructureFieldInfo::NullFieldHandling::eOmit },
{ Stroika_Foundation_DataExchange_ObjectVariantMapper_FieldInfoKey (VolumeInfo, fDeviceOrVolumeName), String_Constant (L"Device-Name"), StructureFieldInfo::NullFieldHandling::eOmit },
{ Stroika_Foundation_DataExchange_ObjectVariantMapper_FieldInfoKey (VolumeInfo, fVolumeID), String_Constant (L"Volume-ID"), StructureFieldInfo::NullFieldHandling::eOmit },
{ Stroika_Foundation_DataExchange_ObjectVariantMapper_FieldInfoKey (VolumeInfo, fMountedOnName), String_Constant (L"Mounted-On") },
{ Stroika_Foundation_DataExchange_ObjectVariantMapper_FieldInfoKey (VolumeInfo, fDiskSizeInBytes), String_Constant (L"Disk-Size"), StructureFieldInfo::NullFieldHandling::eOmit },
{ Stroika_Foundation_DataExchange_ObjectVariantMapper_FieldInfoKey (VolumeInfo, fUsedSizeInBytes), String_Constant (L"Disk-Used-Size"), StructureFieldInfo::NullFieldHandling::eOmit },
});
DISABLE_COMPILER_GCC_WARNING_END("GCC diagnostic ignored \"-Winvalid-offsetof\"");
DISABLE_COMPILER_CLANG_WARNING_END("clang diagnostic ignored \"-Winvalid-offsetof\"");
mapper.AddCommonType<Collection<VolumeInfo>> ();
mapper.AddCommonType<Sequence<VolumeInfo>> ();
return mapper;
} ();
return sMapper_;
}
/*
********************************************************************************
************* Instruments::MountedFilesystemUsage::GetInstrument ***************
********************************************************************************
*/
Instrument SystemPerformance::Instruments::MountedFilesystemUsage::GetInstrument ()
{
static Instrument kInstrument_ = Instrument (
InstrumentNameType (String_Constant (L"Mounted-Filesystem-Usage")),
[] () -> MeasurementSet {
MeasurementSet results;
DateTime before = DateTime::Now ();
Sequence<VolumeInfo> volumes = capture_ ();
results.fMeasuredAt = DateTimeRange (before, DateTime::Now ());
Measurement m;
m.fValue = MountedFilesystemUsage::GetObjectVariantMapper ().FromObject (volumes);
m.fType = kMountedVolumeUsage;
results.fMeasurements.Add (m);
return results;
},
{kMountedVolumeUsage}
);
return kInstrument_;
}
Instrument SystemPerformance::Instruments::GetMountedFilesystemUsage ()
{
return MountedFilesystemUsage::GetInstrument ();
}
<|endoftext|>
|
<commit_before>/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "OpenwireEnhancedConnectionTest.h"
#include <activemq/core/ActiveMQConnectionFactory.h>
#include <activemq/core/ActiveMQConnection.h>
#include <activemq/core/ActiveMQSession.h>
#include <activemq/exceptions/ActiveMQException.h>
#include <decaf/lang/Pointer.h>
#include <decaf/lang/Thread.h>
#include <decaf/lang/Thread.h>
#include <decaf/util/UUID.h>
#include <decaf/util/concurrent/TimeUnit.h>
#include <cms/ConnectionFactory.h>
#include <cms/Connection.h>
#include <cms/Session.h>
#include <cms/ConnectionFactory.h>
#include <cms/Connection.h>
#include <cms/DestinationListener.h>
#include <cms/DestinationSource.h>
#include <cms/EnhancedConnection.h>
#include <memory>
using namespace cms;
using namespace std;
using namespace decaf;
using namespace decaf::lang;
using namespace decaf::lang::exceptions;
using namespace decaf::util;
using namespace decaf::util::concurrent;
using namespace activemq;
using namespace activemq::core;
using namespace activemq::commands;
using namespace activemq::exceptions;
using namespace activemq::test;
using namespace activemq::test::openwire;
////////////////////////////////////////////////////////////////////////////////
OpenwireEnhancedConnectionTest::OpenwireEnhancedConnectionTest() {
}
////////////////////////////////////////////////////////////////////////////////
OpenwireEnhancedConnectionTest::~OpenwireEnhancedConnectionTest() {
}
////////////////////////////////////////////////////////////////////////////////
namespace {
class TestDestinationListener : public DestinationListener {
public:
int queueCount;
int topicCount;
int tempQueueCount;
int tempTopicCount;
TestDestinationListener() : DestinationListener(),
queueCount(0),
topicCount(0),
tempQueueCount(0),
tempTopicCount(0) {
}
virtual void onDestinationEvent(cms::DestinationEvent* event) {
cms::Destination::DestinationType type = event->getDestination()->getDestinationType();
switch (type) {
case cms::Destination::QUEUE:
if (event->isAddOperation()) {
queueCount++;
} else {
queueCount--;
}
break;
case cms::Destination::TOPIC:
if (event->isAddOperation()) {
topicCount++;
} else {
topicCount--;
}
break;
case cms::Destination::TEMPORARY_QUEUE:
if (event->isAddOperation()) {
tempQueueCount++;
} else {
tempQueueCount--;
}
break;
case cms::Destination::TEMPORARY_TOPIC:
if (event->isAddOperation()) {
tempTopicCount++;
} else {
tempTopicCount--;
}
break;
default:
break;
}
}
void reset() {
queueCount = 0;
topicCount = 0;
tempQueueCount = 0;
tempTopicCount = 0;
}
};
}
////////////////////////////////////////////////////////////////////////////////
void OpenwireEnhancedConnectionTest::testDestinationSourceGetters() {
TestDestinationListener listener;
std::auto_ptr<ConnectionFactory> factory(
ConnectionFactory::createCMSConnectionFactory( getBrokerURL() ) );
CPPUNIT_ASSERT( factory.get() != NULL );
std::auto_ptr<Connection> connection( factory->createConnection() );
CPPUNIT_ASSERT( connection.get() != NULL );
std::auto_ptr<Session> session( connection->createSession() );
CPPUNIT_ASSERT( session.get() != NULL );
ActiveMQConnection* amq = dynamic_cast<ActiveMQConnection*>(connection.get());
CPPUNIT_ASSERT(amq != NULL);
cms::EnhancedConnection* enhanced = dynamic_cast<cms::EnhancedConnection*>(connection.get());
CPPUNIT_ASSERT(enhanced != NULL);
std::auto_ptr<cms::DestinationSource> source(enhanced->getDestinationSource());
CPPUNIT_ASSERT(source.get() != NULL);
source->setListener(&listener);
connection->start();
source->start();
std::auto_ptr<Destination> destination1( session->createTopic("Test.Topic") );
std::auto_ptr<MessageConsumer> consumer1( session->createConsumer( destination1.get() ) );
std::auto_ptr<Destination> destination2( session->createQueue("Test.Queue") );
std::auto_ptr<MessageConsumer> consumer2( session->createConsumer( destination2.get() ) );
consumer1->close();
consumer2->close();
std::auto_ptr<Destination> destination3( session->createTemporaryQueue() );
std::auto_ptr<Destination> destination4( session->createTemporaryTopic() );
Thread::sleep(1500);
CPPUNIT_ASSERT_EQUAL_MESSAGE("Should be one Queue", 1, listener.queueCount);
CPPUNIT_ASSERT_MESSAGE("Should be at least Topic", listener.topicCount >= 1);
CPPUNIT_ASSERT_EQUAL_MESSAGE("Should be one temp Queue", 1, listener.tempQueueCount);
CPPUNIT_ASSERT_EQUAL_MESSAGE("Should be one temp Topic", 1, listener.tempTopicCount);
amq->destroyDestination(destination1.get());
amq->destroyDestination(destination2.get());
Thread::sleep(1500);
CPPUNIT_ASSERT_EQUAL_MESSAGE("Should be no Queues", 0, listener.queueCount);
source->stop();
std::auto_ptr<Destination> destination5( session->createTemporaryQueue() );
std::auto_ptr<Destination> destination6( session->createTemporaryTopic() );
CPPUNIT_ASSERT_EQUAL_MESSAGE("Should be one temp Queue", 1, listener.tempQueueCount);
CPPUNIT_ASSERT_EQUAL_MESSAGE("Should be one temp Topic", 1, listener.tempTopicCount);
listener.reset();
source->start();
std::auto_ptr<Destination> destination7( session->createTemporaryQueue() );
std::auto_ptr<Destination> destination8( session->createTemporaryTopic() );
Thread::sleep(1500);
CPPUNIT_ASSERT_EQUAL_MESSAGE("Should be two temp Queues", 3, listener.tempQueueCount);
CPPUNIT_ASSERT_EQUAL_MESSAGE("Should be two temp Topics", 3, listener.tempTopicCount);
source->stop();
connection->close();
}
////////////////////////////////////////////////////////////////////////////////
void OpenwireEnhancedConnectionTest::testDestinationSource() {
TestDestinationListener listener;
std::auto_ptr<ConnectionFactory> factory(
ConnectionFactory::createCMSConnectionFactory( getBrokerURL() ) );
CPPUNIT_ASSERT( factory.get() != NULL );
std::auto_ptr<Connection> connection( factory->createConnection() );
CPPUNIT_ASSERT( connection.get() != NULL );
std::auto_ptr<Session> session( connection->createSession() );
CPPUNIT_ASSERT( session.get() != NULL );
ActiveMQConnection* amq = dynamic_cast<ActiveMQConnection*>(connection.get());
CPPUNIT_ASSERT(amq != NULL);
cms::EnhancedConnection* enhanced = dynamic_cast<cms::EnhancedConnection*>(connection.get());
CPPUNIT_ASSERT(enhanced != NULL);
std::auto_ptr<cms::DestinationSource> source(enhanced->getDestinationSource());
CPPUNIT_ASSERT(source.get() != NULL);
source->setListener(&listener);
connection->start();
source->start();
TimeUnit::SECONDS.sleep(1);
CPPUNIT_ASSERT_EQUAL(0, (int)source->getQueues().size());
CPPUNIT_ASSERT_EQUAL(0, (int)source->getTopics().size());
CPPUNIT_ASSERT_EQUAL(0, (int)source->getTemporaryQueues().size());
CPPUNIT_ASSERT_EQUAL(0, (int)source->getTemporaryTopics().size());
std::auto_ptr<Destination> destination1(session->createTemporaryQueue());
std::auto_ptr<Destination> destination2(session->createTemporaryTopic());
std::auto_ptr<Destination> destination3(session->createTemporaryQueue());
std::auto_ptr<Destination> destination4(session->createTemporaryTopic());
std::auto_ptr<Destination> destination5(session->createTemporaryQueue());
std::auto_ptr<Destination> destination6(session->createTemporaryTopic());
TimeUnit::SECONDS.sleep(2);
std::vector<cms::TemporaryQueue*> tempQueues = source->getTemporaryQueues();
std::vector<cms::TemporaryTopic*> tempTopics = source->getTemporaryTopics();
CPPUNIT_ASSERT_EQUAL(3, (int)tempQueues.size());
CPPUNIT_ASSERT_EQUAL(3, (int)tempTopics.size());
for (int i = 0; i < 3; ++i) {
delete tempQueues[i];
delete tempTopics[i];
}
source->stop();
connection->close();
}
<commit_msg>make test tolerant of running on a non-clean broker. <commit_after>/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "OpenwireEnhancedConnectionTest.h"
#include <activemq/core/ActiveMQConnectionFactory.h>
#include <activemq/core/ActiveMQConnection.h>
#include <activemq/core/ActiveMQSession.h>
#include <activemq/exceptions/ActiveMQException.h>
#include <decaf/lang/Pointer.h>
#include <decaf/lang/Thread.h>
#include <decaf/lang/Thread.h>
#include <decaf/util/UUID.h>
#include <decaf/util/concurrent/TimeUnit.h>
#include <cms/ConnectionFactory.h>
#include <cms/Connection.h>
#include <cms/Session.h>
#include <cms/ConnectionFactory.h>
#include <cms/Connection.h>
#include <cms/DestinationListener.h>
#include <cms/DestinationSource.h>
#include <cms/EnhancedConnection.h>
#include <memory>
using namespace cms;
using namespace std;
using namespace decaf;
using namespace decaf::lang;
using namespace decaf::lang::exceptions;
using namespace decaf::util;
using namespace decaf::util::concurrent;
using namespace activemq;
using namespace activemq::core;
using namespace activemq::commands;
using namespace activemq::exceptions;
using namespace activemq::test;
using namespace activemq::test::openwire;
////////////////////////////////////////////////////////////////////////////////
OpenwireEnhancedConnectionTest::OpenwireEnhancedConnectionTest() {
}
////////////////////////////////////////////////////////////////////////////////
OpenwireEnhancedConnectionTest::~OpenwireEnhancedConnectionTest() {
}
////////////////////////////////////////////////////////////////////////////////
namespace {
class TestDestinationListener : public DestinationListener {
public:
int queueCount;
int topicCount;
int tempQueueCount;
int tempTopicCount;
TestDestinationListener() : DestinationListener(),
queueCount(0),
topicCount(0),
tempQueueCount(0),
tempTopicCount(0) {
}
virtual void onDestinationEvent(cms::DestinationEvent* event) {
cms::Destination::DestinationType type = event->getDestination()->getDestinationType();
switch (type) {
case cms::Destination::QUEUE:
if (event->isAddOperation()) {
queueCount++;
} else {
queueCount--;
}
break;
case cms::Destination::TOPIC:
if (event->isAddOperation()) {
topicCount++;
} else {
topicCount--;
}
break;
case cms::Destination::TEMPORARY_QUEUE:
if (event->isAddOperation()) {
tempQueueCount++;
} else {
tempQueueCount--;
}
break;
case cms::Destination::TEMPORARY_TOPIC:
if (event->isAddOperation()) {
tempTopicCount++;
} else {
tempTopicCount--;
}
break;
default:
break;
}
}
void reset() {
queueCount = 0;
topicCount = 0;
tempQueueCount = 0;
tempTopicCount = 0;
}
};
}
////////////////////////////////////////////////////////////////////////////////
void OpenwireEnhancedConnectionTest::testDestinationSourceGetters() {
TestDestinationListener listener;
std::auto_ptr<ConnectionFactory> factory(
ConnectionFactory::createCMSConnectionFactory( getBrokerURL() ) );
CPPUNIT_ASSERT( factory.get() != NULL );
std::auto_ptr<Connection> connection( factory->createConnection() );
CPPUNIT_ASSERT( connection.get() != NULL );
std::auto_ptr<Session> session( connection->createSession() );
CPPUNIT_ASSERT( session.get() != NULL );
ActiveMQConnection* amq = dynamic_cast<ActiveMQConnection*>(connection.get());
CPPUNIT_ASSERT(amq != NULL);
cms::EnhancedConnection* enhanced = dynamic_cast<cms::EnhancedConnection*>(connection.get());
CPPUNIT_ASSERT(enhanced != NULL);
std::auto_ptr<cms::DestinationSource> source(enhanced->getDestinationSource());
CPPUNIT_ASSERT(source.get() != NULL);
source->setListener(&listener);
connection->start();
source->start();
TimeUnit::SECONDS.sleep(2);
int currentQueueCount = listener.queueCount;
int currentTopicCount = listener.topicCount;
int currentTempQueueCount = listener.tempQueueCount;
int currentTempTopicCount = listener.tempTopicCount;
std::auto_ptr<Destination> destination1( session->createTopic("Test.Topic") );
std::auto_ptr<MessageConsumer> consumer1( session->createConsumer( destination1.get() ) );
std::auto_ptr<Destination> destination2( session->createQueue("Test.Queue") );
std::auto_ptr<MessageConsumer> consumer2( session->createConsumer( destination2.get() ) );
consumer1->close();
consumer2->close();
std::auto_ptr<Destination> destination3( session->createTemporaryQueue() );
std::auto_ptr<Destination> destination4( session->createTemporaryTopic() );
TimeUnit::SECONDS.sleep(2);
CPPUNIT_ASSERT_EQUAL_MESSAGE("Should be one Queue", currentQueueCount + 1, listener.queueCount);
CPPUNIT_ASSERT_MESSAGE("Should be at least Topic", listener.topicCount > currentTopicCount);
CPPUNIT_ASSERT_EQUAL_MESSAGE("Should be one temp Queue", currentTempQueueCount + 1, listener.tempQueueCount);
CPPUNIT_ASSERT_EQUAL_MESSAGE("Should be one temp Topic", currentTempTopicCount + 1, listener.tempTopicCount);
amq->destroyDestination(destination1.get());
amq->destroyDestination(destination2.get());
TimeUnit::SECONDS.sleep(2);
CPPUNIT_ASSERT_EQUAL_MESSAGE("Should be no Queues created by this test",
currentQueueCount, listener.queueCount);
source->stop();
std::auto_ptr<Destination> destination5( session->createTemporaryQueue() );
std::auto_ptr<Destination> destination6( session->createTemporaryTopic() );
CPPUNIT_ASSERT_EQUAL_MESSAGE("Temp Queue Counts shouldn't change", currentTempQueueCount + 1, listener.tempQueueCount);
CPPUNIT_ASSERT_EQUAL_MESSAGE("Temp Topic Counts shouldn't change", currentTempTopicCount + 1, listener.tempTopicCount);
listener.reset();
source->start();
std::auto_ptr<Destination> destination7( session->createTemporaryQueue() );
std::auto_ptr<Destination> destination8( session->createTemporaryTopic() );
TimeUnit::SECONDS.sleep(2);
CPPUNIT_ASSERT_EQUAL_MESSAGE("Should be three total temp Queues from this test",
currentTempQueueCount + 3, listener.tempQueueCount);
CPPUNIT_ASSERT_EQUAL_MESSAGE("Should be three total temp Topics from this test",
currentTempTopicCount + 3, listener.tempTopicCount);
source->stop();
connection->close();
}
////////////////////////////////////////////////////////////////////////////////
void OpenwireEnhancedConnectionTest::testDestinationSource() {
TestDestinationListener listener;
std::auto_ptr<ConnectionFactory> factory(
ConnectionFactory::createCMSConnectionFactory( getBrokerURL() ) );
CPPUNIT_ASSERT( factory.get() != NULL );
std::auto_ptr<Connection> connection( factory->createConnection() );
CPPUNIT_ASSERT( connection.get() != NULL );
std::auto_ptr<Session> session( connection->createSession() );
CPPUNIT_ASSERT( session.get() != NULL );
ActiveMQConnection* amq = dynamic_cast<ActiveMQConnection*>(connection.get());
CPPUNIT_ASSERT(amq != NULL);
cms::EnhancedConnection* enhanced = dynamic_cast<cms::EnhancedConnection*>(connection.get());
CPPUNIT_ASSERT(enhanced != NULL);
std::auto_ptr<cms::DestinationSource> source(enhanced->getDestinationSource());
CPPUNIT_ASSERT(source.get() != NULL);
source->setListener(&listener);
connection->start();
source->start();
TimeUnit::SECONDS.sleep(2);
int currTempQueueCount = (int)source->getTemporaryQueues().size();
int currTempTopicCount = (int)source->getTemporaryTopics().size();
std::auto_ptr<Destination> destination1(session->createTemporaryQueue());
std::auto_ptr<Destination> destination2(session->createTemporaryTopic());
std::auto_ptr<Destination> destination3(session->createTemporaryQueue());
std::auto_ptr<Destination> destination4(session->createTemporaryTopic());
std::auto_ptr<Destination> destination5(session->createTemporaryQueue());
std::auto_ptr<Destination> destination6(session->createTemporaryTopic());
TimeUnit::SECONDS.sleep(2);
std::vector<cms::TemporaryQueue*> tempQueues = source->getTemporaryQueues();
std::vector<cms::TemporaryTopic*> tempTopics = source->getTemporaryTopics();
CPPUNIT_ASSERT_EQUAL(currTempQueueCount + 3, (int)tempQueues.size());
CPPUNIT_ASSERT_EQUAL(currTempTopicCount + 3, (int)tempTopics.size());
for (int i = 0; i < 3; ++i) {
delete tempQueues[i];
delete tempTopics[i];
}
source->stop();
connection->close();
}
<|endoftext|>
|
<commit_before>// for some reason, we have to include windows.h for this to run
#ifdef _MSC_VER
#include <windows.h>
#endif
#include <wx/wx.h>
#include <audiere.h>
using namespace audiere;
bool TryDevice(const char* name);
enum {
DEVICE_NEW_DEVICE,
DEVICE_OPEN_STREAM,
DEVICE_OPEN_SOUND,
DEVICE_CREATE_TONE,
DEVICE_CLOSE,
STREAM_PLAY,
STREAM_STOP,
STREAM_RESET,
STREAM_REPEAT,
STREAM_VOLUME,
STREAM_PAN,
STREAM_POS,
STREAM_UPDATE,
};
class StreamFrame : public wxMDIChildFrame {
public:
StreamFrame(wxMDIParentFrame* parent, wxString& title, OutputStream* stream)
: wxMDIChildFrame(parent, -1, title)
{
m_stream = stream;
int slider_max = (m_stream->isSeekable() ? m_stream->getLength() : 1);
m_repeating = new wxCheckBox(this, STREAM_REPEAT, "Repeating");
m_volume_pan_label = new wxStaticText(this, -1, "Volume - Pan");
m_volume = new wxSlider(this, STREAM_VOLUME, 100, 0, 100);
m_pan = new wxSlider(this, STREAM_PAN, 0, -100, 100);
m_length_pos_label = new wxStaticText(this, -1, "Length - Pos");
m_pos = new wxSlider(this, STREAM_POS, 0, 0, slider_max);
wxBoxSizer* sizer = new wxBoxSizer(wxVERTICAL);
sizer->Add(
new wxButton(this, STREAM_PLAY, "Play"),
1, wxEXPAND | wxALL, 4);
sizer->Add(
new wxButton(this, STREAM_STOP, "Stop"),
1, wxEXPAND | wxALL, 4);
sizer->Add(
new wxButton(this, STREAM_RESET, "Reset"),
1, wxEXPAND | wxALL, 4);
sizer->Add(m_repeating, 1, wxEXPAND | wxALL, 4);
sizer->Add(m_volume_pan_label, 1, wxEXPAND | wxALL, 4);
sizer->Add(m_volume, 1, wxEXPAND | wxALL, 4);
sizer->Add(m_pan, 1, wxEXPAND | wxALL, 4);
sizer->Add(m_length_pos_label, 1, wxEXPAND | wxALL, 4);
sizer->Add(m_pos, 1, wxEXPAND | wxALL, 4);
if (!m_stream->isSeekable()) {
m_pos->Enable(false);
}
UpdateVolumePanLabel();
UpdateLengthPosLabel();
SetAutoLayout(true);
SetSizer(sizer);
sizer->Fit(this);
sizer->SetSizeHints(this);
// create a timer to update the current position
wxTimer* timer = new wxTimer(this, STREAM_UPDATE);
timer->Start(200);
}
void OnPlay() {
m_stream->play();
}
void OnStop() {
m_stream->stop();
}
void OnReset() {
m_stream->reset();
}
void OnRepeat() {
m_stream->setRepeat(m_repeating->GetValue());
}
void OnChangeVolume() {
m_stream->setVolume(m_volume->GetValue() / 100.0f);
UpdateVolumePanLabel();
}
void OnChangePan() {
m_stream->setPan(m_pan->GetValue() / 100.0f);
UpdateVolumePanLabel();
}
void OnChangePos() {
m_stream->setPosition(m_pos->GetValue());
}
void OnUpdatePosition() {
if (m_stream->isSeekable()) {
m_pos->SetValue(m_stream->getPosition());
}
UpdateLengthPosLabel();
}
void UpdateVolumePanLabel() {
wxString label;
label.Printf(
"Volume: %1.2f Pan: %1.2f",
m_volume->GetValue() / 100.0f,
m_pan->GetValue() / 100.0f);
m_volume_pan_label->SetLabel(label);
}
void UpdateLengthPosLabel() {
if (m_stream->isSeekable()) {
wxString label;
label.Printf(
"Length: %d Pos: %d",
m_stream->getLength(),
m_stream->getPosition());
m_length_pos_label->SetLabel(label);
} else {
m_length_pos_label->SetLabel("Unseekable Stream");
}
}
private:
RefPtr<OutputStream> m_stream;
wxCheckBox* m_repeating;
wxStaticText* m_volume_pan_label;
wxSlider* m_volume;
wxSlider* m_pan;
wxStaticText* m_length_pos_label;
wxSlider* m_pos;
DECLARE_EVENT_TABLE()
};
BEGIN_EVENT_TABLE(StreamFrame, wxMDIChildFrame)
EVT_BUTTON(STREAM_PLAY, StreamFrame::OnPlay)
EVT_BUTTON(STREAM_STOP, StreamFrame::OnStop)
EVT_BUTTON(STREAM_RESET, StreamFrame::OnReset)
EVT_CHECKBOX(STREAM_REPEAT, StreamFrame::OnRepeat)
EVT_COMMAND_SCROLL(STREAM_VOLUME, StreamFrame::OnChangeVolume)
EVT_COMMAND_SCROLL(STREAM_PAN, StreamFrame::OnChangePan)
EVT_COMMAND_SCROLL(STREAM_POS, StreamFrame::OnChangePos)
EVT_TIMER(STREAM_UPDATE, StreamFrame::OnUpdatePosition)
END_EVENT_TABLE()
class DeviceFrame : public wxMDIParentFrame {
public:
DeviceFrame(AudioDevice* device, const wxString& device_name)
: wxMDIParentFrame(NULL, -1, "Device Window - " + device_name)
{
m_device = device;
wxMenu* fileMenu = new wxMenu();
fileMenu->Append(DEVICE_NEW_DEVICE, "&New Device...");
fileMenu->AppendSeparator();
fileMenu->Append(DEVICE_OPEN_STREAM, "&Open Stream...");
fileMenu->Append(DEVICE_OPEN_SOUND, "Open &Sound...");
fileMenu->Append(DEVICE_CREATE_TONE, "Create &Tone...");
fileMenu->AppendSeparator();
fileMenu->Append(DEVICE_CLOSE, "&Close Device");
wxMenuBar* menuBar = new wxMenuBar();
menuBar->Append(fileMenu, "&Device");
SetMenuBar(menuBar);
}
void OnDeviceNewDevice() {
wxString name = wxGetTextFromUser(
"New Device",
"Enter Device Name",
"autodetect",
this);
if (!name.empty()) {
if (!TryDevice(name)) {
wxMessageBox(
"Could not open audio device: " + name,
"New Device", wxOK | wxCENTRE, this);
}
}
}
wxString GetSoundFile() {
return wxFileSelector(
"Select a sound file", "", "", "",
"Sound Files (*.wav,*.ogg,*.mod,*.it,*.xm,*.s3m)|" \
"*.wav;*.ogg;*.mod;*.it;*.xm;*.s3m",
wxOPEN, this);
}
void OnDeviceOpenStream() {
wxString filename(GetSoundFile());
if (filename.empty()) {
return;
}
OutputStream* stream = m_device->openStream(OpenSampleSource(filename));
if (!stream) {
wxMessageBox(
"Could not open stream: " + filename,
"Open Stream", wxOK | wxCENTRE, this);
return;
}
// get the basename of the path for the window title
wxString basename = wxFileNameFromPath(filename);;
wxString title;
title.sprintf("Stream: %s", basename.c_str());
new StreamFrame(this, title, stream);
}
void OnDeviceOpenSound() {
wxString filename(GetSoundFile());
if (filename.empty()) {
return;
}
OutputStream* stream = OpenSound(m_device.get(), filename);
if (!stream) {
wxMessageBox(
"Could not open sound: " + filename,
"Open Stream", wxOK | wxCENTRE, this);
return;
}
// get the basename of the path for the window title
wxString basename = wxFileNameFromPath(filename);;
wxString title;
title.sprintf("Sound: %s", basename.c_str());
new StreamFrame(this, title, stream);
}
void OnDeviceCreateTone() {
int frequency = wxGetNumberFromUser(
"Value must be between 1 and 30000.", "Enter frequency in Hz",
"Create Tone", 256, 1, 30000, this);
if (frequency != -1) {
OutputStream* stream = m_device->openStream(CreateTone(frequency));
if (!stream) {
wxMessageBox(
"Could not open output stream",
"Create Tone", wxOK | wxCENTRE, this);
} else {
wxString title;
title.sprintf("Tone: %d Hz", frequency);
new StreamFrame(this, title, stream);
}
}
}
void OnDeviceClose() {
Close();
}
private:
RefPtr<AudioDevice> m_device;
DECLARE_EVENT_TABLE()
};
BEGIN_EVENT_TABLE(DeviceFrame, wxMDIParentFrame)
EVT_MENU(DEVICE_NEW_DEVICE, DeviceFrame::OnDeviceNewDevice)
EVT_MENU(DEVICE_OPEN_STREAM, DeviceFrame::OnDeviceOpenStream)
EVT_MENU(DEVICE_OPEN_SOUND, DeviceFrame::OnDeviceOpenSound)
EVT_MENU(DEVICE_CREATE_TONE, DeviceFrame::OnDeviceCreateTone)
EVT_MENU(DEVICE_CLOSE, DeviceFrame::OnDeviceClose)
END_EVENT_TABLE()
bool TryDevice(const char* name) {
if (RefPtr<AudioDevice> device = audiere::OpenDevice(name)) {
DeviceFrame* frame = new DeviceFrame(device.get(), name);
frame->Show(true);
return true;
} else {
return false;
}
}
class wxPlayer : public wxApp {
public:
bool OnInit() {
bool result = (TryDevice("autodetect") || TryDevice("null"));
if (!result) {
wxMessageBox("Could not open output device", "wxPlayer");
}
return result;
}
};
IMPLEMENT_APP(wxPlayer)
<commit_msg>update wxPlayer for new OpenSound API<commit_after>// for some reason, we have to include windows.h for this to run
#ifdef _MSC_VER
#include <windows.h>
#endif
#include <wx/wx.h>
#include <audiere.h>
using namespace audiere;
bool TryDevice(const char* name);
enum {
DEVICE_NEW_DEVICE,
DEVICE_OPEN_STREAM,
DEVICE_OPEN_SOUND,
DEVICE_CREATE_TONE,
DEVICE_CLOSE,
STREAM_PLAY,
STREAM_STOP,
STREAM_RESET,
STREAM_REPEAT,
STREAM_VOLUME,
STREAM_PAN,
STREAM_POS,
STREAM_UPDATE,
};
class StreamFrame : public wxMDIChildFrame {
public:
StreamFrame(wxMDIParentFrame* parent, wxString& title, OutputStream* stream)
: wxMDIChildFrame(parent, -1, title)
{
m_stream = stream;
int slider_max = (m_stream->isSeekable() ? m_stream->getLength() : 1);
m_repeating = new wxCheckBox(this, STREAM_REPEAT, "Repeating");
m_volume_pan_label = new wxStaticText(this, -1, "Volume - Pan");
m_volume = new wxSlider(this, STREAM_VOLUME, 100, 0, 100);
m_pan = new wxSlider(this, STREAM_PAN, 0, -100, 100);
m_length_pos_label = new wxStaticText(this, -1, "Length - Pos");
m_pos = new wxSlider(this, STREAM_POS, 0, 0, slider_max);
wxBoxSizer* sizer = new wxBoxSizer(wxVERTICAL);
sizer->Add(
new wxButton(this, STREAM_PLAY, "Play"),
1, wxEXPAND | wxALL, 4);
sizer->Add(
new wxButton(this, STREAM_STOP, "Stop"),
1, wxEXPAND | wxALL, 4);
sizer->Add(
new wxButton(this, STREAM_RESET, "Reset"),
1, wxEXPAND | wxALL, 4);
sizer->Add(m_repeating, 1, wxEXPAND | wxALL, 4);
sizer->Add(m_volume_pan_label, 1, wxEXPAND | wxALL, 4);
sizer->Add(m_volume, 1, wxEXPAND | wxALL, 4);
sizer->Add(m_pan, 1, wxEXPAND | wxALL, 4);
sizer->Add(m_length_pos_label, 1, wxEXPAND | wxALL, 4);
sizer->Add(m_pos, 1, wxEXPAND | wxALL, 4);
if (!m_stream->isSeekable()) {
m_pos->Enable(false);
}
UpdateVolumePanLabel();
UpdateLengthPosLabel();
SetAutoLayout(true);
SetSizer(sizer);
sizer->Fit(this);
sizer->SetSizeHints(this);
// create a timer to update the current position
wxTimer* timer = new wxTimer(this, STREAM_UPDATE);
timer->Start(200);
}
void OnPlay() {
m_stream->play();
}
void OnStop() {
m_stream->stop();
}
void OnReset() {
m_stream->reset();
}
void OnRepeat() {
m_stream->setRepeat(m_repeating->GetValue());
}
void OnChangeVolume() {
m_stream->setVolume(m_volume->GetValue() / 100.0f);
UpdateVolumePanLabel();
}
void OnChangePan() {
m_stream->setPan(m_pan->GetValue() / 100.0f);
UpdateVolumePanLabel();
}
void OnChangePos() {
m_stream->setPosition(m_pos->GetValue());
}
void OnUpdatePosition() {
if (m_stream->isSeekable()) {
m_pos->SetValue(m_stream->getPosition());
}
UpdateLengthPosLabel();
}
void UpdateVolumePanLabel() {
wxString label;
label.Printf(
"Volume: %1.2f Pan: %1.2f",
m_volume->GetValue() / 100.0f,
m_pan->GetValue() / 100.0f);
m_volume_pan_label->SetLabel(label);
}
void UpdateLengthPosLabel() {
if (m_stream->isSeekable()) {
wxString label;
label.Printf(
"Length: %d Pos: %d",
m_stream->getLength(),
m_stream->getPosition());
m_length_pos_label->SetLabel(label);
} else {
m_length_pos_label->SetLabel("Unseekable Stream");
}
}
private:
RefPtr<OutputStream> m_stream;
wxCheckBox* m_repeating;
wxStaticText* m_volume_pan_label;
wxSlider* m_volume;
wxSlider* m_pan;
wxStaticText* m_length_pos_label;
wxSlider* m_pos;
DECLARE_EVENT_TABLE()
};
BEGIN_EVENT_TABLE(StreamFrame, wxMDIChildFrame)
EVT_BUTTON(STREAM_PLAY, StreamFrame::OnPlay)
EVT_BUTTON(STREAM_STOP, StreamFrame::OnStop)
EVT_BUTTON(STREAM_RESET, StreamFrame::OnReset)
EVT_CHECKBOX(STREAM_REPEAT, StreamFrame::OnRepeat)
EVT_COMMAND_SCROLL(STREAM_VOLUME, StreamFrame::OnChangeVolume)
EVT_COMMAND_SCROLL(STREAM_PAN, StreamFrame::OnChangePan)
EVT_COMMAND_SCROLL(STREAM_POS, StreamFrame::OnChangePos)
EVT_TIMER(STREAM_UPDATE, StreamFrame::OnUpdatePosition)
END_EVENT_TABLE()
class DeviceFrame : public wxMDIParentFrame {
public:
DeviceFrame(AudioDevice* device, const wxString& device_name)
: wxMDIParentFrame(NULL, -1, "Device Window - " + device_name)
{
m_device = device;
wxMenu* fileMenu = new wxMenu();
fileMenu->Append(DEVICE_NEW_DEVICE, "&New Device...");
fileMenu->AppendSeparator();
fileMenu->Append(DEVICE_OPEN_STREAM, "&Open Stream...");
fileMenu->Append(DEVICE_OPEN_SOUND, "Open &Sound...");
fileMenu->Append(DEVICE_CREATE_TONE, "Create &Tone...");
fileMenu->AppendSeparator();
fileMenu->Append(DEVICE_CLOSE, "&Close Device");
wxMenuBar* menuBar = new wxMenuBar();
menuBar->Append(fileMenu, "&Device");
SetMenuBar(menuBar);
}
void OnDeviceNewDevice() {
wxString name = wxGetTextFromUser(
"New Device",
"Enter Device Name",
"autodetect",
this);
if (!name.empty()) {
if (!TryDevice(name)) {
wxMessageBox(
"Could not open audio device: " + name,
"New Device", wxOK | wxCENTRE, this);
}
}
}
wxString GetSoundFile() {
return wxFileSelector(
"Select a sound file", "", "", "",
"Sound Files (*.wav,*.ogg,*.mod,*.it,*.xm,*.s3m)|" \
"*.wav;*.ogg;*.mod;*.it;*.xm;*.s3m",
wxOPEN, this);
}
void OnDeviceOpenStream() {
wxString filename(GetSoundFile());
if (filename.empty()) {
return;
}
OutputStream* stream = OpenSound(m_device.get(), filename, true);
if (!stream) {
wxMessageBox(
"Could not open stream: " + filename,
"Open Stream", wxOK | wxCENTRE, this);
return;
}
// get the basename of the path for the window title
wxString basename = wxFileNameFromPath(filename);;
wxString title;
title.sprintf("Stream: %s", basename.c_str());
new StreamFrame(this, title, stream);
}
void OnDeviceOpenSound() {
wxString filename(GetSoundFile());
if (filename.empty()) {
return;
}
OutputStream* stream = OpenSound(m_device.get(), filename);
if (!stream) {
wxMessageBox(
"Could not open sound: " + filename,
"Open Stream", wxOK | wxCENTRE, this);
return;
}
// get the basename of the path for the window title
wxString basename = wxFileNameFromPath(filename);;
wxString title;
title.sprintf("Sound: %s", basename.c_str());
new StreamFrame(this, title, stream);
}
void OnDeviceCreateTone() {
int frequency = wxGetNumberFromUser(
"Value must be between 1 and 30000.", "Enter frequency in Hz",
"Create Tone", 256, 1, 30000, this);
if (frequency != -1) {
OutputStream* stream = m_device->openStream(CreateTone(frequency));
if (!stream) {
wxMessageBox(
"Could not open output stream",
"Create Tone", wxOK | wxCENTRE, this);
} else {
wxString title;
title.sprintf("Tone: %d Hz", frequency);
new StreamFrame(this, title, stream);
}
}
}
void OnDeviceClose() {
Close();
}
private:
RefPtr<AudioDevice> m_device;
DECLARE_EVENT_TABLE()
};
BEGIN_EVENT_TABLE(DeviceFrame, wxMDIParentFrame)
EVT_MENU(DEVICE_NEW_DEVICE, DeviceFrame::OnDeviceNewDevice)
EVT_MENU(DEVICE_OPEN_STREAM, DeviceFrame::OnDeviceOpenStream)
EVT_MENU(DEVICE_OPEN_SOUND, DeviceFrame::OnDeviceOpenSound)
EVT_MENU(DEVICE_CREATE_TONE, DeviceFrame::OnDeviceCreateTone)
EVT_MENU(DEVICE_CLOSE, DeviceFrame::OnDeviceClose)
END_EVENT_TABLE()
bool TryDevice(const char* name) {
if (RefPtr<AudioDevice> device = audiere::OpenDevice(name)) {
DeviceFrame* frame = new DeviceFrame(device.get(), name);
frame->Show(true);
return true;
} else {
return false;
}
}
class wxPlayer : public wxApp {
public:
bool OnInit() {
bool result = (TryDevice("autodetect") || TryDevice("null"));
if (!result) {
wxMessageBox("Could not open output device", "wxPlayer");
}
return result;
}
};
IMPLEMENT_APP(wxPlayer)
<|endoftext|>
|
<commit_before>// Copyright Verizon Media. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
#include <vespa/eval/eval/fast_value.h>
#include <vespa/eval/eval/operation.h>
#include <vespa/eval/eval/tensor_function.h>
#include <vespa/eval/eval/test/eval_fixture.h>
#include <vespa/eval/eval/test/gen_spec.h>
#include <vespa/eval/instruction/dense_multi_matmul_function.h>
#include <vespa/vespalib/testkit/test_kit.h>
#include <vespa/vespalib/util/stash.h>
#include <vespa/vespalib/util/stringfmt.h>
using namespace vespalib;
using namespace vespalib::eval;
using namespace vespalib::eval::test;
using namespace vespalib::eval::tensor_function;
const ValueBuilderFactory &prod_factory = FastValueBuilderFactory::get();
GenSpec G(std::vector<std::pair<const char *, size_t>> dims) {
GenSpec result;
for (const auto & dim : dims) {
result.idx(dim.first, dim.second);
}
return result;
}
EvalFixture::ParamRepo make_params() {
return EvalFixture::ParamRepo()
.add_variants("A2B1C3a2d3", G({{"A",2}, {"B",1}, {"C",3}, {"a",2}, {"d",3}})) // inner/inner
.add_variants("A2B1C3D1a2c1d3e1", G({{"A",2}, {"B",1}, {"C",3}, {"D",1}, {"a",2}, {"c",1}, {"d",3}, {"e",1}}))// inner/inner, extra dims
.add_variants("B1C3a2d3", G({{"B",1}, {"C",3}, {"a",2}, {"d",3}})) // inner/inner, missing A
.add_variants("A1a2d3", G({{"A",1}, {"a",2}, {"d",3}})) // inner/inner, single mat
.add_variants("A2D3a2b1c3", G({{"A",2}, {"D",3}, {"a",2}, {"b",1}, {"c",3}})) // inner/inner, inverted
.add_variants("A2B1C3a2b5", G({{"A",2}, {"B",1}, {"C",3}, {"a",2}, {"b",5}})) // inner/outer
.add_variants("A2B1C3b5c2", G({{"A",2}, {"B",1}, {"C",3}, {"b",5}, {"c",2}})) // outer/outer
.add_variants("A2B1C3a2c3", G({{"A",2}, {"B",1}, {"C",3}, {"a",2}, {"c",3}})) // not matching
//----------------------------------------------------------------------------------------
.add_variants("A2B1C3b5d3", G({{"A",2}, {"B",1}, {"C",3}, {"b",5}, {"d",3}})) // fixed param
.add_variants("B1C3b5d3", G({{"B",1}, {"C",3}, {"b",5}, {"d",3}})) // fixed param, missing A
.add_variants("A1b5d3", G({{"A",1}, {"b",5}, {"d",3}})) // fixed param, single mat
.add_variants("B5D3a2b1c3", G({{"B",5}, {"D",3}, {"a",2}, {"b",1}, {"c",3}})); // fixed param, inverted
}
EvalFixture::ParamRepo param_repo = make_params();
void verify_optimized(const vespalib::string &expr,
size_t lhs_size, size_t common_size, size_t rhs_size, size_t matmul_cnt,
bool lhs_inner, bool rhs_inner)
{
EvalFixture slow_fixture(prod_factory, expr, param_repo, false);
EvalFixture fixture(prod_factory, expr, param_repo, true);
EXPECT_EQUAL(fixture.result(), EvalFixture::ref(expr, param_repo));
EXPECT_EQUAL(fixture.result(), slow_fixture.result());
auto info = fixture.find_all<DenseMultiMatMulFunction>();
ASSERT_EQUAL(info.size(), 1u);
EXPECT_TRUE(info[0]->result_is_mutable());
EXPECT_EQUAL(info[0]->lhs_size(), lhs_size);
EXPECT_EQUAL(info[0]->common_size(), common_size);
EXPECT_EQUAL(info[0]->rhs_size(), rhs_size);
EXPECT_EQUAL(info[0]->matmul_cnt(), matmul_cnt);
EXPECT_EQUAL(info[0]->lhs_common_inner(), lhs_inner);
EXPECT_EQUAL(info[0]->rhs_common_inner(), rhs_inner);
}
void verify_not_optimized(const vespalib::string &expr) {
EvalFixture slow_fixture(prod_factory, expr, param_repo, false);
EvalFixture fixture(prod_factory, expr, param_repo, true);
EXPECT_EQUAL(fixture.result(), EvalFixture::ref(expr, param_repo));
EXPECT_EQUAL(fixture.result(), slow_fixture.result());
auto info = fixture.find_all<DenseMultiMatMulFunction>();
EXPECT_TRUE(info.empty());
}
TEST("require that multi matmul can be optimized") {
TEST_DO(verify_optimized("reduce(A2B1C3a2d3*A2B1C3b5d3,sum,d)", 2, 3, 5, 6, true, true));
}
TEST("require that single multi matmul can be optimized") {
TEST_DO(verify_optimized("reduce(A1a2d3*A1b5d3,sum,d)", 2, 3, 5, 1, true, true));
}
TEST("require that multi matmul with lambda can be optimized") {
TEST_DO(verify_optimized("reduce(join(A2B1C3a2d3,A2B1C3b5d3,f(x,y)(x*y)),sum,d)", 2, 3, 5, 6, true, true));
}
TEST("require that expressions similar to multi matmul are not optimized") {
TEST_DO(verify_not_optimized("reduce(A2B1C3a2d3*A2B1C3b5d3,sum,a)"));
TEST_DO(verify_not_optimized("reduce(A2B1C3a2d3*A2B1C3b5d3,sum,b)"));
TEST_DO(verify_not_optimized("reduce(A2B1C3a2d3*A2B1C3b5d3,prod,d)"));
TEST_DO(verify_not_optimized("reduce(A2B1C3a2d3*A2B1C3b5d3,sum)"));
TEST_DO(verify_not_optimized("reduce(join(A2B1C3a2d3,A2B1C3b5d3,f(x,y)(y*x)),sum,d)"));
TEST_DO(verify_not_optimized("reduce(join(A2B1C3a2d3,A2B1C3b5d3,f(x,y)(x+y)),sum,d)"));
TEST_DO(verify_not_optimized("reduce(join(A2B1C3a2d3,A2B1C3b5d3,f(x,y)(x*x)),sum,d)"));
TEST_DO(verify_not_optimized("reduce(join(A2B1C3a2d3,A2B1C3b5d3,f(x,y)(y*y)),sum,d)"));
TEST_DO(verify_not_optimized("reduce(join(A2B1C3a2d3,A2B1C3b5d3,f(x,y)(x*y*1)),sum,d)"));
TEST_DO(verify_not_optimized("reduce(A2B1C3a2c3*A2B1C3b5d3,sum,d)"));
TEST_DO(verify_not_optimized("reduce(A2B1C3a2c3*A2B1C3b5d3,sum,c)"));
}
TEST("require that multi matmul must have matching cell type") {
TEST_DO(verify_not_optimized("reduce(A2B1C3a2d3_f*A2B1C3b5d3,sum,d)"));
TEST_DO(verify_not_optimized("reduce(A2B1C3a2d3*A2B1C3b5d3_f,sum,d)"));
}
TEST("require that multi matmul must have matching dimension prefix") {
TEST_DO(verify_not_optimized("reduce(B1C3a2d3*A2B1C3b5d3,sum,d)"));
TEST_DO(verify_not_optimized("reduce(A2B1C3a2d3*B1C3b5d3,sum,d)"));
}
TEST("require that multi matmul must have inner nesting of matmul dimensions") {
TEST_DO(verify_not_optimized("reduce(A2D3a2b1c3*B5D3a2b1c3,sum,D)"));
TEST_DO(verify_not_optimized("reduce(B5D3a2b1c3*A2D3a2b1c3,sum,D)"));
}
TEST("require that multi matmul ignores trivial dimensions") {
TEST_DO(verify_optimized("reduce(A2B1C3D1a2c1d3e1*A2B1C3b5d3,sum,d)", 2, 3, 5, 6, true, true));
TEST_DO(verify_optimized("reduce(A2B1C3b5d3*A2B1C3D1a2c1d3e1,sum,d)", 2, 3, 5, 6, true, true));
}
TEST("require that multi matmul function can be debug dumped") {
EvalFixture fixture(prod_factory, "reduce(A2B1C3a2d3*A2B1C3b5d3,sum,d)", param_repo, true);
auto info = fixture.find_all<DenseMultiMatMulFunction>();
ASSERT_EQUAL(info.size(), 1u);
fprintf(stderr, "%s\n", info[0]->as_string().c_str());
}
vespalib::string make_expr(const vespalib::string &a, const vespalib::string &b, const vespalib::string &common,
bool float_cells)
{
return make_string("reduce(%s%s*%s%s,sum,%s)", a.c_str(), float_cells ? "_f" : "", b.c_str(), float_cells ? "_f" : "", common.c_str());
}
void verify_optimized_multi(const vespalib::string &a, const vespalib::string &b, const vespalib::string &common,
size_t lhs_size, size_t common_size, size_t rhs_size, size_t matmul_cnt,
bool lhs_inner, bool rhs_inner)
{
for (bool float_cells: {false, true}) {
{
auto expr = make_expr(a, b, common, float_cells);
TEST_STATE(expr.c_str());
TEST_DO(verify_optimized(expr, lhs_size, common_size, rhs_size, matmul_cnt, lhs_inner, rhs_inner));
}
{
auto expr = make_expr(b, a, common, float_cells);
TEST_STATE(expr.c_str());
TEST_DO(verify_optimized(expr, lhs_size, common_size, rhs_size, matmul_cnt, lhs_inner, rhs_inner));
}
}
}
TEST("require that multi matmul inner/inner works correctly") {
TEST_DO(verify_optimized_multi("A2B1C3a2d3", "A2B1C3b5d3", "d", 2, 3, 5, 6, true, true));
}
TEST("require that multi matmul inner/outer works correctly") {
TEST_DO(verify_optimized_multi("A2B1C3a2b5", "A2B1C3b5d3", "b", 2, 5, 3, 6, true, false));
}
TEST("require that multi matmul outer/outer works correctly") {
TEST_DO(verify_optimized_multi("A2B1C3b5c2", "A2B1C3b5d3", "b", 2, 5, 3, 6, false, false));
}
TEST_MAIN() { TEST_RUN_ALL(); }
<commit_msg>rewrite DenseMultiMatMulFunction test<commit_after>// Copyright Verizon Media. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
#include <vespa/eval/eval/fast_value.h>
#include <vespa/eval/eval/operation.h>
#include <vespa/eval/eval/tensor_function.h>
#include <vespa/eval/eval/test/eval_fixture.h>
#include <vespa/eval/eval/test/gen_spec.h>
#include <vespa/eval/instruction/dense_multi_matmul_function.h>
#include <vespa/vespalib/testkit/test_kit.h>
#include <vespa/vespalib/util/stash.h>
#include <vespa/vespalib/util/stringfmt.h>
using namespace vespalib;
using namespace vespalib::eval;
using namespace vespalib::eval::test;
using namespace vespalib::eval::tensor_function;
const ValueBuilderFactory &prod_factory = FastValueBuilderFactory::get();
struct FunInfo {
using LookFor = DenseMultiMatMulFunction;
size_t lhs_size;
size_t common_size;
size_t rhs_size;
size_t matmul_cnt;
bool lhs_inner;
bool rhs_inner;
void verify(const LookFor &fun) const {
EXPECT_TRUE(fun.result_is_mutable());
EXPECT_EQUAL(fun.lhs_size(), lhs_size);
EXPECT_EQUAL(fun.common_size(), common_size);
EXPECT_EQUAL(fun.rhs_size(), rhs_size);
EXPECT_EQUAL(fun.matmul_cnt(), matmul_cnt);
EXPECT_EQUAL(fun.lhs_common_inner(), lhs_inner);
EXPECT_EQUAL(fun.rhs_common_inner(), rhs_inner);
}
};
void verify_optimized(const vespalib::string &expr, const FunInfo &details)
{
TEST_STATE(expr.c_str());
auto same_types = CellTypeSpace(CellTypeUtils::list_types(), 2).same();
EvalFixture::verify<FunInfo>(expr, {details}, same_types);
auto diff_types = CellTypeSpace(CellTypeUtils::list_types(), 2).different();
EvalFixture::verify<FunInfo>(expr, {}, diff_types);
}
void verify_not_optimized(const vespalib::string &expr) {
TEST_STATE(expr.c_str());
CellTypeSpace just_double({CellType::DOUBLE}, 2);
EvalFixture::verify<FunInfo>(expr, {}, just_double);
}
TEST("require that multi matmul can be optimized") {
FunInfo details = { .lhs_size = 2, .common_size = 3, .rhs_size = 5,
.matmul_cnt = 6, .lhs_inner = true, .rhs_inner = true };
TEST_DO(verify_optimized("reduce(A2B1C3a2d3*A2B1C3b5d3,sum,d)", details));
TEST_DO(verify_optimized("reduce(A2B1C3a2d3*A2B1C3b5d3,sum,d)", details));
}
TEST("require that single multi matmul can be optimized") {
FunInfo details = { .lhs_size = 2, .common_size = 3, .rhs_size = 5,
.matmul_cnt = 1, .lhs_inner = true, .rhs_inner = true };
TEST_DO(verify_optimized("reduce(A1a2d3*A1b5d3,sum,d)", details));
}
TEST("require that multi matmul with lambda can be optimized") {
FunInfo details = { .lhs_size = 2, .common_size = 3, .rhs_size = 5,
.matmul_cnt = 6, .lhs_inner = true, .rhs_inner = true };
TEST_DO(verify_optimized("reduce(join(A2B1C3a2d3,A2B1C3b5d3,f(x,y)(x*y)),sum,d)", details));
}
TEST("require that expressions similar to multi matmul are not optimized") {
TEST_DO(verify_not_optimized("reduce(A2B1C3a2d3*A2B1C3b5d3,sum,a)"));
TEST_DO(verify_not_optimized("reduce(A2B1C3a2d3*A2B1C3b5d3,sum,b)"));
TEST_DO(verify_not_optimized("reduce(A2B1C3a2d3*A2B1C3b5d3,prod,d)"));
TEST_DO(verify_not_optimized("reduce(A2B1C3a2d3*A2B1C3b5d3,sum)"));
TEST_DO(verify_not_optimized("reduce(join(A2B1C3a2d3,A2B1C3b5d3,f(x,y)(y*x)),sum,d)"));
TEST_DO(verify_not_optimized("reduce(join(A2B1C3a2d3,A2B1C3b5d3,f(x,y)(x+y)),sum,d)"));
TEST_DO(verify_not_optimized("reduce(join(A2B1C3a2d3,A2B1C3b5d3,f(x,y)(x*x)),sum,d)"));
TEST_DO(verify_not_optimized("reduce(join(A2B1C3a2d3,A2B1C3b5d3,f(x,y)(y*y)),sum,d)"));
TEST_DO(verify_not_optimized("reduce(join(A2B1C3a2d3,A2B1C3b5d3,f(x,y)(x*y*1)),sum,d)"));
TEST_DO(verify_not_optimized("reduce(A2B1C3a2c3*A2B1C3b5d3,sum,d)"));
TEST_DO(verify_not_optimized("reduce(A2B1C3a2c3*A2B1C3b5d3,sum,c)"));
}
TEST("require that multi matmul must have matching dimension prefix") {
TEST_DO(verify_not_optimized("reduce(B1C3a2d3*A2B1C3b5d3,sum,d)"));
TEST_DO(verify_not_optimized("reduce(A2B1C3a2d3*B1C3b5d3,sum,d)"));
}
TEST("require that multi matmul must have inner nesting of matmul dimensions") {
TEST_DO(verify_not_optimized("reduce(A2D3a2b1c3*B5D3a2b1c3,sum,D)"));
TEST_DO(verify_not_optimized("reduce(B5D3a2b1c3*A2D3a2b1c3,sum,D)"));
}
TEST("require that multi matmul ignores trivial dimensions") {
FunInfo details = { .lhs_size = 2, .common_size = 3, .rhs_size = 5,
.matmul_cnt = 6, .lhs_inner = true, .rhs_inner = true };
TEST_DO(verify_optimized("reduce(A2B1C3D1a2c1d3e1*A2B1C3b5d3,sum,d)", details));
TEST_DO(verify_optimized("reduce(A2B1C3b5d3*A2B1C3D1a2c1d3e1,sum,d)", details));
}
TEST("require that multi matmul function can be debug dumped") {
EvalFixture fixture(prod_factory, "reduce(m1*m2,sum,d)", EvalFixture::ParamRepo()
.add("m1", GenSpec::from_desc("A2B1C3a2d3"))
.add("m2", GenSpec::from_desc("A2B1C3b5d3")), true);
auto info = fixture.find_all<DenseMultiMatMulFunction>();
ASSERT_EQUAL(info.size(), 1u);
fprintf(stderr, "%s\n", info[0]->as_string().c_str());
}
TEST("require that multi matmul inner/inner works correctly") {
FunInfo details = { .lhs_size = 2, .common_size = 3, .rhs_size = 5,
.matmul_cnt = 6, .lhs_inner = true, .rhs_inner = true };
TEST_DO(verify_optimized("reduce(A2B1C3a2d3*A2B1C3b5d3,sum,d)", details));
}
TEST("require that multi matmul inner/outer works correctly") {
FunInfo details = { .lhs_size = 2, .common_size = 5, .rhs_size = 3,
.matmul_cnt = 6, .lhs_inner = true, .rhs_inner = false };
TEST_DO(verify_optimized("reduce(A2B1C3a2b5*A2B1C3b5d3,sum,b)", details));
}
TEST("require that multi matmul outer/outer works correctly") {
FunInfo details = { .lhs_size = 2, .common_size = 5, .rhs_size = 3,
.matmul_cnt = 6, .lhs_inner = false, .rhs_inner = false };
TEST_DO(verify_optimized("reduce(A2B1C3b5c2*A2B1C3b5d3,sum,b)", details));
}
TEST_MAIN() { TEST_RUN_ALL(); }
<|endoftext|>
|
<commit_before>#include <errno.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <syslog.h>
#include <sys/socket.h>
#include <sys/stat.h>
#include <sys/time.h>
#include <sys/types.h>
#include <sys/un.h>
#include <time.h>
#include <unistd.h>
#include <string>
using std::string;
const int kDefaultLengthSecs = 25 * 60;
const char* kDefaultDoneMessage = "";
string SocketName() {
string socket_name;
socket_name.append(P_tmpdir);
socket_name.append("/.tpm-");
socket_name.append(getenv("USER"));
return socket_name;
}
string MakePostHookPath() {
string post_hook;
post_hook = getenv("HOME");
post_hook += "/.tpm-post.sh";
return post_hook;
}
int ClientMain(string done_message) {
int sock_fd;
struct sockaddr_un remote;
if ((sock_fd = socket(AF_UNIX, SOCK_STREAM, 0)) == -1) {
perror("socket");
exit(1);
}
remote.sun_family = AF_UNIX;
string socket_name = SocketName();
strcpy(remote.sun_path, socket_name.c_str());
int len = strlen(remote.sun_path) + sizeof(remote.sun_family) + 1;
if (connect(sock_fd, (struct sockaddr *)&remote, len) == -1) {
printf("%s\n", done_message.c_str());
return 0;
}
int recv_length;
char buf[100];
if ((recv_length = recv(sock_fd, buf, 100, 0)) > 0) {
buf[recv_length] = '\0';
printf("%s\n", buf);
}
close(sock_fd);
return 0;
}
int DaemonMain(int countdown_time) {
/* Our process ID and Session ID */
int ok;
pid_t pid, sid;
struct timespec ts;
ts.tv_sec = 0;
ts.tv_nsec = 1000 /*micro*/ * 1000 /* milli */ * 50;
string socket_name = SocketName();
int sock_fd;
struct sockaddr_un local, remote;
if ((sock_fd = socket(AF_UNIX, SOCK_STREAM, 0)) == -1) {
perror("socket");
exit(1);
}
local.sun_family = AF_UNIX;
strcpy(local.sun_path, socket_name.c_str());
unlink(local.sun_path);
int len = strlen(local.sun_path) + sizeof(local.sun_family) + 1;
if (bind(sock_fd, (struct sockaddr *)&local, len) == -1) {
perror("bind");
exit(1);
}
int flags = fcntl(sock_fd,F_GETFL,0);
fcntl(sock_fd, F_SETFL, flags | O_NONBLOCK);
/* Fork off the parent process */
pid = fork();
if (pid < 0) {
exit(EXIT_FAILURE);
}
/* If we got a good PID, then
we can exit the parent process. */
if (pid > 0) {
exit(EXIT_SUCCESS);
}
/* Change the file mode mask */
umask(0);
/* Open any logs here */
/* Create a new SID for the child process */
sid = setsid();
if (sid < 0) {
/* Log the failure */
exit(EXIT_FAILURE);
}
/* Change the current working directory */
if ((chdir("/")) < 0) {
/* Log the failure */
exit(EXIT_FAILURE);
}
/* Close out the standard file descriptors */
close(STDIN_FILENO);
close(STDOUT_FILENO);
close(STDERR_FILENO);
if (listen(sock_fd, 5) == -1) {
exit(1);
}
struct timeval start_time;
ok = gettimeofday(&start_time, NULL);
int remote_fd = -1;
bool wakeup = false;
while (!wakeup) {
struct timeval current_time;
struct timeval diff_time;
ok = gettimeofday(¤t_time, NULL);
timersub(¤t_time, &start_time, &diff_time);
if (diff_time.tv_sec >= countdown_time) {
wakeup = true;
continue;
}
long remaining_time = (long)countdown_time - diff_time.tv_sec;
socklen_t t = sizeof(remote);
while ((remote_fd = accept(sock_fd, (struct sockaddr *)&remote, &t)) != -1) {
char message[100];
int message_len = snprintf(message, 100, "%ld:%02ld", remaining_time / 60, remaining_time % 60);
if (send(remote_fd, message, message_len, 0) < 0) {
exit(1);
}
close(remote_fd);
}
// Make sure it was just EWOULDBLOCK
if (errno != EAGAIN && errno != EWOULDBLOCK) {
exit(1);
}
ok = nanosleep(&ts, NULL);
}
close(sock_fd);
printf("%s\n", local.sun_path);
unlink(local.sun_path);
string post_hook = MakePostHookPath();
char* argv[0];
if (access(post_hook.c_str(), X_OK) != -1) {
execv(post_hook.c_str(), argv);
}
exit(EXIT_SUCCESS);
}
int main(int argc, char** argv) {
int c;
int countdown_time = kDefaultLengthSecs;
string done_message = kDefaultDoneMessage;
int got_positional = 0;
string command = "";
while (1) {
while ( (c = getopt(argc, argv, "bs:m:d:")) != -1) {
switch (c) {
case 's':
countdown_time = atoi(optarg);
break;
case 'm':
countdown_time = atoi(optarg) * 60;
break;
case 'd':
done_message = optarg;
break;
}
}
if (optind < argc && !got_positional) {
command = argv[optind];
got_positional = 1;
} else {
break;
}
optind++;
}
if (command == "start") {
DaemonMain(countdown_time);
}
else {
return ClientMain(done_message);
}
exit(0);
}
<commit_msg>better execv in cpp<commit_after>#include <errno.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <syslog.h>
#include <sys/socket.h>
#include <sys/stat.h>
#include <sys/time.h>
#include <sys/types.h>
#include <sys/un.h>
#include <time.h>
#include <unistd.h>
#include <string>
using std::string;
const int kDefaultLengthSecs = 25 * 60;
const char* kDefaultDoneMessage = "";
string SocketName() {
string socket_name;
socket_name.append(P_tmpdir);
socket_name.append("/.tpm-");
socket_name.append(getenv("USER"));
return socket_name;
}
string MakePostHookPath() {
string post_hook;
post_hook = getenv("HOME");
post_hook += "/.tpm-post.sh";
return post_hook;
}
int ClientMain(string done_message) {
int sock_fd;
struct sockaddr_un remote;
if ((sock_fd = socket(AF_UNIX, SOCK_STREAM, 0)) == -1) {
perror("socket");
exit(1);
}
remote.sun_family = AF_UNIX;
string socket_name = SocketName();
strcpy(remote.sun_path, socket_name.c_str());
int len = strlen(remote.sun_path) + sizeof(remote.sun_family) + 1;
if (connect(sock_fd, (struct sockaddr *)&remote, len) == -1) {
printf("%s\n", done_message.c_str());
return 0;
}
int recv_length;
char buf[100];
if ((recv_length = recv(sock_fd, buf, 100, 0)) > 0) {
buf[recv_length] = '\0';
printf("%s\n", buf);
}
close(sock_fd);
return 0;
}
int DaemonMain(int countdown_time) {
/* Our process ID and Session ID */
int ok;
pid_t pid, sid;
struct timespec ts;
ts.tv_sec = 0;
ts.tv_nsec = 1000 /*micro*/ * 1000 /* milli */ * 50;
string socket_name = SocketName();
int sock_fd;
struct sockaddr_un local, remote;
if ((sock_fd = socket(AF_UNIX, SOCK_STREAM, 0)) == -1) {
perror("socket");
exit(1);
}
local.sun_family = AF_UNIX;
strcpy(local.sun_path, socket_name.c_str());
unlink(local.sun_path);
int len = strlen(local.sun_path) + sizeof(local.sun_family) + 1;
if (bind(sock_fd, (struct sockaddr *)&local, len) == -1) {
perror("bind");
exit(1);
}
int flags = fcntl(sock_fd,F_GETFL,0);
fcntl(sock_fd, F_SETFL, flags | O_NONBLOCK);
/* Fork off the parent process */
pid = fork();
if (pid < 0) {
exit(EXIT_FAILURE);
}
/* If we got a good PID, then
we can exit the parent process. */
if (pid > 0) {
exit(EXIT_SUCCESS);
}
/* Change the file mode mask */
umask(0);
/* Open any logs here */
/* Create a new SID for the child process */
sid = setsid();
if (sid < 0) {
/* Log the failure */
exit(EXIT_FAILURE);
}
/* Change the current working directory */
if ((chdir("/")) < 0) {
/* Log the failure */
exit(EXIT_FAILURE);
}
/* Close out the standard file descriptors */
close(STDIN_FILENO);
close(STDOUT_FILENO);
close(STDERR_FILENO);
if (listen(sock_fd, 5) == -1) {
exit(1);
}
struct timeval start_time;
ok = gettimeofday(&start_time, NULL);
int remote_fd = -1;
bool wakeup = false;
while (!wakeup) {
struct timeval current_time;
struct timeval diff_time;
ok = gettimeofday(¤t_time, NULL);
timersub(¤t_time, &start_time, &diff_time);
if (diff_time.tv_sec >= countdown_time) {
wakeup = true;
continue;
}
long remaining_time = (long)countdown_time - diff_time.tv_sec;
socklen_t t = sizeof(remote);
while ((remote_fd = accept(sock_fd, (struct sockaddr *)&remote, &t)) != -1) {
char message[100];
int message_len = snprintf(message, 100, "%ld:%02ld", remaining_time / 60, remaining_time % 60);
if (send(remote_fd, message, message_len, 0) < 0) {
exit(1);
}
close(remote_fd);
}
// Make sure it was just EWOULDBLOCK
if (errno != EAGAIN && errno != EWOULDBLOCK) {
exit(1);
}
ok = nanosleep(&ts, NULL);
}
close(sock_fd);
printf("%s\n", local.sun_path);
unlink(local.sun_path);
string post_hook = MakePostHookPath();
char* argv[] = {(char *)post_hook.c_str(), NULL};
if (access(post_hook.c_str(), X_OK) != -1) {
execv(post_hook.c_str(), argv);
}
exit(EXIT_SUCCESS);
}
int main(int argc, char** argv) {
int c;
int countdown_time = kDefaultLengthSecs;
string done_message = kDefaultDoneMessage;
int got_positional = 0;
string command = "";
while (1) {
while ( (c = getopt(argc, argv, "bs:m:d:")) != -1) {
switch (c) {
case 's':
countdown_time = atoi(optarg);
break;
case 'm':
countdown_time = atoi(optarg) * 60;
break;
case 'd':
done_message = optarg;
break;
}
}
if (optind < argc && !got_positional) {
command = argv[optind];
got_positional = 1;
} else {
break;
}
optind++;
}
if (command == "start") {
DaemonMain(countdown_time);
}
else {
return ClientMain(done_message);
}
exit(0);
}
<|endoftext|>
|
<commit_before><commit_msg>improve coverage of matrix-vector product<commit_after><|endoftext|>
|
<commit_before>/*
Copyright (c) 2009 Kevin Ottens <ervin@kde.org>
This library is free software; you can redistribute it and/or modify it
under the terms of the GNU Library General Public License as published by
the Free Software Foundation; either version 2 of the License, or (at your
option) any later version.
This library is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public
License for more details.
You should have received a copy of the GNU Library General Public License
along with this library; see the file COPYING.LIB. If not, write to the
Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
02110-1301, USA.
*/
#include "quotacolorproxymodel.h"
#include <akonadi/entitytreemodel.h>
#include <akonadi/collectionquotaattribute.h>
#include <QtGui/QColor>
using namespace Akonadi;
/**
* @internal
*/
class QuotaColorProxyModel::Private
{
public:
Private( QuotaColorProxyModel *parent )
: mParent( parent ), mThreshold( 100.0 ), mColor( Qt::red )
{
}
QuotaColorProxyModel *mParent;
qreal mThreshold;
QColor mColor;
};
QuotaColorProxyModel::QuotaColorProxyModel( QObject *parent )
: QSortFilterProxyModel( parent ),
d( new Private( this ) )
{
}
QuotaColorProxyModel::~QuotaColorProxyModel()
{
delete d;
}
void QuotaColorProxyModel::setWarningThreshold( qreal threshold )
{
d->mThreshold = threshold;
}
qreal QuotaColorProxyModel::warningThreshold() const
{
return d->mThreshold;
}
void QuotaColorProxyModel::setWarningColor( const QColor &color )
{
d->mColor = color;
}
QColor QuotaColorProxyModel::warningColor() const
{
return d->mColor;
}
QVariant QuotaColorProxyModel::data( const QModelIndex & index, int role) const
{
if ( role == Qt::ForegroundRole ) {
const QModelIndex sourceIndex = mapToSource( index );
const QModelIndex rowIndex = sourceIndex.sibling( sourceIndex.row(), 0 );
Collection collection = sourceModel()->data( rowIndex, EntityTreeModel::CollectionRole ).value<Collection>();
if ( collection.isValid() && collection.hasAttribute<CollectionQuotaAttribute>() ) {
CollectionQuotaAttribute *quota = collection.attribute<CollectionQuotaAttribute>();
if ( quota->currentValue() > -1 && quota->maxValue() > 0 ) {
qreal percentage = ( 100.0 * quota->currentValue() ) / quota->maxValue();
if ( percentage >= d->mThreshold ) {
return d->mColor;
}
}
}
}
return QAbstractProxyModel::data( index, role );
}
bool QuotaColorProxyModel::dropMimeData( const QMimeData * data, Qt::DropAction action, int row, int column, const QModelIndex & parent )
{
Q_ASSERT(sourceModel());
const QModelIndex sourceParent = mapToSource(parent);
return sourceModel()->dropMimeData(data, action, row, column, sourceParent);
}
QMimeData* QuotaColorProxyModel::mimeData( const QModelIndexList & indexes ) const
{
Q_ASSERT(sourceModel());
QModelIndexList sourceIndexes;
foreach(const QModelIndex& index, indexes)
sourceIndexes << mapToSource(index);
return sourceModel()->mimeData(sourceIndexes);
}
QStringList QuotaColorProxyModel::mimeTypes() const
{
Q_ASSERT(sourceModel());
return sourceModel()->mimeTypes();
}
#include "quotacolorproxymodel.moc"
<commit_msg>Fix the build CCMAIL: ervin@kde.org<commit_after>/*
Copyright (c) 2009 Kevin Ottens <ervin@kde.org>
This library is free software; you can redistribute it and/or modify it
under the terms of the GNU Library General Public License as published by
the Free Software Foundation; either version 2 of the License, or (at your
option) any later version.
This library is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public
License for more details.
You should have received a copy of the GNU Library General Public License
along with this library; see the file COPYING.LIB. If not, write to the
Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
02110-1301, USA.
*/
#include "quotacolorproxymodel.h"
#include <akonadi/entitytreemodel.h>
#include <akonadi/collectionquotaattribute.h>
#include <QtGui/QColor>
using namespace Akonadi;
/**
* @internal
*/
class QuotaColorProxyModel::Private
{
public:
Private( QuotaColorProxyModel *parent )
: mParent( parent ), mThreshold( 100.0 ), mColor( Qt::red )
{
}
QuotaColorProxyModel *mParent;
qreal mThreshold;
QColor mColor;
};
QuotaColorProxyModel::QuotaColorProxyModel( QObject *parent )
: QSortFilterProxyModel( parent ),
d( new Private( this ) )
{
}
QuotaColorProxyModel::~QuotaColorProxyModel()
{
delete d;
}
void QuotaColorProxyModel::setWarningThreshold( qreal threshold )
{
d->mThreshold = threshold;
}
qreal QuotaColorProxyModel::warningThreshold() const
{
return d->mThreshold;
}
void QuotaColorProxyModel::setWarningColor( const QColor &color )
{
d->mColor = color;
}
QColor QuotaColorProxyModel::warningColor() const
{
return d->mColor;
}
QVariant QuotaColorProxyModel::data( const QModelIndex & index, int role) const
{
if ( role == Qt::ForegroundRole ) {
const QModelIndex sourceIndex = mapToSource( index );
const QModelIndex rowIndex = sourceIndex.sibling( sourceIndex.row(), 0 );
Collection collection = sourceModel()->data( rowIndex, EntityTreeModel::CollectionRole ).value<Collection>();
if ( collection.isValid() && collection.hasAttribute<CollectionQuotaAttribute>() ) {
CollectionQuotaAttribute *quota = collection.attribute<CollectionQuotaAttribute>();
if ( quota->currentValue() > -1 && quota->maximumValue() > 0 ) {
qreal percentage = ( 100.0 * quota->currentValue() ) / quota->maximumValue();
if ( percentage >= d->mThreshold ) {
return d->mColor;
}
}
}
}
return QAbstractProxyModel::data( index, role );
}
bool QuotaColorProxyModel::dropMimeData( const QMimeData * data, Qt::DropAction action, int row, int column, const QModelIndex & parent )
{
Q_ASSERT(sourceModel());
const QModelIndex sourceParent = mapToSource(parent);
return sourceModel()->dropMimeData(data, action, row, column, sourceParent);
}
QMimeData* QuotaColorProxyModel::mimeData( const QModelIndexList & indexes ) const
{
Q_ASSERT(sourceModel());
QModelIndexList sourceIndexes;
foreach(const QModelIndex& index, indexes)
sourceIndexes << mapToSource(index);
return sourceModel()->mimeData(sourceIndexes);
}
QStringList QuotaColorProxyModel::mimeTypes() const
{
Q_ASSERT(sourceModel());
return sourceModel()->mimeTypes();
}
#include "quotacolorproxymodel.moc"
<|endoftext|>
|
<commit_before>/*
* =====================================================================================
*
* Filename: 3.cpp
*
* Description: Solution to the third problem of the `evens' section.
*
* Version: 1.0
* Created: 28.01.2015 6,00,07
* Revision: none
* Compiler: gcc
*
* Author: Radoslav Georgiev (sid), rgeorgiev583@gmail.com
* Company: Faculty of Mathematics and Informatics at Sofia University
*
* =====================================================================================
*/
#include <iostream>
#include <cstring>
using namespace std;
const int MAX_SIZE = 1000;
const char diff = 'a' - 'A';
bool isInnerWordChar(char c)
{
return c == '-' || c >= 'A' && c <= 'Z' || c >= 'a' && c <= 'z';
}
bool isBeginWordChar(char c)
{
return isInnerWordChar(c) || c == '"' || c == '\'' || c == '(';
}
bool isEndWordChar(char c)
{
return isInnerWordChar(c) || c == '"' || c == '\'' || c == ')';
}
char toUpper(char c)
{
return c >= 'a' && c <= 'z' ? c - diff : c;
}
char toLower(char c)
{
return c >= 'A' && c <= 'Z' ? c + diff : c;
}
void swap(char* a, char* b)
{
char x = *a;
*a = *b;
*b = x;
}
const char* goToEnd(const char* s)
{
while (*s)
s++;
return s;
}
// Ако изречението е невалидно, връщаме NULL
char* reverseSentence(char* rev, const char* s)
{
if (!s)
return NULL;
const char* end = goToEnd(s);
end--;
if (end < s || *end != '!' && *end != '.' && *end != '?')
return NULL;
const char* stop = end;
end--;
if (end < s)
return NULL;
do
{
const char *beg = end;
if (!isEndWordChar(*beg))
return NULL;
beg--;
while (beg >= s && isInnerWordChar(*beg))
beg--;
if (beg < s || !isBeginWordChar(*beg))
beg++;
if (isInnerWordChar(*beg) && !isInnerWordChar(*end))
if (*end != ')')
strncat(rev, end, 1);
else
strcat(rev, "(");
if (isInnerWordChar(*end) && !isInnerWordChar(*beg))
beg++;
if (beg == s)
{
char first[2];
first[0] = *beg;
first[1] = 0;
first[0] = toLower(first[0]);
strcat(rev, first);
strncat(rev, beg + 1, end - beg);
}
else
{
strncat(rev, beg, end - beg + 1);
beg--;
if (isInnerWordChar(*end) && isBeginWordChar(*beg) && !isInnerWordChar(*beg))
beg--;
if (*beg != ' ')
return NULL;
beg--;
if (beg < s)
return NULL;
if (*beg == ',' || *beg == ':' || *beg == ';' || *beg == '(' || *beg == ')')
strncat(rev, beg, 1);
strncat(rev, beg + 1, 1);
beg += 2;
}
if (isInnerWordChar(*end) && isBeginWordChar(*beg) && !isInnerWordChar(*beg))
if (*beg != '(')
strncat(rev, beg, 1);
else
strcat(rev, ")");
end = beg - 2;
}
while (end >= s);
strncat(rev, stop, 1);
*rev = toUpper(*rev);
/* char *p = rev, *lp = NULL;
int b = 0;
while (*p)
{
if (*p == '(')
{
b++;
if (lp && b == 0)
{
swap(p, lp);
lp = NULL;
}
}
else if (*p == ')')
{
b--;
if (b == -1)
lp = p;
}
p++;
}
*/
return rev;
}
int main()
{
char s[MAX_SIZE], rev[MAX_SIZE];
cin.getline(s, MAX_SIZE);
cout << reverseSentence(rev, s) << endl;
return 0;
}
<commit_msg>added appending function<commit_after>/*
* =====================================================================================
*
* Filename: 3.cpp
*
* Description: Solution to the third problem of the `evens' section.
*
* Version: 1.0
* Created: 28.01.2015 6,00,07
* Revision: none
* Compiler: gcc
*
* Author: Radoslav Georgiev (sid), rgeorgiev583@gmail.com
* Company: Faculty of Mathematics and Informatics at Sofia University
*
* =====================================================================================
*/
#include <iostream>
#include <cstring>
using namespace std;
const int MAX_SIZE = 1000;
const char diff = 'a' - 'A';
bool isInnerWordChar(char c)
{
return c == '-' || c >= 'A' && c <= 'Z' || c >= 'a' && c <= 'z';
}
bool isBeginWordChar(char c)
{
return isInnerWordChar(c) || c == '"' || c == '\'' || c == '(';
}
bool isEndWordChar(char c)
{
return isInnerWordChar(c) || c == '"' || c == '\'' || c == ')';
}
char toUpper(char c)
{
return c >= 'a' && c <= 'z' ? c - diff : c;
}
char toLower(char c)
{
return c >= 'A' && c <= 'Z' ? c + diff : c;
}
void swap(char* a, char* b)
{
char x = *a;
*a = *b;
*b = x;
}
const char* goToEnd(const char* s)
{
while (*s)
s++;
return s;
}
char* appendBegin(char* rev, const char* beg, const char* end)
{
if (isInnerWordChar(*end) && isBeginWordChar(*beg) && !isInnerWordChar(*beg))
if (*beg != '(')
strncat(rev, beg, 1);
else
strcat(rev, ")");
return rev;
}
// Ако изречението е невалидно, връщаме NULL
char* reverseSentence(char* rev, const char* s)
{
if (!s)
return NULL;
const char* end = goToEnd(s);
end--;
if (end < s || *end != '!' && *end != '.' && *end != '?')
return NULL;
const char* stop = end;
end--;
if (end < s)
return NULL;
do
{
const char *beg = end;
if (!isEndWordChar(*beg))
return NULL;
beg--;
while (beg >= s && isInnerWordChar(*beg))
beg--;
if (beg < s || !isBeginWordChar(*beg))
beg++;
if (isInnerWordChar(*beg) && !isInnerWordChar(*end))
if (*end != ')')
strncat(rev, end, 1);
else
strcat(rev, "(");
if (isInnerWordChar(*end) && !isInnerWordChar(*beg))
beg++;
if (beg == s)
{
char first[2];
first[0] = *beg;
first[1] = 0;
first[0] = toLower(first[0]);
strcat(rev, first);
strncat(rev, beg + 1, (!isInnerWordChar(*end) ? end - 1 : end) - beg);
appendBegin(rev, beg - 1, end);
}
else
{
strncat(rev, beg, end - beg + 1);
beg--;
if (isInnerWordChar(*end) && isBeginWordChar(*beg) && !isInnerWordChar(*beg))
beg--;
if (*beg != ' ')
return NULL;
beg--;
if (beg < s)
return NULL;
if (*beg == ',' || *beg == ':' || *beg == ';' || *beg == '(' || *beg == ')')
strncat(rev, beg, 1);
strncat(rev, beg + 1, 1);
beg += 2;
appendBegin(rev, beg, end);
strncat(rev, beg - 1, 1);
}
end = beg - 2;
}
while (end >= s);
strncat(rev, stop, 1);
*rev = toUpper(*rev);
/* char *p = rev, *lp = NULL;
int b = 0;
while (*p)
{
if (*p == '(')
{
b++;
if (lp && b == 0)
{
swap(p, lp);
lp = NULL;
}
}
else if (*p == ')')
{
b--;
if (b == -1)
lp = p;
}
p++;
}
*/
return rev;
}
int main()
{
char s[MAX_SIZE], rev[MAX_SIZE];
cin.getline(s, MAX_SIZE);
cout << reverseSentence(rev, s) << endl;
return 0;
}
<|endoftext|>
|
<commit_before>#include <gtest/gtest.h>
#include <utility>
#include "OsiSolverInterface.hpp"
#include "OsiClpSolverInterface.hpp"
#include "CoinPackedMatrix.hpp"
#include "CoinModel.hpp"
#include "coin_helpers.h"
#include "exchange_graph.h"
#include "equality_helpers.h"
#include "prog_translator.h"
#include "solver_factory.h"
#include "logger.h"
namespace cyclus {
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
TEST(ProgTranslatorTests, translation) {
// Logger::ReportLevel() = Logger::ToLogLevel("LEV_DEBUG2");
int narcs = 5;
int nfaux = 2;
int nrows = 8;
int nexcl = 3;
double prefs [] = {0.2, 1.2, 4, 5, 1.3, -1, -1};
double ucaps_a_0 [] = {0.5, 0.4};
double ucaps_a_3 [] = {0.3, 0.6};
double ucaps_b_1 [] = {0.9};
double ucaps_b_2 [] = {0.8};
double ucaps_b_4 [] = {0.7};
double ucaps_c_0 [] = {0.7};
double ucaps_c_1 [] = {0.8};
double ucaps_c_2 [] = {0.9};
double ucaps_d_3 [] = {1.3, 2};
double ucaps_d_4 [] = {1.4, 1.9};
double ucaps_5 [] = {1.0};
double ucaps_6 [] = {1.0};
double dem_a [] = {5.0, 4.9};
double dem_b [] = {4.0};
double sup_c [] = {10.0};
double sup_d [] = {10.1, 9.1};
int excl_arcs [] = {1, 2, 4};
double excl_flow [] = {0, 2, 2, 0, 2, 0, 0};
std::vector<double> obj_coeffs;
for (int i = 0; i != narcs + nfaux; i++) {
obj_coeffs.push_back((excl_flow[i] != 0) ?
excl_flow[i] * prefs[i] : prefs[i]);
}
ExchangeNode::Ptr a0(new ExchangeNode());
ExchangeNode::Ptr a1(new ExchangeNode());
ExchangeNode::Ptr b0(new ExchangeNode());
ExchangeNode::Ptr b1(new ExchangeNode());
ExchangeNode::Ptr c0(new ExchangeNode());
ExchangeNode::Ptr c1(new ExchangeNode());
ExchangeNode::Ptr c2(new ExchangeNode());
ExchangeNode::Ptr d0(new ExchangeNode());
ExchangeNode::Ptr d1(new ExchangeNode());
Arc x0(a0, c0);
Arc x1(b0, c1, true, excl_flow[1]);
Arc x2(b1, c2, true, excl_flow[2]);
Arc x3(a1, d0);
Arc x4(b1, d1, true, excl_flow[4]);
a0->unit_capacities[x0] = std::vector<double>(
ucaps_a_0, ucaps_a_0 + sizeof(ucaps_a_0) / sizeof(ucaps_a_0[0]) );
a1->unit_capacities[x3] = std::vector<double>(
ucaps_a_3, ucaps_a_3 + sizeof(ucaps_a_3) / sizeof(ucaps_a_3[0]) );
b0->unit_capacities[x1] = std::vector<double>(
ucaps_b_1, ucaps_b_1 + sizeof(ucaps_b_1) / sizeof(ucaps_b_1[0]) );
b1->unit_capacities[x2] = std::vector<double>(
ucaps_b_2, ucaps_b_2 + sizeof(ucaps_b_2) / sizeof(ucaps_b_2[0]) );
b1->unit_capacities[x4] = std::vector<double>(
ucaps_b_4, ucaps_b_4 + sizeof(ucaps_b_4) / sizeof(ucaps_b_4[0]) );
c0->unit_capacities[x0] = std::vector<double>(
ucaps_c_0, ucaps_c_0 + sizeof(ucaps_c_0) / sizeof(ucaps_c_0[0]) );
c1->unit_capacities[x1] = std::vector<double>(
ucaps_c_1, ucaps_c_1 + sizeof(ucaps_c_1) / sizeof(ucaps_c_1[0]) );
c2->unit_capacities[x2] = std::vector<double>(
ucaps_c_2, ucaps_c_2 + sizeof(ucaps_c_2) / sizeof(ucaps_c_2[0]) );
d0->unit_capacities[x3] = std::vector<double>(
ucaps_d_3, ucaps_d_3 + sizeof(ucaps_d_3) / sizeof(ucaps_d_3[0]) );
d1->unit_capacities[x4] = std::vector<double>(
ucaps_d_4, ucaps_d_4 + sizeof(ucaps_d_4) / sizeof(ucaps_d_4[0]) );
a0->prefs[x0] = prefs[0];
b0->prefs[x1] = prefs[1];
b1->prefs[x2] = prefs[2];
a1->prefs[x3] = prefs[3];
b1->prefs[x4] = prefs[4];
RequestGroup::Ptr a(new RequestGroup()); // new RequestGroup(dem_a[0])?
a->AddExchangeNode(a0);
a->AddExchangeNode(a1);
a->AddCapacity(dem_a[0]);
a->AddCapacity(dem_a[1]);
RequestGroup::Ptr b(new RequestGroup()); // new RequestGroup(dem_b[0])?
b->AddExchangeNode(b0);
b->AddExchangeNode(b1);
b->AddCapacity(dem_b[0]);
ExchangeNodeGroup::Ptr c(new ExchangeNodeGroup());
c->AddExchangeNode(c0);
c->AddExchangeNode(c1);
c->AddExchangeNode(c2);
c->AddCapacity(sup_c[0]);
ExchangeNodeGroup::Ptr d(new ExchangeNodeGroup());
d->AddExchangeNode(d0);
d->AddExchangeNode(d1);
d->AddCapacity(sup_d[0]);
d->AddCapacity(sup_d[1]);
ExchangeGraph g;
g.AddRequestGroup(a);
g.AddRequestGroup(b);
g.AddSupplyGroup(c);
g.AddSupplyGroup(d);
g.AddArc(x0);
g.AddArc(x1);
g.AddArc(x2);
g.AddArc(x3);
g.AddArc(x4);
SolverFactory sf;
sf.solver_t("cbc");
OsiSolverInterface* iface = sf.get();
CoinMessageHandler h;
h.setLogLevel(0);
iface->passInMessageHandler(&h);
bool excl = true;
ProgTranslator pt(&g, iface, excl);
EXPECT_NO_THROW(pt.Translate());
double inf = iface->getInfinity();
// test non-coin xlate members
double col_lbs [] = {0, 0, 0, 0, 0, 0, 0};
double col_ubs [] = {inf, 1, 1, inf, 1, inf, inf};
double row_lbs [] = {0, 0, 0, dem_a[0], dem_a[1], dem_b[0], 0, 0};
double row_ubs [] = {sup_c[0], sup_d[0], sup_d[1], inf, inf, inf, 1, 1};
array_double_eq(&obj_coeffs[0], &pt.ctx().obj_coeffs[0], narcs + nfaux, "obj");
array_double_eq(col_ubs, &pt.ctx().col_ubs[0], narcs + nfaux, "col_ub");
array_double_eq(col_lbs, &pt.ctx().col_lbs[0], narcs + nfaux, "col_lb");
array_double_eq(row_ubs, &pt.ctx().row_ubs[0], nrows, "row_ub");
array_double_eq(row_lbs, &pt.ctx().row_lbs[0], nrows, "row_lb");
for (int i = 0; i != 7; i++) {
EXPECT_DOUBLE_EQ(col_lbs[i], pt.ctx().col_lbs[i]);
}
// test coin xlate members
CoinPackedMatrix m(false, 0, 0);
m.setDimensions(0, narcs + nfaux);
int row_ind_0 [] = {0, 1, 2};
double row_val_0 [] = {ucaps_c_0[0],
ucaps_c_1[0] * excl_flow[1],
ucaps_c_2[0] * excl_flow[2]};
m.appendRow(3, row_ind_0, row_val_0);
int row_ind_1 [] = {3, 4};
double row_val_1 [] = {ucaps_d_3[0],
ucaps_d_4[0] * excl_flow[4]};
m.appendRow(2, row_ind_1, row_val_1);
int row_ind_2 [] = {3, 4};
double row_val_2 [] = {ucaps_d_3[1],
ucaps_d_4[1] * excl_flow[4]};
m.appendRow(2, row_ind_2, row_val_2);
int row_ind_3 [] = {0, 3, 5};
double row_val_3 [] = {ucaps_a_0[0], ucaps_a_3[0], 1};
m.appendRow(3, row_ind_3, row_val_3);
int row_ind_4 [] = {0, 3, 5};
double row_val_4 [] = {ucaps_a_0[1], ucaps_a_3[1], 1};
m.appendRow(3, row_ind_4, row_val_4);
int row_ind_5 [] = {1, 2, 4, 6};
double row_val_5 [] = {ucaps_b_1[0] * excl_flow[1],
ucaps_b_2[0] * excl_flow[2],
ucaps_b_4[0] * excl_flow[4],
1};
m.appendRow(4, row_ind_5, row_val_5);
int row_ind_6 [] = {1};
double row_val_6 [] = {1};
m.appendRow(1, row_ind_6, row_val_6);
int row_ind_7 [] = {2, 4};
double row_val_7 [] = {1, 1};
m.appendRow(2, row_ind_7, row_val_7);
EXPECT_TRUE(m.isEquivalent2(pt.ctx().m));
// test population
EXPECT_NO_THROW(pt.Populate());
for (int i = 0; i != nexcl; i++) {
EXPECT_TRUE(iface->isInteger(excl_arcs[i]));
}
// verify problem instance
OsiClpSolverInterface checkface;
checkface.loadProblem(m, &col_lbs[0], &col_ubs[0],
&obj_coeffs[0], &row_lbs[0], &row_ubs[0]);
for (int i = 0; i != nexcl; i++) {
checkface.setInteger(excl_arcs[i]);
}
EXPECT_EQ(0, differentModel(*iface, checkface));
differentModel(*iface, checkface);
checkface.passInMessageHandler(&h);
checkface.setObjSense(-1.0);
checkface.initialSolve();
checkface.branchAndBound();
// verify solution
EXPECT_NO_THROW(Solve(iface));
const double* soln = iface->getColSolution();
const double* check = checkface.getColSolution();
array_double_eq(soln, check, narcs + nfaux);
// validate solution
double x0_flow = (sup_c[0] -
ucaps_c_1[0] * excl_flow[1] - ucaps_c_2[0] * excl_flow[2]) /
ucaps_c_0[0]; // 9.42857..
double x1_flow = excl_flow[1];
double x2_flow = excl_flow[2];
double x3_flow = sup_d[1] / ucaps_d_3[1]; // 4.55
double x4_flow = 0;
// first faux arc
double x5_flow = 0;
// second faux arc
double x6_flow = dem_b[0] -
ucaps_b_1[0] * excl_flow[1] -
ucaps_b_2[0] * excl_flow[2]; // 0.6;
EXPECT_DOUBLE_EQ(soln[0], x0_flow);
EXPECT_EQ(soln[1], 1);
EXPECT_EQ(soln[2], 1);
EXPECT_DOUBLE_EQ(soln[3], x3_flow);
EXPECT_EQ(soln[4], 0);
EXPECT_DOUBLE_EQ(soln[5], 0);
EXPECT_DOUBLE_EQ(soln[6], x6_flow);
// check back translation
pt.FromProg();
const std::vector<Match>& matches = g.matches();
EXPECT_EQ(4, matches.size());
pair_double_eq(matches[0], std::pair<Arc, double>(x0, x0_flow));
pair_double_eq(matches[1], std::pair<Arc, double>(x1, x1_flow));
pair_double_eq(matches[2], std::pair<Arc, double>(x2, x2_flow));
pair_double_eq(matches[3], std::pair<Arc, double>(x3, x3_flow));
delete iface;
};
} // namespace cyclus
<commit_msg>expect->assert eq<commit_after>#include <gtest/gtest.h>
#include <utility>
#include "OsiSolverInterface.hpp"
#include "OsiClpSolverInterface.hpp"
#include "CoinPackedMatrix.hpp"
#include "CoinModel.hpp"
#include "coin_helpers.h"
#include "exchange_graph.h"
#include "equality_helpers.h"
#include "prog_translator.h"
#include "solver_factory.h"
#include "logger.h"
namespace cyclus {
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
TEST(ProgTranslatorTests, translation) {
// Logger::ReportLevel() = Logger::ToLogLevel("LEV_DEBUG2");
int narcs = 5;
int nfaux = 2;
int nrows = 8;
int nexcl = 3;
double prefs [] = {0.2, 1.2, 4, 5, 1.3, -1, -1};
double ucaps_a_0 [] = {0.5, 0.4};
double ucaps_a_3 [] = {0.3, 0.6};
double ucaps_b_1 [] = {0.9};
double ucaps_b_2 [] = {0.8};
double ucaps_b_4 [] = {0.7};
double ucaps_c_0 [] = {0.7};
double ucaps_c_1 [] = {0.8};
double ucaps_c_2 [] = {0.9};
double ucaps_d_3 [] = {1.3, 2};
double ucaps_d_4 [] = {1.4, 1.9};
double ucaps_5 [] = {1.0};
double ucaps_6 [] = {1.0};
double dem_a [] = {5.0, 4.9};
double dem_b [] = {4.0};
double sup_c [] = {10.0};
double sup_d [] = {10.1, 9.1};
int excl_arcs [] = {1, 2, 4};
double excl_flow [] = {0, 2, 2, 0, 2, 0, 0};
std::vector<double> obj_coeffs;
for (int i = 0; i != narcs + nfaux; i++) {
obj_coeffs.push_back((excl_flow[i] != 0) ?
excl_flow[i] * prefs[i] : prefs[i]);
}
ExchangeNode::Ptr a0(new ExchangeNode());
ExchangeNode::Ptr a1(new ExchangeNode());
ExchangeNode::Ptr b0(new ExchangeNode());
ExchangeNode::Ptr b1(new ExchangeNode());
ExchangeNode::Ptr c0(new ExchangeNode());
ExchangeNode::Ptr c1(new ExchangeNode());
ExchangeNode::Ptr c2(new ExchangeNode());
ExchangeNode::Ptr d0(new ExchangeNode());
ExchangeNode::Ptr d1(new ExchangeNode());
Arc x0(a0, c0);
Arc x1(b0, c1, true, excl_flow[1]);
Arc x2(b1, c2, true, excl_flow[2]);
Arc x3(a1, d0);
Arc x4(b1, d1, true, excl_flow[4]);
a0->unit_capacities[x0] = std::vector<double>(
ucaps_a_0, ucaps_a_0 + sizeof(ucaps_a_0) / sizeof(ucaps_a_0[0]) );
a1->unit_capacities[x3] = std::vector<double>(
ucaps_a_3, ucaps_a_3 + sizeof(ucaps_a_3) / sizeof(ucaps_a_3[0]) );
b0->unit_capacities[x1] = std::vector<double>(
ucaps_b_1, ucaps_b_1 + sizeof(ucaps_b_1) / sizeof(ucaps_b_1[0]) );
b1->unit_capacities[x2] = std::vector<double>(
ucaps_b_2, ucaps_b_2 + sizeof(ucaps_b_2) / sizeof(ucaps_b_2[0]) );
b1->unit_capacities[x4] = std::vector<double>(
ucaps_b_4, ucaps_b_4 + sizeof(ucaps_b_4) / sizeof(ucaps_b_4[0]) );
c0->unit_capacities[x0] = std::vector<double>(
ucaps_c_0, ucaps_c_0 + sizeof(ucaps_c_0) / sizeof(ucaps_c_0[0]) );
c1->unit_capacities[x1] = std::vector<double>(
ucaps_c_1, ucaps_c_1 + sizeof(ucaps_c_1) / sizeof(ucaps_c_1[0]) );
c2->unit_capacities[x2] = std::vector<double>(
ucaps_c_2, ucaps_c_2 + sizeof(ucaps_c_2) / sizeof(ucaps_c_2[0]) );
d0->unit_capacities[x3] = std::vector<double>(
ucaps_d_3, ucaps_d_3 + sizeof(ucaps_d_3) / sizeof(ucaps_d_3[0]) );
d1->unit_capacities[x4] = std::vector<double>(
ucaps_d_4, ucaps_d_4 + sizeof(ucaps_d_4) / sizeof(ucaps_d_4[0]) );
a0->prefs[x0] = prefs[0];
b0->prefs[x1] = prefs[1];
b1->prefs[x2] = prefs[2];
a1->prefs[x3] = prefs[3];
b1->prefs[x4] = prefs[4];
RequestGroup::Ptr a(new RequestGroup()); // new RequestGroup(dem_a[0])?
a->AddExchangeNode(a0);
a->AddExchangeNode(a1);
a->AddCapacity(dem_a[0]);
a->AddCapacity(dem_a[1]);
RequestGroup::Ptr b(new RequestGroup()); // new RequestGroup(dem_b[0])?
b->AddExchangeNode(b0);
b->AddExchangeNode(b1);
b->AddCapacity(dem_b[0]);
ExchangeNodeGroup::Ptr c(new ExchangeNodeGroup());
c->AddExchangeNode(c0);
c->AddExchangeNode(c1);
c->AddExchangeNode(c2);
c->AddCapacity(sup_c[0]);
ExchangeNodeGroup::Ptr d(new ExchangeNodeGroup());
d->AddExchangeNode(d0);
d->AddExchangeNode(d1);
d->AddCapacity(sup_d[0]);
d->AddCapacity(sup_d[1]);
ExchangeGraph g;
g.AddRequestGroup(a);
g.AddRequestGroup(b);
g.AddSupplyGroup(c);
g.AddSupplyGroup(d);
g.AddArc(x0);
g.AddArc(x1);
g.AddArc(x2);
g.AddArc(x3);
g.AddArc(x4);
SolverFactory sf;
sf.solver_t("cbc");
OsiSolverInterface* iface = sf.get();
CoinMessageHandler h;
h.setLogLevel(0);
iface->passInMessageHandler(&h);
bool excl = true;
ProgTranslator pt(&g, iface, excl);
EXPECT_NO_THROW(pt.Translate());
double inf = iface->getInfinity();
// test non-coin xlate members
double col_lbs [] = {0, 0, 0, 0, 0, 0, 0};
double col_ubs [] = {inf, 1, 1, inf, 1, inf, inf};
double row_lbs [] = {0, 0, 0, dem_a[0], dem_a[1], dem_b[0], 0, 0};
double row_ubs [] = {sup_c[0], sup_d[0], sup_d[1], inf, inf, inf, 1, 1};
array_double_eq(&obj_coeffs[0], &pt.ctx().obj_coeffs[0], narcs + nfaux, "obj");
array_double_eq(col_ubs, &pt.ctx().col_ubs[0], narcs + nfaux, "col_ub");
array_double_eq(col_lbs, &pt.ctx().col_lbs[0], narcs + nfaux, "col_lb");
array_double_eq(row_ubs, &pt.ctx().row_ubs[0], nrows, "row_ub");
array_double_eq(row_lbs, &pt.ctx().row_lbs[0], nrows, "row_lb");
for (int i = 0; i != 7; i++) {
EXPECT_DOUBLE_EQ(col_lbs[i], pt.ctx().col_lbs[i]);
}
// test coin xlate members
CoinPackedMatrix m(false, 0, 0);
m.setDimensions(0, narcs + nfaux);
int row_ind_0 [] = {0, 1, 2};
double row_val_0 [] = {ucaps_c_0[0],
ucaps_c_1[0] * excl_flow[1],
ucaps_c_2[0] * excl_flow[2]};
m.appendRow(3, row_ind_0, row_val_0);
int row_ind_1 [] = {3, 4};
double row_val_1 [] = {ucaps_d_3[0],
ucaps_d_4[0] * excl_flow[4]};
m.appendRow(2, row_ind_1, row_val_1);
int row_ind_2 [] = {3, 4};
double row_val_2 [] = {ucaps_d_3[1],
ucaps_d_4[1] * excl_flow[4]};
m.appendRow(2, row_ind_2, row_val_2);
int row_ind_3 [] = {0, 3, 5};
double row_val_3 [] = {ucaps_a_0[0], ucaps_a_3[0], 1};
m.appendRow(3, row_ind_3, row_val_3);
int row_ind_4 [] = {0, 3, 5};
double row_val_4 [] = {ucaps_a_0[1], ucaps_a_3[1], 1};
m.appendRow(3, row_ind_4, row_val_4);
int row_ind_5 [] = {1, 2, 4, 6};
double row_val_5 [] = {ucaps_b_1[0] * excl_flow[1],
ucaps_b_2[0] * excl_flow[2],
ucaps_b_4[0] * excl_flow[4],
1};
m.appendRow(4, row_ind_5, row_val_5);
int row_ind_6 [] = {1};
double row_val_6 [] = {1};
m.appendRow(1, row_ind_6, row_val_6);
int row_ind_7 [] = {2, 4};
double row_val_7 [] = {1, 1};
m.appendRow(2, row_ind_7, row_val_7);
EXPECT_TRUE(m.isEquivalent2(pt.ctx().m));
// test population
EXPECT_NO_THROW(pt.Populate());
for (int i = 0; i != nexcl; i++) {
EXPECT_TRUE(iface->isInteger(excl_arcs[i]));
}
// verify problem instance
OsiClpSolverInterface checkface;
checkface.loadProblem(m, &col_lbs[0], &col_ubs[0],
&obj_coeffs[0], &row_lbs[0], &row_ubs[0]);
for (int i = 0; i != nexcl; i++) {
checkface.setInteger(excl_arcs[i]);
}
EXPECT_EQ(0, differentModel(*iface, checkface));
differentModel(*iface, checkface);
checkface.passInMessageHandler(&h);
checkface.setObjSense(-1.0);
checkface.initialSolve();
checkface.branchAndBound();
// verify solution
EXPECT_NO_THROW(Solve(iface));
const double* soln = iface->getColSolution();
const double* check = checkface.getColSolution();
array_double_eq(soln, check, narcs + nfaux);
// validate solution
double x0_flow = (sup_c[0] -
ucaps_c_1[0] * excl_flow[1] - ucaps_c_2[0] * excl_flow[2]) /
ucaps_c_0[0]; // 9.42857..
double x1_flow = excl_flow[1];
double x2_flow = excl_flow[2];
double x3_flow = sup_d[1] / ucaps_d_3[1]; // 4.55
double x4_flow = 0;
// first faux arc
double x5_flow = 0;
// second faux arc
double x6_flow = dem_b[0] -
ucaps_b_1[0] * excl_flow[1] -
ucaps_b_2[0] * excl_flow[2]; // 0.6;
EXPECT_DOUBLE_EQ(soln[0], x0_flow);
EXPECT_EQ(soln[1], 1);
EXPECT_EQ(soln[2], 1);
EXPECT_DOUBLE_EQ(soln[3], x3_flow);
EXPECT_EQ(soln[4], 0);
EXPECT_DOUBLE_EQ(soln[5], 0);
EXPECT_DOUBLE_EQ(soln[6], x6_flow);
// check back translation
pt.FromProg();
const std::vector<Match>& matches = g.matches();
ASSERT_EQ(4, matches.size());
pair_double_eq(matches[0], std::pair<Arc, double>(x0, x0_flow));
pair_double_eq(matches[1], std::pair<Arc, double>(x1, x1_flow));
pair_double_eq(matches[2], std::pair<Arc, double>(x2, x2_flow));
pair_double_eq(matches[3], std::pair<Arc, double>(x3, x3_flow));
delete iface;
};
} // namespace cyclus
<|endoftext|>
|
<commit_before>/**
* @file
*/
#include "bi/type/FunctionType.hpp"
#include "bi/visitor/all.hpp"
bi::FunctionType::FunctionType(Type* params, Type* returnType, Location* loc,
const bool assignable) :
Type(loc, assignable),
ReturnTyped(returnType),
params(params) {
//
}
bi::FunctionType::~FunctionType() {
//
}
bool bi::FunctionType::isFunction() const {
return true;
}
bi::Type* bi::FunctionType::resolve(Type* args) {
if (args->definitely(*params)) {
return returnType;
} else {
return nullptr;
}
}
bi::Type* bi::FunctionType::accept(Cloner* visitor) const {
return visitor->clone(this);
}
bi::Type* bi::FunctionType::accept(Modifier* visitor) {
return visitor->modify(this);
}
void bi::FunctionType::accept(Visitor* visitor) const {
return visitor->visit(this);
}
bool bi::FunctionType::dispatchDefinitely(const Type& o) const {
return o.definitely(*this);
}
bool bi::FunctionType::definitely(const AliasType& o) const {
return definitely(*o.target->base);
}
bool bi::FunctionType::definitely(const FunctionType& o) const {
return params->definitely(*o.params);
}
bool bi::FunctionType::definitely(const OptionalType& o) const {
return definitely(*o.single);
}
bool bi::FunctionType::definitely(const ParenthesesType& o) const {
return definitely(*o.single);
}
bool bi::FunctionType::dispatchPossibly(const Type& o) const {
return o.possibly(*this);
}
bool bi::FunctionType::possibly(const AliasType& o) const {
return possibly(*o.target->base);
}
bool bi::FunctionType::possibly(const FunctionType& o) const {
return params->possibly(*o.params);
}
bool bi::FunctionType::possibly(const OptionalType& o) const {
return possibly(*o.single);
}
bool bi::FunctionType::possibly(const ParenthesesType& o) const {
return possibly(*o.single);
}
<commit_msg>Added return type to function type comparisons (needed for e.g. lambdas, posets of functions use only the type of parameters for ordering anyway).<commit_after>/**
* @file
*/
#include "bi/type/FunctionType.hpp"
#include "bi/visitor/all.hpp"
bi::FunctionType::FunctionType(Type* params, Type* returnType, Location* loc,
const bool assignable) :
Type(loc, assignable),
ReturnTyped(returnType),
params(params) {
//
}
bi::FunctionType::~FunctionType() {
//
}
bool bi::FunctionType::isFunction() const {
return true;
}
bi::Type* bi::FunctionType::resolve(Type* args) {
if (args->definitely(*params)) {
return returnType;
} else {
return nullptr;
}
}
bi::Type* bi::FunctionType::accept(Cloner* visitor) const {
return visitor->clone(this);
}
bi::Type* bi::FunctionType::accept(Modifier* visitor) {
return visitor->modify(this);
}
void bi::FunctionType::accept(Visitor* visitor) const {
return visitor->visit(this);
}
bool bi::FunctionType::dispatchDefinitely(const Type& o) const {
return o.definitely(*this);
}
bool bi::FunctionType::definitely(const AliasType& o) const {
return definitely(*o.target->base);
}
bool bi::FunctionType::definitely(const FunctionType& o) const {
return params->definitely(*o.params)
&& returnType->definitely(*o.returnType);
}
bool bi::FunctionType::definitely(const OptionalType& o) const {
return definitely(*o.single);
}
bool bi::FunctionType::definitely(const ParenthesesType& o) const {
return definitely(*o.single);
}
bool bi::FunctionType::dispatchPossibly(const Type& o) const {
return o.possibly(*this);
}
bool bi::FunctionType::possibly(const AliasType& o) const {
return possibly(*o.target->base);
}
bool bi::FunctionType::possibly(const FunctionType& o) const {
return params->possibly(*o.params) && returnType->possibly(*o.returnType);
}
bool bi::FunctionType::possibly(const OptionalType& o) const {
return possibly(*o.single);
}
bool bi::FunctionType::possibly(const ParenthesesType& o) const {
return possibly(*o.single);
}
<|endoftext|>
|
<commit_before>/*=========================================================================
Program: ORFEO Toolbox
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.
See OTBCopyright.txt for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
=========================================================================*/
// Software Guide : BeginLatex
//
// After having generated a classification map, it is possible to
// regularize such a labeled image in order to obtain more homogeneous
// areas, which makes the interpretation of its classes easier. For this
// purpose, the \doxygen{otb}{NeighborhoodMajorityVotingImageFilter} was
// implemented. Like a morphological filter, this filter uses majority
// voting in a ball shaped neighborhood in order to set each pixel of the
// classification map to the more representative label value in its
// neighborhood.
//
// In this example we will illustrate its use. We start by including the
// appropriate header file.
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
#include "otbNeighborhoodMajorityVotingImageFilter.h"
// Software Guide : EndCodeSnippet
#include "itkMacro.h"
#include "otbImage.h"
#include <iostream>
#include <otbImageFileReader.h>
#include "otbImageFileWriter.h"
#include "itkTimeProbe.h"
int main(int argc, char * argv[])
{
// Software Guide : BeginLatex
//
// Since the input image is a classification map, we will assume a
// single band input image for which each pixel value is a label coded
// on 8 bits as an integer between 0 and 255.
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
typedef unsigned char InputLabelPixelType;
typedef unsigned char OutputLabelPixelType;
const unsigned int Dimension = 2;
// Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
//
// Thus, both input and output images are single band labeled images,
// which are composed of the same type of pixels in this example
// (unsigned char).
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
typedef otb::Image<InputLabelPixelType, Dimension> InputLabelImageType;
typedef otb::Image<OutputLabelPixelType, Dimension> OutputLabelImageType;
// Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
//
// We can now define the type for the neighborhood majority voting filter,
// which is templated over its input and output images types and over its
// structuring element type.
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
// Neighborhood majority voting filter type
typedef otb::NeighborhoodMajorityVotingImageFilter<InputLabelImageType,
OutputLabelImageType> NeighborhoodMajorityVotingFilterType;
// Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
//
// Since the \doxygen{otb}{NeighborhoodMajorityVotingImageFilter} is a
// neighborhood based image filter, it is necessary to set the structuring
// element which will be used for the majority voting process. By default, the
// structuring element is a ball
// (\doxygen{itk}{BinaryBallStructuringElement}) with a radius defined by two sizes
// (respectively along X and Y). Thus, it is possible to handle anisotropic
// structuring elements such as ovals.
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
// Binary ball Structuring Element type
typedef NeighborhoodMajorityVotingFilterType::KernelType StructuringType;
typedef StructuringType::RadiusType RadiusType;
// Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
//
// Finally, we define the reader and the writer.
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
typedef otb::ImageFileReader<InputLabelImageType> ReaderType;
typedef otb::ImageFileWriter<OutputLabelImageType> WriterType;
// Software Guide : EndCodeSnippet
const char * inputFileName = argv[1];
const char * outputFileName = argv[2];
// Software Guide : BeginLatex
//
// We instantiate the \doxygen{otb}{NeighborhoodMajorityVotingImageFilter} and the
// reader objects.
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
// Neighborhood majority voting filter
NeighborhoodMajorityVotingFilterType::Pointer NeighMajVotingFilter;
NeighMajVotingFilter = NeighborhoodMajorityVotingFilterType::New();
ReaderType::Pointer reader = ReaderType::New();
reader->SetFileName(inputFileName);
// Software Guide : EndCodeSnippet
std::string KeepOriginalLabelBoolStr = argv[3];
unsigned int radiusX = atoi(argv[4]);
unsigned int radiusY = atoi(argv[5]);
OutputLabelPixelType noDataValue = atoi(argv[6]);
OutputLabelPixelType undecidedValue = atoi(argv[7]);
// Software Guide : BeginLatex
//
// The ball shaped structuring element seBall is instantiated and its
// two radii along X and Y are initialized.
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
StructuringType seBall;
RadiusType rad;
rad[0] = radiusX;
rad[1] = radiusY;
seBall.SetRadius(rad);
seBall.CreateStructuringElement();
// Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
//
// Then, this ball shaped neighborhood is used as the kernel structuring element
// for the \doxygen{otb}{NeighborhoodMajorityVotingImageFilter}.
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
NeighMajVotingFilter->SetKernel(seBall);
// Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
//
// Not classified input pixels are assumed to have the noDataValue label
// and will keep this label in the output image.
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
NeighMajVotingFilter->SetLabelForNoDataPixels(noDataValue);
// Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
//
// Moreover, since the majority voting regularization may lead to not unique
// majority labels in the neighborhood, it is important to define which behaviour
// the filter must have in this case. For this purpose, a Boolean parameter is used
// in the filter to choose whether pixels with more than one majority class are set
// to undecidedValue (true), or to their Original labels (false = default value)
// in the output image.
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
NeighMajVotingFilter->SetLabelForUndecidedPixels(undecidedValue);
if (KeepOriginalLabelBoolStr.compare("true") == 0)
{
NeighMajVotingFilter->SetKeepOriginalLabelBool(true);
}
else
{
NeighMajVotingFilter->SetKeepOriginalLabelBool(false);
}
// Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
//
// We plug the pipeline and
// trigger its execution by updating the output of the writer.
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
NeighMajVotingFilter->SetInput(reader->GetOutput());
WriterType::Pointer writer = WriterType::New();
writer->SetFileName(outputFileName);
writer->SetInput(NeighMajVotingFilter->GetOutput());
writer->Update();
// Software Guide : EndCodeSnippet
return EXIT_SUCCESS;
}
<commit_msg>STYLE<commit_after>/*=========================================================================
Program: ORFEO Toolbox
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.
See OTBCopyright.txt for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
=========================================================================*/
// Software Guide : BeginLatex
//
// After having generated a classification map, it is possible to
// regularize such a labeled image in order to obtain more homogeneous
// areas, which makes the interpretation of its classes easier. For this
// purpose, the \doxygen{otb}{NeighborhoodMajorityVotingImageFilter} was
// implemented. Like a morphological filter, this filter uses majority
// voting in a ball shaped neighborhood in order to set each pixel of the
// classification map to the more representative label value in its
// neighborhood.
//
// In this example we will illustrate its use. We start by including the
// appropriate header file.
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
#include "otbNeighborhoodMajorityVotingImageFilter.h"
// Software Guide : EndCodeSnippet
#include "itkMacro.h"
#include "otbImage.h"
#include <iostream>
#include <otbImageFileReader.h>
#include "otbImageFileWriter.h"
#include "itkTimeProbe.h"
int main(int argc, char * argv[])
{
// Software Guide : BeginLatex
//
// Since the input image is a classification map, we will assume a
// single band input image for which each pixel value is a label coded
// on 8 bits as an integer between 0 and 255.
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
typedef unsigned char InputLabelPixelType;
typedef unsigned char OutputLabelPixelType;
const unsigned int Dimension = 2;
// Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
//
// Thus, both input and output images are single band labeled images,
// which are composed of the same type of pixels in this example
// (unsigned char).
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
typedef otb::Image<InputLabelPixelType, Dimension> InputLabelImageType;
typedef otb::Image<OutputLabelPixelType, Dimension> OutputLabelImageType;
// Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
//
// We can now define the type for the neighborhood majority voting filter,
// which is templated over its input and output images types and over its
// structuring element type.
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
// Neighborhood majority voting filter type
typedef otb::NeighborhoodMajorityVotingImageFilter<InputLabelImageType,
OutputLabelImageType> NeighborhoodMajorityVotingFilterType;
// Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
//
// Since the \doxygen{otb}{NeighborhoodMajorityVotingImageFilter} is a
// neighborhood based image filter, it is necessary to set the structuring
// element which will be used for the majority voting process. By default, the
// structuring element is a ball
// (\doxygen{itk}{BinaryBallStructuringElement}) with a radius defined by two sizes
// (respectively along X and Y). Thus, it is possible to handle anisotropic
// structuring elements such as ovals.
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
// Binary ball Structuring Element type
typedef NeighborhoodMajorityVotingFilterType::KernelType StructuringType;
typedef StructuringType::RadiusType RadiusType;
// Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
//
// Finally, we define the reader and the writer.
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
typedef otb::ImageFileReader<InputLabelImageType> ReaderType;
typedef otb::ImageFileWriter<OutputLabelImageType> WriterType;
// Software Guide : EndCodeSnippet
const char * inputFileName = argv[1];
const char * outputFileName = argv[2];
// Software Guide : BeginLatex
//
// We instantiate the \doxygen{otb}{NeighborhoodMajorityVotingImageFilter} and the
// reader objects.
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
// Neighborhood majority voting filter
NeighborhoodMajorityVotingFilterType::Pointer NeighMajVotingFilter;
NeighMajVotingFilter = NeighborhoodMajorityVotingFilterType::New();
ReaderType::Pointer reader = ReaderType::New();
reader->SetFileName(inputFileName);
// Software Guide : EndCodeSnippet
std::string KeepOriginalLabelBoolStr = argv[3];
unsigned int radiusX = atoi(argv[4]);
unsigned int radiusY = atoi(argv[5]);
OutputLabelPixelType noDataValue = atoi(argv[6]);
OutputLabelPixelType undecidedValue = atoi(argv[7]);
// Software Guide : BeginLatex
//
// The ball shaped structuring element seBall is instantiated and its
// two radii along X and Y are initialized.
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
StructuringType seBall;
RadiusType rad;
rad[0] = radiusX;
rad[1] = radiusY;
seBall.SetRadius(rad);
seBall.CreateStructuringElement();
// Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
//
// Then, this ball shaped neighborhood is used as the kernel structuring element
// for the \doxygen{otb}{NeighborhoodMajorityVotingImageFilter}.
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
NeighMajVotingFilter->SetKernel(seBall);
// Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
//
// Not classified input pixels are assumed to have the noDataValue label
// and will keep this label in the output image.
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
NeighMajVotingFilter->SetLabelForNoDataPixels(noDataValue);
// Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
//
// Moreover, since the majority voting regularization may lead to not unique
// majority labels in the neighborhood, it is important to define which behaviour
// the filter must have in this case. For this purpose, a Boolean parameter is used
// in the filter to choose whether pixels with more than one majority class are set
// to undecidedValue (true), or to their Original labels (false = default value)
// in the output image.
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
NeighMajVotingFilter->SetLabelForUndecidedPixels(undecidedValue);
if (KeepOriginalLabelBoolStr.compare("true") == 0)
{
NeighMajVotingFilter->SetKeepOriginalLabelBool(true);
}
else
{
NeighMajVotingFilter->SetKeepOriginalLabelBool(false);
}
// Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
//
// We plug the pipeline and
// trigger its execution by updating the output of the writer.
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
NeighMajVotingFilter->SetInput(reader->GetOutput());
WriterType::Pointer writer = WriterType::New();
writer->SetFileName(outputFileName);
writer->SetInput(NeighMajVotingFilter->GetOutput());
writer->Update();
// Software Guide : EndCodeSnippet
return EXIT_SUCCESS;
}
<|endoftext|>
|
<commit_before>// Copyright (c) 2020 The Orbit 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 "orbiteventiterator.h"
#include "absl/strings/str_format.h"
#include "ui_orbiteventiterator.h"
//-----------------------------------------------------------------------------
OrbitEventIterator::OrbitEventIterator(QWidget* parent)
: QFrame(parent), ui(new Ui::OrbitEventIterator) {
ui->setupUi(this);
}
//-----------------------------------------------------------------------------
OrbitEventIterator::~OrbitEventIterator() { delete ui; }
//-----------------------------------------------------------------------------
void OrbitEventIterator::on_NextButton_clicked() {
if (next_button_callback_) {
next_button_callback_();
}
}
//-----------------------------------------------------------------------------
void OrbitEventIterator::on_PreviousButton_clicked() {
if (previous_button_callback_) {
previous_button_callback_();
}
}
//-----------------------------------------------------------------------------
void OrbitEventIterator::on_DeleteButton_clicked() {
if (delete_button_callback_) {
delete_button_callback_();
}
}
//-----------------------------------------------------------------------------
void OrbitEventIterator::SetFunctionName(const std::string& function_name) {
ui->Label->setTextWithElision(QString::fromStdString(function_name));
}
//-----------------------------------------------------------------------------
void OrbitEventIterator::SetMaxCount(int max_count) {
max_count_ = max_count;
UpdateCountLabel();
}
//-----------------------------------------------------------------------------
void OrbitEventIterator::SetIndex(int current_index) {
current_index_ = 0;
UpdateCountLabel();
}
//-----------------------------------------------------------------------------
void OrbitEventIterator::IncrementIndex() {
if (current_index_ < max_count_ - 1) {
++current_index_;
UpdateCountLabel();
}
}
//-----------------------------------------------------------------------------
void OrbitEventIterator::DecrementIndex() {
if (current_index_ > 0) {
--current_index_;
UpdateCountLabel();
}
}
//-----------------------------------------------------------------------------
void OrbitEventIterator::UpdateCountLabel() {
ui->CountLabel->setText(QString::fromStdString(
absl::StrFormat("%d / %d", current_index_, max_count_)));
}
//-----------------------------------------------------------------------------
void OrbitEventIterator::HideDeleteButton() { ui->DeleteButton->hide(); }
//-----------------------------------------------------------------------------
void OrbitEventIterator::EnableButtons() {
ui->NextButton->setEnabled(true);
ui->PreviousButton->setEnabled(true);
}
//-----------------------------------------------------------------------------
void OrbitEventIterator::DisableButtons() {
ui->NextButton->setEnabled(false);
ui->PreviousButton->setEnabled(false);
}<commit_msg>Show instances of function calls starting at 1 not at index 0<commit_after>// Copyright (c) 2020 The Orbit 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 "orbiteventiterator.h"
#include "absl/strings/str_format.h"
#include "ui_orbiteventiterator.h"
//-----------------------------------------------------------------------------
OrbitEventIterator::OrbitEventIterator(QWidget* parent)
: QFrame(parent), ui(new Ui::OrbitEventIterator) {
ui->setupUi(this);
}
//-----------------------------------------------------------------------------
OrbitEventIterator::~OrbitEventIterator() { delete ui; }
//-----------------------------------------------------------------------------
void OrbitEventIterator::on_NextButton_clicked() {
if (next_button_callback_) {
next_button_callback_();
}
}
//-----------------------------------------------------------------------------
void OrbitEventIterator::on_PreviousButton_clicked() {
if (previous_button_callback_) {
previous_button_callback_();
}
}
//-----------------------------------------------------------------------------
void OrbitEventIterator::on_DeleteButton_clicked() {
if (delete_button_callback_) {
delete_button_callback_();
}
}
//-----------------------------------------------------------------------------
void OrbitEventIterator::SetFunctionName(const std::string& function_name) {
ui->Label->setTextWithElision(QString::fromStdString(function_name));
}
//-----------------------------------------------------------------------------
void OrbitEventIterator::SetMaxCount(int max_count) {
max_count_ = max_count;
UpdateCountLabel();
}
//-----------------------------------------------------------------------------
void OrbitEventIterator::SetIndex(int current_index) {
current_index_ = 0;
UpdateCountLabel();
}
//-----------------------------------------------------------------------------
void OrbitEventIterator::IncrementIndex() {
if (current_index_ < max_count_ - 1) {
++current_index_;
UpdateCountLabel();
}
}
//-----------------------------------------------------------------------------
void OrbitEventIterator::DecrementIndex() {
if (current_index_ > 0) {
--current_index_;
UpdateCountLabel();
}
}
//-----------------------------------------------------------------------------
void OrbitEventIterator::UpdateCountLabel() {
// Indices start at 0, so we display index + 1 in the UI.
ui->CountLabel->setText(QString::fromStdString(
absl::StrFormat("%d / %d", current_index_ + 1, max_count_)));
}
//-----------------------------------------------------------------------------
void OrbitEventIterator::HideDeleteButton() { ui->DeleteButton->hide(); }
//-----------------------------------------------------------------------------
void OrbitEventIterator::EnableButtons() {
ui->NextButton->setEnabled(true);
ui->PreviousButton->setEnabled(true);
}
//-----------------------------------------------------------------------------
void OrbitEventIterator::DisableButtons() {
ui->NextButton->setEnabled(false);
ui->PreviousButton->setEnabled(false);
}<|endoftext|>
|
<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
* This file is part of the LibreOffice project.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
#include <GL3DBarChart.hxx>
#include <GL/glew.h>
#include <glm/glm.hpp>
#include <glm/gtx/transform.hpp>
#include "3DChartObjects.hxx"
#include "GL3DRenderer.hxx"
#include <ExplicitCategoriesProvider.hxx>
#include <DataSeriesHelper.hxx>
using namespace com::sun::star;
namespace chart {
GL3DBarChart::GL3DBarChart(
const css::uno::Reference<css::chart2::XChartType>& xChartType,
const boost::ptr_vector<VDataSeries>& rDataSeries,
OpenGLWindow& rWindow, ExplicitCategoriesProvider& rCatProvider ) :
mxChartType(xChartType),
maDataSeries(rDataSeries),
mpRenderer(new opengl3D::OpenGL3DRenderer()),
mrWindow(rWindow),
mrCatProvider(rCatProvider)
{
}
GL3DBarChart::~GL3DBarChart()
{
}
void GL3DBarChart::create3DShapes()
{
// Each series of data flows from left to right, and multiple series are
// stacked vertically along y axis.
// NOTE: These objects are created and positioned in a totally blind
// fashion since we don't even have a way to see them on screen. So, no
// guarantee they are positioned correctly. In fact, they are guaranteed
// to be positioned incorrectly.
const float nBarSizeX = 10;
const float nBarSizeY = 10;
const float nBarDistanceX = nBarSizeX / 2;
const float nBarDistanceY = nBarSizeY / 2;
sal_uInt32 nId = 1;
std::vector<opengl3D::Text*> aYAxisTexts;
float nYPos = 0.0;
maShapes.clear();
maShapes.push_back(new opengl3D::Camera(mpRenderer.get()));
sal_Int32 nSeriesIndex = 0;
for (boost::ptr_vector<VDataSeries>::const_iterator itr = maDataSeries.begin(),
itrEnd = maDataSeries.end(); itr != itrEnd; ++itr)
{
nYPos = nSeriesIndex * (nBarSizeY + nBarDistanceY);
const VDataSeries& rDataSeries = *itr;
sal_Int32 nPointCount = rDataSeries.getTotalPointCount();
// Create series name text object.
OUString aSeriesName =
DataSeriesHelper::getDataSeriesLabel(
rDataSeries.getModel(), mxChartType->getRoleOfSequenceForSeriesLabel());
aYAxisTexts.push_back(new opengl3D::Text(mpRenderer.get(), aSeriesName, nId++));
opengl3D::Text* p = aYAxisTexts.back();
Size aTextSize = p->getSize();
glm::vec3 aTopLeft, aTopRight, aBottomRight;
aTopLeft.x = aTextSize.getWidth() * -1.0;
aTopLeft.y = nYPos;
aTopRight.y = nYPos;
aBottomRight = aTopRight;
aBottomRight.y += aTextSize.getHeight();
p->setPosition(aTopLeft, aTopRight, aBottomRight);
for(sal_Int32 nIndex = 0; nIndex < nPointCount; ++nIndex)
{
float nVal = rDataSeries.getYValue(nIndex);
float nXPos = nIndex * (nBarSizeX + nBarDistanceX);
sal_Int32 nColor = COL_BLUE;
glm::mat4 aBarPosition;
aBarPosition = glm::scale(aBarPosition, nBarSizeX, nBarSizeY, nVal);
aBarPosition = glm::translate(aBarPosition, nXPos, nYPos, nVal/2);
maShapes.push_back(new opengl3D::Bar(mpRenderer.get(), aBarPosition, nColor, nId++));
}
++nSeriesIndex;
}
nYPos += nBarSizeY + nBarDistanceY;
// Create category texts along X-axis at the bottom.
uno::Sequence<OUString> aCats = mrCatProvider.getSimpleCategories();
for (sal_Int32 i = 0; i < aCats.getLength(); ++i)
{
float nXPos = i * (nBarSizeX + nBarDistanceX);
maShapes.push_back(new opengl3D::Text(mpRenderer.get(), aCats[i], nId++));
opengl3D::Text* p = static_cast<opengl3D::Text*>(&maShapes.back());
Size aTextSize = p->getSize();
glm::vec3 aTopLeft;
aTopLeft.x = nXPos;
aTopLeft.y = nYPos;
glm::vec3 aTopRight = aTopLeft;
aTopRight.x += aTextSize.getWidth();
glm::vec3 aBottomRight = aTopRight;
aBottomRight.y += aTextSize.getHeight();
p->setPosition(aTopLeft, aTopRight, aBottomRight);
}
// Transfer all Y-axis text objects to the shape collection.
std::copy(aYAxisTexts.begin(), aYAxisTexts.end(), std::back_inserter(maShapes));
aYAxisTexts.clear();
}
void GL3DBarChart::render()
{
mrWindow.getContext()->makeCurrent();
Size aSize = mrWindow.GetSizePixel();
mpRenderer->SetSize(aSize);
mrWindow.getContext()->setWinSize(aSize);
for(boost::ptr_vector<opengl3D::Renderable3DObject>::iterator itr = maShapes.begin(),
itrEnd = maShapes.end(); itr != itrEnd; ++itr)
{
itr->render();
}
mrWindow.getContext()->swapBuffers();
}
}
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<commit_msg>Try without std::back_inserter. Some tinderboxes don't like that.<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
* This file is part of the LibreOffice project.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
#include <GL3DBarChart.hxx>
#include <GL/glew.h>
#include <glm/glm.hpp>
#include <glm/gtx/transform.hpp>
#include "3DChartObjects.hxx"
#include "GL3DRenderer.hxx"
#include <ExplicitCategoriesProvider.hxx>
#include <DataSeriesHelper.hxx>
using namespace com::sun::star;
namespace chart {
GL3DBarChart::GL3DBarChart(
const css::uno::Reference<css::chart2::XChartType>& xChartType,
const boost::ptr_vector<VDataSeries>& rDataSeries,
OpenGLWindow& rWindow, ExplicitCategoriesProvider& rCatProvider ) :
mxChartType(xChartType),
maDataSeries(rDataSeries),
mpRenderer(new opengl3D::OpenGL3DRenderer()),
mrWindow(rWindow),
mrCatProvider(rCatProvider)
{
}
GL3DBarChart::~GL3DBarChart()
{
}
void GL3DBarChart::create3DShapes()
{
// Each series of data flows from left to right, and multiple series are
// stacked vertically along y axis.
// NOTE: These objects are created and positioned in a totally blind
// fashion since we don't even have a way to see them on screen. So, no
// guarantee they are positioned correctly. In fact, they are guaranteed
// to be positioned incorrectly.
const float nBarSizeX = 10;
const float nBarSizeY = 10;
const float nBarDistanceX = nBarSizeX / 2;
const float nBarDistanceY = nBarSizeY / 2;
sal_uInt32 nId = 1;
std::vector<opengl3D::Text*> aYAxisTexts;
float nYPos = 0.0;
maShapes.clear();
maShapes.push_back(new opengl3D::Camera(mpRenderer.get()));
sal_Int32 nSeriesIndex = 0;
for (boost::ptr_vector<VDataSeries>::const_iterator itr = maDataSeries.begin(),
itrEnd = maDataSeries.end(); itr != itrEnd; ++itr)
{
nYPos = nSeriesIndex * (nBarSizeY + nBarDistanceY);
const VDataSeries& rDataSeries = *itr;
sal_Int32 nPointCount = rDataSeries.getTotalPointCount();
// Create series name text object.
OUString aSeriesName =
DataSeriesHelper::getDataSeriesLabel(
rDataSeries.getModel(), mxChartType->getRoleOfSequenceForSeriesLabel());
aYAxisTexts.push_back(new opengl3D::Text(mpRenderer.get(), aSeriesName, nId++));
opengl3D::Text* p = aYAxisTexts.back();
Size aTextSize = p->getSize();
glm::vec3 aTopLeft, aTopRight, aBottomRight;
aTopLeft.x = aTextSize.getWidth() * -1.0;
aTopLeft.y = nYPos;
aTopRight.y = nYPos;
aBottomRight = aTopRight;
aBottomRight.y += aTextSize.getHeight();
p->setPosition(aTopLeft, aTopRight, aBottomRight);
for(sal_Int32 nIndex = 0; nIndex < nPointCount; ++nIndex)
{
float nVal = rDataSeries.getYValue(nIndex);
float nXPos = nIndex * (nBarSizeX + nBarDistanceX);
sal_Int32 nColor = COL_BLUE;
glm::mat4 aBarPosition;
aBarPosition = glm::scale(aBarPosition, nBarSizeX, nBarSizeY, nVal);
aBarPosition = glm::translate(aBarPosition, nXPos, nYPos, nVal/2);
maShapes.push_back(new opengl3D::Bar(mpRenderer.get(), aBarPosition, nColor, nId++));
}
++nSeriesIndex;
}
nYPos += nBarSizeY + nBarDistanceY;
// Create category texts along X-axis at the bottom.
uno::Sequence<OUString> aCats = mrCatProvider.getSimpleCategories();
for (sal_Int32 i = 0; i < aCats.getLength(); ++i)
{
float nXPos = i * (nBarSizeX + nBarDistanceX);
maShapes.push_back(new opengl3D::Text(mpRenderer.get(), aCats[i], nId++));
opengl3D::Text* p = static_cast<opengl3D::Text*>(&maShapes.back());
Size aTextSize = p->getSize();
glm::vec3 aTopLeft;
aTopLeft.x = nXPos;
aTopLeft.y = nYPos;
glm::vec3 aTopRight = aTopLeft;
aTopRight.x += aTextSize.getWidth();
glm::vec3 aBottomRight = aTopRight;
aBottomRight.y += aTextSize.getHeight();
p->setPosition(aTopLeft, aTopRight, aBottomRight);
}
{
// Transfer all Y-axis text objects to the shape collection.
std::vector<opengl3D::Text*>::iterator itText = aYAxisTexts.begin(), itTextEnd = aYAxisTexts.end();
for (; itText != itTextEnd; ++itText)
maShapes.push_back(*itText);
}
aYAxisTexts.clear();
}
void GL3DBarChart::render()
{
mrWindow.getContext()->makeCurrent();
Size aSize = mrWindow.GetSizePixel();
mpRenderer->SetSize(aSize);
mrWindow.getContext()->setWinSize(aSize);
for(boost::ptr_vector<opengl3D::Renderable3DObject>::iterator itr = maShapes.begin(),
itrEnd = maShapes.end(); itr != itrEnd; ++itr)
{
itr->render();
}
mrWindow.getContext()->swapBuffers();
}
}
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<|endoftext|>
|
<commit_before>#include "gtest/gtest.h"
#include <SessionInfo.h>
#include <CryptokiException.h>
using namespace objck;
TEST(SessionInfo_test, constructor) {
CK_SESSION_INFO info = {
37,
CKS_RW_PUBLIC_SESSION,
CKF_SERIAL_SESSION,
2
};
SessionInfo sInfo(info);
EXPECT_EQ(sInfo.slotId(), 37);
EXPECT_EQ(sInfo.state(), CKS_RW_PUBLIC_SESSION);
EXPECT_EQ(sInfo.flags(), SessionInfo::SessionFlags::SERIAL_SESSION);
EXPECT_EQ(sInfo.deviceError(), 2);
CK_SESSION_INFO recoveredInfo = sInfo.getSessionInfo();
EXPECT_EQ(recoveredInfo.slotID, info.slotID);
EXPECT_EQ(recoveredInfo.state, info.state);
EXPECT_EQ(recoveredInfo.flags, info.flags);
EXPECT_EQ(recoveredInfo.ulDeviceError, info.ulDeviceError);
}
<commit_msg>Testing empty and unknown cases for SessionInfo<commit_after>#include "gtest/gtest.h"
#include <SessionInfo.h>
#include <CryptokiException.h>
using namespace objck;
TEST(SessionInfo_test, constructor) {
CK_SESSION_INFO info = {
37,
CKS_RW_PUBLIC_SESSION,
CKF_SERIAL_SESSION,
2
};
SessionInfo sInfo(info);
EXPECT_EQ(sInfo.slotId(), 37);
EXPECT_EQ(sInfo.state(), CKS_RW_PUBLIC_SESSION);
EXPECT_EQ(sInfo.flags(), SessionInfo::SessionFlags::SERIAL_SESSION);
EXPECT_EQ(sInfo.deviceError(), 2);
CK_SESSION_INFO recoveredInfo = sInfo.getSessionInfo();
EXPECT_EQ(recoveredInfo.slotID, info.slotID);
EXPECT_EQ(recoveredInfo.state, info.state);
EXPECT_EQ(recoveredInfo.flags, info.flags);
EXPECT_EQ(recoveredInfo.ulDeviceError, info.ulDeviceError);
}
TEST(SessionInfo_test, empty_and_unknown_flags) {
CK_SESSION_INFO info = { 0, 0, 0, 0 };
SessionInfo sInfo(info);
EXPECT_EQ(sInfo.flags(), SessionInfo::SessionFlags::EMPTY);
info.flags = 8;
sInfo = SessionInfo(info);
EXPECT_EQ(sInfo.flags(), SessionInfo::SessionFlags::UNKNOWN);
}
<|endoftext|>
|
<commit_before>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/ui/webui/new_profile_handler.h"
#include "base/string_number_conversions.h"
#include "base/values.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/profiles/profile_info_cache.h"
#include "chrome/browser/profiles/profile_manager.h"
#include "chrome/common/url_constants.h"
#include "content/browser/tab_contents/tab_contents.h"
NewProfileHandler::NewProfileHandler() {
}
void NewProfileHandler::RegisterMessages() {
web_ui_->RegisterMessageCallback("create",
NewCallback(this, &NewProfileHandler::HandleCreate));
web_ui_->RegisterMessageCallback("cancel",
NewCallback(this, &NewProfileHandler::HandleCancel));
web_ui_->RegisterMessageCallback("requestProfileInfo",
NewCallback(this, &NewProfileHandler::HandleRequestProfileInfo));
}
void NewProfileHandler::HandleCreate(const ListValue* args) {
string16 profile_name;
bool ret = args->GetString(0, &profile_name);
if (!ret || profile_name.empty())
return;
std::string string_index;
ret = args->GetString(1, &string_index);
if (!ret || string_index.empty())
return;
int profile_avatar_index;
if (!base::StringToInt(string_index, &profile_avatar_index))
return;
ProfileInfoCache& cache =
g_browser_process->profile_manager()->GetProfileInfoCache();
size_t index = cache.GetIndexOfProfileWithPath(
web_ui_->GetProfile()->GetPath());
if (index != std::string::npos) {
cache.SetNameOfProfileAtIndex(index, profile_name);
cache.SetAvatarIconOfProfileAtIndex(index, profile_avatar_index);
}
web_ui_->tab_contents()->OpenURL(GURL(chrome::kChromeUINewTabURL),
GURL(), CURRENT_TAB,
PageTransition::LINK);
}
void NewProfileHandler::HandleCancel(const ListValue* args) {
// TODO(sail): delete this profile.
}
void NewProfileHandler::HandleRequestProfileInfo(const ListValue* args) {
SendDefaultAvatarImages();
SendProfileInfo();
}
void NewProfileHandler::SendDefaultAvatarImages() {
ListValue image_url_list;
for (size_t i = 0; i < ProfileInfoCache::GetDefaultAvatarIconCount(); i++) {
std::string url = ProfileInfoCache::GetDefaultAvatarIconUrl(i);
image_url_list.Append(Value::CreateStringValue(url));
}
web_ui_->CallJavascriptFunction("newProfile.setDefaultAvatarImages",
image_url_list);
}
void NewProfileHandler::SendProfileInfo() {
ProfileInfoCache& cache =
g_browser_process->profile_manager()->GetProfileInfoCache();
size_t index = cache.GetIndexOfProfileWithPath(
web_ui_->GetProfile()->GetPath());
if (index != std::string::npos) {
StringValue profile_name(cache.GetNameOfProfileAtIndex(index));
FundamentalValue profile_icon_index(static_cast<int>(
cache.GetAvatarIconIndexOfProfileAtIndex(index)));
web_ui_->CallJavascriptFunction("newProfile.setProfileInfo",
profile_name,
profile_icon_index);
}
}
<commit_msg>Multi-Profiles: Hook up cancel button in chrome://newprofile<commit_after>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/ui/webui/new_profile_handler.h"
#include "base/string_number_conversions.h"
#include "base/values.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/profiles/profile_info_cache.h"
#include "chrome/browser/profiles/profile_manager.h"
#include "chrome/common/url_constants.h"
#include "content/browser/tab_contents/tab_contents.h"
NewProfileHandler::NewProfileHandler() {
}
void NewProfileHandler::RegisterMessages() {
web_ui_->RegisterMessageCallback("create",
NewCallback(this, &NewProfileHandler::HandleCreate));
web_ui_->RegisterMessageCallback("cancel",
NewCallback(this, &NewProfileHandler::HandleCancel));
web_ui_->RegisterMessageCallback("requestProfileInfo",
NewCallback(this, &NewProfileHandler::HandleRequestProfileInfo));
}
void NewProfileHandler::HandleCreate(const ListValue* args) {
string16 profile_name;
bool ret = args->GetString(0, &profile_name);
if (!ret || profile_name.empty())
return;
std::string string_index;
ret = args->GetString(1, &string_index);
if (!ret || string_index.empty())
return;
int profile_avatar_index;
if (!base::StringToInt(string_index, &profile_avatar_index))
return;
ProfileInfoCache& cache =
g_browser_process->profile_manager()->GetProfileInfoCache();
size_t index = cache.GetIndexOfProfileWithPath(
web_ui_->GetProfile()->GetPath());
if (index != std::string::npos) {
cache.SetNameOfProfileAtIndex(index, profile_name);
cache.SetAvatarIconOfProfileAtIndex(index, profile_avatar_index);
}
web_ui_->tab_contents()->OpenURL(GURL(chrome::kChromeUINewTabURL),
GURL(), CURRENT_TAB,
PageTransition::LINK);
}
void NewProfileHandler::HandleCancel(const ListValue* args) {
g_browser_process->profile_manager()->ScheduleProfileForDeletion(
web_ui_->GetProfile()->GetPath());
}
void NewProfileHandler::HandleRequestProfileInfo(const ListValue* args) {
SendDefaultAvatarImages();
SendProfileInfo();
}
void NewProfileHandler::SendDefaultAvatarImages() {
ListValue image_url_list;
for (size_t i = 0; i < ProfileInfoCache::GetDefaultAvatarIconCount(); i++) {
std::string url = ProfileInfoCache::GetDefaultAvatarIconUrl(i);
image_url_list.Append(Value::CreateStringValue(url));
}
web_ui_->CallJavascriptFunction("newProfile.setDefaultAvatarImages",
image_url_list);
}
void NewProfileHandler::SendProfileInfo() {
ProfileInfoCache& cache =
g_browser_process->profile_manager()->GetProfileInfoCache();
size_t index = cache.GetIndexOfProfileWithPath(
web_ui_->GetProfile()->GetPath());
if (index != std::string::npos) {
StringValue profile_name(cache.GetNameOfProfileAtIndex(index));
FundamentalValue profile_icon_index(static_cast<int>(
cache.GetAvatarIconIndexOfProfileAtIndex(index)));
web_ui_->CallJavascriptFunction("newProfile.setProfileInfo",
profile_name,
profile_icon_index);
}
}
<|endoftext|>
|
<commit_before>// Copyright (c) 2006-2008 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 <dwmapi.h>
#include "chrome/browser/views/frame/aero_glass_frame.h"
#include "chrome/app/theme/theme_resources.h"
#include "chrome/browser/frame_util.h"
#include "chrome/browser/views/frame/browser_view2.h"
#include "chrome/browser/views/frame/aero_glass_non_client_view.h"
#include "chrome/common/resource_bundle.h"
#include "chrome/views/window_delegate.h"
// static
// The width of the sizing borders.
static const int kResizeBorder = 8;
// By how much the toolbar overlaps with the tab strip.
static const int kToolbarOverlapVertOffset = 5;
// This is the width of the default client edge provided by Windows. In some
// circumstances we provide our own client edge, so we use this width to
// remove it.
static const int kWindowsDWMBevelSize = 2;
///////////////////////////////////////////////////////////////////////////////
// AeroGlassFrame, public:
AeroGlassFrame::AeroGlassFrame(BrowserView2* browser_view)
: Window(browser_view),
browser_view_(browser_view),
frame_initialized_(false) {
non_client_view_ = new AeroGlassNonClientView(this, browser_view);
browser_view_->set_frame(this);
}
AeroGlassFrame::~AeroGlassFrame() {
}
void AeroGlassFrame::Init(const gfx::Rect& bounds) {
Window::Init(NULL, bounds);
}
int AeroGlassFrame::GetMinimizeButtonOffset() const {
TITLEBARINFOEX titlebar_info;
titlebar_info.cbSize = sizeof(TITLEBARINFOEX);
SendMessage(GetHWND(), WM_GETTITLEBARINFOEX, 0, (WPARAM)&titlebar_info);
RECT wr;
GetWindowRect(&wr);
return wr.right - titlebar_info.rgrect[2].left;
}
///////////////////////////////////////////////////////////////////////////////
// AeroGlassFrame, BrowserFrame implementation:
gfx::Rect AeroGlassFrame::GetWindowBoundsForClientBounds(
const gfx::Rect& client_bounds) {
RECT rect = client_bounds.ToRECT();
AdjustWindowRectEx(&rect, window_style(), FALSE, window_ex_style());
return gfx::Rect(rect);
}
void AeroGlassFrame::SizeToContents(const gfx::Rect& contents_bounds) {
// TODO(beng): implement me.
}
gfx::Rect AeroGlassFrame::GetBoundsForTabStrip(TabStrip* tabstrip) const {
return GetAeroGlassNonClientView()->GetBoundsForTabStrip(tabstrip);
}
ChromeViews::Window* AeroGlassFrame::GetWindow() {
return this;
}
///////////////////////////////////////////////////////////////////////////////
// AeroGlassFrame, ChromeViews::Window overrides:
void AeroGlassFrame::UpdateWindowIcon() {
Window::UpdateWindowIcon();
// TODO(beng): do something in the non-client view when this builds on Vista.
}
///////////////////////////////////////////////////////////////////////////////
// AeroGlassFrame, ChromeViews::HWNDViewContainer implementation:
void AeroGlassFrame::OnInitMenuPopup(HMENU menu, UINT position,
BOOL is_system_menu) {
browser_view_->PrepareToRunSystemMenu(menu);
}
void AeroGlassFrame::OnEndSession(BOOL ending, UINT logoff) {
FrameUtil::EndSession();
}
void AeroGlassFrame::OnExitMenuLoop(bool is_track_popup_menu) {
browser_view_->SystemMenuEnded();
}
LRESULT AeroGlassFrame::OnMouseActivate(HWND window, UINT hittest_code,
UINT message) {
return browser_view_->ActivateAppModalDialog() ? MA_NOACTIVATEANDEAT
: MA_ACTIVATE;
}
void AeroGlassFrame::OnMove(const CPoint& point) {
browser_view_->WindowMoved();
}
void AeroGlassFrame::OnMoving(UINT param, const RECT* new_bounds) {
browser_view_->WindowMoved();
}
LRESULT AeroGlassFrame::OnNCActivate(BOOL active) {
if (browser_view_->ActivateAppModalDialog())
return TRUE;
if (!frame_initialized_) {
::SetWindowPos(GetHWND(), NULL, 0, 0, 0, 0,
SWP_NOSIZE | SWP_NOMOVE | SWP_FRAMECHANGED);
UpdateDWMFrame();
frame_initialized_ = true;
}
browser_view_->ActivationChanged(!!active);
return TRUE;
}
LRESULT AeroGlassFrame::OnNCCalcSize(BOOL mode, LPARAM l_param) {
// By default the client side is set to the window size which is what
// we want.
if (browser_view_->IsToolbarVisible() && mode == TRUE) {
// To be on the safe side and avoid side-effects, we only adjust the client
// size to non-standard values when we must - i.e. when we're showing a
// TabStrip.
if (browser_view_->IsTabStripVisible()) {
// Calculate new NCCALCSIZE_PARAMS based on custom NCA inset.
NCCALCSIZE_PARAMS* params = reinterpret_cast<NCCALCSIZE_PARAMS*>(l_param);
// Hack necessary to stop black background flicker, we cut out
// resizeborder here to save us from having to do too much
// addition and subtraction in Layout(). We don't cut off the
// top + titlebar as that prevents the window controls from
// highlighting.
params->rgrc[0].left += kResizeBorder;
params->rgrc[0].right -= kResizeBorder;
params->rgrc[0].bottom -= kResizeBorder;
SetMsgHandled(TRUE);
} else {
// We don't adjust the client size for detached popups, so we need to
// tell Windows we didn't handle the message here so that it doesn't
// screw up the non-client area.
SetMsgHandled(FALSE);
}
// We need to reset the frame, as Vista resets it whenever it changes
// composition modes (and NCCALCSIZE is the closest thing we get to
// a reliable message about the change).
UpdateDWMFrame();
return 0;
}
SetMsgHandled(FALSE);
return 0;
}
LRESULT AeroGlassFrame::OnNCHitTest(const CPoint& pt) {
LRESULT result;
if (DwmDefWindowProc(GetHWND(), WM_NCHITTEST, 0, MAKELPARAM(pt.x, pt.y),
&result)) {
return result;
}
return Window::OnNCHitTest(pt);
}
///////////////////////////////////////////////////////////////////////////////
// AeroGlassFrame, ChromeViews::HWNDViewContainer overrides:
bool AeroGlassFrame::AcceleratorPressed(
ChromeViews::Accelerator* accelerator) {
return browser_view_->AcceleratorPressed(*accelerator);
}
bool AeroGlassFrame::GetAccelerator(int cmd_id,
ChromeViews::Accelerator* accelerator) {
return browser_view_->GetAccelerator(cmd_id, accelerator);
}
///////////////////////////////////////////////////////////////////////////////
// AeroGlassFrame, private:
void AeroGlassFrame::UpdateDWMFrame() {
// Nothing to do yet.
if (!client_view())
return;
// TODO(beng): when TabStrip is hooked up, obtain this offset from its
// bounds.
int toolbar_y = 36;
// We only adjust the DWM's glass rendering when we're a browser window or a
// detached popup. App windows get the standard client edge.
if (browser_view_->IsTabStripVisible() ||
browser_view_->IsToolbarVisible()) {
// By default, we just want to adjust the glass by the width of the inner
// bevel that aero renders to demarcate the client area. We supply our own
// client edge for the browser window and detached popups, so we don't want
// to show the default one.
int client_edge_left_width = kWindowsDWMBevelSize;
int client_edge_right_width = kWindowsDWMBevelSize;
int client_edge_bottom_height = kWindowsDWMBevelSize;
int client_edge_top_height = kWindowsDWMBevelSize;
if (browser_view_->IsTabStripVisible()) {
client_edge_top_height =
client_view()->GetY() + kToolbarOverlapVertOffset + toolbar_y;
}
// Now poke the DWM.
MARGINS margins = { client_edge_left_width, client_edge_right_width,
client_edge_top_height, client_edge_bottom_height };
// Note: we don't use DwmEnableBlurBehindWindow because any region not
// included in the glass region is composited source over. This means
// that anything drawn directly with GDI appears fully transparent.
DwmExtendFrameIntoClientArea(GetHWND(), &margins);
}
}
AeroGlassNonClientView* AeroGlassFrame::GetAeroGlassNonClientView() const {
// We can safely assume that this conversion is true.
return static_cast<AeroGlassNonClientView*>(non_client_view_);
}
<commit_msg>Fix the include order in aero_glass_frame.cc. This was causing issues with WPO enabled. Review URL: http://codereview.chromium.org/430<commit_after>// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/views/frame/aero_glass_frame.h"
#include <dwmapi.h>
#include "chrome/app/theme/theme_resources.h"
#include "chrome/browser/frame_util.h"
#include "chrome/browser/views/frame/browser_view2.h"
#include "chrome/browser/views/frame/aero_glass_non_client_view.h"
#include "chrome/common/resource_bundle.h"
#include "chrome/views/window_delegate.h"
// static
// The width of the sizing borders.
static const int kResizeBorder = 8;
// By how much the toolbar overlaps with the tab strip.
static const int kToolbarOverlapVertOffset = 5;
// This is the width of the default client edge provided by Windows. In some
// circumstances we provide our own client edge, so we use this width to
// remove it.
static const int kWindowsDWMBevelSize = 2;
///////////////////////////////////////////////////////////////////////////////
// AeroGlassFrame, public:
AeroGlassFrame::AeroGlassFrame(BrowserView2* browser_view)
: Window(browser_view),
browser_view_(browser_view),
frame_initialized_(false) {
non_client_view_ = new AeroGlassNonClientView(this, browser_view);
browser_view_->set_frame(this);
}
AeroGlassFrame::~AeroGlassFrame() {
}
void AeroGlassFrame::Init(const gfx::Rect& bounds) {
Window::Init(NULL, bounds);
}
int AeroGlassFrame::GetMinimizeButtonOffset() const {
TITLEBARINFOEX titlebar_info;
titlebar_info.cbSize = sizeof(TITLEBARINFOEX);
SendMessage(GetHWND(), WM_GETTITLEBARINFOEX, 0, (WPARAM)&titlebar_info);
RECT wr;
GetWindowRect(&wr);
return wr.right - titlebar_info.rgrect[2].left;
}
///////////////////////////////////////////////////////////////////////////////
// AeroGlassFrame, BrowserFrame implementation:
gfx::Rect AeroGlassFrame::GetWindowBoundsForClientBounds(
const gfx::Rect& client_bounds) {
RECT rect = client_bounds.ToRECT();
AdjustWindowRectEx(&rect, window_style(), FALSE, window_ex_style());
return gfx::Rect(rect);
}
void AeroGlassFrame::SizeToContents(const gfx::Rect& contents_bounds) {
// TODO(beng): implement me.
}
gfx::Rect AeroGlassFrame::GetBoundsForTabStrip(TabStrip* tabstrip) const {
return GetAeroGlassNonClientView()->GetBoundsForTabStrip(tabstrip);
}
ChromeViews::Window* AeroGlassFrame::GetWindow() {
return this;
}
///////////////////////////////////////////////////////////////////////////////
// AeroGlassFrame, ChromeViews::Window overrides:
void AeroGlassFrame::UpdateWindowIcon() {
Window::UpdateWindowIcon();
// TODO(beng): do something in the non-client view when this builds on Vista.
}
///////////////////////////////////////////////////////////////////////////////
// AeroGlassFrame, ChromeViews::HWNDViewContainer implementation:
void AeroGlassFrame::OnInitMenuPopup(HMENU menu, UINT position,
BOOL is_system_menu) {
browser_view_->PrepareToRunSystemMenu(menu);
}
void AeroGlassFrame::OnEndSession(BOOL ending, UINT logoff) {
FrameUtil::EndSession();
}
void AeroGlassFrame::OnExitMenuLoop(bool is_track_popup_menu) {
browser_view_->SystemMenuEnded();
}
LRESULT AeroGlassFrame::OnMouseActivate(HWND window, UINT hittest_code,
UINT message) {
return browser_view_->ActivateAppModalDialog() ? MA_NOACTIVATEANDEAT
: MA_ACTIVATE;
}
void AeroGlassFrame::OnMove(const CPoint& point) {
browser_view_->WindowMoved();
}
void AeroGlassFrame::OnMoving(UINT param, const RECT* new_bounds) {
browser_view_->WindowMoved();
}
LRESULT AeroGlassFrame::OnNCActivate(BOOL active) {
if (browser_view_->ActivateAppModalDialog())
return TRUE;
if (!frame_initialized_) {
::SetWindowPos(GetHWND(), NULL, 0, 0, 0, 0,
SWP_NOSIZE | SWP_NOMOVE | SWP_FRAMECHANGED);
UpdateDWMFrame();
frame_initialized_ = true;
}
browser_view_->ActivationChanged(!!active);
return TRUE;
}
LRESULT AeroGlassFrame::OnNCCalcSize(BOOL mode, LPARAM l_param) {
// By default the client side is set to the window size which is what
// we want.
if (browser_view_->IsToolbarVisible() && mode == TRUE) {
// To be on the safe side and avoid side-effects, we only adjust the client
// size to non-standard values when we must - i.e. when we're showing a
// TabStrip.
if (browser_view_->IsTabStripVisible()) {
// Calculate new NCCALCSIZE_PARAMS based on custom NCA inset.
NCCALCSIZE_PARAMS* params = reinterpret_cast<NCCALCSIZE_PARAMS*>(l_param);
// Hack necessary to stop black background flicker, we cut out
// resizeborder here to save us from having to do too much
// addition and subtraction in Layout(). We don't cut off the
// top + titlebar as that prevents the window controls from
// highlighting.
params->rgrc[0].left += kResizeBorder;
params->rgrc[0].right -= kResizeBorder;
params->rgrc[0].bottom -= kResizeBorder;
SetMsgHandled(TRUE);
} else {
// We don't adjust the client size for detached popups, so we need to
// tell Windows we didn't handle the message here so that it doesn't
// screw up the non-client area.
SetMsgHandled(FALSE);
}
// We need to reset the frame, as Vista resets it whenever it changes
// composition modes (and NCCALCSIZE is the closest thing we get to
// a reliable message about the change).
UpdateDWMFrame();
return 0;
}
SetMsgHandled(FALSE);
return 0;
}
LRESULT AeroGlassFrame::OnNCHitTest(const CPoint& pt) {
LRESULT result;
if (DwmDefWindowProc(GetHWND(), WM_NCHITTEST, 0, MAKELPARAM(pt.x, pt.y),
&result)) {
return result;
}
return Window::OnNCHitTest(pt);
}
///////////////////////////////////////////////////////////////////////////////
// AeroGlassFrame, ChromeViews::HWNDViewContainer overrides:
bool AeroGlassFrame::AcceleratorPressed(
ChromeViews::Accelerator* accelerator) {
return browser_view_->AcceleratorPressed(*accelerator);
}
bool AeroGlassFrame::GetAccelerator(int cmd_id,
ChromeViews::Accelerator* accelerator) {
return browser_view_->GetAccelerator(cmd_id, accelerator);
}
///////////////////////////////////////////////////////////////////////////////
// AeroGlassFrame, private:
void AeroGlassFrame::UpdateDWMFrame() {
// Nothing to do yet.
if (!client_view())
return;
// TODO(beng): when TabStrip is hooked up, obtain this offset from its
// bounds.
int toolbar_y = 36;
// We only adjust the DWM's glass rendering when we're a browser window or a
// detached popup. App windows get the standard client edge.
if (browser_view_->IsTabStripVisible() ||
browser_view_->IsToolbarVisible()) {
// By default, we just want to adjust the glass by the width of the inner
// bevel that aero renders to demarcate the client area. We supply our own
// client edge for the browser window and detached popups, so we don't want
// to show the default one.
int client_edge_left_width = kWindowsDWMBevelSize;
int client_edge_right_width = kWindowsDWMBevelSize;
int client_edge_bottom_height = kWindowsDWMBevelSize;
int client_edge_top_height = kWindowsDWMBevelSize;
if (browser_view_->IsTabStripVisible()) {
client_edge_top_height =
client_view()->GetY() + kToolbarOverlapVertOffset + toolbar_y;
}
// Now poke the DWM.
MARGINS margins = { client_edge_left_width, client_edge_right_width,
client_edge_top_height, client_edge_bottom_height };
// Note: we don't use DwmEnableBlurBehindWindow because any region not
// included in the glass region is composited source over. This means
// that anything drawn directly with GDI appears fully transparent.
DwmExtendFrameIntoClientArea(GetHWND(), &margins);
}
}
AeroGlassNonClientView* AeroGlassFrame::GetAeroGlassNonClientView() const {
// We can safely assume that this conversion is true.
return static_cast<AeroGlassNonClientView*>(non_client_view_);
}
<|endoftext|>
|
<commit_before>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/renderer/pepper_plugin_delegate_impl.h"
#include "app/surface/transport_dib.h"
#include "base/logging.h"
#include "base/scoped_ptr.h"
#include "chrome/common/render_messages.h"
#include "chrome/renderer/audio_message_filter.h"
#include "chrome/renderer/render_view.h"
#include "third_party/WebKit/WebKit/chromium/public/WebFileChooserCompletion.h"
#include "third_party/WebKit/WebKit/chromium/public/WebFileChooserParams.h"
#include "webkit/glue/plugins/pepper_plugin_instance.h"
#if defined(OS_MACOSX)
#include "chrome/common/render_messages.h"
#include "chrome/renderer/render_thread.h"
#endif
namespace {
// Implements the Image2D using a TransportDIB.
class PlatformImage2DImpl : public pepper::PluginDelegate::PlatformImage2D {
public:
// This constructor will take ownership of the dib pointer.
PlatformImage2DImpl(int width, int height, TransportDIB* dib)
: width_(width),
height_(height),
dib_(dib) {
}
virtual skia::PlatformCanvas* Map() {
return dib_->GetPlatformCanvas(width_, height_);
}
virtual intptr_t GetSharedMemoryHandle() const {
return reinterpret_cast<intptr_t>(dib_.get());
}
private:
int width_;
int height_;
scoped_ptr<TransportDIB> dib_;
DISALLOW_COPY_AND_ASSIGN(PlatformImage2DImpl);
};
class PlatformAudioImpl
: public pepper::PluginDelegate::PlatformAudio,
public AudioMessageFilter::Delegate {
public:
explicit PlatformAudioImpl(scoped_refptr<AudioMessageFilter> filter)
: client_(NULL), filter_(filter), stream_id_(0) {
DCHECK(filter_);
}
virtual ~PlatformAudioImpl() {
// Make sure we have been shut down.
DCHECK_EQ(0, stream_id_);
DCHECK(!client_);
}
// Initialize this audio context. StreamCreated() will be called when the
// stream is created.
bool Initialize(uint32_t sample_rate, uint32_t sample_count,
pepper::PluginDelegate::PlatformAudio::Client* client);
virtual bool StartPlayback() {
return filter_ && filter_->Send(
new ViewHostMsg_PlayAudioStream(0, stream_id_));
}
virtual bool StopPlayback() {
return filter_ && filter_->Send(
new ViewHostMsg_PauseAudioStream(0, stream_id_));
}
virtual void ShutDown();
private:
virtual void OnRequestPacket(uint32 bytes_in_buffer,
const base::Time& message_timestamp) {
LOG(FATAL) << "Should never get OnRequestPacket in PlatformAudioImpl";
}
virtual void OnStateChanged(const ViewMsg_AudioStreamState_Params& state) { }
virtual void OnCreated(base::SharedMemoryHandle handle, uint32 length) {
LOG(FATAL) << "Should never get OnCreated in PlatformAudioImpl";
}
virtual void OnLowLatencyCreated(base::SharedMemoryHandle handle,
base::SyncSocket::Handle socket_handle,
uint32 length);
virtual void OnVolume(double volume) { }
// The client to notify when the stream is created.
pepper::PluginDelegate::PlatformAudio::Client* client_;
// MessageFilter used to send/receive IPC.
scoped_refptr<AudioMessageFilter> filter_;
// Our ID on the MessageFilter.
int32 stream_id_;
DISALLOW_COPY_AND_ASSIGN(PlatformAudioImpl);
};
bool PlatformAudioImpl::Initialize(
uint32_t sample_rate, uint32_t sample_count,
pepper::PluginDelegate::PlatformAudio::Client* client) {
DCHECK(client);
// Make sure we don't call init more than once.
DCHECK_EQ(0, stream_id_);
client_ = client;
ViewHostMsg_Audio_CreateStream_Params params;
params.format = AudioManager::AUDIO_PCM_LINEAR;
params.channels = 2;
params.sample_rate = sample_rate;
params.bits_per_sample = 16;
params.packet_size = sample_count * params.channels *
(params.bits_per_sample >> 3);
stream_id_ = filter_->AddDelegate(this);
return filter_->Send(new ViewHostMsg_CreateAudioStream(0, stream_id_, params,
true));
}
void PlatformAudioImpl::OnLowLatencyCreated(
base::SharedMemoryHandle handle, base::SyncSocket::Handle socket_handle,
uint32 length) {
#if defined(OS_WIN)
DCHECK(handle);
DCHECK(socket_handle);
#else
DCHECK_NE(-1, handle.fd);
DCHECK_NE(-1, socket_handle);
#endif
DCHECK(length);
client_->StreamCreated(handle, length, socket_handle);
}
void PlatformAudioImpl::ShutDown() {
// Make sure we don't call shutdown more than once.
if (!stream_id_) {
return;
}
filter_->Send(new ViewHostMsg_CloseAudioStream(0, stream_id_));
filter_->RemoveDelegate(stream_id_);
stream_id_ = 0;
client_ = NULL;
}
// Implements the VideoDecoder.
class PlatformVideoDecoderImpl
: public pepper::PluginDelegate::PlatformVideoDecoder {
public:
PlatformVideoDecoderImpl()
: input_buffer_size_(0),
next_dib_id_(0),
dib_(NULL) {
memset(&flush_callback_, 0, sizeof(flush_callback_));
}
virtual bool Init(const PP_VideoDecoderConfig& decoder_config) {
decoder_config_ = decoder_config;
input_buffer_size_ = 1024 << 4;
// Allocate the transport DIB.
TransportDIB* dib = TransportDIB::Create(input_buffer_size_,
next_dib_id_++);
if (!dib)
return false;
// TODO(wjia): Create video decoder in GPU process.
return true;
}
virtual bool Decode(PP_VideoCompressedDataBuffer& input_buffer) {
// TODO(wjia): Implement me!
NOTIMPLEMENTED();
input_buffers_.push(&input_buffer);
// Copy input data to dib_ and send it to GPU video decoder.
return false;
}
virtual int32_t Flush(PP_CompletionCallback& callback) {
// TODO(wjia): Implement me!
NOTIMPLEMENTED();
// Do nothing if there is a flush pending.
if (flush_callback_.func)
return PP_ERROR_BADARGUMENT;
flush_callback_ = callback;
// Call GPU video decoder to flush.
return PP_ERROR_WOULDBLOCK;
}
virtual bool ReturnUncompressedDataBuffer(
PP_VideoUncompressedDataBuffer& buffer) {
// TODO(wjia): Implement me!
NOTIMPLEMENTED();
// Deliver the buffer to GPU video decoder.
return false;
}
void OnFlushDone() {
if (!flush_callback_.func)
return;
flush_callback_.func(flush_callback_.user_data, PP_OK);
flush_callback_.func = NULL;
}
virtual intptr_t GetSharedMemoryHandle() const {
return reinterpret_cast<intptr_t>(dib_.get());
}
private:
size_t input_buffer_size_;
int next_dib_id_;
scoped_ptr<TransportDIB> dib_;
PP_VideoDecoderConfig decoder_config_;
std::queue<PP_VideoCompressedDataBuffer*> input_buffers_;
PP_CompletionCallback flush_callback_;
DISALLOW_COPY_AND_ASSIGN(PlatformVideoDecoderImpl);
};
} // namespace
PepperPluginDelegateImpl::PepperPluginDelegateImpl(RenderView* render_view)
: render_view_(render_view) {
}
void PepperPluginDelegateImpl::ViewInitiatedPaint() {
// Notify all of our instances that we started painting. This is used for
// internal bookkeeping only, so we know that the set can not change under
// us.
for (std::set<pepper::PluginInstance*>::iterator i =
active_instances_.begin();
i != active_instances_.end(); ++i)
(*i)->ViewInitiatedPaint();
}
void PepperPluginDelegateImpl::ViewFlushedPaint() {
// Notify all instances that we painted. This will call into the plugin, and
// we it may ask to close itself as a result. This will, in turn, modify our
// set, possibly invalidating the iterator. So we iterate on a copy that
// won't change out from under us.
std::set<pepper::PluginInstance*> plugins = active_instances_;
for (std::set<pepper::PluginInstance*>::iterator i = plugins.begin();
i != plugins.end(); ++i) {
// The copy above makes sure our iterator is never invalid if some plugins
// are destroyed. But some plugin may decide to close all of its views in
// response to a paint in one of them, so we need to make sure each one is
// still "current" before using it.
//
// It's possible that a plugin was destroyed, but another one was created
// with the same address. In this case, we'll call ViewFlushedPaint on that
// new plugin. But that's OK for this particular case since we're just
// notifying all of our instances that the view flushed, and the new one is
// one of our instances.
//
// What about the case where a new one is created in a callback at a new
// address and we don't issue the callback? We're still OK since this
// callback is used for flush callbacks and we could not have possibly
// started a new paint (ViewInitiatedPaint) for the new plugin while
// processing a previous paint for an existing one.
if (active_instances_.find(*i) != active_instances_.end())
(*i)->ViewFlushedPaint();
}
}
void PepperPluginDelegateImpl::InstanceCreated(
pepper::PluginInstance* instance) {
active_instances_.insert(instance);
}
void PepperPluginDelegateImpl::InstanceDeleted(
pepper::PluginInstance* instance) {
active_instances_.erase(instance);
}
pepper::PluginDelegate::PlatformImage2D*
PepperPluginDelegateImpl::CreateImage2D(int width, int height) {
uint32 buffer_size = width * height * 4;
// Allocate the transport DIB and the PlatformCanvas pointing to it.
#if defined(OS_MACOSX)
// On the Mac, shared memory has to be created in the browser in order to
// work in the sandbox. Do this by sending a message to the browser
// requesting a TransportDIB (see also
// chrome/renderer/webplugin_delegate_proxy.cc, method
// WebPluginDelegateProxy::CreateBitmap() for similar code). Note that the
// TransportDIB is _not_ cached in the browser; this is because this memory
// gets flushed by the renderer into another TransportDIB that represents the
// page, which is then in turn flushed to the screen by the browser process.
// When |transport_dib_| goes out of scope in the dtor, all of its shared
// memory gets reclaimed.
TransportDIB::Handle dib_handle;
IPC::Message* msg = new ViewHostMsg_AllocTransportDIB(buffer_size,
false,
&dib_handle);
if (!RenderThread::current()->Send(msg))
return NULL;
if (!TransportDIB::is_valid(dib_handle))
return NULL;
TransportDIB* dib = TransportDIB::Map(dib_handle);
#else
static int next_dib_id = 0;
TransportDIB* dib = TransportDIB::Create(buffer_size, next_dib_id++);
if (!dib)
return NULL;
#endif
return new PlatformImage2DImpl(width, height, dib);
}
pepper::PluginDelegate::PlatformVideoDecoder*
PepperPluginDelegateImpl::CreateVideoDecoder(
const PP_VideoDecoderConfig& decoder_config) {
scoped_ptr<PlatformVideoDecoderImpl> decoder(new PlatformVideoDecoderImpl());
if (!decoder->Init(decoder_config))
return NULL;
return decoder.release();
}
void PepperPluginDelegateImpl::DidChangeNumberOfFindResults(int identifier,
int total,
bool final_result) {
if (total == 0) {
render_view_->ReportNoFindInPageResults(identifier);
} else {
render_view_->reportFindInPageMatchCount(identifier, total, final_result);
}
}
void PepperPluginDelegateImpl::DidChangeSelectedFindResult(int identifier,
int index) {
render_view_->reportFindInPageSelection(
identifier, index + 1, WebKit::WebRect());
}
pepper::PluginDelegate::PlatformAudio* PepperPluginDelegateImpl::CreateAudio(
uint32_t sample_rate, uint32_t sample_count,
pepper::PluginDelegate::PlatformAudio::Client* client) {
scoped_ptr<PlatformAudioImpl> audio(
new PlatformAudioImpl(render_view_->audio_message_filter()));
if (audio->Initialize(sample_rate, sample_count, client)) {
return audio.release();
} else {
return NULL;
}
}
bool PepperPluginDelegateImpl::RunFileChooser(
const WebKit::WebFileChooserParams& params,
WebKit::WebFileChooserCompletion* chooser_completion) {
return render_view_->runFileChooser(params, chooser_completion);
}
<commit_msg>Initialize member struct in Pepper plugin.<commit_after>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/renderer/pepper_plugin_delegate_impl.h"
#include "app/surface/transport_dib.h"
#include "base/logging.h"
#include "base/scoped_ptr.h"
#include "chrome/common/render_messages.h"
#include "chrome/renderer/audio_message_filter.h"
#include "chrome/renderer/render_view.h"
#include "third_party/WebKit/WebKit/chromium/public/WebFileChooserCompletion.h"
#include "third_party/WebKit/WebKit/chromium/public/WebFileChooserParams.h"
#include "webkit/glue/plugins/pepper_plugin_instance.h"
#if defined(OS_MACOSX)
#include "chrome/common/render_messages.h"
#include "chrome/renderer/render_thread.h"
#endif
namespace {
// Implements the Image2D using a TransportDIB.
class PlatformImage2DImpl : public pepper::PluginDelegate::PlatformImage2D {
public:
// This constructor will take ownership of the dib pointer.
PlatformImage2DImpl(int width, int height, TransportDIB* dib)
: width_(width),
height_(height),
dib_(dib) {
}
virtual skia::PlatformCanvas* Map() {
return dib_->GetPlatformCanvas(width_, height_);
}
virtual intptr_t GetSharedMemoryHandle() const {
return reinterpret_cast<intptr_t>(dib_.get());
}
private:
int width_;
int height_;
scoped_ptr<TransportDIB> dib_;
DISALLOW_COPY_AND_ASSIGN(PlatformImage2DImpl);
};
class PlatformAudioImpl
: public pepper::PluginDelegate::PlatformAudio,
public AudioMessageFilter::Delegate {
public:
explicit PlatformAudioImpl(scoped_refptr<AudioMessageFilter> filter)
: client_(NULL), filter_(filter), stream_id_(0) {
DCHECK(filter_);
}
virtual ~PlatformAudioImpl() {
// Make sure we have been shut down.
DCHECK_EQ(0, stream_id_);
DCHECK(!client_);
}
// Initialize this audio context. StreamCreated() will be called when the
// stream is created.
bool Initialize(uint32_t sample_rate, uint32_t sample_count,
pepper::PluginDelegate::PlatformAudio::Client* client);
virtual bool StartPlayback() {
return filter_ && filter_->Send(
new ViewHostMsg_PlayAudioStream(0, stream_id_));
}
virtual bool StopPlayback() {
return filter_ && filter_->Send(
new ViewHostMsg_PauseAudioStream(0, stream_id_));
}
virtual void ShutDown();
private:
virtual void OnRequestPacket(uint32 bytes_in_buffer,
const base::Time& message_timestamp) {
LOG(FATAL) << "Should never get OnRequestPacket in PlatformAudioImpl";
}
virtual void OnStateChanged(const ViewMsg_AudioStreamState_Params& state) { }
virtual void OnCreated(base::SharedMemoryHandle handle, uint32 length) {
LOG(FATAL) << "Should never get OnCreated in PlatformAudioImpl";
}
virtual void OnLowLatencyCreated(base::SharedMemoryHandle handle,
base::SyncSocket::Handle socket_handle,
uint32 length);
virtual void OnVolume(double volume) { }
// The client to notify when the stream is created.
pepper::PluginDelegate::PlatformAudio::Client* client_;
// MessageFilter used to send/receive IPC.
scoped_refptr<AudioMessageFilter> filter_;
// Our ID on the MessageFilter.
int32 stream_id_;
DISALLOW_COPY_AND_ASSIGN(PlatformAudioImpl);
};
bool PlatformAudioImpl::Initialize(
uint32_t sample_rate, uint32_t sample_count,
pepper::PluginDelegate::PlatformAudio::Client* client) {
DCHECK(client);
// Make sure we don't call init more than once.
DCHECK_EQ(0, stream_id_);
client_ = client;
ViewHostMsg_Audio_CreateStream_Params params;
params.format = AudioManager::AUDIO_PCM_LINEAR;
params.channels = 2;
params.sample_rate = sample_rate;
params.bits_per_sample = 16;
params.packet_size = sample_count * params.channels *
(params.bits_per_sample >> 3);
stream_id_ = filter_->AddDelegate(this);
return filter_->Send(new ViewHostMsg_CreateAudioStream(0, stream_id_, params,
true));
}
void PlatformAudioImpl::OnLowLatencyCreated(
base::SharedMemoryHandle handle, base::SyncSocket::Handle socket_handle,
uint32 length) {
#if defined(OS_WIN)
DCHECK(handle);
DCHECK(socket_handle);
#else
DCHECK_NE(-1, handle.fd);
DCHECK_NE(-1, socket_handle);
#endif
DCHECK(length);
client_->StreamCreated(handle, length, socket_handle);
}
void PlatformAudioImpl::ShutDown() {
// Make sure we don't call shutdown more than once.
if (!stream_id_) {
return;
}
filter_->Send(new ViewHostMsg_CloseAudioStream(0, stream_id_));
filter_->RemoveDelegate(stream_id_);
stream_id_ = 0;
client_ = NULL;
}
// Implements the VideoDecoder.
class PlatformVideoDecoderImpl
: public pepper::PluginDelegate::PlatformVideoDecoder {
public:
PlatformVideoDecoderImpl()
: input_buffer_size_(0),
next_dib_id_(0),
dib_(NULL) {
memset(&decoder_config_, 0, sizeof(decoder_config_));
memset(&flush_callback_, 0, sizeof(flush_callback_));
}
virtual bool Init(const PP_VideoDecoderConfig& decoder_config) {
decoder_config_ = decoder_config;
input_buffer_size_ = 1024 << 4;
// Allocate the transport DIB.
TransportDIB* dib = TransportDIB::Create(input_buffer_size_,
next_dib_id_++);
if (!dib)
return false;
// TODO(wjia): Create video decoder in GPU process.
return true;
}
virtual bool Decode(PP_VideoCompressedDataBuffer& input_buffer) {
// TODO(wjia): Implement me!
NOTIMPLEMENTED();
input_buffers_.push(&input_buffer);
// Copy input data to dib_ and send it to GPU video decoder.
return false;
}
virtual int32_t Flush(PP_CompletionCallback& callback) {
// TODO(wjia): Implement me!
NOTIMPLEMENTED();
// Do nothing if there is a flush pending.
if (flush_callback_.func)
return PP_ERROR_BADARGUMENT;
flush_callback_ = callback;
// Call GPU video decoder to flush.
return PP_ERROR_WOULDBLOCK;
}
virtual bool ReturnUncompressedDataBuffer(
PP_VideoUncompressedDataBuffer& buffer) {
// TODO(wjia): Implement me!
NOTIMPLEMENTED();
// Deliver the buffer to GPU video decoder.
return false;
}
void OnFlushDone() {
if (!flush_callback_.func)
return;
flush_callback_.func(flush_callback_.user_data, PP_OK);
flush_callback_.func = NULL;
}
virtual intptr_t GetSharedMemoryHandle() const {
return reinterpret_cast<intptr_t>(dib_.get());
}
private:
size_t input_buffer_size_;
int next_dib_id_;
scoped_ptr<TransportDIB> dib_;
PP_VideoDecoderConfig decoder_config_;
std::queue<PP_VideoCompressedDataBuffer*> input_buffers_;
PP_CompletionCallback flush_callback_;
DISALLOW_COPY_AND_ASSIGN(PlatformVideoDecoderImpl);
};
} // namespace
PepperPluginDelegateImpl::PepperPluginDelegateImpl(RenderView* render_view)
: render_view_(render_view) {
}
void PepperPluginDelegateImpl::ViewInitiatedPaint() {
// Notify all of our instances that we started painting. This is used for
// internal bookkeeping only, so we know that the set can not change under
// us.
for (std::set<pepper::PluginInstance*>::iterator i =
active_instances_.begin();
i != active_instances_.end(); ++i)
(*i)->ViewInitiatedPaint();
}
void PepperPluginDelegateImpl::ViewFlushedPaint() {
// Notify all instances that we painted. This will call into the plugin, and
// we it may ask to close itself as a result. This will, in turn, modify our
// set, possibly invalidating the iterator. So we iterate on a copy that
// won't change out from under us.
std::set<pepper::PluginInstance*> plugins = active_instances_;
for (std::set<pepper::PluginInstance*>::iterator i = plugins.begin();
i != plugins.end(); ++i) {
// The copy above makes sure our iterator is never invalid if some plugins
// are destroyed. But some plugin may decide to close all of its views in
// response to a paint in one of them, so we need to make sure each one is
// still "current" before using it.
//
// It's possible that a plugin was destroyed, but another one was created
// with the same address. In this case, we'll call ViewFlushedPaint on that
// new plugin. But that's OK for this particular case since we're just
// notifying all of our instances that the view flushed, and the new one is
// one of our instances.
//
// What about the case where a new one is created in a callback at a new
// address and we don't issue the callback? We're still OK since this
// callback is used for flush callbacks and we could not have possibly
// started a new paint (ViewInitiatedPaint) for the new plugin while
// processing a previous paint for an existing one.
if (active_instances_.find(*i) != active_instances_.end())
(*i)->ViewFlushedPaint();
}
}
void PepperPluginDelegateImpl::InstanceCreated(
pepper::PluginInstance* instance) {
active_instances_.insert(instance);
}
void PepperPluginDelegateImpl::InstanceDeleted(
pepper::PluginInstance* instance) {
active_instances_.erase(instance);
}
pepper::PluginDelegate::PlatformImage2D*
PepperPluginDelegateImpl::CreateImage2D(int width, int height) {
uint32 buffer_size = width * height * 4;
// Allocate the transport DIB and the PlatformCanvas pointing to it.
#if defined(OS_MACOSX)
// On the Mac, shared memory has to be created in the browser in order to
// work in the sandbox. Do this by sending a message to the browser
// requesting a TransportDIB (see also
// chrome/renderer/webplugin_delegate_proxy.cc, method
// WebPluginDelegateProxy::CreateBitmap() for similar code). Note that the
// TransportDIB is _not_ cached in the browser; this is because this memory
// gets flushed by the renderer into another TransportDIB that represents the
// page, which is then in turn flushed to the screen by the browser process.
// When |transport_dib_| goes out of scope in the dtor, all of its shared
// memory gets reclaimed.
TransportDIB::Handle dib_handle;
IPC::Message* msg = new ViewHostMsg_AllocTransportDIB(buffer_size,
false,
&dib_handle);
if (!RenderThread::current()->Send(msg))
return NULL;
if (!TransportDIB::is_valid(dib_handle))
return NULL;
TransportDIB* dib = TransportDIB::Map(dib_handle);
#else
static int next_dib_id = 0;
TransportDIB* dib = TransportDIB::Create(buffer_size, next_dib_id++);
if (!dib)
return NULL;
#endif
return new PlatformImage2DImpl(width, height, dib);
}
pepper::PluginDelegate::PlatformVideoDecoder*
PepperPluginDelegateImpl::CreateVideoDecoder(
const PP_VideoDecoderConfig& decoder_config) {
scoped_ptr<PlatformVideoDecoderImpl> decoder(new PlatformVideoDecoderImpl());
if (!decoder->Init(decoder_config))
return NULL;
return decoder.release();
}
void PepperPluginDelegateImpl::DidChangeNumberOfFindResults(int identifier,
int total,
bool final_result) {
if (total == 0) {
render_view_->ReportNoFindInPageResults(identifier);
} else {
render_view_->reportFindInPageMatchCount(identifier, total, final_result);
}
}
void PepperPluginDelegateImpl::DidChangeSelectedFindResult(int identifier,
int index) {
render_view_->reportFindInPageSelection(
identifier, index + 1, WebKit::WebRect());
}
pepper::PluginDelegate::PlatformAudio* PepperPluginDelegateImpl::CreateAudio(
uint32_t sample_rate, uint32_t sample_count,
pepper::PluginDelegate::PlatformAudio::Client* client) {
scoped_ptr<PlatformAudioImpl> audio(
new PlatformAudioImpl(render_view_->audio_message_filter()));
if (audio->Initialize(sample_rate, sample_count, client)) {
return audio.release();
} else {
return NULL;
}
}
bool PepperPluginDelegateImpl::RunFileChooser(
const WebKit::WebFileChooserParams& params,
WebKit::WebFileChooserCompletion* chooser_completion) {
return render_view_->runFileChooser(params, chooser_completion);
}
<|endoftext|>
|
<commit_before>/**
* The handler always needs to know what the previous node/way/relation
* in the file looked like to answer questions like "what is the
* valid_from date of the current entity" or "is this the last version
* of that entity". The EntityTracker takes care of keeping the
* current and the previous entity, free them as required and do basic
* comparations.
*/
#ifndef IMPORTER_ENTITYTRACKER_HPP
#define IMPORTER_ENTITYTRACKER_HPP
/**
* Tracks a previous and a current entity, provides a method to make the
* current entity the previous one and manages freeing of the entities.
* It is templated to allow nodes, ways and relations as child objects.
*/
template <class TObject>
class EntityTracker {
private:
/**
* pointer to the previous entity
*/
shared_ptr<TObject const> m_prev;
/**
* pointer to the current entity
*/
shared_ptr<TObject const> m_cur;
public:
/**
* get the pointer to the previous entity
*/
const shared_ptr<TObject const> prev() {
return m_prev;
}
/**
* get the pointer to the current entity
*/
const shared_ptr<TObject const> cur() {
return m_cur;
}
/**
* returns if the tracker currently tracks a previous entity
*/
bool has_prev() {
return m_prev;
}
/**
* returns if the tracker currently tracks a current entity
*/
bool has_cur() {
return m_cur;
}
/**
* returns if the tracker currently tracks a previous and a current
* entity with the same id
*/
bool cur_is_same_entity() {
return has_prev() && has_cur() && (prev()->id() == cur()->id());
}
/**
* feed in a new object as the current one
*
* if a current one still exists, the program will abort with an
* assertation error, because the current enity needs to be swapped
* away using the swap-method below, before feeding in a new one.
*/
void feed(const shared_ptr<TObject const> obj) {
assert(!m_cur);
m_cur = obj;
}
/**
* make the current entity the previous and delete the previous entity
*/
void swap() {
m_prev = m_cur;
m_cur.reset();
}
};
#endif // IMPORTER_ENTITYTRACKER_HPP
<commit_msg>explain upcoming changes<commit_after>/**
* The handler always needs to know what the next node/way/relation
* in the file lookes like to answer questions like "what is the
* valid_to date of the current entity" or "is this the last version
* of that entity". It also sometimes needs to know hot the previous
* entity looks like to answer questions like "was this an area or a line
* before it got deleted". The EntityTracker takes care of keeping the
* previous, current and next entity, frees them as required and does
* basic comparations.
*/
#ifndef IMPORTER_ENTITYTRACKER_HPP
#define IMPORTER_ENTITYTRACKER_HPP
/**
* Tracks the previous, the current and the next entity, provides
* a method to shift the entities into the next state and manages
* freeing of the entities. It is templated to allow nodes, ways
* and relations as child objects.
*/
template <class TObject>
class EntityTracker {
private:
/**
* pointer to the previous entity
*/
shared_ptr<TObject const> m_prev;
/**
* pointer to the current entity
*/
shared_ptr<TObject const> m_cur;
public:
/**
* get the pointer to the previous entity
*/
const shared_ptr<TObject const> prev() {
return m_prev;
}
/**
* get the pointer to the current entity
*/
const shared_ptr<TObject const> cur() {
return m_cur;
}
/**
* returns if the tracker currently tracks a previous entity
*/
bool has_prev() {
return m_prev;
}
/**
* returns if the tracker currently tracks a current entity
*/
bool has_cur() {
return m_cur;
}
/**
* returns if the tracker currently tracks a previous and a current
* entity with the same id
*/
bool cur_is_same_entity() {
return has_prev() && has_cur() && (prev()->id() == cur()->id());
}
/**
* feed in a new object as the current one
*
* if a current one still exists, the program will abort with an
* assertation error, because the current enity needs to be swapped
* away using the swap-method below, before feeding in a new one.
*/
void feed(const shared_ptr<TObject const> obj) {
assert(!m_cur);
m_cur = obj;
}
/**
* make the current entity the previous and delete the previous entity
*/
void swap() {
m_prev = m_cur;
m_cur.reset();
}
};
#endif // IMPORTER_ENTITYTRACKER_HPP
<|endoftext|>
|
<commit_before>#include "PanelComponents.h"
#include "Application.h"
#include "ModuleWindow.h"
#include "GameObject.h"
#include "ComponentTransformation.h"
#include "ComponentMesh.h"
#include "ComponentMaterial.h"
#include "ComponentCamera.h"
#include "ModuleCamera3D.h"
#include "ModuleRenderer3D.h"
#include "ModuleGOManager.h"
#include "Mesh.h"
#include "ImGui/imgui.h"
PanelComponents::PanelComponents() : Panel("Components")
{
active = false;
set_size = true;
last_go = nullptr;
}
PanelComponents::~PanelComponents()
{
}
void PanelComponents::Draw(GameObject* selected_go)
{
if (selected_go != nullptr)
{
ImGui::SetNextWindowPos(ImVec2(((App->window->GetWindowSize().x - 335)), 25));
if (set_size == true)
{
ImGui::SetNextWindowSize(ImVec2(330, 610));
set_size = false;
}
ImGui::Begin("Components", &active);
ImGui::TextColored(ImVec4(0.90f, 0.90f, 0.00f, 1.00f), "GameObject: ");
ImGui::SameLine();
ImGui::Text(selected_go->GetName());
if (ImGui::BeginMenu("Add component"))
{
if (ImGui::MenuItem("Camera"))
{
selected_go->CreateComponent(Component::Type::Camera);
}
ImGui::EndMenu();
}
if (ImGui::Button("Center view"))
{
App->camera->LookAt(selected_go->transform->GetPosition());
}
if (ImGui::Checkbox("Static test", &selected_go->static_go))
{
if (selected_go->children.size() != 0)
{
static_ask = selected_go->static_go;
}
}
if (static_ask)
{
ImGuiWindowFlags window_flags = (ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_ShowBorders);
ImGui::SetNextWindowPos(ImVec2((App->window->GetWindowSize().x / 2) - 190, (App->window->GetWindowSize().y / 2) - 50));
ImGui::Begin("Hierarchy problem", nullptr, window_flags);
ImGui::Text("Convert all %s children to static?", selected_go->GetName());
ImVec2 size = ImVec2(80.0f, 20.0f);
ImGui::PushStyleColor(ImGuiCol_Button, ImVec4(0.0f, 0.5f, 0.0f, 0.75f));
ImGui::PushStyleColor(ImGuiCol_ButtonHovered, ImVec4(0.0f, 0.75f, 0.0f, 0.75f));
ImGui::PushStyleColor(ImGuiCol_ButtonActive, ImVec4(0.0f, 0.75f, 0.0f, 1.0f));
if (ImGui::Button("Yes", size))
{
selected_go->static_children = true;
static_ask = false;
}
ImGui::PopStyleColor(3);
ImGui::SameLine(0.0f, 100.0f);
ImGui::PushStyleColor(ImGuiCol_Button, ImVec4(0.5f, 0.0f, 0.0f, 0.75f));
ImGui::PushStyleColor(ImGuiCol_ButtonHovered, ImVec4(0.75f, 0.0f, 0.0f, 0.75f));
ImGui::PushStyleColor(ImGuiCol_ButtonActive, ImVec4(0.75f, 0.0f, 0.0f, 1.0f));
if (ImGui::Button("No", size))
{
selected_go->static_children = false;
static_ask = false;
}
ImGui::PopStyleColor(3);
ImGui::End();
}
//If actual game object is diferent of last one it must to set transformation
if (last_go != selected_go || selected_go->static_go == true)
{
pos.Set(selected_go->transform->GetPosition().x, selected_go->transform->GetPosition().y, selected_go->transform->GetPosition().z);
sca.Set(selected_go->transform->GetScale().x, selected_go->transform->GetScale().y, selected_go->transform->GetScale().z);
rot.Set(selected_go->transform->GetRotation().x, selected_go->transform->GetRotation().y, selected_go->transform->GetRotation().z);
}
DrawTransformation(selected_go->transform, selected_go);
for (std::vector<Component*>::iterator tmp = selected_go->components.begin(); tmp != selected_go->components.end(); tmp++)
{
if ((*tmp)->GetType() == Component::Type::Geometry)
{
if (last_go == selected_go)
{
((ComponentMesh*)(*tmp))->wirefr = true;
}
else
{
if (last_go != nullptr)
{
if (last_go->GetComponentByType(Component::Type::Geometry) != nullptr)
{
((ComponentMesh*)last_go->GetComponentByType(Component::Type::Geometry))->wirefr = false;
}
}
}
DrawMesh(((ComponentMesh*)(*tmp)), selected_go);
}
if ((*tmp)->GetType() == Component::Type::Material)
{
DrawMaterial(((ComponentMaterial*)(*tmp)), selected_go);
}
if ((*tmp)->GetType() == Component::Type::Camera)
{
DrawCamera(((ComponentCamera*)(*tmp)), selected_go);
}
}
last_go = selected_go;
ImGui::End();
}
else
{
if (last_go != nullptr)
{
if (last_go->GetComponentByType(Component::Type::Geometry) != nullptr)
{
((ComponentMesh*)last_go->GetComponentByType(Component::Type::Geometry))->wirefr = false;
}
}
}
}
void PanelComponents::DrawTransformation(ComponentTransformation* go_transform, GameObject* go_selected)
{
if (ImGui::CollapsingHeader(go_transform->name.c_str()))
{
ImGui::TextColored(ImVec4(1.0f, 0.5, 0.0f, 1.0f), "Component ID: ");
ImGui::SameLine();
ImGui::Text("%d", go_transform->GetID());
ImGui::Separator();
if (ImGui::DragFloat3("Postion", pos.ptr()))
{
go_transform->SetPos(pos.x, pos.y, pos.z);
}
if (ImGui::DragFloat3("Scale", sca.ptr(), 0.01f))
{
go_transform->SetScale(sca.x, sca.y, sca.z);
}
if (ImGui::DragFloat3("Rotation", rot.ptr()))
{
go_transform->SetRotEuler(rot.x, rot.y, rot.z);
}
}
}
void PanelComponents::DrawMesh(ComponentMesh* go_mesh, GameObject* go_selected)
{
if (ImGui::CollapsingHeader(go_mesh->name.c_str()))
{
ImGui::TextColored(ImVec4(1.0f, 0.5, 0.0f, 1.0f), "Component ID: ");
ImGui::SameLine();
ImGui::Text("%d", (go_mesh->GetID()));
ImGui::Separator();
ImGui::SameLine(ImGui::GetWindowWidth() - 105);
ImGui::Text("Active:");
ImGui::SameLine(ImGui::GetWindowWidth() - 50);
ImGui::Checkbox(go_mesh->is_active.c_str(), &go_mesh->active);
ImGui::Checkbox(go_mesh->wire.c_str(), &go_mesh->wirefr);
ImGui::Checkbox("AABB", &go_selected->aabb_debug);
ImGui::Checkbox("OBB", &go_selected->obb_debug);
ImGui::Separator();
ImGui::Text("Number of vertex(Indices): %d", go_mesh->GetMesh()->num_indices);
ImGui::Text("Number of vertex in memory: %d", go_mesh->GetMesh()->num_vertices);
ImGui::Text("Number of normals: %d", go_mesh->GetMesh()->num_normals);
ImGui::Text("Number of texture coordinates: %d", go_mesh->GetMesh()->num_tex_coord);
}
}
void PanelComponents::DrawMaterial(ComponentMaterial* go_material, GameObject* go_selected)
{
if (ImGui::CollapsingHeader(go_material->name.c_str()))
{
ImGui::TextColored(ImVec4(1.0f, 0.5, 0.0f, 1.0f), "Component ID: ");
ImGui::SameLine();
ImGui::Text("%d", go_material->GetID());
ImGui::Separator();
ImGui::Image((ImTextureID*)go_material->GetTexture(), ImVec2(200, 200), ImVec2(0, 0), ImVec2(1, 1), ImVec4(1, 1, 1, 1), ImVec4(0.0f, 0.6f, 0.6f, 1.0f));
ImGui::Text("%s%s", "Texture path: ", go_material->tex_path.c_str());
}
}
void PanelComponents::DrawCamera(ComponentCamera* go_camera, GameObject* go_selected)
{
if (ImGui::CollapsingHeader(go_camera->name.c_str()))
{
near_plane = go_camera->GetNearPlane();
far_plane = go_camera->GetFarPlane();
field_of_view = go_camera->GetFOV();
aspect_ratio = go_camera->GetAspectRatio();
ImGui::TextColored(ImVec4(1.0f, 0.5, 0.0f, 1.0f), "Component ID: ");
ImGui::SameLine();
ImGui::Text("%d", go_camera->GetID());
ImGui::Separator();
ImGui::Checkbox("Camera frustrum", &go_camera->debug_draw);
if (ImGui::Checkbox("Camera culling", &go_camera->frustum_culling))
{
App->go_manager->AddCameraCulling(go_camera, go_camera->frustum_culling);
}
if (ImGui::Checkbox("Use camera", &render_camera))
{
App->renderer3D->camera = go_camera;
App->renderer3D->update_proj_matrix = true;
App->camera->controls_disabled = true;
}
if (render_camera == false)
{
App->renderer3D->camera = App->camera->GetCamera();
App->camera->controls_disabled = false;
App->renderer3D->update_proj_matrix = true;
}
if (ImGui::DragFloat("Near plane", &near_plane, 0.1f))
{
go_camera->SetNearPlane(near_plane);
if (render_camera)
{
App->renderer3D->update_proj_matrix = true;
}
}
if (ImGui::DragFloat("Far plane", &far_plane, 0.1f))
{
go_camera->SetFarPlane(far_plane);
if (render_camera)
{
App->renderer3D->update_proj_matrix = true;
}
}
if (ImGui::DragFloat("Field of view", &field_of_view, 0.1f))
{
go_camera->SetFOV(field_of_view);
if (render_camera)
{
App->renderer3D->update_proj_matrix = true;
}
}
if (ImGui::DragFloat("Aspect ratio", &aspect_ratio, 0.01f))
{
go_camera->SetAspectRatio(aspect_ratio);
if (render_camera)
{
App->renderer3D->update_proj_matrix = true;
}
}
}
}<commit_msg>Little material color indicator on panel components, material.<commit_after>#include "PanelComponents.h"
#include "Application.h"
#include "ModuleWindow.h"
#include "GameObject.h"
#include "ComponentTransformation.h"
#include "ComponentMesh.h"
#include "ComponentMaterial.h"
#include "ComponentCamera.h"
#include "ModuleCamera3D.h"
#include "ModuleRenderer3D.h"
#include "ModuleGOManager.h"
#include "Mesh.h"
#include "ImGui/imgui.h"
PanelComponents::PanelComponents() : Panel("Components")
{
active = false;
set_size = true;
last_go = nullptr;
}
PanelComponents::~PanelComponents()
{
}
void PanelComponents::Draw(GameObject* selected_go)
{
if (selected_go != nullptr)
{
ImGui::SetNextWindowPos(ImVec2(((App->window->GetWindowSize().x - 335)), 25));
if (set_size == true)
{
ImGui::SetNextWindowSize(ImVec2(330, 610));
set_size = false;
}
ImGui::Begin("Components", &active);
ImGui::TextColored(ImVec4(0.90f, 0.90f, 0.00f, 1.00f), "GameObject: ");
ImGui::SameLine();
ImGui::Text(selected_go->GetName());
if (ImGui::BeginMenu("Add component"))
{
if (ImGui::MenuItem("Camera"))
{
selected_go->CreateComponent(Component::Type::Camera);
}
ImGui::EndMenu();
}
if (ImGui::Button("Center view"))
{
App->camera->LookAt(selected_go->transform->GetPosition());
}
if (ImGui::Checkbox("Static test", &selected_go->static_go))
{
if (selected_go->children.size() != 0)
{
static_ask = selected_go->static_go;
}
}
if (static_ask)
{
ImGuiWindowFlags window_flags = (ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_ShowBorders);
ImGui::SetNextWindowPos(ImVec2((App->window->GetWindowSize().x / 2) - 190, (App->window->GetWindowSize().y / 2) - 50));
ImGui::Begin("Hierarchy problem", nullptr, window_flags);
ImGui::Text("Convert all %s children to static?", selected_go->GetName());
ImVec2 size = ImVec2(80.0f, 20.0f);
ImGui::PushStyleColor(ImGuiCol_Button, ImVec4(0.0f, 0.5f, 0.0f, 0.75f));
ImGui::PushStyleColor(ImGuiCol_ButtonHovered, ImVec4(0.0f, 0.75f, 0.0f, 0.75f));
ImGui::PushStyleColor(ImGuiCol_ButtonActive, ImVec4(0.0f, 0.75f, 0.0f, 1.0f));
if (ImGui::Button("Yes", size))
{
selected_go->static_children = true;
static_ask = false;
}
ImGui::PopStyleColor(3);
ImGui::SameLine(0.0f, 100.0f);
ImGui::PushStyleColor(ImGuiCol_Button, ImVec4(0.5f, 0.0f, 0.0f, 0.75f));
ImGui::PushStyleColor(ImGuiCol_ButtonHovered, ImVec4(0.75f, 0.0f, 0.0f, 0.75f));
ImGui::PushStyleColor(ImGuiCol_ButtonActive, ImVec4(0.75f, 0.0f, 0.0f, 1.0f));
if (ImGui::Button("No", size))
{
selected_go->static_children = false;
static_ask = false;
}
ImGui::PopStyleColor(3);
ImGui::End();
}
//If actual game object is diferent of last one it must to set transformation
if (last_go != selected_go || selected_go->static_go == true)
{
pos.Set(selected_go->transform->GetPosition().x, selected_go->transform->GetPosition().y, selected_go->transform->GetPosition().z);
sca.Set(selected_go->transform->GetScale().x, selected_go->transform->GetScale().y, selected_go->transform->GetScale().z);
rot.Set(selected_go->transform->GetRotation().x, selected_go->transform->GetRotation().y, selected_go->transform->GetRotation().z);
}
DrawTransformation(selected_go->transform, selected_go);
for (std::vector<Component*>::iterator tmp = selected_go->components.begin(); tmp != selected_go->components.end(); tmp++)
{
if ((*tmp)->GetType() == Component::Type::Geometry)
{
if (last_go == selected_go)
{
((ComponentMesh*)(*tmp))->wirefr = true;
}
else
{
if (last_go != nullptr)
{
if (last_go->GetComponentByType(Component::Type::Geometry) != nullptr)
{
((ComponentMesh*)last_go->GetComponentByType(Component::Type::Geometry))->wirefr = false;
}
}
}
DrawMesh(((ComponentMesh*)(*tmp)), selected_go);
}
if ((*tmp)->GetType() == Component::Type::Material)
{
DrawMaterial(((ComponentMaterial*)(*tmp)), selected_go);
}
if ((*tmp)->GetType() == Component::Type::Camera)
{
DrawCamera(((ComponentCamera*)(*tmp)), selected_go);
}
}
last_go = selected_go;
ImGui::End();
}
else
{
if (last_go != nullptr)
{
if (last_go->GetComponentByType(Component::Type::Geometry) != nullptr)
{
((ComponentMesh*)last_go->GetComponentByType(Component::Type::Geometry))->wirefr = false;
}
}
}
}
void PanelComponents::DrawTransformation(ComponentTransformation* go_transform, GameObject* go_selected)
{
if (ImGui::CollapsingHeader(go_transform->name.c_str()))
{
ImGui::TextColored(ImVec4(1.0f, 0.5, 0.0f, 1.0f), "Component ID: ");
ImGui::SameLine();
ImGui::Text("%d", go_transform->GetID());
ImGui::Separator();
if (ImGui::DragFloat3("Postion", pos.ptr()))
{
go_transform->SetPos(pos.x, pos.y, pos.z);
}
if (ImGui::DragFloat3("Scale", sca.ptr(), 0.01f))
{
go_transform->SetScale(sca.x, sca.y, sca.z);
}
if (ImGui::DragFloat3("Rotation", rot.ptr()))
{
go_transform->SetRotEuler(rot.x, rot.y, rot.z);
}
}
}
void PanelComponents::DrawMesh(ComponentMesh* go_mesh, GameObject* go_selected)
{
if (ImGui::CollapsingHeader(go_mesh->name.c_str()))
{
ImGui::TextColored(ImVec4(1.0f, 0.5, 0.0f, 1.0f), "Component ID: ");
ImGui::SameLine();
ImGui::Text("%d", (go_mesh->GetID()));
ImGui::Separator();
ImGui::SameLine(ImGui::GetWindowWidth() - 105);
ImGui::Text("Active:");
ImGui::SameLine(ImGui::GetWindowWidth() - 50);
ImGui::Checkbox(go_mesh->is_active.c_str(), &go_mesh->active);
ImGui::Checkbox(go_mesh->wire.c_str(), &go_mesh->wirefr);
ImGui::Checkbox("AABB", &go_selected->aabb_debug);
ImGui::Checkbox("OBB", &go_selected->obb_debug);
ImGui::Separator();
ImGui::Text("Number of vertex(Indices): %d", go_mesh->GetMesh()->num_indices);
ImGui::Text("Number of vertex in memory: %d", go_mesh->GetMesh()->num_vertices);
ImGui::Text("Number of normals: %d", go_mesh->GetMesh()->num_normals);
ImGui::Text("Number of texture coordinates: %d", go_mesh->GetMesh()->num_tex_coord);
}
}
void PanelComponents::DrawMaterial(ComponentMaterial* go_material, GameObject* go_selected)
{
if (ImGui::CollapsingHeader(go_material->name.c_str()))
{
ImGui::TextColored(ImVec4(1.0f, 0.5, 0.0f, 1.0f), "Component ID: ");
ImGui::SameLine();
ImGui::Text("%d", go_material->GetID());
ImGui::Separator();
ImGui::Image((ImTextureID*)go_material->GetTexture(), ImVec2(200, 200), ImVec2(0, 0), ImVec2(1, 1), ImVec4(1, 1, 1, 1), ImVec4(0.0f, 0.6f, 0.6f, 1.0f));
ImGui::Text("%s%s", "Texture path: ", go_material->tex_path.c_str());
ImGui::Text("Material color:");
ImGui::SameLine(120, 0);
ImGui::ColorButton(ImVec4(go_material->GetMaterialColor().r, go_material->GetMaterialColor().g, go_material->GetMaterialColor().b, go_material->GetMaterialColor().a));
}
}
void PanelComponents::DrawCamera(ComponentCamera* go_camera, GameObject* go_selected)
{
if (ImGui::CollapsingHeader(go_camera->name.c_str()))
{
near_plane = go_camera->GetNearPlane();
far_plane = go_camera->GetFarPlane();
field_of_view = go_camera->GetFOV();
aspect_ratio = go_camera->GetAspectRatio();
ImGui::TextColored(ImVec4(1.0f, 0.5, 0.0f, 1.0f), "Component ID: ");
ImGui::SameLine();
ImGui::Text("%d", go_camera->GetID());
ImGui::Separator();
ImGui::Checkbox("Camera frustrum", &go_camera->debug_draw);
if (ImGui::Checkbox("Camera culling", &go_camera->frustum_culling))
{
App->go_manager->AddCameraCulling(go_camera, go_camera->frustum_culling);
}
if (ImGui::Checkbox("Use camera", &render_camera))
{
App->renderer3D->camera = go_camera;
App->renderer3D->update_proj_matrix = true;
App->camera->controls_disabled = true;
}
if (render_camera == false)
{
App->renderer3D->camera = App->camera->GetCamera();
App->camera->controls_disabled = false;
App->renderer3D->update_proj_matrix = true;
}
if (ImGui::DragFloat("Near plane", &near_plane, 0.1f))
{
go_camera->SetNearPlane(near_plane);
if (render_camera)
{
App->renderer3D->update_proj_matrix = true;
}
}
if (ImGui::DragFloat("Far plane", &far_plane, 0.1f))
{
go_camera->SetFarPlane(far_plane);
if (render_camera)
{
App->renderer3D->update_proj_matrix = true;
}
}
if (ImGui::DragFloat("Field of view", &field_of_view, 0.1f))
{
go_camera->SetFOV(field_of_view);
if (render_camera)
{
App->renderer3D->update_proj_matrix = true;
}
}
if (ImGui::DragFloat("Aspect ratio", &aspect_ratio, 0.01f))
{
go_camera->SetAspectRatio(aspect_ratio);
if (render_camera)
{
App->renderer3D->update_proj_matrix = true;
}
}
}
}<|endoftext|>
|
<commit_before>/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/*
* This file is part of the libvisio project.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
#include "VSDMetaData.h"
#include <cassert>
#include <cmath>
#include <cstdio>
#include <cstring>
#include <string>
#include <unicode/ucnv.h>
#include <ctime>
libvisio::VSDMetaData::VSDMetaData()
: m_idsAndOffsets(), m_typedPropertyValues(), m_metaData()
{
}
libvisio::VSDMetaData::~VSDMetaData()
{
}
enum PIDDSI
{
PIDDSI_CODEPAGE = 0x00000001,
PIDDSI_CATEGORY = 0x00000002,
PIDDSI_PRESFORMAT = 0x00000003,
PIDDSI_BYTECOUNT = 0x00000004,
PIDDSI_LINECOUNT = 0x00000005,
PIDDSI_PARACOUNT = 0x00000006,
PIDDSI_SLIDECOUNT = 0x00000007,
PIDDSI_NOTECOUNT = 0x00000008,
PIDDSI_HIDDENCOUNT = 0x00000009,
PIDDSI_MMCLIPCOUNT = 0x0000000A,
PIDDSI_SCALE = 0x0000000B,
PIDDSI_HEADINGPAIR = 0x0000000C,
PIDDSI_DOCPARTS = 0x0000000D,
PIDDSI_MANAGER = 0x0000000E,
PIDDSI_COMPANY = 0x0000000F,
PIDDSI_LINKSDIRTY = 0x00000010,
PIDDSI_CCHWITHSPACES = 0x00000011,
PIDDSI_SHAREDDOC = 0x00000013,
PIDDSI_LINKBASE = 0x00000014,
PIDDSI_HLINKS = 0x00000015,
PIDDSI_HYPERLINKSCHANGED = 0x00000016,
PIDDSI_VERSION = 0x00000017,
PIDDSI_DIGSIG = 0x00000018,
PIDDSI_CONTENTTYPE = 0x0000001A,
PIDDSI_CONTENTSTATUS = 0x0000001B,
PIDDSI_LANGUAGE = 0x0000001C,
PIDDSI_DOCVERSION = 0x0000001D
};
enum PIDSI
{
CODEPAGE_PROPERTY_IDENTIFIER = 0x00000001,
PIDSI_TITLE = 0x00000002,
PIDSI_SUBJECT = 0x00000003,
PIDSI_AUTHOR = 0x00000004,
PIDSI_KEYWORDS = 0x00000005,
PIDSI_COMMENTS = 0x00000006,
PIDSI_TEMPLATE = 0x00000007,
PIDSI_LASTAUTHOR = 0x00000008,
PIDSI_REVNUMBER = 0x00000009,
PIDSI_EDITTIME = 0x0000000A,
PIDSI_LASTPRINTED = 0x0000000B,
PIDSI_CREATE_DTM = 0x0000000C,
PIDSI_LASTSAVE_DTM = 0x0000000D,
PIDSI_PAGECOUNT = 0x0000000E,
PIDSI_WORDCOUNT = 0x0000000F,
PIDSI_CHARCOUNT = 0x00000010,
PIDSI_THUMBNAIL = 0x00000011,
PIDSI_APPNAME = 0x00000012,
PIDSI_DOC_SECURITY = 0x00000013
};
bool libvisio::VSDMetaData::parse(librevenge::RVNGInputStream *input)
{
if (!input)
return false;
readPropertySetStream(input);
return true;
}
void libvisio::VSDMetaData::readPropertySetStream(librevenge::RVNGInputStream *input)
{
// ByteOrder
input->seek(2, librevenge::RVNG_SEEK_CUR);
// Version
input->seek(2, librevenge::RVNG_SEEK_CUR);
// SystemIdentifier
input->seek(4, librevenge::RVNG_SEEK_CUR);
// CLSID
input->seek(16, librevenge::RVNG_SEEK_CUR);
// NumPropertySets
input->seek(4, librevenge::RVNG_SEEK_CUR);
// FMTID0
//input->seek(16, librevenge::RVNG_SEEK_CUR);
uint32_t data1 = readU32(input);
uint16_t data2 = readU16(input);
uint16_t data3 = readU16(input);
uint8_t data4[8];
for (unsigned char &i : data4)
{
i = readU8(input);
}
// Pretty-printed GUID is 36 bytes + the terminating null-character.
char FMTID0[37];
sprintf(FMTID0, "%08x-%04x-%04x-%02x%02x-%02x%02x%02x%02x%02x%02x", data1, data2, data3,
data4[0], data4[1], data4[2], data4[3], data4[4], data4[5], data4[6], data4[7]);
uint32_t offset0 = readU32(input);
readPropertySet(input, offset0, FMTID0);
}
void libvisio::VSDMetaData::readPropertySet(librevenge::RVNGInputStream *input, uint32_t offset, char *FMTID)
{
input->seek(offset, librevenge::RVNG_SEEK_SET);
// Size
input->seek(4, librevenge::RVNG_SEEK_CUR);
uint32_t numProperties = readU32(input);
for (uint32_t i = 0; i < numProperties; ++i)
readPropertyIdentifierAndOffset(input);
for (uint32_t i = 0; i < numProperties; ++i)
{
if (i >= m_idsAndOffsets.size())
break;
readTypedPropertyValue(input, i, offset + m_idsAndOffsets[i].second, FMTID);
}
}
uint32_t libvisio::VSDMetaData::getCodePage()
{
for (size_t i = 0; i < m_idsAndOffsets.size(); ++i)
{
if (m_idsAndOffsets[i].first == CODEPAGE_PROPERTY_IDENTIFIER)
{
if (i >= m_typedPropertyValues.size())
break;
return m_typedPropertyValues[i];
}
}
return 0;
}
void libvisio::VSDMetaData::readPropertyIdentifierAndOffset(librevenge::RVNGInputStream *input)
{
uint32_t propertyIdentifier = readU32(input);
uint32_t offset = readU32(input);
m_idsAndOffsets.push_back(std::make_pair(propertyIdentifier, offset));
}
#define VT_I2 0x0002
#define VT_LPSTR 0x001E
void libvisio::VSDMetaData::readTypedPropertyValue(librevenge::RVNGInputStream *input,
uint32_t index,
uint32_t offset,
char *FMTID)
{
input->seek(offset, librevenge::RVNG_SEEK_SET);
uint16_t type = readU16(input);
// Padding
input->seek(2, librevenge::RVNG_SEEK_CUR);
if (type == VT_I2)
{
uint16_t value = readU16(input);
m_typedPropertyValues[index] = value;
}
else if (type == VT_LPSTR)
{
librevenge::RVNGString string = readCodePageString(input);
if (!string.empty())
{
if (index >= m_idsAndOffsets.size())
return;
if (!strcmp(FMTID, "f29f85e0-4ff9-1068-ab91-08002b27b3d9"))
{
switch (m_idsAndOffsets[index].first)
{
case PIDSI_TITLE:
m_metaData.insert("dc:title", string);
break;
case PIDSI_SUBJECT:
m_metaData.insert("dc:subject", string);
break;
case PIDSI_AUTHOR:
m_metaData.insert("meta:initial-creator", string);
m_metaData.insert("dc:creator", string);
break;
case PIDSI_KEYWORDS:
m_metaData.insert("meta:keyword", string);
break;
case PIDSI_COMMENTS:
m_metaData.insert("dc:description", string);
break;
case PIDSI_TEMPLATE:
std::string templateHref(string.cstr());
size_t found = templateHref.find_last_of("/\\");
if (found != std::string::npos)
string = librevenge::RVNGString(templateHref.substr(found+1).c_str());
m_metaData.insert("librevenge:template", string);
break;
}
}
else if (!strcmp(FMTID,"d5cdd502-2e9c-101b-9397-08002b2cf9ae"))
{
switch (m_idsAndOffsets[index].first)
{
case PIDDSI_CATEGORY:
m_metaData.insert("librevenge:category", string);
break;
case PIDDSI_LINECOUNT:
// this should actually be PIDDSI_COMPANY but this
// is what company is mapped to
m_metaData.insert("librevenge:company", string);
break;
case PIDDSI_LANGUAGE:
m_metaData.insert("dc:language", string);
break;
}
}
}
}
}
librevenge::RVNGString libvisio::VSDMetaData::readCodePageString(librevenge::RVNGInputStream *input)
{
uint32_t size = readU32(input);
if (size > getRemainingLength(input))
size = getRemainingLength(input);
if (size == 0)
return librevenge::RVNGString();
std::vector<unsigned char> characters;
for (uint32_t i = 0; i < size; ++i)
characters.push_back(readU8(input));
uint32_t codepage = getCodePage();
librevenge::RVNGString string;
if (codepage == 65001)
{
// http://msdn.microsoft.com/en-us/library/windows/desktop/dd374130%28v=vs.85%29.aspx
// says this is UTF-8.
characters.push_back(0);
string.append(reinterpret_cast<const char *>(characters.data()));
}
else
{
UErrorCode status = U_ZERO_ERROR;
UConverter *conv = nullptr;
switch (codepage)
{
case 1252:
// http://msdn.microsoft.com/en-us/goglobal/bb964654
conv = ucnv_open("windows-1252", &status);
break;
}
if (U_SUCCESS(status) && conv)
{
assert(!characters.empty());
const char *src = (const char *)&characters[0];
const char *srcLimit = (const char *)src + characters.size();
while (src < srcLimit)
{
UChar32 ucs4Character = ucnv_getNextUChar(conv, &src, srcLimit, &status);
if (U_SUCCESS(status) && U_IS_UNICODE_CHAR(ucs4Character))
appendUCS4(string, ucs4Character);
}
}
if (conv)
ucnv_close(conv);
}
return string;
}
bool libvisio::VSDMetaData::parseTimes(librevenge::RVNGInputStream *input)
{
// Parse the header
// HeaderSignature: 8 bytes
// HeaderCLSID: 16 bytes
// MinorVersion: 2 bytes
// MajorVersion: 2 bytes
// ByteOrder: 2 bytes
input->seek(30, librevenge::RVNG_SEEK_CUR);
uint16_t sectorShift = readU16(input);
// MiniSectorShift: 2 bytes
// Reserved: 6 bytes
// NumDirectorySectors: 4 bytes
// NumFATSectors: 4 bytes
input->seek(16, librevenge::RVNG_SEEK_CUR);
uint32_t firstDirSectorLocation = readU32(input);
// Seek to the Root Directory Entry
size_t sectorSize = std::pow(2, sectorShift);
input->seek((firstDirSectorLocation + 1) * sectorSize, librevenge::RVNG_SEEK_SET);
// DirectoryEntryName: 64 bytes
// DirectoryEntryNameLength: 2 bytes
// ObjectType: 1 byte
// ColorFlag: 1 byte
// LeftSiblingID: 4 bytes
// RightSiblingID: 4 bytes
// ChildID: 4 bytes
// CLSID: 16 bytes
// StateBits: 4 bytes
// CreationTime: 8 bytes
input->seek(108, librevenge::RVNG_SEEK_CUR);
uint64_t modifiedTime = readU64(input);
// modifiedTime is number of 100ns since Jan 1 1601
const uint64_t epoch = uint64_t(116444736UL) * 100;
time_t sec = (modifiedTime / 10000000) - epoch;
const struct tm *time = localtime(&sec);
if (time)
{
static const int MAX_BUFFER = 1024;
char buffer[MAX_BUFFER];
strftime(&buffer[0], MAX_BUFFER-1, "%Y-%m-%dT%H:%M:%SZ", time);
librevenge::RVNGString result;
result.append(buffer);
// Visio UI uses modifiedTime for both purposes.
m_metaData.insert("meta:creation-date", result);
m_metaData.insert("dc:date", result);
return true;
}
return false;
}
const librevenge::RVNGPropertyList &libvisio::VSDMetaData::getMetaData()
{
return m_metaData;
}
/* vim:set shiftwidth=2 softtabstop=2 expandtab: */
<commit_msg>cid#1312142 sanitize loop bound<commit_after>/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/*
* This file is part of the libvisio project.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
#include "VSDMetaData.h"
#include <cassert>
#include <cmath>
#include <cstdio>
#include <cstring>
#include <string>
#include <unicode/ucnv.h>
#include <ctime>
libvisio::VSDMetaData::VSDMetaData()
: m_idsAndOffsets(), m_typedPropertyValues(), m_metaData()
{
}
libvisio::VSDMetaData::~VSDMetaData()
{
}
enum PIDDSI
{
PIDDSI_CODEPAGE = 0x00000001,
PIDDSI_CATEGORY = 0x00000002,
PIDDSI_PRESFORMAT = 0x00000003,
PIDDSI_BYTECOUNT = 0x00000004,
PIDDSI_LINECOUNT = 0x00000005,
PIDDSI_PARACOUNT = 0x00000006,
PIDDSI_SLIDECOUNT = 0x00000007,
PIDDSI_NOTECOUNT = 0x00000008,
PIDDSI_HIDDENCOUNT = 0x00000009,
PIDDSI_MMCLIPCOUNT = 0x0000000A,
PIDDSI_SCALE = 0x0000000B,
PIDDSI_HEADINGPAIR = 0x0000000C,
PIDDSI_DOCPARTS = 0x0000000D,
PIDDSI_MANAGER = 0x0000000E,
PIDDSI_COMPANY = 0x0000000F,
PIDDSI_LINKSDIRTY = 0x00000010,
PIDDSI_CCHWITHSPACES = 0x00000011,
PIDDSI_SHAREDDOC = 0x00000013,
PIDDSI_LINKBASE = 0x00000014,
PIDDSI_HLINKS = 0x00000015,
PIDDSI_HYPERLINKSCHANGED = 0x00000016,
PIDDSI_VERSION = 0x00000017,
PIDDSI_DIGSIG = 0x00000018,
PIDDSI_CONTENTTYPE = 0x0000001A,
PIDDSI_CONTENTSTATUS = 0x0000001B,
PIDDSI_LANGUAGE = 0x0000001C,
PIDDSI_DOCVERSION = 0x0000001D
};
enum PIDSI
{
CODEPAGE_PROPERTY_IDENTIFIER = 0x00000001,
PIDSI_TITLE = 0x00000002,
PIDSI_SUBJECT = 0x00000003,
PIDSI_AUTHOR = 0x00000004,
PIDSI_KEYWORDS = 0x00000005,
PIDSI_COMMENTS = 0x00000006,
PIDSI_TEMPLATE = 0x00000007,
PIDSI_LASTAUTHOR = 0x00000008,
PIDSI_REVNUMBER = 0x00000009,
PIDSI_EDITTIME = 0x0000000A,
PIDSI_LASTPRINTED = 0x0000000B,
PIDSI_CREATE_DTM = 0x0000000C,
PIDSI_LASTSAVE_DTM = 0x0000000D,
PIDSI_PAGECOUNT = 0x0000000E,
PIDSI_WORDCOUNT = 0x0000000F,
PIDSI_CHARCOUNT = 0x00000010,
PIDSI_THUMBNAIL = 0x00000011,
PIDSI_APPNAME = 0x00000012,
PIDSI_DOC_SECURITY = 0x00000013
};
bool libvisio::VSDMetaData::parse(librevenge::RVNGInputStream *input)
{
if (!input)
return false;
readPropertySetStream(input);
return true;
}
void libvisio::VSDMetaData::readPropertySetStream(librevenge::RVNGInputStream *input)
{
// ByteOrder
input->seek(2, librevenge::RVNG_SEEK_CUR);
// Version
input->seek(2, librevenge::RVNG_SEEK_CUR);
// SystemIdentifier
input->seek(4, librevenge::RVNG_SEEK_CUR);
// CLSID
input->seek(16, librevenge::RVNG_SEEK_CUR);
// NumPropertySets
input->seek(4, librevenge::RVNG_SEEK_CUR);
// FMTID0
//input->seek(16, librevenge::RVNG_SEEK_CUR);
uint32_t data1 = readU32(input);
uint16_t data2 = readU16(input);
uint16_t data3 = readU16(input);
uint8_t data4[8];
for (unsigned char &i : data4)
{
i = readU8(input);
}
// Pretty-printed GUID is 36 bytes + the terminating null-character.
char FMTID0[37];
sprintf(FMTID0, "%08x-%04x-%04x-%02x%02x-%02x%02x%02x%02x%02x%02x", data1, data2, data3,
data4[0], data4[1], data4[2], data4[3], data4[4], data4[5], data4[6], data4[7]);
uint32_t offset0 = readU32(input);
readPropertySet(input, offset0, FMTID0);
}
void libvisio::VSDMetaData::readPropertySet(librevenge::RVNGInputStream *input, uint32_t offset, char *FMTID)
{
input->seek(offset, librevenge::RVNG_SEEK_SET);
// Size
input->seek(4, librevenge::RVNG_SEEK_CUR);
uint32_t numProperties = readU32(input);
// The exact size of a property is not known beforehand: check upper bound
if (numProperties > getRemainingLength(input) / 12)
numProperties = getRemainingLength(input) / 12;
for (uint32_t i = 0; i < numProperties; ++i)
readPropertyIdentifierAndOffset(input);
for (uint32_t i = 0; i < numProperties; ++i)
{
if (i >= m_idsAndOffsets.size())
break;
readTypedPropertyValue(input, i, offset + m_idsAndOffsets[i].second, FMTID);
}
}
uint32_t libvisio::VSDMetaData::getCodePage()
{
for (size_t i = 0; i < m_idsAndOffsets.size(); ++i)
{
if (m_idsAndOffsets[i].first == CODEPAGE_PROPERTY_IDENTIFIER)
{
if (i >= m_typedPropertyValues.size())
break;
return m_typedPropertyValues[i];
}
}
return 0;
}
void libvisio::VSDMetaData::readPropertyIdentifierAndOffset(librevenge::RVNGInputStream *input)
{
uint32_t propertyIdentifier = readU32(input);
uint32_t offset = readU32(input);
m_idsAndOffsets.push_back(std::make_pair(propertyIdentifier, offset));
}
#define VT_I2 0x0002
#define VT_LPSTR 0x001E
void libvisio::VSDMetaData::readTypedPropertyValue(librevenge::RVNGInputStream *input,
uint32_t index,
uint32_t offset,
char *FMTID)
{
input->seek(offset, librevenge::RVNG_SEEK_SET);
uint16_t type = readU16(input);
// Padding
input->seek(2, librevenge::RVNG_SEEK_CUR);
if (type == VT_I2)
{
uint16_t value = readU16(input);
m_typedPropertyValues[index] = value;
}
else if (type == VT_LPSTR)
{
librevenge::RVNGString string = readCodePageString(input);
if (!string.empty())
{
if (index >= m_idsAndOffsets.size())
return;
if (!strcmp(FMTID, "f29f85e0-4ff9-1068-ab91-08002b27b3d9"))
{
switch (m_idsAndOffsets[index].first)
{
case PIDSI_TITLE:
m_metaData.insert("dc:title", string);
break;
case PIDSI_SUBJECT:
m_metaData.insert("dc:subject", string);
break;
case PIDSI_AUTHOR:
m_metaData.insert("meta:initial-creator", string);
m_metaData.insert("dc:creator", string);
break;
case PIDSI_KEYWORDS:
m_metaData.insert("meta:keyword", string);
break;
case PIDSI_COMMENTS:
m_metaData.insert("dc:description", string);
break;
case PIDSI_TEMPLATE:
std::string templateHref(string.cstr());
size_t found = templateHref.find_last_of("/\\");
if (found != std::string::npos)
string = librevenge::RVNGString(templateHref.substr(found+1).c_str());
m_metaData.insert("librevenge:template", string);
break;
}
}
else if (!strcmp(FMTID,"d5cdd502-2e9c-101b-9397-08002b2cf9ae"))
{
switch (m_idsAndOffsets[index].first)
{
case PIDDSI_CATEGORY:
m_metaData.insert("librevenge:category", string);
break;
case PIDDSI_LINECOUNT:
// this should actually be PIDDSI_COMPANY but this
// is what company is mapped to
m_metaData.insert("librevenge:company", string);
break;
case PIDDSI_LANGUAGE:
m_metaData.insert("dc:language", string);
break;
}
}
}
}
}
librevenge::RVNGString libvisio::VSDMetaData::readCodePageString(librevenge::RVNGInputStream *input)
{
uint32_t size = readU32(input);
if (size > getRemainingLength(input))
size = getRemainingLength(input);
if (size == 0)
return librevenge::RVNGString();
std::vector<unsigned char> characters;
for (uint32_t i = 0; i < size; ++i)
characters.push_back(readU8(input));
uint32_t codepage = getCodePage();
librevenge::RVNGString string;
if (codepage == 65001)
{
// http://msdn.microsoft.com/en-us/library/windows/desktop/dd374130%28v=vs.85%29.aspx
// says this is UTF-8.
characters.push_back(0);
string.append(reinterpret_cast<const char *>(characters.data()));
}
else
{
UErrorCode status = U_ZERO_ERROR;
UConverter *conv = nullptr;
switch (codepage)
{
case 1252:
// http://msdn.microsoft.com/en-us/goglobal/bb964654
conv = ucnv_open("windows-1252", &status);
break;
}
if (U_SUCCESS(status) && conv)
{
assert(!characters.empty());
const char *src = (const char *)&characters[0];
const char *srcLimit = (const char *)src + characters.size();
while (src < srcLimit)
{
UChar32 ucs4Character = ucnv_getNextUChar(conv, &src, srcLimit, &status);
if (U_SUCCESS(status) && U_IS_UNICODE_CHAR(ucs4Character))
appendUCS4(string, ucs4Character);
}
}
if (conv)
ucnv_close(conv);
}
return string;
}
bool libvisio::VSDMetaData::parseTimes(librevenge::RVNGInputStream *input)
{
// Parse the header
// HeaderSignature: 8 bytes
// HeaderCLSID: 16 bytes
// MinorVersion: 2 bytes
// MajorVersion: 2 bytes
// ByteOrder: 2 bytes
input->seek(30, librevenge::RVNG_SEEK_CUR);
uint16_t sectorShift = readU16(input);
// MiniSectorShift: 2 bytes
// Reserved: 6 bytes
// NumDirectorySectors: 4 bytes
// NumFATSectors: 4 bytes
input->seek(16, librevenge::RVNG_SEEK_CUR);
uint32_t firstDirSectorLocation = readU32(input);
// Seek to the Root Directory Entry
size_t sectorSize = std::pow(2, sectorShift);
input->seek((firstDirSectorLocation + 1) * sectorSize, librevenge::RVNG_SEEK_SET);
// DirectoryEntryName: 64 bytes
// DirectoryEntryNameLength: 2 bytes
// ObjectType: 1 byte
// ColorFlag: 1 byte
// LeftSiblingID: 4 bytes
// RightSiblingID: 4 bytes
// ChildID: 4 bytes
// CLSID: 16 bytes
// StateBits: 4 bytes
// CreationTime: 8 bytes
input->seek(108, librevenge::RVNG_SEEK_CUR);
uint64_t modifiedTime = readU64(input);
// modifiedTime is number of 100ns since Jan 1 1601
const uint64_t epoch = uint64_t(116444736UL) * 100;
time_t sec = (modifiedTime / 10000000) - epoch;
const struct tm *time = localtime(&sec);
if (time)
{
static const int MAX_BUFFER = 1024;
char buffer[MAX_BUFFER];
strftime(&buffer[0], MAX_BUFFER-1, "%Y-%m-%dT%H:%M:%SZ", time);
librevenge::RVNGString result;
result.append(buffer);
// Visio UI uses modifiedTime for both purposes.
m_metaData.insert("meta:creation-date", result);
m_metaData.insert("dc:date", result);
return true;
}
return false;
}
const librevenge::RVNGPropertyList &libvisio::VSDMetaData::getMetaData()
{
return m_metaData;
}
/* vim:set shiftwidth=2 softtabstop=2 expandtab: */
<|endoftext|>
|
<commit_before>/**
@file Datastore.hpp
@brief Datastore class.
@author Tim Howard
@copyright 2013 Tim Howard under the MIT license;
see @ref index or the accompanying LICENSE file for full text.
*/
#ifndef HORD_DATASTORE_HPP_
#define HORD_DATASTORE_HPP_
#include "./config.hpp"
#include "./traits.hpp"
#include "./common_types.hpp"
#include "./common_enums.hpp"
#include "./Prop.hpp"
#include "./Hive.hpp"
#include <functional>
#include <iosfwd>
namespace Hord {
// Forward declarations
class Datastore;
/**
@addtogroup serialization
@{
*/
/**
@addtogroup datastore
@{
*/
/**
Base datastore.
This is the data interface for hives.
@note %Datastores must be locked when a single prop stream is
active.
@remarks The datastore's hive should not be used by
an implementation to lookup objects within the datastore. The
hive is not guaranteed to contain the entire idset at runtime.
@remarks The hive will always have a valid ID, but
note that the hive's ID is <strong>not</strong> within the ID
space of its children -- see @ref hive.
*/
class Datastore {
public:
/**
Type info.
*/
struct type_info final {
/**
Construct a datastore of this type.
@returns
- The constructed datastore;
- or @c nullptr if construction failed.
@param root_path Root path.
@param id %Hive ID.
*/
Datastore* (&construct)(String root_path, HiveID const id) noexcept;
};
/**
Ensure traits for deriving classes.
@tparam D Deriving class.
*/
template<typename D>
struct ensure_traits :
traits::require_t<
D,
tw::capture_post<std::is_base_of, Datastore>::type,
// FIXME: libstdc++ 4.7.3 doesn't have the nothrow version
std::is_destructible,
tw::is_fully_moveable
>,
traits::disallow_t<
D,
std::is_default_constructible,
tw::is_fully_copyable
>
{};
private:
unsigned m_states;
String m_root_path;
Hive m_hive;
Datastore()=delete;
Datastore(Datastore const&)=delete;
Datastore& operator=(Datastore const&)=delete;
protected:
/** @name Implementation */ /// @{
/**
open() implementation.
*/
virtual void open_impl()=0;
/**
close() implementation.
@remarks This is not called if @c is_open()==false.
*/
virtual void close_impl()=0;
/**
Acquire raw stream implementation.
@{
*/
virtual std::istream& acquire_input_stream_impl(
PropInfo const& prop_info
)=0;
virtual std::ostream& acquire_output_stream_impl(
PropInfo const& prop_info
)=0;
/** @} */
/**
Release raw stream implementation.
@{
*/
virtual void release_input_stream_impl(
PropInfo const& prop_info
)=0;
virtual void release_output_stream_impl(
PropInfo const& prop_info
)=0;
/** @} */
/// @}
/** @name Internal state */ /// @{
/**
States.
Implementations are permitted to define states @c 1<<8
to @c 1<<31.
*/
enum class State : uint32_t {
/** %Datastore is open. */
opened =1<<0,
/** %Datastore is locked. */
locked =1<<1,
/** First reserved state. */
RESERVED_FIRST=1<<2,
/** Last reserved state. */
RESERVED_LAST=1<<7
};
/**
Enable state.
@param state %State to enable.
*/
void enable_state(State const state) noexcept;
/**
Disable state.
@param state %State to disable.
*/
void disable_state(State const state) noexcept;
/**
Check if a state is enabled.
@returns
- @c true if the state is enabled;
- @c false if the state is disabled.
@param state %State to test.
*/
bool has_state(State const state) const noexcept;
/// @}
/** @name Constructors and destructor */ /// @{
/**
Constructor with root path and hive ID.
@param root_path Root path.
@param id %Hive ID.
*/
Datastore(String root_path, HiveID const id) noexcept;
/** Move constructor. */
Datastore(Datastore&&);
public:
/** Destructor. */
virtual ~Datastore()=0;
/// @}
protected:
/** @name Operators */ /// @{
/** Move assignment operator. */
Datastore& operator=(Datastore&&);
/// @}
public:
/** @name Properties */ /// @{
/**
Set root path.
@throws Error{ErrorCode::datastore_property_immutable}
If the datastore is open.
@param root_path New root path.
*/
void set_root_path(String root_path);
/**
Get root path.
@returns Root path.
*/
String const& get_root_path() const noexcept
{ return m_root_path; }
/**
Get hive.
@returns %Hive.
*/
Hive const& get_hive() const noexcept
{ return m_hive; }
/**
Get mutable hive.
@returns Mutable hive.
*/
Hive& get_hive() noexcept
{ return m_hive; }
/**
Check if the datastore is open.
@returns
- @c true if the datastore is open;
- @c false if it is closed.
*/
bool is_open() const noexcept
{ return has_state(State::opened); }
/**
Check if the datastore is locked.
@returns
- @c true if the datastore is locked;
- @c false if it is not locked.
*/
bool is_locked() const noexcept
{ return has_state(State::locked); }
/// @}
/** @name Operations */ /// @{
/**
Open the datastore.
@throws Error{ErrorCode::datastore_open_already}
If the datastore is already open.
@throws Error{ErrorCode::datastore_open_failed}
If the datastore failed to open.
*/
void open();
/**
Close the datastore.
@throws Error{ErrorCode::datastore_locked}
If the datastore is locked.
*/
void close();
/**
Acquire raw stream for prop.
@throws Error{ErrorCode::datastore_closed}
If the datastore is closed.
@throws Error{ErrorCode::datastore_locked}
If the datastore is locked.
@throws Error{ErrorCode::datastore_object_not_found}
If @c prop_info.object_id does not exist in the datastore.
@throws Error{ErrorCode::datastore_prop_unsupplied}
If the object for @c prop_info.object_id does not supply the
requested prop.
@throws Error{..}
<em>Implementation-defined exceptions.</em>
@returns Raw prop stream.
@param prop_info Prop info.
@sa PropInfo,
InputPropStream,
OutputPropStream
@{
*/
std::istream& acquire_input_stream(PropInfo const& prop_info);
std::ostream& acquire_output_stream(PropInfo const& prop_info);
/** @} */
/**
Release raw stream for prop.
@throws Error{ErrorCode::datastore_closed}
If the datastore is closed.
@throws Error{ErrorCode::datastore_prop_not_locked}
If either @a prop_info does not match the currently locked
prop stream or there is no currently locked prop stream.
@throws Error{ErrorCode::datastore_object_not_found}
If @c prop_info.object_id does not exist in the datastore.
@throws Error{ErrorCode::datastore_prop_unsupplied}
If the object for @c prop_info.object_id does not supply
the requested prop.
@throws Error{..}
<em>Implementation-defined exceptions.</em>
@param prop_info Prop info.
@sa PropInfo,
InputPropStream,
OutputPropStream
@{
*/
void release_input_stream(PropInfo const& prop_info);
void release_output_stream(PropInfo const& prop_info);
/** @} */
/// @}
};
template struct traits::require_t<
Datastore,
std::has_virtual_destructor
>;
/** @} */ // end of doc-group datastore
/** @} */ // end of doc-group serialization
} // namespace Hord
#endif // HORD_DATASTORE_HPP_
<commit_msg>Datastore: (poorly) fixed doc grouping¹.<commit_after>/**
@file Datastore.hpp
@brief Datastore class.
@author Tim Howard
@copyright 2013 Tim Howard under the MIT license;
see @ref index or the accompanying LICENSE file for full text.
*/
#ifndef HORD_DATASTORE_HPP_
#define HORD_DATASTORE_HPP_
#include "./config.hpp"
#include "./traits.hpp"
#include "./common_types.hpp"
#include "./common_enums.hpp"
#include "./Prop.hpp"
#include "./Hive.hpp"
#include <functional>
#include <iosfwd>
namespace Hord {
// Forward declarations
class Datastore;
/**
@addtogroup serialization
@{
*/
/**
@addtogroup datastore
@{
*/
/**
Base datastore.
This is the data interface for hives.
@note %Datastores must be locked when a single prop stream is
active.
@remarks The datastore's hive should not be used by
an implementation to lookup objects within the datastore. The
hive is not guaranteed to contain the entire idset at runtime.
@remarks The hive will always have a valid ID, but
note that the hive's ID is <strong>not</strong> within the ID
space of its children -- see @ref hive.
*/
class Datastore {
public:
/**
Type info.
*/
struct type_info final {
/**
Construct a datastore of this type.
@returns
- The constructed datastore;
- or @c nullptr if construction failed.
@param root_path Root path.
@param id %Hive ID.
*/
Datastore* (&construct)(String root_path, HiveID const id) noexcept;
};
/**
Ensure traits for deriving classes.
@tparam D Deriving class.
*/
template<typename D>
struct ensure_traits :
traits::require_t<
D,
tw::capture_post<std::is_base_of, Datastore>::type,
// FIXME: libstdc++ 4.7.3 doesn't have the nothrow version
std::is_destructible,
tw::is_fully_moveable
>,
traits::disallow_t<
D,
std::is_default_constructible,
tw::is_fully_copyable
>
{};
private:
unsigned m_states;
String m_root_path;
Hive m_hive;
Datastore()=delete;
Datastore(Datastore const&)=delete;
Datastore& operator=(Datastore const&)=delete;
protected:
/** @name Implementation */ /// @{
/**
open() implementation.
*/
virtual void open_impl()=0;
/**
close() implementation.
@remarks This is not called if @c is_open()==false.
*/
virtual void close_impl()=0;
/**
acquire_input_stream() implementation.
*/
virtual std::istream& acquire_input_stream_impl(
PropInfo const& prop_info
)=0;
/**
acquire_output_stream() implementation.
*/
virtual std::ostream& acquire_output_stream_impl(
PropInfo const& prop_info
)=0;
/**
release_input_stream() implementation.
*/
virtual void release_input_stream_impl(
PropInfo const& prop_info
)=0;
/**
release_output_stream() implementation.
*/
virtual void release_output_stream_impl(
PropInfo const& prop_info
)=0;
/// @}
/** @name Internal state */ /// @{
/**
States.
Implementations are permitted to define states @c 1<<8
to @c 1<<31.
*/
enum class State : uint32_t {
/** %Datastore is open. */
opened =1<<0,
/** %Datastore is locked. */
locked =1<<1,
/** First reserved state. */
RESERVED_FIRST=1<<2,
/** Last reserved state. */
RESERVED_LAST=1<<7
};
/**
Enable state.
@param state %State to enable.
*/
void enable_state(State const state) noexcept;
/**
Disable state.
@param state %State to disable.
*/
void disable_state(State const state) noexcept;
/**
Check if a state is enabled.
@returns
- @c true if the state is enabled;
- @c false if the state is disabled.
@param state %State to test.
*/
bool has_state(State const state) const noexcept;
/// @}
/** @name Constructors and destructor */ /// @{
/**
Constructor with root path and hive ID.
@param root_path Root path.
@param id %Hive ID.
*/
Datastore(String root_path, HiveID const id) noexcept;
/** Move constructor. */
Datastore(Datastore&&);
public:
/** Destructor. */
virtual ~Datastore()=0;
/// @}
protected:
/** @name Operators */ /// @{
/** Move assignment operator. */
Datastore& operator=(Datastore&&);
/// @}
public:
/** @name Properties */ /// @{
/**
Set root path.
@throws Error{ErrorCode::datastore_property_immutable}
If the datastore is open.
@param root_path New root path.
*/
void set_root_path(String root_path);
/**
Get root path.
@returns Root path.
*/
String const& get_root_path() const noexcept
{ return m_root_path; }
/**
Get hive.
@returns %Hive.
*/
Hive const& get_hive() const noexcept
{ return m_hive; }
/**
Get mutable hive.
@returns Mutable hive.
*/
Hive& get_hive() noexcept
{ return m_hive; }
/**
Check if the datastore is open.
@returns
- @c true if the datastore is open;
- @c false if it is closed.
*/
bool is_open() const noexcept
{ return has_state(State::opened); }
/**
Check if the datastore is locked.
@returns
- @c true if the datastore is locked;
- @c false if it is not locked.
*/
bool is_locked() const noexcept
{ return has_state(State::locked); }
/// @}
/** @name Operations */ /// @{
/**
Open the datastore.
@throws Error{ErrorCode::datastore_open_already}
If the datastore is already open.
@throws Error{ErrorCode::datastore_open_failed}
If the datastore failed to open.
*/
void open();
/**
Close the datastore.
@throws Error{ErrorCode::datastore_locked}
If the datastore is locked.
*/
void close();
/**
Acquire raw stream for prop.
@throws Error{ErrorCode::datastore_closed}
If the datastore is closed.
@throws Error{ErrorCode::datastore_locked}
If the datastore is locked.
@throws Error{ErrorCode::datastore_object_not_found}
If @c prop_info.object_id does not exist in the datastore.
@throws Error{ErrorCode::datastore_prop_unsupplied}
If the object for @c prop_info.object_id does not supply the
requested prop.
@throws Error{..}
<em>Implementation-defined exceptions.</em>
@returns Raw prop stream.
@param prop_info Prop info.
@sa PropInfo,
InputPropStream,
OutputPropStream
*/
std::istream& acquire_input_stream(PropInfo const& prop_info);
/** @copydoc acquire_input_stream(PropInfo const&) */
std::ostream& acquire_output_stream(PropInfo const& prop_info);
/**
Release raw stream for prop.
@throws Error{ErrorCode::datastore_closed}
If the datastore is closed.
@throws Error{ErrorCode::datastore_prop_not_locked}
If either @a prop_info does not match the currently locked
prop stream or there is no currently locked prop stream.
@throws Error{ErrorCode::datastore_object_not_found}
If @c prop_info.object_id does not exist in the datastore.
@throws Error{ErrorCode::datastore_prop_unsupplied}
If the object for @c prop_info.object_id does not supply
the requested prop.
@throws Error{..}
<em>Implementation-defined exceptions.</em>
@param prop_info Prop info.
@sa PropInfo,
InputPropStream,
OutputPropStream
*/
void release_input_stream(PropInfo const& prop_info);
/** @copydoc release_input_stream(PropInfo const&) */
void release_output_stream(PropInfo const& prop_info);
/// @}
};
template struct traits::require_t<
Datastore,
std::has_virtual_destructor
>;
/** @} */ // end of doc-group datastore
/** @} */ // end of doc-group serialization
} // namespace Hord
#endif // HORD_DATASTORE_HPP_
<|endoftext|>
|
<commit_before>///
/// @file aligned_vector.hpp
///
/// Copyright (C) 2017 Kim Walisch, <kim.walisch@gmail.com>
///
/// This file is distributed under the BSD License. See the COPYING
/// file in the top level directory.
///
#ifndef ALIGNED_VECTOR_HPP
#define ALIGNED_VECTOR_HPP
#include <cstddef>
#include <vector>
namespace primecount {
/// The aligned_vector class aligns each of its elements on a
/// new cache line in order to avoid false sharing (cache trashing)
/// when multiple threads write to adjacent elements.
///
template <typename T>
class aligned_vector
{
public:
aligned_vector(std::size_t size)
: vect_(size) { }
std::size_t size() const { return vect_.size(); }
T& operator[](std::size_t pos) { return vect_[pos].val; }
private:
struct aligned_t
{
// maximum cache line size of current CPUs
alignas(128) T val;
};
std::vector<aligned_t> vect_;
};
} // namespace
#endif
<commit_msg>define CACHE_LINE_SIZE<commit_after>///
/// @file aligned_vector.hpp
///
/// Copyright (C) 2017 Kim Walisch, <kim.walisch@gmail.com>
///
/// This file is distributed under the BSD License. See the COPYING
/// file in the top level directory.
///
#ifndef ALIGNED_VECTOR_HPP
#define ALIGNED_VECTOR_HPP
#include <cstddef>
#include <vector>
// Maximum cache line size of current CPUs
#ifndef CACHE_LINE_SIZE
#define CACHE_LINE_SIZE 128
#endif
namespace primecount {
/// The aligned_vector class aligns each of its elements on a
/// new cache line in order to avoid false sharing (cache trashing)
/// when multiple threads write to adjacent elements.
///
template <typename T>
class aligned_vector
{
public:
aligned_vector(std::size_t size)
: vect_(size) { }
std::size_t size() const { return vect_.size(); }
T& operator[](std::size_t pos) { return vect_[pos].val; }
private:
struct alignas(CACHE_LINE_SIZE) align_t
{
T val;
};
std::vector<align_t> vect_;
};
} // namespace
#endif
<|endoftext|>
|
<commit_before>///
/// @file aligned_vector.hpp
///
/// Copyright (C) 2019 Kim Walisch, <kim.walisch@gmail.com>
///
/// This file is distributed under the BSD License. See the COPYING
/// file in the top level directory.
///
#ifndef ALIGNED_VECTOR_HPP
#define ALIGNED_VECTOR_HPP
#include <cstddef>
#include <vector>
/// Maximum cache line size of current CPUs.
/// Note that in 2019 all x86 CPU have a cache line size of 64 bytes.
/// However there are CPUs out there that have much larger cache line
/// sizes e.g. IBM z13 CPUs from 2015 have a cache line size of 256
/// bytes. Hence in order to be future-proof we set the maximum cache
/// line size to 1 kilobyte.
///
#ifndef CACHE_LINE_SIZE
#define CACHE_LINE_SIZE 1024
#endif
namespace primecount {
/// The aligned_vector class aligns each of its
/// elements on a new cache line in order to avoid
/// false sharing (cache trashing) when multiple
/// threads write to adjacent elements
///
template <typename T>
class aligned_vector
{
public:
aligned_vector(std::size_t size)
: vect_(size) { }
std::size_t size() const { return vect_.size(); }
T& operator[](std::size_t pos) { return vect_[pos].val[0]; }
private:
struct align_t
{
T val[CACHE_LINE_SIZE / sizeof(T)];
};
std::vector<align_t> vect_;
};
} // namespace
#endif
<commit_msg>Reduce maximum cache line size<commit_after>///
/// @file aligned_vector.hpp
///
/// Copyright (C) 2019 Kim Walisch, <kim.walisch@gmail.com>
///
/// This file is distributed under the BSD License. See the COPYING
/// file in the top level directory.
///
#ifndef ALIGNED_VECTOR_HPP
#define ALIGNED_VECTOR_HPP
#include <cstddef>
#include <vector>
/// Maximum cache line size of current CPUs.
/// Note that in 2019 all x86 CPU have a cache line size of 64 bytes.
/// However there are CPUs out there that have much larger cache line
/// sizes e.g. IBM z13 CPUs from 2015 have a cache line size of 256
/// bytes. Hence in order to be future-proof we set the maximum cache
/// line size to 512 bytes.
///
#ifndef CACHE_LINE_SIZE
#define CACHE_LINE_SIZE 512
#endif
namespace primecount {
/// The aligned_vector class aligns each of its
/// elements on a new cache line in order to avoid
/// false sharing (cache trashing) when multiple
/// threads write to adjacent elements
///
template <typename T>
class aligned_vector
{
public:
aligned_vector(std::size_t size)
: vect_(size) { }
std::size_t size() const { return vect_.size(); }
T& operator[](std::size_t pos) { return vect_[pos].val[0]; }
private:
struct align_t
{
T val[CACHE_LINE_SIZE / sizeof(T)];
};
std::vector<align_t> vect_;
};
} // namespace
#endif
<|endoftext|>
|
<commit_before>/*
* Copyright (c) 2015-2016 Fotonic
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* and Apache License v2.0 which accompanies this distribution.
*
* The Eclipse Public License is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* The Apache License v2.0 is available at
* http://www.opensource.org/licenses/apache2.0.php
*
* You can redistribute this code under either of these licenses.
* For more information; see http://www.arrowhead.eu/licensing
*/
/**
* @file
* @brief JSON processing API declarations
*
* @author Joakim Nohlgård <joakim@nohlgard.se>
*/
#ifndef ARROWHEAD_JSON_HPP_
#define ARROWHEAD_JSON_HPP_
#include "arrowhead/config.h"
#include <cstddef> // for size_t
namespace Arrowhead {
} /* namespace Arrowhead */
/* Template definitions are found in detail/json.hpp */
#include "arrowhead/detail/json.hpp"
#endif /* ARROWHEAD_JSON_HPP_ */
<commit_msg>delete old empty include json.hpp<commit_after><|endoftext|>
|
<commit_before>#pragma once
/**
@file
@brief int type definition and macros
Copyright (C) 2008 Cybozu Labs, Inc., all rights reserved.
*/
#if defined(_MSC_VER) && (MSC_VER <= 1500)
typedef __int64 int64_t;
typedef unsigned __int64 uint64_t;
typedef unsigned int uint32_t;
typedef int int32_t;
typedef unsigned short uint16_t;
typedef short int16_t;
typedef unsigned char uint8_t;
typedef signed char int8_t;
#else
#include <stdint.h>
#endif
#ifdef _MSC_VER
#ifndef CYBOZU_DEFINED_SSIZE_T
#define CYBOZU_DEFINED_SSIZE_T
#ifdef _WIN64
typedef int64_t ssize_t;
#else
typedef int32_t ssize_t;
#endif
#endif
#else
#include <unistd.h> // for ssize_t
#endif
#ifndef CYBOZU_ALIGN
#ifdef _MSC_VER
#define CYBOZU_ALIGN(x) __declspec(align(x))
#else
#define CYBOZU_ALIGN(x) __attribute__((aligned(x)))
#endif
#endif
#ifndef CYBOZU_ALLOCA
#ifdef _MSC_VER
#include <malloc.h>
#define CYBOZU_ALLOCA(x) _malloca(x)
#else
#define CYBOZU_ALLOCA_(x) __builtin_alloca(x)
#endif
#endif
#ifndef CYBOZU_FOREACH
// std::vector<int> v; CYBOZU_FOREACH(auto x, v) {...}
#if defined(_MSC_VER) && (_MSC_VER >= 1400)
#define CYBOZU_FOREACH(type_x, xs) for each (type_x in xs)
#elif defined(__GNUC__)
#define CYBOZU_FOREACH(type_x, xs) for (type_x : xs)
#endif
#endif
#ifndef CYBOZU_NUM_OF_ARRAY
#define CYBOZU_NUM_OF_ARRAY(x) (sizeof(x) / sizeof(*x))
#endif
#ifndef CYBOZU_SNPRINTF
#ifdef _MSC_VER
#define CYBOZU_SNPRINTF(x, len, ...) _snprintf_s(x, len - 1, __VA_ARGS__)
#else
#define CYBOZU_SNPRINTF(x, len, ...) snprintf(x, len, __VA_ARGS__)
#endif
#endif
#define CYBOZU_CPP_VERSION_CPP03 0
#define CYBOZU_CPP_VERSION_TR1 1
#define CYBOZU_CPP_VERSION_CPP11 2
#if (__cplusplus >= 201103) || (_MSC_VER >= 1500) || defined(__GXX_EXPERIMENTAL_CXX0X__)
#if defined(_MSC_VER) && (_MSC_VER <= 1600)
#define CYBOZU_CPP_VERSION CYBOZU_CPP_VERSION_TR1
#else
#define CYBOZU_CPP_VERSION CYBOZU_CPP_VERSION_CPP11
#endif
#elif (__GNUC__ >= 4 && __GNUC_MINOR__ >= 5) || (__clang_major__ >= 3)
#define CYBOZU_CPP_VERSION CYBOZU_CPP_VERSION_TR1
#else
#define CYBOZU_CPP_VERSION CYBOZU_CPP_VERSION_CPP03
#endif
#if (CYBOZU_CPP_VERSION == CYBOZU_CPP_VERSION_TR1)
#define CYBOZU_NAMESPACE_STD std::tr1
#define CYBOZU_NAMESPACE_TR1_BEGIN namespace tr1 {
#define CYBOZU_NAMESPACE_TR1_END }
#else
#define CYBOZU_NAMESPACE_STD std
#define CYBOZU_NAMESPACE_TR1_BEGIN
#define CYBOZU_NAMESPACE_TR1_END
#endif
#ifndef CYBOZU_OS_BIT
#if defined(_WIN64) || defined(__x86_64__)
#define CYBOZU_OS_BIT 64
#else
#define CYBOZU_OS_BIT 32
#endif
#endif
#ifndef CYBOZU_ENDIAN
#define CYBOZU_ENDIAN_UNKNOWN 0
#define CYBOZU_ENDIAN_LITTLE 1
#define CYBOZU_ENDIAN_BIG 2
#if defined(_M_IX86) || defined(_M_AMD64) || defined(__x86_64__) || defined(__i386__)
#define CYBOZU_ENDIAN CYBOZU_ENDIAN_LITTLE
#else
#define CYBOZU_ENDIAN CYBOZU_ENDIAN_UNKNOWN
#endif
#endif
namespace cybozu {
template<class T>
void disable_warning_unused_variable(const T&) { }
template<class T, class S>
T cast(const S* ptr) { return static_cast<T>(static_cast<const void*>(ptr)); }
template<class T, class S>
T cast(S* ptr) { return static_cast<T>(static_cast<void*>(ptr)); }
} // cybozu
<commit_msg>avoid to use return value<commit_after>#pragma once
/**
@file
@brief int type definition and macros
Copyright (C) 2008 Cybozu Labs, Inc., all rights reserved.
*/
#if defined(_MSC_VER) && (MSC_VER <= 1500)
typedef __int64 int64_t;
typedef unsigned __int64 uint64_t;
typedef unsigned int uint32_t;
typedef int int32_t;
typedef unsigned short uint16_t;
typedef short int16_t;
typedef unsigned char uint8_t;
typedef signed char int8_t;
#else
#include <stdint.h>
#endif
#ifdef _MSC_VER
#ifndef CYBOZU_DEFINED_SSIZE_T
#define CYBOZU_DEFINED_SSIZE_T
#ifdef _WIN64
typedef int64_t ssize_t;
#else
typedef int32_t ssize_t;
#endif
#endif
#else
#include <unistd.h> // for ssize_t
#endif
#ifndef CYBOZU_ALIGN
#ifdef _MSC_VER
#define CYBOZU_ALIGN(x) __declspec(align(x))
#else
#define CYBOZU_ALIGN(x) __attribute__((aligned(x)))
#endif
#endif
#ifndef CYBOZU_ALLOCA
#ifdef _MSC_VER
#include <malloc.h>
#define CYBOZU_ALLOCA(x) _malloca(x)
#else
#define CYBOZU_ALLOCA_(x) __builtin_alloca(x)
#endif
#endif
#ifndef CYBOZU_FOREACH
// std::vector<int> v; CYBOZU_FOREACH(auto x, v) {...}
#if defined(_MSC_VER) && (_MSC_VER >= 1400)
#define CYBOZU_FOREACH(type_x, xs) for each (type_x in xs)
#elif defined(__GNUC__)
#define CYBOZU_FOREACH(type_x, xs) for (type_x : xs)
#endif
#endif
#ifndef CYBOZU_NUM_OF_ARRAY
#define CYBOZU_NUM_OF_ARRAY(x) (sizeof(x) / sizeof(*x))
#endif
#ifndef CYBOZU_SNPRINTF
#ifdef _MSC_VER
#define CYBOZU_SNPRINTF(x, len, ...) (void)_snprintf_s(x, len, len - 1, __VA_ARGS__)
#else
#define CYBOZU_SNPRINTF(x, len, ...) (void)snprintf(x, len, __VA_ARGS__)
#endif
#endif
#define CYBOZU_CPP_VERSION_CPP03 0
#define CYBOZU_CPP_VERSION_TR1 1
#define CYBOZU_CPP_VERSION_CPP11 2
#if (__cplusplus >= 201103) || (_MSC_VER >= 1500) || defined(__GXX_EXPERIMENTAL_CXX0X__)
#if defined(_MSC_VER) && (_MSC_VER <= 1600)
#define CYBOZU_CPP_VERSION CYBOZU_CPP_VERSION_TR1
#else
#define CYBOZU_CPP_VERSION CYBOZU_CPP_VERSION_CPP11
#endif
#elif (__GNUC__ >= 4 && __GNUC_MINOR__ >= 5) || (__clang_major__ >= 3)
#define CYBOZU_CPP_VERSION CYBOZU_CPP_VERSION_TR1
#else
#define CYBOZU_CPP_VERSION CYBOZU_CPP_VERSION_CPP03
#endif
#if (CYBOZU_CPP_VERSION == CYBOZU_CPP_VERSION_TR1)
#define CYBOZU_NAMESPACE_STD std::tr1
#define CYBOZU_NAMESPACE_TR1_BEGIN namespace tr1 {
#define CYBOZU_NAMESPACE_TR1_END }
#else
#define CYBOZU_NAMESPACE_STD std
#define CYBOZU_NAMESPACE_TR1_BEGIN
#define CYBOZU_NAMESPACE_TR1_END
#endif
#ifndef CYBOZU_OS_BIT
#if defined(_WIN64) || defined(__x86_64__)
#define CYBOZU_OS_BIT 64
#else
#define CYBOZU_OS_BIT 32
#endif
#endif
#ifndef CYBOZU_ENDIAN
#define CYBOZU_ENDIAN_UNKNOWN 0
#define CYBOZU_ENDIAN_LITTLE 1
#define CYBOZU_ENDIAN_BIG 2
#if defined(_M_IX86) || defined(_M_AMD64) || defined(__x86_64__) || defined(__i386__)
#define CYBOZU_ENDIAN CYBOZU_ENDIAN_LITTLE
#else
#define CYBOZU_ENDIAN CYBOZU_ENDIAN_UNKNOWN
#endif
#endif
namespace cybozu {
template<class T>
void disable_warning_unused_variable(const T&) { }
template<class T, class S>
T cast(const S* ptr) { return static_cast<T>(static_cast<const void*>(ptr)); }
template<class T, class S>
T cast(S* ptr) { return static_cast<T>(static_cast<void*>(ptr)); }
} // cybozu
<|endoftext|>
|
<commit_before>// Own header
#include "sized_glyph.h"
// Project headers
#include "master_glyph.h"
#include "text_renderer_aa_internals.h"
// Standard headers
#include <algorithm>
#include <stdlib.h>
// ***************************************************************************
// SizedGlyph
// ***************************************************************************
void SizedGlyph::PutPix(unsigned x, unsigned y, unsigned char val)
{
unsigned char *line = m_pixelData + y * m_width;
line[x] = val;
}
SizedGlyph::SizedGlyph(MasterGlyph *mg, unsigned output_size)
{
// The downsampling code below if mostly cut-n-paste from code written by
// Ryan Geiss (http://www.geisswerks.com/ryan/FAQS/resize.html)
double scale_factor = (double)output_size / (double)MASTER_GLYPH_RESOLUTION;
m_height = round(mg->m_height * scale_factor);
m_width = round(mg->m_width * scale_factor);
m_pixelData = new unsigned char[m_width * m_height];
int w1 = mg->m_width;
int h1 = mg->m_height;
int w2 = m_width;
int h2 = m_height;
float fh = 256*h1 / (float)h2;
float fw = 256*w1 / (float)w2;
// FOR EVERY OUTPUT PIXEL
for (int y2 = 0; y2 < h2; y2++)
{
// find the y-range of input pixels that will contribute:
int y1a = (int)((y2 )*fh);
int y1b = (int)((y2+1)*fh);
y1b = std::min(y1b, 256*h1 - 1);
int y1c = y1a >> 8;
int y1d = y1b >> 8;
y1a &= 0xff;
y1b &= 0xff;
for (int x2 = 0; x2 < w2; x2++)
{
// find the x-range of input pixels that will contribute:
int x1a = (int)((x2)*fw);
int x1b = (int)((x2 + 1)*fw);
x1b = std::min(x1b, 256 * w1 - 1);
int x1c = x1a >> 8;
int x1d = x1b >> 8;
x1a &= 0xff;
x1b &= 0xff;
// ADD UP ALL INPUT PIXELS CONTRIBUTING TO THIS OUTPUT PIXEL:
unsigned int accumulatedBrightness = 0;
for (int y = y1c; y <= y1d; y++)
{
unsigned int weight_y = 256;
if (y1c != y1d)
{
if (y == y1c)
weight_y = 256 - y1a;
else if (y == y1d)
weight_y = y1b;
}
unsigned char *line = mg->m_pixelData + y * mg->m_widthBytes;
unsigned accumulatedBrightnessX = 0;
unsigned int weight_x = 256 - x1a;
unsigned char pixelByte = line[x1c >> 3];
unsigned char shiftedPixelByte = pixelByte >> (x1c & 0x7);
accumulatedBrightnessX += (shiftedPixelByte & 1) * weight_x;
for (int x = x1c + 1; x < x1d; x++)
{
pixelByte = line[x >> 3];
shiftedPixelByte = pixelByte >> (x & 0x7);
accumulatedBrightnessX += (shiftedPixelByte & 1) << 8;
}
pixelByte = line[x1d >> 3];
shiftedPixelByte = pixelByte >> (x1d & 0x7);
accumulatedBrightnessX += (shiftedPixelByte & 1) * x1b;
accumulatedBrightness += accumulatedBrightnessX * weight_y;
}
int xSize = (256 - x1a) + (256 * (x1d - x1c - 1)) + (x1b);
int ySize = (256 - y1a) + (256 * (y1d - y1c - 1)) + (y1b);
int accumulatedArea = xSize * ySize;
// write results
unsigned int c = accumulatedBrightness / (accumulatedArea >> 8);
c = std::min(c, (unsigned)255);
PutPix(x2, y2, c);
}
}
for (unsigned i = 0; i < 255; i++)
m_kerning[i] = round(mg->m_kerning[i] * scale_factor) + 1;
}
// ***************************************************************************
// SizedGlyphSet
// ***************************************************************************
SizedGlyphSet::SizedGlyphSet(MasterGlyph *masterGlyphSet[256], int size)
{
for (int i = 0; i < 256; i++)
{
MasterGlyph *mg = masterGlyphSet[i];
if (mg)
{
m_sizedGlyphs[i] = new SizedGlyph(mg, size);
}
else
{
m_sizedGlyphs[i] = NULL;
}
}
}
<commit_msg>Cosmetic change only<commit_after>// Own header
#include "sized_glyph.h"
// Project headers
#include "master_glyph.h"
#include "text_renderer_aa_internals.h"
// Standard headers
#include <algorithm>
#include <stdlib.h>
// ***************************************************************************
// SizedGlyph
// ***************************************************************************
void SizedGlyph::PutPix(unsigned x, unsigned y, unsigned char val)
{
unsigned char *line = m_pixelData + y * m_width;
line[x] = val;
}
SizedGlyph::SizedGlyph(MasterGlyph *mg, unsigned output_size)
{
// The downsampling code below is based on code written by Ryan Geiss.
// (http://www.geisswerks.com/ryan/FAQS/resize.html)
double scale_factor = (double)output_size / (double)MASTER_GLYPH_RESOLUTION;
m_height = round(mg->m_height * scale_factor);
m_width = round(mg->m_width * scale_factor);
m_pixelData = new unsigned char[m_width * m_height];
int w1 = mg->m_width;
int h1 = mg->m_height;
int w2 = m_width;
int h2 = m_height;
float fh = 256*h1 / (float)h2;
float fw = 256*w1 / (float)w2;
// FOR EVERY OUTPUT PIXEL
for (int y2 = 0; y2 < h2; y2++)
{
// find the y-range of input pixels that will contribute:
int y1a = (int)((y2 )*fh);
int y1b = (int)((y2+1)*fh);
y1b = std::min(y1b, 256*h1 - 1);
int y1c = y1a >> 8;
int y1d = y1b >> 8;
y1a &= 0xff;
y1b &= 0xff;
for (int x2 = 0; x2 < w2; x2++)
{
// find the x-range of input pixels that will contribute:
int x1a = (int)((x2)*fw);
int x1b = (int)((x2 + 1)*fw);
x1b = std::min(x1b, 256 * w1 - 1);
int x1c = x1a >> 8;
int x1d = x1b >> 8;
x1a &= 0xff;
x1b &= 0xff;
// ADD UP ALL INPUT PIXELS CONTRIBUTING TO THIS OUTPUT PIXEL:
unsigned int accumulatedBrightness = 0;
for (int y = y1c; y <= y1d; y++)
{
unsigned int weight_y = 256;
if (y1c != y1d)
{
if (y == y1c)
weight_y = 256 - y1a;
else if (y == y1d)
weight_y = y1b;
}
unsigned char *line = mg->m_pixelData + y * mg->m_widthBytes;
unsigned accumulatedBrightnessX = 0;
unsigned int weight_x = 256 - x1a;
unsigned char pixelByte = line[x1c >> 3];
unsigned char shiftedPixelByte = pixelByte >> (x1c & 0x7);
accumulatedBrightnessX += (shiftedPixelByte & 1) * weight_x;
for (int x = x1c + 1; x < x1d; x++)
{
pixelByte = line[x >> 3];
shiftedPixelByte = pixelByte >> (x & 0x7);
accumulatedBrightnessX += (shiftedPixelByte & 1) << 8;
}
pixelByte = line[x1d >> 3];
shiftedPixelByte = pixelByte >> (x1d & 0x7);
accumulatedBrightnessX += (shiftedPixelByte & 1) * x1b;
accumulatedBrightness += accumulatedBrightnessX * weight_y;
}
int xSize = (256 - x1a) + (256 * (x1d - x1c - 1)) + (x1b);
int ySize = (256 - y1a) + (256 * (y1d - y1c - 1)) + (y1b);
int accumulatedArea = xSize * ySize;
// write results
unsigned int c = accumulatedBrightness / (accumulatedArea >> 8);
c = std::min(c, (unsigned)255);
PutPix(x2, y2, c);
}
}
for (unsigned i = 0; i < 255; i++)
m_kerning[i] = round(mg->m_kerning[i] * scale_factor) + 1;
}
// ***************************************************************************
// SizedGlyphSet
// ***************************************************************************
SizedGlyphSet::SizedGlyphSet(MasterGlyph *masterGlyphSet[256], int size)
{
for (int i = 0; i < 256; i++)
{
MasterGlyph *mg = masterGlyphSet[i];
if (mg)
{
m_sizedGlyphs[i] = new SizedGlyph(mg, size);
}
else
{
m_sizedGlyphs[i] = NULL;
}
}
}
<|endoftext|>
|
<commit_before>#include <QtWidgets>
#include <QObject>
#include <QStandardPaths>
#include "mainwindow.h"
#include "timer.h"
#include "../../Numeric/CRC.hpp"
/*
General Qt implementation notes:
* it seems like Qt doesn't offer a way to constrain the aspect ratio of a view by constraining
the size of the window (i.e. you can use a custom layout to constrain a view, but that won't
affect the window, so isn't useful for this project). Therefore the emulation window
*/
MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent)
, ui(new Ui::MainWindow)
{
ui->setupUi(this);
createActions();
qApp->installEventFilter(this);
// Set up the emulation timer. Bluffer's guide: the QTimer will post an
// event to an event loop. QThread is a thread with an event loop.
// My class, Timer, will be wired up to receive the QTimer's events.
qTimer = std::make_unique<QTimer>(this);
qTimer->setInterval(1);
timerThread = std::make_unique<QThread>(this);
timer = std::make_unique<Timer>();
timer->moveToThread(timerThread.get());
connect(qTimer.get(), SIGNAL(timeout()), timer.get(), SLOT(tick()));
// Hide the missing ROMs box unless or until it's needed; grab the text it
// began with as a prefix for future mutation.
ui->missingROMsBox->setVisible(false);
romRequestBaseText = ui->missingROMsBox->toPlainText();
}
void MainWindow::createActions() {
// Create a file menu.
QMenu *fileMenu = menuBar()->addMenu(tr("&File"));
// QAction *newAct = new QAction(tr("&New"), this);
// newAct->setShortcuts(QKeySequence::New);
// newAct->setStatusTip(tr("Create a new file"));
// connect(newAct, &QAction::triggered, this, &MainWindow::newFile);
// fileMenu->addAction(newAct);
// Add file option: 'Open..."
QAction *openAct = new QAction(tr("&Open..."), this);
openAct->setShortcuts(QKeySequence::Open);
openAct->setStatusTip(tr("Open an existing file"));
connect(openAct, &QAction::triggered, this, &MainWindow::open);
fileMenu->addAction(openAct);
}
void MainWindow::open() {
QString fileName = QFileDialog::getOpenFileName(this);
if(!fileName.isEmpty()) {
targets = Analyser::Static::GetTargets(fileName.toStdString());
if(targets.empty()) {
qDebug() << "Not media:" << fileName;
} else {
qDebug() << "Got media:" << fileName;
launchMachine();
}
}
}
MainWindow::~MainWindow() {
// Stop the timer by asking its QThread to exit and
// waiting for it to do so.
timerThread->exit();
while(timerThread->isRunning());
}
// MARK: Machine launch.
namespace {
std::unique_ptr<std::vector<uint8_t>> fileContentsAndClose(FILE *file) {
auto data = std::make_unique<std::vector<uint8_t>>();
fseek(file, 0, SEEK_END);
data->resize(std::ftell(file));
fseek(file, 0, SEEK_SET);
size_t read = fread(data->data(), 1, data->size(), file);
fclose(file);
if(read == data->size()) {
return data;
}
return nullptr;
}
}
void MainWindow::launchMachine() {
const QStringList appDataLocations = QStandardPaths::standardLocations(QStandardPaths::AppDataLocation);
missingRoms.clear();
ROMMachine::ROMFetcher rom_fetcher = [&appDataLocations, this]
(const std::vector<ROMMachine::ROM> &roms) -> std::vector<std::unique_ptr<std::vector<uint8_t>>> {
std::vector<std::unique_ptr<std::vector<uint8_t>>> results;
for(const auto &rom: roms) {
FILE *file = nullptr;
for(const auto &path: appDataLocations) {
const std::string source = path.toStdString() + "/ROMImages/" + rom.machine_name + "/" + rom.file_name;
const std::string nativeSource = QDir::toNativeSeparators(QString::fromStdString(source)).toStdString();
qDebug() << "Taking a run at " << nativeSource.c_str();
file = fopen(nativeSource.c_str(), "rb");
if(file) break;
}
if(file) {
auto data = fileContentsAndClose(file);
if(data) {
results.push_back(std::move(data));
continue;
}
}
results.push_back(nullptr);
missingRoms.push_back(rom);
}
return results;
};
Machine::Error error;
machine.reset(Machine::MachineForTargets(targets, rom_fetcher, error));
switch(error) {
default: {
// TODO: correct assumptions herein that this is the first machine to be
// assigned to this window.
ui->missingROMsBox->setVisible(false);
uiPhase = UIPhase::RunningMachine;
// Install user-friendly options. TODO: plus user overrides.
// const auto configurable = machine->configurable_device();
// if(configurable) {
// configurable->set_options(configurable->get_options());
// }
// Supply the scan target.
// TODO: in the future, hypothetically, deal with non-scan producers.
const auto scan_producer = machine->scan_producer();
if(scan_producer) {
scan_producer->set_scan_target(ui->openGLWidget->getScanTarget());
}
// Install audio output if required.
const auto audio_producer = machine->audio_producer();
if(audio_producer) {
const auto speaker = audio_producer->get_speaker();
if(speaker) {
const QAudioDeviceInfo &defaultDeviceInfo = QAudioDeviceInfo::defaultOutputDevice();
QAudioFormat idealFormat = defaultDeviceInfo.preferredFormat();
// Use the ideal format's sample rate, provide stereo as long as at least two channels
// are available, and — at least for now — assume 512 samples/buffer is a good size.
audioIsStereo = (idealFormat.channelCount() > 1) && speaker->get_is_stereo();
audioIs8bit = idealFormat.sampleSize() < 16;
const int samplesPerBuffer = 512;
speaker->set_output_rate(idealFormat.sampleRate(), samplesPerBuffer, audioIsStereo);
// Adjust format appropriately, and create an audio output.
idealFormat.setChannelCount(1 + int(audioIsStereo));
idealFormat.setSampleSize(audioIs8bit ? 8 : 16);
audioOutput = std::make_unique<QAudioOutput>(idealFormat, this);
audioOutput->setBufferSize(samplesPerBuffer * (audioIsStereo ? 2 : 1) * (audioIs8bit ? 1 : 2));
qDebug() << idealFormat;
// Start the output.
speaker->set_delegate(this);
audioIODevice = audioOutput->start();
}
}
// If this is a timed machine, start up the timer.
const auto timedMachine = machine->timed_machine();
if(timedMachine) {
timer->setMachine(timedMachine, &machineMutex);
timerThread->start();
qTimer->start();
}
} break;
case Machine::Error::MissingROM: {
ui->missingROMsBox->setVisible(true);
uiPhase = UIPhase::RequestingROMs;
// Populate request text.
QString requestText = romRequestBaseText;
size_t index = 0;
for(const auto rom: missingRoms) {
requestText += "• ";
requestText += rom.descriptive_name.c_str();
++index;
if(index == missingRoms.size()) {
requestText += ".\n";
continue;
}
if(index == missingRoms.size() - 1) {
requestText += "; and\n";
continue;
}
requestText += ";\n";
}
ui->missingROMsBox->setPlainText(requestText);
} break;
}
}
void MainWindow::speaker_did_complete_samples(Outputs::Speaker::Speaker *, const std::vector<int16_t> &buffer) {
const auto bytesWritten = audioIODevice->write(reinterpret_cast<const char *>(buffer.data()), qint64(buffer.size()));
// qDebug() << bytesWritten << "; " << audioOutput->state();
(void)bytesWritten;
}
void MainWindow::dragEnterEvent(QDragEnterEvent* event) {
// Always accept dragged files.
if(event->mimeData()->hasUrls())
event->accept();
}
void MainWindow::dropEvent(QDropEvent* event) {
if(!event->mimeData()->hasUrls()) {
return;
}
event->accept();
switch(uiPhase) {
case UIPhase::NoFileSelected:
// Treat exactly as a File -> Open... .
break;
case UIPhase::RequestingROMs: {
// Attempt to match up the dragged files to the requested ROM list;
// if and when they match, copy to a writeable QStandardPaths::AppDataLocation
// and try launchMachine() again.
bool foundROM = false;
const auto appDataLocation = QStandardPaths::writableLocation(QStandardPaths::AppDataLocation).toStdString();
for(const auto &url: event->mimeData()->urls()) {
const char *const name = url.toLocalFile().toUtf8();
FILE *const file = fopen(name, "rb");
const auto contents = fileContentsAndClose(file);
if(!contents) continue;
CRC::CRC32 generator;
const uint32_t crc = generator.compute_crc(*contents);
for(const auto &rom: missingRoms) {
if(std::find(rom.crc32s.begin(), rom.crc32s.end(), crc) != rom.crc32s.end()) {
foundROM = true;
// Ensure the destination folder exists.
const std::string path = appDataLocation + "/ROMImages/" + rom.machine_name;
QDir dir(QString::fromStdString(path));
if (!dir.exists())
dir.mkpath(".");
// Write into place.
const std::string destination = QDir::toNativeSeparators(QString::fromStdString(path+ "/" + rom.file_name)).toStdString();
FILE *const target = fopen(destination.c_str(), "wb");
fwrite(contents->data(), 1, contents->size(), target);
fclose(target);
}
}
}
if(foundROM) launchMachine();
} break;
case UIPhase::RunningMachine:
// Attempt to insert into the running machine.
qDebug() << "Should start machine";
break;
}
}
// MARK: Input capture.
bool MainWindow::eventFilter(QObject *obj, QEvent *event) {
switch(event->type()) {
case QEvent::KeyPress:
case QEvent::KeyRelease: {
const auto keyEvent = static_cast<QKeyEvent *>(event);
if(!processEvent(keyEvent)) {
return false;
}
} break;
default:
break;
}
return QObject::eventFilter(obj, event);
}
bool MainWindow::processEvent(QKeyEvent *event) {
if(!machine) return true;
// First version: support keyboard input only.
const auto keyboardMachine = machine->keyboard_machine();
if(!keyboardMachine) return true;
#define BIND2(qtKey, clkKey) case Qt::qtKey: key = Inputs::Keyboard::Key::clkKey; break;
#define BIND(key) BIND2(Key_##key, key)
Inputs::Keyboard::Key key;
switch(event->key()) {
default: return true;
BIND(Escape);
BIND(F1); BIND(F2); BIND(F3); BIND(F4); BIND(F5); BIND(F6);
BIND(F7); BIND(F8); BIND(F9); BIND(F10); BIND(F11); BIND(F12);
BIND2(Key_Print, PrintScreen);
BIND(ScrollLock); BIND(Pause);
BIND2(Key_AsciiTilde, BackTick);
BIND2(Key_1, k1); BIND2(Key_2, k2); BIND2(Key_3, k3); BIND2(Key_4, k4); BIND2(Key_5, k5);
BIND2(Key_6, k6); BIND2(Key_7, k7); BIND2(Key_8, k8); BIND2(Key_9, k9); BIND2(Key_0, k0);
BIND2(Key_Minus, Hyphen);
BIND2(Key_Plus, Equals);
BIND(Backspace);
BIND(Tab); BIND(Q); BIND(W); BIND(E); BIND(R); BIND(T); BIND(Y);
BIND(U); BIND(I); BIND(O); BIND(P);
BIND2(Key_BraceLeft, OpenSquareBracket);
BIND2(Key_BraceRight, CloseSquareBracket);
BIND(Backslash);
BIND(CapsLock); BIND(A); BIND(S); BIND(D); BIND(F); BIND(G);
BIND(H); BIND(J); BIND(K); BIND(L);
BIND(Semicolon);
BIND2(Key_QuoteDbl, Quote);
// TODO: something to hash?
BIND2(Key_Return, Enter);
BIND2(Key_Shift, LeftShift);
BIND(Z); BIND(X); BIND(C); BIND(V);
BIND(B); BIND(N); BIND(M);
BIND(Comma);
BIND2(Key_Period, FullStop);
BIND2(Key_Slash, ForwardSlash);
// Omitted: right shift.
BIND2(Key_Control, LeftControl);
BIND2(Key_Alt, LeftOption);
BIND2(Key_Meta, LeftMeta);
BIND(Space);
BIND2(Key_AltGr, RightOption);
BIND(Left); BIND(Right); BIND(Up); BIND(Down);
BIND(Insert); BIND(Home); BIND(PageUp); BIND(Delete); BIND(End); BIND(PageDown);
BIND(NumLock);
}
std::unique_lock lock(machineMutex);
keyboardMachine->get_keyboard().set_key_pressed(key, event->text()[0].toLatin1(), event->type() == QEvent::KeyPress);
return true;
}
<commit_msg>QIODevice isn't guaranteed thread safe, so use of it is now thread confined.<commit_after>#include <QtWidgets>
#include <QObject>
#include <QStandardPaths>
#include "mainwindow.h"
#include "timer.h"
#include "../../Numeric/CRC.hpp"
namespace {
struct AudioEvent: public QEvent {
AudioEvent() : QEvent(QEvent::Type::User) {}
std::vector<int16_t> audio;
};
}
/*
General Qt implementation notes:
* it seems like Qt doesn't offer a way to constrain the aspect ratio of a view by constraining
the size of the window (i.e. you can use a custom layout to constrain a view, but that won't
affect the window, so isn't useful for this project). Therefore the emulation window
*/
MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent)
, ui(new Ui::MainWindow)
{
ui->setupUi(this);
createActions();
qApp->installEventFilter(this);
// Set up the emulation timer. Bluffer's guide: the QTimer will post an
// event to an event loop. QThread is a thread with an event loop.
// My class, Timer, will be wired up to receive the QTimer's events.
qTimer = std::make_unique<QTimer>(this);
qTimer->setInterval(1);
timerThread = std::make_unique<QThread>(this);
timer = std::make_unique<Timer>();
timer->moveToThread(timerThread.get());
connect(qTimer.get(), SIGNAL(timeout()), timer.get(), SLOT(tick()));
// Hide the missing ROMs box unless or until it's needed; grab the text it
// began with as a prefix for future mutation.
ui->missingROMsBox->setVisible(false);
romRequestBaseText = ui->missingROMsBox->toPlainText();
}
void MainWindow::createActions() {
// Create a file menu.
QMenu *fileMenu = menuBar()->addMenu(tr("&File"));
// QAction *newAct = new QAction(tr("&New"), this);
// newAct->setShortcuts(QKeySequence::New);
// newAct->setStatusTip(tr("Create a new file"));
// connect(newAct, &QAction::triggered, this, &MainWindow::newFile);
// fileMenu->addAction(newAct);
// Add file option: 'Open..."
QAction *openAct = new QAction(tr("&Open..."), this);
openAct->setShortcuts(QKeySequence::Open);
openAct->setStatusTip(tr("Open an existing file"));
connect(openAct, &QAction::triggered, this, &MainWindow::open);
fileMenu->addAction(openAct);
}
void MainWindow::open() {
QString fileName = QFileDialog::getOpenFileName(this);
if(!fileName.isEmpty()) {
targets = Analyser::Static::GetTargets(fileName.toStdString());
if(targets.empty()) {
qDebug() << "Not media:" << fileName;
} else {
qDebug() << "Got media:" << fileName;
launchMachine();
}
}
}
MainWindow::~MainWindow() {
// Stop the timer by asking its QThread to exit and
// waiting for it to do so.
timerThread->exit();
while(timerThread->isRunning());
}
// MARK: Machine launch.
namespace {
std::unique_ptr<std::vector<uint8_t>> fileContentsAndClose(FILE *file) {
auto data = std::make_unique<std::vector<uint8_t>>();
fseek(file, 0, SEEK_END);
data->resize(std::ftell(file));
fseek(file, 0, SEEK_SET);
size_t read = fread(data->data(), 1, data->size(), file);
fclose(file);
if(read == data->size()) {
return data;
}
return nullptr;
}
}
void MainWindow::launchMachine() {
const QStringList appDataLocations = QStandardPaths::standardLocations(QStandardPaths::AppDataLocation);
missingRoms.clear();
ROMMachine::ROMFetcher rom_fetcher = [&appDataLocations, this]
(const std::vector<ROMMachine::ROM> &roms) -> std::vector<std::unique_ptr<std::vector<uint8_t>>> {
std::vector<std::unique_ptr<std::vector<uint8_t>>> results;
for(const auto &rom: roms) {
FILE *file = nullptr;
for(const auto &path: appDataLocations) {
const std::string source = path.toStdString() + "/ROMImages/" + rom.machine_name + "/" + rom.file_name;
const std::string nativeSource = QDir::toNativeSeparators(QString::fromStdString(source)).toStdString();
qDebug() << "Taking a run at " << nativeSource.c_str();
file = fopen(nativeSource.c_str(), "rb");
if(file) break;
}
if(file) {
auto data = fileContentsAndClose(file);
if(data) {
results.push_back(std::move(data));
continue;
}
}
results.push_back(nullptr);
missingRoms.push_back(rom);
}
return results;
};
Machine::Error error;
machine.reset(Machine::MachineForTargets(targets, rom_fetcher, error));
switch(error) {
default: {
// TODO: correct assumptions herein that this is the first machine to be
// assigned to this window.
ui->missingROMsBox->setVisible(false);
uiPhase = UIPhase::RunningMachine;
// Install user-friendly options. TODO: plus user overrides.
// const auto configurable = machine->configurable_device();
// if(configurable) {
// configurable->set_options(configurable->get_options());
// }
// Supply the scan target.
// TODO: in the future, hypothetically, deal with non-scan producers.
const auto scan_producer = machine->scan_producer();
if(scan_producer) {
scan_producer->set_scan_target(ui->openGLWidget->getScanTarget());
}
// Install audio output if required.
const auto audio_producer = machine->audio_producer();
if(audio_producer) {
const auto speaker = audio_producer->get_speaker();
if(speaker) {
const QAudioDeviceInfo &defaultDeviceInfo = QAudioDeviceInfo::defaultOutputDevice();
QAudioFormat idealFormat = defaultDeviceInfo.preferredFormat();
// Use the ideal format's sample rate, provide stereo as long as at least two channels
// are available, and — at least for now — assume 512 samples/buffer is a good size.
audioIsStereo = (idealFormat.channelCount() > 1) && speaker->get_is_stereo();
audioIs8bit = idealFormat.sampleSize() < 16;
const int samplesPerBuffer = 65536;
speaker->set_output_rate(idealFormat.sampleRate(), samplesPerBuffer, audioIsStereo);
// Adjust format appropriately, and create an audio output.
idealFormat.setChannelCount(1 + int(audioIsStereo));
idealFormat.setSampleSize(audioIs8bit ? 8 : 16);
audioOutput = std::make_unique<QAudioOutput>(idealFormat, this);
audioOutput->setBufferSize(samplesPerBuffer * (audioIsStereo ? 2 : 1) * (audioIs8bit ? 1 : 2));
qDebug() << idealFormat;
// Start the output.
speaker->set_delegate(this);
audioIODevice = audioOutput->start();
}
}
// If this is a timed machine, start up the timer.
const auto timedMachine = machine->timed_machine();
if(timedMachine) {
timer->setMachine(timedMachine, &machineMutex);
timerThread->start();
qTimer->start();
}
} break;
case Machine::Error::MissingROM: {
ui->missingROMsBox->setVisible(true);
uiPhase = UIPhase::RequestingROMs;
// Populate request text.
QString requestText = romRequestBaseText;
size_t index = 0;
for(const auto rom: missingRoms) {
requestText += "• ";
requestText += rom.descriptive_name.c_str();
++index;
if(index == missingRoms.size()) {
requestText += ".\n";
continue;
}
if(index == missingRoms.size() - 1) {
requestText += "; and\n";
continue;
}
requestText += ";\n";
}
ui->missingROMsBox->setPlainText(requestText);
} break;
}
}
void MainWindow::speaker_did_complete_samples(Outputs::Speaker::Speaker *, const std::vector<int16_t> &buffer) {
// Forward this buffrer to the QThread that QAudioOutput lives on.
AudioEvent *event = new AudioEvent;
event->audio = buffer;
QApplication::instance()->postEvent(this, event);
// const auto bytesWritten = audioIODevice->write(reinterpret_cast<const char *>(buffer.data()), qint64(buffer.size()));
// qDebug() << bytesWritten << "; " << audioOutput->state();
// (void)bytesWritten;
}
void MainWindow::dragEnterEvent(QDragEnterEvent* event) {
// Always accept dragged files.
if(event->mimeData()->hasUrls())
event->accept();
}
void MainWindow::dropEvent(QDropEvent* event) {
if(!event->mimeData()->hasUrls()) {
return;
}
event->accept();
switch(uiPhase) {
case UIPhase::NoFileSelected:
// Treat exactly as a File -> Open... .
break;
case UIPhase::RequestingROMs: {
// Attempt to match up the dragged files to the requested ROM list;
// if and when they match, copy to a writeable QStandardPaths::AppDataLocation
// and try launchMachine() again.
bool foundROM = false;
const auto appDataLocation = QStandardPaths::writableLocation(QStandardPaths::AppDataLocation).toStdString();
for(const auto &url: event->mimeData()->urls()) {
const char *const name = url.toLocalFile().toUtf8();
FILE *const file = fopen(name, "rb");
const auto contents = fileContentsAndClose(file);
if(!contents) continue;
CRC::CRC32 generator;
const uint32_t crc = generator.compute_crc(*contents);
for(const auto &rom: missingRoms) {
if(std::find(rom.crc32s.begin(), rom.crc32s.end(), crc) != rom.crc32s.end()) {
foundROM = true;
// Ensure the destination folder exists.
const std::string path = appDataLocation + "/ROMImages/" + rom.machine_name;
QDir dir(QString::fromStdString(path));
if (!dir.exists())
dir.mkpath(".");
// Write into place.
const std::string destination = QDir::toNativeSeparators(QString::fromStdString(path+ "/" + rom.file_name)).toStdString();
FILE *const target = fopen(destination.c_str(), "wb");
fwrite(contents->data(), 1, contents->size(), target);
fclose(target);
}
}
}
if(foundROM) launchMachine();
} break;
case UIPhase::RunningMachine:
// Attempt to insert into the running machine.
qDebug() << "Should start machine";
break;
}
}
// MARK: Input capture.
bool MainWindow::eventFilter(QObject *obj, QEvent *event) {
switch(event->type()) {
case QEvent::KeyPress:
case QEvent::KeyRelease: {
const auto keyEvent = static_cast<QKeyEvent *>(event);
if(!processEvent(keyEvent)) {
return false;
}
} break;
case QEvent::User: {
const auto audioEvent = dynamic_cast<AudioEvent *>(event);
if(audioEvent) {
audioIODevice->write(reinterpret_cast<const char *>(audioEvent->audio.data()), qint64(audioEvent->audio.size()));
}
} break;
default:
break;
}
return QObject::eventFilter(obj, event);
}
bool MainWindow::processEvent(QKeyEvent *event) {
if(!machine) return true;
// First version: support keyboard input only.
const auto keyboardMachine = machine->keyboard_machine();
if(!keyboardMachine) return true;
#define BIND2(qtKey, clkKey) case Qt::qtKey: key = Inputs::Keyboard::Key::clkKey; break;
#define BIND(key) BIND2(Key_##key, key)
Inputs::Keyboard::Key key;
switch(event->key()) {
default: return true;
BIND(Escape);
BIND(F1); BIND(F2); BIND(F3); BIND(F4); BIND(F5); BIND(F6);
BIND(F7); BIND(F8); BIND(F9); BIND(F10); BIND(F11); BIND(F12);
BIND2(Key_Print, PrintScreen);
BIND(ScrollLock); BIND(Pause);
BIND2(Key_AsciiTilde, BackTick);
BIND2(Key_1, k1); BIND2(Key_2, k2); BIND2(Key_3, k3); BIND2(Key_4, k4); BIND2(Key_5, k5);
BIND2(Key_6, k6); BIND2(Key_7, k7); BIND2(Key_8, k8); BIND2(Key_9, k9); BIND2(Key_0, k0);
BIND2(Key_Minus, Hyphen);
BIND2(Key_Plus, Equals);
BIND(Backspace);
BIND(Tab); BIND(Q); BIND(W); BIND(E); BIND(R); BIND(T); BIND(Y);
BIND(U); BIND(I); BIND(O); BIND(P);
BIND2(Key_BraceLeft, OpenSquareBracket);
BIND2(Key_BraceRight, CloseSquareBracket);
BIND(Backslash);
BIND(CapsLock); BIND(A); BIND(S); BIND(D); BIND(F); BIND(G);
BIND(H); BIND(J); BIND(K); BIND(L);
BIND(Semicolon);
BIND2(Key_QuoteDbl, Quote);
// TODO: something to hash?
BIND2(Key_Return, Enter);
BIND2(Key_Shift, LeftShift);
BIND(Z); BIND(X); BIND(C); BIND(V);
BIND(B); BIND(N); BIND(M);
BIND(Comma);
BIND2(Key_Period, FullStop);
BIND2(Key_Slash, ForwardSlash);
// Omitted: right shift.
BIND2(Key_Control, LeftControl);
BIND2(Key_Alt, LeftOption);
BIND2(Key_Meta, LeftMeta);
BIND(Space);
BIND2(Key_AltGr, RightOption);
BIND(Left); BIND(Right); BIND(Up); BIND(Down);
BIND(Insert); BIND(Home); BIND(PageUp); BIND(Delete); BIND(End); BIND(PageDown);
BIND(NumLock);
}
std::unique_lock lock(machineMutex);
keyboardMachine->get_keyboard().set_key_pressed(key, event->text()[0].toLatin1(), event->type() == QEvent::KeyPress);
return true;
}
<|endoftext|>
|
<commit_before>#include <netdb.h>
#include <stdio.h>
#include <string.h>
#include <arpa/inet.h>
#include <iostream>
#include <string>
#include <boost/unordered_map.hpp>
#include "config.hpp"
#include "pid.hpp"
#include "process.hpp"
using std::istream;
using std::ostream;
using std::size_t;
using std::string;
namespace process {
UPID::UPID(const char* s)
{
std::istringstream in(s);
in >> *this;
}
UPID::UPID(const std::string& s)
{
std::istringstream in(s);
in >> *this;
}
// TODO(benh): Make this inline-able (cyclic dependency issues).
UPID::UPID(const ProcessBase& process)
{
id = process.self().id;
ip = process.self().ip;
port = process.self().port;
}
UPID::operator std::string() const
{
std::ostringstream out;
out << *this;
return out.str();
}
ostream& operator << (ostream& stream, const UPID& pid)
{
// Call inet_ntop since inet_ntoa is not thread-safe!
char ip[INET_ADDRSTRLEN];
if (inet_ntop(AF_INET, (in_addr *) &pid.ip, ip, INET_ADDRSTRLEN) == NULL)
memset(ip, 0, INET_ADDRSTRLEN);
stream << pid.id << "@" << ip << ":" << pid.port;
return stream;
}
istream& operator >> (istream& stream, UPID& pid)
{
pid.id = "";
pid.ip = 0;
pid.port = 0;
string str;
if (!(stream >> str)) {
stream.setstate(std::ios_base::badbit);
return stream;
}
if (str.size() > 512) {
stream.setstate(std::ios_base::badbit);
return stream;
}
string id;
string host;
unsigned short port;
size_t index = str.find('@');
if (index != string::npos) {
id = str.substr(0, index);
} else {
stream.setstate(std::ios_base::badbit);
return stream;
}
str = str.substr(index + 1, str.size() - index);
index = str.find(':');
if (index != string::npos) {
host = str.substr(0, index);
} else {
stream.setstate(std::ios_base::badbit);
return stream;
}
hostent *he = gethostbyname2(host.c_str(), AF_INET);
if (!he) {
stream.setstate(std::ios_base::badbit);
return stream;
}
str = str.substr(index + 1, str.size() - index);
if (sscanf(str.c_str(), "%hu", &port) != 1) {
stream.setstate(std::ios_base::badbit);
return stream;
}
pid.id = id;
pid.ip = *((uint32_t *) he->h_addr);
pid.port = port;
return stream;
}
size_t hash_value(const UPID& pid)
{
size_t seed = 0;
boost::hash_combine(seed, pid.id);
boost::hash_combine(seed, pid.ip);
boost::hash_combine(seed, pid.port);
return seed;
}
} // namespace process {
<commit_msg>Updated parsing of pids to account for bad DNS resolutions (e.g., sometimes DNS fails and will return nothing).<commit_after>#include <netdb.h>
#include <stdio.h>
#include <string.h>
#include <arpa/inet.h>
#include <iostream>
#include <string>
#include <boost/unordered_map.hpp>
#include "config.hpp"
#include "pid.hpp"
#include "process.hpp"
using std::istream;
using std::ostream;
using std::size_t;
using std::string;
namespace process {
UPID::UPID(const char* s)
{
std::istringstream in(s);
in >> *this;
}
UPID::UPID(const std::string& s)
{
std::istringstream in(s);
in >> *this;
}
// TODO(benh): Make this inline-able (cyclic dependency issues).
UPID::UPID(const ProcessBase& process)
{
id = process.self().id;
ip = process.self().ip;
port = process.self().port;
}
UPID::operator std::string() const
{
std::ostringstream out;
out << *this;
return out.str();
}
ostream& operator << (ostream& stream, const UPID& pid)
{
// Call inet_ntop since inet_ntoa is not thread-safe!
char ip[INET_ADDRSTRLEN];
if (inet_ntop(AF_INET, (in_addr *) &pid.ip, ip, INET_ADDRSTRLEN) == NULL)
memset(ip, 0, INET_ADDRSTRLEN);
stream << pid.id << "@" << ip << ":" << pid.port;
return stream;
}
istream& operator >> (istream& stream, UPID& pid)
{
pid.id = "";
pid.ip = 0;
pid.port = 0;
string str;
if (!(stream >> str)) {
stream.setstate(std::ios_base::badbit);
return stream;
}
if (str.size() == 0) {
stream.setstate(std::ios_base::badbit);
return stream;
}
string id;
string host;
unsigned short port;
size_t index = str.find('@');
if (index != string::npos) {
id = str.substr(0, index);
} else {
stream.setstate(std::ios_base::badbit);
return stream;
}
str = str.substr(index + 1, str.size() - index);
index = str.find(':');
if (index != string::npos) {
host = str.substr(0, index);
} else {
stream.setstate(std::ios_base::badbit);
return stream;
}
hostent* he = gethostbyname2(host.c_str(), AF_INET);
if (he == NULL) {
stream.setstate(std::ios_base::badbit);
return stream;
}
if (he->h_addr_list[0] == NULL) {
stream.setstate(std::ios_base::badbit);
return stream;
}
str = str.substr(index + 1, str.size() - index);
if (sscanf(str.c_str(), "%hu", &port) != 1) {
stream.setstate(std::ios_base::badbit);
return stream;
}
pid.id = id;
pid.ip = *((uint32_t*) he->h_addr_list[0]);
pid.port = port;
return stream;
}
size_t hash_value(const UPID& pid)
{
size_t seed = 0;
boost::hash_combine(seed, pid.id);
boost::hash_combine(seed, pid.ip);
boost::hash_combine(seed, pid.port);
return seed;
}
} // namespace process {
<|endoftext|>
|
<commit_before>/*********************************************************************
* Software License Agreement (BSD License)
*
* Copyright (c) 2011, Willow Garage, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
* * Neither the name of Willow Garage nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*********************************************************************/
/* Author: Ioan Sucan */
#include <moveit/planning_scene_monitor/current_state_monitor.h>
#include <tf_conversions/tf_eigen.h>
#include <limits>
planning_scene_monitor::CurrentStateMonitor::CurrentStateMonitor(const robot_model::RobotModelConstPtr &robot_model, const boost::shared_ptr<tf::Transformer> &tf)
: tf_(tf)
, robot_model_(robot_model)
, robot_state_(robot_model)
, state_monitor_started_(false)
, error_(std::numeric_limits<float>::epsilon())
{
robot_state_.setToDefaultValues();
}
planning_scene_monitor::CurrentStateMonitor::~CurrentStateMonitor()
{
stopStateMonitor();
}
robot_state::RobotStatePtr planning_scene_monitor::CurrentStateMonitor::getCurrentState() const
{
boost::mutex::scoped_lock slock(state_update_lock_);
robot_state::RobotState *result = new robot_state::RobotState(robot_state_);
return robot_state::RobotStatePtr(result);
}
ros::Time planning_scene_monitor::CurrentStateMonitor::getCurrentStateTime() const
{
boost::mutex::scoped_lock slock(state_update_lock_);
return current_state_time_;
}
std::pair<robot_state::RobotStatePtr, ros::Time> planning_scene_monitor::CurrentStateMonitor::getCurrentStateAndTime() const
{
boost::mutex::scoped_lock slock(state_update_lock_);
robot_state::RobotState *result = new robot_state::RobotState(robot_state_);
return std::make_pair(robot_state::RobotStatePtr(result), current_state_time_);
}
std::map<std::string, double> planning_scene_monitor::CurrentStateMonitor::getCurrentStateValues() const
{
std::map<std::string, double> m;
boost::mutex::scoped_lock slock(state_update_lock_);
const double *pos = robot_state_.getVariablePositions();
const std::vector<std::string> &names = robot_state_.getVariableNames();
for (std::size_t i = 0 ; i < names.size() ; ++i)
m[names[i]] = pos[i];
return m;
}
void planning_scene_monitor::CurrentStateMonitor::setToCurrentState(robot_state::RobotState &upd) const
{
boost::mutex::scoped_lock slock(state_update_lock_);
upd = robot_state_;
}
void planning_scene_monitor::CurrentStateMonitor::addUpdateCallback(const JointStateUpdateCallback &fn)
{
if (fn)
update_callbacks_.push_back(fn);
}
void planning_scene_monitor::CurrentStateMonitor::clearUpdateCallbacks()
{
update_callbacks_.clear();
}
void planning_scene_monitor::CurrentStateMonitor::startStateMonitor(const std::string &joint_states_topic)
{
if (!state_monitor_started_ && robot_model_)
{
joint_time_.clear();
if (joint_states_topic.empty())
ROS_ERROR("The joint states topic cannot be an empty string");
else
joint_state_subscriber_ = nh_.subscribe(joint_states_topic, 25, &CurrentStateMonitor::jointStateCallback, this);
state_monitor_started_ = true;
monitor_start_time_ = ros::Time::now();
ROS_DEBUG("Listening to joint states on topic '%s'", nh_.resolveName(joint_states_topic).c_str());
}
}
bool planning_scene_monitor::CurrentStateMonitor::isActive() const
{
return state_monitor_started_;
}
void planning_scene_monitor::CurrentStateMonitor::stopStateMonitor()
{
if (state_monitor_started_)
{
joint_state_subscriber_.shutdown();
ROS_DEBUG("No longer listening o joint states");
state_monitor_started_ = false;
}
}
std::string planning_scene_monitor::CurrentStateMonitor::getMonitoredTopic() const
{
if (joint_state_subscriber_)
return joint_state_subscriber_.getTopic();
else
return "";
}
bool planning_scene_monitor::CurrentStateMonitor::isPassiveDOF(const std::string &dof) const
{
if (robot_model_->hasJointModel(dof))
{
if (robot_model_->getJointModel(dof)->isPassive())
return true;
}
else
{
// check if this DOF is part of a multi-dof passive joint
std::size_t slash = dof.find_last_of("/");
if (slash != std::string::npos)
{
std::string joint_name = dof.substr(0, slash);
if (robot_model_->hasJointModel(joint_name))
if (robot_model_->getJointModel(joint_name)->isPassive())
return true;
}
}
return false;
}
bool planning_scene_monitor::CurrentStateMonitor::haveCompleteState() const
{
bool result = true;
const std::vector<std::string> &dof = robot_model_->getVariableNames();
boost::mutex::scoped_lock slock(state_update_lock_);
for (std::size_t i = 0 ; i < dof.size() ; ++i)
if (joint_time_.find(dof[i]) == joint_time_.end())
{
if (!isPassiveDOF(dof[i]))
{
ROS_DEBUG("Joint variable '%s' has never been updated", dof[i].c_str());
result = false;
}
}
return result;
}
bool planning_scene_monitor::CurrentStateMonitor::haveCompleteState(std::vector<std::string> &missing_states) const
{
bool result = true;
const std::vector<std::string> &dof = robot_model_->getVariableNames();
boost::mutex::scoped_lock slock(state_update_lock_);
for (std::size_t i = 0 ; i < dof.size() ; ++i)
if (joint_time_.find(dof[i]) == joint_time_.end())
if (!isPassiveDOF(dof[i]))
{
ROS_DEBUG("Joint variable '%s' has never been updated", dof[i].c_str());
missing_states.push_back(dof[i]);
result = false;
}
return result;
}
bool planning_scene_monitor::CurrentStateMonitor::haveCompleteState(const ros::Duration &age) const
{
bool result = true;
const std::vector<std::string> &dof = robot_model_->getVariableNames();
ros::Time now = ros::Time::now();
ros::Time old = now - age;
boost::mutex::scoped_lock slock(state_update_lock_);
for (std::size_t i = 0 ; i < dof.size() ; ++i)
{
if (isPassiveDOF(dof[i]))
continue;
std::map<std::string, ros::Time>::const_iterator it = joint_time_.find(dof[i]);
if (it == joint_time_.end())
{
ROS_DEBUG("Joint variable '%s' has never been updated", dof[i].c_str());
result = false;
}
else
if (it->second < old)
{
ROS_DEBUG("Joint variable '%s' was last updated %0.3lf seconds ago (older than the allowed %0.3lf seconds)",
dof[i].c_str(), (now - it->second).toSec(), age.toSec());
result = false;
}
}
return result;
}
bool planning_scene_monitor::CurrentStateMonitor::haveCompleteState(const ros::Duration &age,
std::vector<std::string> &missing_states) const
{
bool result = true;
const std::vector<std::string> &dof = robot_model_->getVariableNames();
ros::Time now = ros::Time::now();
ros::Time old = now - age;
boost::mutex::scoped_lock slock(state_update_lock_);
for (std::size_t i = 0 ; i < dof.size() ; ++i)
{
if (isPassiveDOF(dof[i]))
continue;
std::map<std::string, ros::Time>::const_iterator it = joint_time_.find(dof[i]);
if (it == joint_time_.end())
{
ROS_DEBUG("Joint variable '%s' has never been updated", dof[i].c_str());
missing_states.push_back(dof[i]);
result = false;
}
else
if (it->second < old)
{
ROS_DEBUG("Joint variable '%s' was last updated %0.3lf seconds ago (older than the allowed %0.3lf seconds)",
dof[i].c_str(), (now - it->second).toSec(), age.toSec());
missing_states.push_back(dof[i]);
result = false;
}
}
return result;
}
bool planning_scene_monitor::CurrentStateMonitor::waitForCurrentState(double wait_time) const
{
double slept_time = 0.0;
double sleep_step_s = std::min(0.05, wait_time / 10.0);
ros::Duration sleep_step(sleep_step_s);
while (!haveCompleteState() && slept_time < wait_time)
{
sleep_step.sleep();
slept_time += sleep_step_s;
}
return haveCompleteState();
}
bool planning_scene_monitor::CurrentStateMonitor::waitForCurrentState(const std::string &group, double wait_time) const
{
if (waitForCurrentState(wait_time))
return true;
bool ok = true;
// check to see if we have a fully known state for the joints we want to record
std::vector<std::string> missing_joints;
if (!haveCompleteState(missing_joints))
{
const robot_model::JointModelGroup *jmg = robot_model_->getJointModelGroup(group);
if (jmg)
{
std::set<std::string> mj;
mj.insert(missing_joints.begin(), missing_joints.end());
const std::vector<std::string> &names= jmg->getJointModelNames();
bool ok = true;
for (std::size_t i = 0 ; ok && i < names.size() ; ++i)
if (mj.find(names[i]) != mj.end())
ok = false;
}
else
ok = false;
}
return ok;
}
void planning_scene_monitor::CurrentStateMonitor::jointStateCallback(const sensor_msgs::JointStateConstPtr &joint_state)
{
if (joint_state->name.size() != joint_state->position.size())
{
ROS_ERROR_THROTTLE(1, "State monitor received invalid joint state (number of joint names does not match number of positions)");
return;
}
{
boost::mutex::scoped_lock _(state_update_lock_);
// read the received values, and update their time stamps
std::size_t n = joint_state->name.size();
current_state_time_ = joint_state->header.stamp;
for (std::size_t i = 0 ; i < n ; ++i)
{
const robot_model::JointModel* jm = robot_model_->getJointModel(joint_state->name[i]);
if (!jm)
continue;
// ignore fixed joints, multi-dof joints (they should not even be in the message)
if (jm->getVariableCount() != 1)
continue;
robot_state_.setJointPositions(jm, &(joint_state->position[i]));
joint_time_[joint_state->name[i]] = joint_state->header.stamp;
// continuous joints wrap, so we don't modify them (even if they are outside bounds!)
if (jm->getType() == robot_model::JointModel::REVOLUTE)
if (static_cast<const robot_model::RevoluteJointModel*>(jm)->isContinuous())
continue;
const robot_model::VariableBounds &b = jm->getVariableBounds()[0]; // only one variable in the joint, so we get its bounds
// if the read variable is 'almost' within bounds (up to error_ difference), then consider it to be within bounds
if (joint_state->position[i] < b.min_position_ && joint_state->position[i] >= b.min_position_ - error_)
robot_state_.setJointPositions(jm, &b.min_position_);
else
if (joint_state->position[i] > b.max_position_ && joint_state->position[i] <= b.max_position_ + error_)
robot_state_.setJointPositions(jm, &b.max_position_);
}
// read root transform, if needed
if (tf_ && (robot_model_->getRootJoint()->getType() == robot_model::JointModel::PLANAR ||
robot_model_->getRootJoint()->getType() == robot_model::JointModel::FLOATING))
{
const std::string &child_frame = robot_model_->getRootLink()->getName();
const std::string &parent_frame = robot_model_->getModelFrame();
std::string err;
ros::Time tm;
tf::StampedTransform transf;
bool ok = false;
if (tf_->getLatestCommonTime(parent_frame, child_frame, tm, &err) == tf::NO_ERROR)
{
try
{
tf_->lookupTransform(parent_frame, child_frame, tm, transf);
ok = true;
}
catch(tf::TransformException& ex)
{
ROS_ERROR_THROTTLE(1, "Unable to lookup transform from %s to %s. Exception: %s", parent_frame.c_str(), child_frame.c_str(), ex.what());
}
}
else
ROS_DEBUG_THROTTLE(1, "Unable to lookup transform from %s to %s: no common time.", parent_frame.c_str(), child_frame.c_str());
if (ok)
{
const std::vector<std::string> &vars = robot_model_->getRootJoint()->getVariableNames();
for (std::size_t j = 0; j < vars.size() ; ++j)
joint_time_[vars[j]] = tm;
Eigen::Affine3d eigen_transf;
tf::transformTFToEigen(transf, eigen_transf);
robot_state_.setJointPositions(robot_model_->getRootJoint(), eigen_transf);
}
}
}
// callbacks, if needed
for (std::size_t i = 0 ; i < update_callbacks_.size() ; ++i)
update_callbacks_[i](joint_state);
}
<commit_msg>Removed misleading and duplicate debug message<commit_after>/*********************************************************************
* Software License Agreement (BSD License)
*
* Copyright (c) 2011, Willow Garage, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
* * Neither the name of Willow Garage nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*********************************************************************/
/* Author: Ioan Sucan */
#include <moveit/planning_scene_monitor/current_state_monitor.h>
#include <tf_conversions/tf_eigen.h>
#include <limits>
planning_scene_monitor::CurrentStateMonitor::CurrentStateMonitor(const robot_model::RobotModelConstPtr &robot_model, const boost::shared_ptr<tf::Transformer> &tf)
: tf_(tf)
, robot_model_(robot_model)
, robot_state_(robot_model)
, state_monitor_started_(false)
, error_(std::numeric_limits<float>::epsilon())
{
robot_state_.setToDefaultValues();
}
planning_scene_monitor::CurrentStateMonitor::~CurrentStateMonitor()
{
stopStateMonitor();
}
robot_state::RobotStatePtr planning_scene_monitor::CurrentStateMonitor::getCurrentState() const
{
boost::mutex::scoped_lock slock(state_update_lock_);
robot_state::RobotState *result = new robot_state::RobotState(robot_state_);
return robot_state::RobotStatePtr(result);
}
ros::Time planning_scene_monitor::CurrentStateMonitor::getCurrentStateTime() const
{
boost::mutex::scoped_lock slock(state_update_lock_);
return current_state_time_;
}
std::pair<robot_state::RobotStatePtr, ros::Time> planning_scene_monitor::CurrentStateMonitor::getCurrentStateAndTime() const
{
boost::mutex::scoped_lock slock(state_update_lock_);
robot_state::RobotState *result = new robot_state::RobotState(robot_state_);
return std::make_pair(robot_state::RobotStatePtr(result), current_state_time_);
}
std::map<std::string, double> planning_scene_monitor::CurrentStateMonitor::getCurrentStateValues() const
{
std::map<std::string, double> m;
boost::mutex::scoped_lock slock(state_update_lock_);
const double *pos = robot_state_.getVariablePositions();
const std::vector<std::string> &names = robot_state_.getVariableNames();
for (std::size_t i = 0 ; i < names.size() ; ++i)
m[names[i]] = pos[i];
return m;
}
void planning_scene_monitor::CurrentStateMonitor::setToCurrentState(robot_state::RobotState &upd) const
{
boost::mutex::scoped_lock slock(state_update_lock_);
upd = robot_state_;
}
void planning_scene_monitor::CurrentStateMonitor::addUpdateCallback(const JointStateUpdateCallback &fn)
{
if (fn)
update_callbacks_.push_back(fn);
}
void planning_scene_monitor::CurrentStateMonitor::clearUpdateCallbacks()
{
update_callbacks_.clear();
}
void planning_scene_monitor::CurrentStateMonitor::startStateMonitor(const std::string &joint_states_topic)
{
if (!state_monitor_started_ && robot_model_)
{
joint_time_.clear();
if (joint_states_topic.empty())
ROS_ERROR("The joint states topic cannot be an empty string");
else
joint_state_subscriber_ = nh_.subscribe(joint_states_topic, 25, &CurrentStateMonitor::jointStateCallback, this);
state_monitor_started_ = true;
monitor_start_time_ = ros::Time::now();
ROS_DEBUG("Listening to joint states on topic '%s'", nh_.resolveName(joint_states_topic).c_str());
}
}
bool planning_scene_monitor::CurrentStateMonitor::isActive() const
{
return state_monitor_started_;
}
void planning_scene_monitor::CurrentStateMonitor::stopStateMonitor()
{
if (state_monitor_started_)
{
joint_state_subscriber_.shutdown();
ROS_DEBUG("No longer listening o joint states");
state_monitor_started_ = false;
}
}
std::string planning_scene_monitor::CurrentStateMonitor::getMonitoredTopic() const
{
if (joint_state_subscriber_)
return joint_state_subscriber_.getTopic();
else
return "";
}
bool planning_scene_monitor::CurrentStateMonitor::isPassiveDOF(const std::string &dof) const
{
if (robot_model_->hasJointModel(dof))
{
if (robot_model_->getJointModel(dof)->isPassive())
return true;
}
else
{
// check if this DOF is part of a multi-dof passive joint
std::size_t slash = dof.find_last_of("/");
if (slash != std::string::npos)
{
std::string joint_name = dof.substr(0, slash);
if (robot_model_->hasJointModel(joint_name))
if (robot_model_->getJointModel(joint_name)->isPassive())
return true;
}
}
return false;
}
bool planning_scene_monitor::CurrentStateMonitor::haveCompleteState() const
{
bool result = true;
const std::vector<std::string> &dof = robot_model_->getVariableNames();
boost::mutex::scoped_lock slock(state_update_lock_);
for (std::size_t i = 0 ; i < dof.size() ; ++i)
if (joint_time_.find(dof[i]) == joint_time_.end())
{
if (!isPassiveDOF(dof[i]))
{
ROS_DEBUG("Joint variable '%s' has never been updated", dof[i].c_str());
result = false;
}
}
return result;
}
bool planning_scene_monitor::CurrentStateMonitor::haveCompleteState(std::vector<std::string> &missing_states) const
{
bool result = true;
const std::vector<std::string> &dof = robot_model_->getVariableNames();
boost::mutex::scoped_lock slock(state_update_lock_);
for (std::size_t i = 0 ; i < dof.size() ; ++i)
if (joint_time_.find(dof[i]) == joint_time_.end())
if (!isPassiveDOF(dof[i]))
{
missing_states.push_back(dof[i]);
result = false;
}
return result;
}
bool planning_scene_monitor::CurrentStateMonitor::haveCompleteState(const ros::Duration &age) const
{
bool result = true;
const std::vector<std::string> &dof = robot_model_->getVariableNames();
ros::Time now = ros::Time::now();
ros::Time old = now - age;
boost::mutex::scoped_lock slock(state_update_lock_);
for (std::size_t i = 0 ; i < dof.size() ; ++i)
{
if (isPassiveDOF(dof[i]))
continue;
std::map<std::string, ros::Time>::const_iterator it = joint_time_.find(dof[i]);
if (it == joint_time_.end())
{
ROS_DEBUG("Joint variable '%s' has never been updated", dof[i].c_str());
result = false;
}
else
if (it->second < old)
{
ROS_DEBUG("Joint variable '%s' was last updated %0.3lf seconds ago (older than the allowed %0.3lf seconds)",
dof[i].c_str(), (now - it->second).toSec(), age.toSec());
result = false;
}
}
return result;
}
bool planning_scene_monitor::CurrentStateMonitor::haveCompleteState(const ros::Duration &age,
std::vector<std::string> &missing_states) const
{
bool result = true;
const std::vector<std::string> &dof = robot_model_->getVariableNames();
ros::Time now = ros::Time::now();
ros::Time old = now - age;
boost::mutex::scoped_lock slock(state_update_lock_);
for (std::size_t i = 0 ; i < dof.size() ; ++i)
{
if (isPassiveDOF(dof[i]))
continue;
std::map<std::string, ros::Time>::const_iterator it = joint_time_.find(dof[i]);
if (it == joint_time_.end())
{
ROS_DEBUG("Joint variable '%s' has never been updated", dof[i].c_str());
missing_states.push_back(dof[i]);
result = false;
}
else
if (it->second < old)
{
ROS_DEBUG("Joint variable '%s' was last updated %0.3lf seconds ago (older than the allowed %0.3lf seconds)",
dof[i].c_str(), (now - it->second).toSec(), age.toSec());
missing_states.push_back(dof[i]);
result = false;
}
}
return result;
}
bool planning_scene_monitor::CurrentStateMonitor::waitForCurrentState(double wait_time) const
{
double slept_time = 0.0;
double sleep_step_s = std::min(0.05, wait_time / 10.0);
ros::Duration sleep_step(sleep_step_s);
while (!haveCompleteState() && slept_time < wait_time)
{
sleep_step.sleep();
slept_time += sleep_step_s;
}
return haveCompleteState();
}
bool planning_scene_monitor::CurrentStateMonitor::waitForCurrentState(const std::string &group, double wait_time) const
{
if (waitForCurrentState(wait_time))
return true;
bool ok = true;
// check to see if we have a fully known state for the joints we want to record
std::vector<std::string> missing_joints;
if (!haveCompleteState(missing_joints))
{
const robot_model::JointModelGroup *jmg = robot_model_->getJointModelGroup(group);
if (jmg)
{
std::set<std::string> mj;
mj.insert(missing_joints.begin(), missing_joints.end());
const std::vector<std::string> &names= jmg->getJointModelNames();
bool ok = true;
for (std::size_t i = 0 ; ok && i < names.size() ; ++i)
if (mj.find(names[i]) != mj.end())
ok = false;
}
else
ok = false;
}
return ok;
}
void planning_scene_monitor::CurrentStateMonitor::jointStateCallback(const sensor_msgs::JointStateConstPtr &joint_state)
{
if (joint_state->name.size() != joint_state->position.size())
{
ROS_ERROR_THROTTLE(1, "State monitor received invalid joint state (number of joint names does not match number of positions)");
return;
}
{
boost::mutex::scoped_lock _(state_update_lock_);
// read the received values, and update their time stamps
std::size_t n = joint_state->name.size();
current_state_time_ = joint_state->header.stamp;
for (std::size_t i = 0 ; i < n ; ++i)
{
const robot_model::JointModel* jm = robot_model_->getJointModel(joint_state->name[i]);
if (!jm)
continue;
// ignore fixed joints, multi-dof joints (they should not even be in the message)
if (jm->getVariableCount() != 1)
continue;
robot_state_.setJointPositions(jm, &(joint_state->position[i]));
joint_time_[joint_state->name[i]] = joint_state->header.stamp;
// continuous joints wrap, so we don't modify them (even if they are outside bounds!)
if (jm->getType() == robot_model::JointModel::REVOLUTE)
if (static_cast<const robot_model::RevoluteJointModel*>(jm)->isContinuous())
continue;
const robot_model::VariableBounds &b = jm->getVariableBounds()[0]; // only one variable in the joint, so we get its bounds
// if the read variable is 'almost' within bounds (up to error_ difference), then consider it to be within bounds
if (joint_state->position[i] < b.min_position_ && joint_state->position[i] >= b.min_position_ - error_)
robot_state_.setJointPositions(jm, &b.min_position_);
else
if (joint_state->position[i] > b.max_position_ && joint_state->position[i] <= b.max_position_ + error_)
robot_state_.setJointPositions(jm, &b.max_position_);
}
// read root transform, if needed
if (tf_ && (robot_model_->getRootJoint()->getType() == robot_model::JointModel::PLANAR ||
robot_model_->getRootJoint()->getType() == robot_model::JointModel::FLOATING))
{
const std::string &child_frame = robot_model_->getRootLink()->getName();
const std::string &parent_frame = robot_model_->getModelFrame();
std::string err;
ros::Time tm;
tf::StampedTransform transf;
bool ok = false;
if (tf_->getLatestCommonTime(parent_frame, child_frame, tm, &err) == tf::NO_ERROR)
{
try
{
tf_->lookupTransform(parent_frame, child_frame, tm, transf);
ok = true;
}
catch(tf::TransformException& ex)
{
ROS_ERROR_THROTTLE(1, "Unable to lookup transform from %s to %s. Exception: %s", parent_frame.c_str(), child_frame.c_str(), ex.what());
}
}
else
ROS_DEBUG_THROTTLE(1, "Unable to lookup transform from %s to %s: no common time.", parent_frame.c_str(), child_frame.c_str());
if (ok)
{
const std::vector<std::string> &vars = robot_model_->getRootJoint()->getVariableNames();
for (std::size_t j = 0; j < vars.size() ; ++j)
joint_time_[vars[j]] = tm;
Eigen::Affine3d eigen_transf;
tf::transformTFToEigen(transf, eigen_transf);
robot_state_.setJointPositions(robot_model_->getRootJoint(), eigen_transf);
}
}
}
// callbacks, if needed
for (std::size_t i = 0 ; i < update_callbacks_.size() ; ++i)
update_callbacks_[i](joint_state);
}
<|endoftext|>
|
<commit_before>/*****************************************************************************
*
* This file is part of Mapnik (c++ mapping toolkit)
*
* Copyright (C) 2014 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_TIFF_IO_HPP
#define MAPNIK_TIFF_IO_HPP
#include <mapnik/global.hpp>
#include <mapnik/image_util.hpp>
#include <mapnik/image_data_any.hpp>
#include <mapnik/util/variant.hpp>
extern "C"
{
#include <tiffio.h>
#define RealTIFFOpen TIFFClientOpen
#define RealTIFFClose TIFFClose
}
namespace mapnik {
static inline tsize_t tiff_write_proc(thandle_t fd, tdata_t buf, tsize_t size)
{
std::ostream* out = reinterpret_cast<std::ostream*>(fd);
std::ios::pos_type pos = out->tellp();
std::streamsize request_size = size;
if (static_cast<tsize_t>(request_size) != size)
return static_cast<tsize_t>(-1);
out->write(reinterpret_cast<const char*>(buf), size);
if( static_cast<std::streamsize>(pos) == -1 )
{
return size;
}
else
{
return static_cast<tsize_t>(out->tellp()-pos);
}
}
static inline toff_t tiff_seek_proc(thandle_t fd, toff_t off, int whence)
{
std::ostream* out = reinterpret_cast<std::ostream*>(fd);
if( out->fail() )
return static_cast<toff_t>(-1);
if( static_cast<std::streamsize>(out->tellp()) == -1)
return static_cast< toff_t >( 0 );
switch(whence)
{
case SEEK_SET:
out->seekp(off, std::ios_base::beg);
break;
case SEEK_CUR:
out->seekp(off, std::ios_base::cur);
break;
case SEEK_END:
out->seekp(off, std::ios_base::end);
break;
}
// grow std::stringstream buffer (re: libtiff/tif_stream.cxx)
std::ios::pos_type pos = out->tellp();
// second check needed for clang (libcxx doesn't set failbit when seeking beyond the current buffer size
if( out->fail() || static_cast<std::streamoff>(off) != pos)
{
std::ios::iostate old_state;
std::ios::pos_type origin;
old_state = out->rdstate();
// reset the fail bit or else tellp() won't work below
out->clear(out->rdstate() & ~std::ios::failbit);
switch( whence )
{
case SEEK_SET:
default:
origin = 0L;
break;
case SEEK_CUR:
origin = out->tellp();
break;
case SEEK_END:
out->seekp(0, std::ios::end);
origin = out->tellp();
break;
}
// restore original stream state
out->clear(old_state);
// only do something if desired seek position is valid
if( (static_cast<uint64_t>(origin) + off) > 0L)
{
uint64_t num_fill;
// clear the fail bit
out->clear(out->rdstate() & ~std::ios::failbit);
// extend the stream to the expected size
out->seekp(0, std::ios::end);
num_fill = (static_cast<uint64_t>(origin)) + off - out->tellp();
for( uint64_t i = 0; i < num_fill; ++i)
out->put('\0');
// retry the seek
out->seekp(static_cast<std::ios::off_type>(static_cast<uint64_t>(origin) + off), std::ios::beg);
}
}
return static_cast<toff_t>(out->tellp());
}
static inline int tiff_close_proc(thandle_t fd)
{
std::ostream* out = (std::ostream*)fd;
out->flush();
return 0;
}
static inline toff_t tiff_size_proc(thandle_t fd)
{
std::ostream* out = reinterpret_cast<std::ostream*>(fd);
std::ios::pos_type pos = out->tellp();
out->seekp(0, std::ios::end);
std::ios::pos_type len = out->tellp();
out->seekp(pos);
return static_cast<toff_t>(len);
}
static inline tsize_t tiff_dummy_read_proc(thandle_t , tdata_t , tsize_t)
{
return 0;
}
static inline void tiff_dummy_unmap_proc(thandle_t , tdata_t , toff_t) {}
static inline int tiff_dummy_map_proc(thandle_t , tdata_t*, toff_t* )
{
return 0;
}
struct tiff_config
{
tiff_config()
: compression(COMPRESSION_ADOBE_DEFLATE),
zlevel(4),
scanline(false) {}
int compression;
int zlevel;
bool scanline;
};
struct tag_setter : public mapnik::util::static_visitor<>
{
tag_setter(TIFF * output, tiff_config & config)
: output_(output),
config_(config) {}
template <typename T>
void operator() (T const&) const
{
// Assume this would be null type
throw ImageWriterException("Could not write TIFF - unknown image type provided");
}
inline void operator() (image_data_rgba8 const&) const
{
TIFFSetField(output_, TIFFTAG_PHOTOMETRIC, PHOTOMETRIC_RGB);
TIFFSetField(output_, TIFFTAG_SAMPLEFORMAT, SAMPLEFORMAT_UINT);
TIFFSetField(output_, TIFFTAG_BITSPERSAMPLE, 8);
TIFFSetField(output_, TIFFTAG_SAMPLESPERPIXEL, 4);
uint16 extras[] = { EXTRASAMPLE_UNASSALPHA };
TIFFSetField(output_, TIFFTAG_EXTRASAMPLES, 1, extras);
if (config_.compression == COMPRESSION_DEFLATE
|| config_.compression == COMPRESSION_ADOBE_DEFLATE
|| config_.compression == COMPRESSION_LZW)
{
TIFFSetField(output_, TIFFTAG_PREDICTOR, PREDICTOR_HORIZONTAL);
}
}
inline void operator() (image_data_gray32f const&) const
{
TIFFSetField(output_, TIFFTAG_PHOTOMETRIC, PHOTOMETRIC_MINISBLACK);
TIFFSetField(output_, TIFFTAG_SAMPLEFORMAT, SAMPLEFORMAT_IEEEFP);
TIFFSetField(output_, TIFFTAG_BITSPERSAMPLE, 32);
TIFFSetField(output_, TIFFTAG_SAMPLESPERPIXEL, 1);
if (config_.compression == COMPRESSION_DEFLATE
|| config_.compression == COMPRESSION_ADOBE_DEFLATE
|| config_.compression == COMPRESSION_LZW)
{
TIFFSetField(output_, TIFFTAG_PREDICTOR, PREDICTOR_FLOATINGPOINT);
}
}
inline void operator() (image_data_gray16 const&) const
{
TIFFSetField(output_, TIFFTAG_PHOTOMETRIC, PHOTOMETRIC_MINISBLACK);
TIFFSetField(output_, TIFFTAG_SAMPLEFORMAT, SAMPLEFORMAT_UINT);
TIFFSetField(output_, TIFFTAG_BITSPERSAMPLE, 16);
TIFFSetField(output_, TIFFTAG_SAMPLESPERPIXEL, 1);
if (config_.compression == COMPRESSION_DEFLATE
|| config_.compression == COMPRESSION_ADOBE_DEFLATE
|| config_.compression == COMPRESSION_LZW)
{
TIFFSetField(output_, TIFFTAG_PREDICTOR, PREDICTOR_HORIZONTAL);
}
}
inline void operator() (image_data_gray8 const&) const
{
TIFFSetField(output_, TIFFTAG_PHOTOMETRIC, PHOTOMETRIC_MINISBLACK);
TIFFSetField(output_, TIFFTAG_SAMPLEFORMAT, SAMPLEFORMAT_UINT);
TIFFSetField(output_, TIFFTAG_BITSPERSAMPLE, 8);
TIFFSetField(output_, TIFFTAG_SAMPLESPERPIXEL, 1);
if (config_.compression == COMPRESSION_DEFLATE
|| config_.compression == COMPRESSION_ADOBE_DEFLATE
|| config_.compression == COMPRESSION_LZW)
{
TIFFSetField(output_, TIFFTAG_PREDICTOR, PREDICTOR_HORIZONTAL);
}
}
inline void operator() (image_data_null const&) const
{
// Assume this would be null type
throw ImageWriterException("Could not write TIFF - Null image provided");
}
private:
TIFF * output_;
tiff_config config_;
};
void set_tiff_config(TIFF* output, tiff_config & config)
{
// Set some constant tiff information that doesn't vary based on type of data
// or image size
TIFFSetField(output, TIFFTAG_PLANARCONFIG, PLANARCONFIG_CONTIG);
// Set the compression for the TIFF
TIFFSetField(output, TIFFTAG_COMPRESSION, config.compression);
if (COMPRESSION_ADOBE_DEFLATE == config.compression || COMPRESSION_DEFLATE == config.compression)
{
// Set the zip level for the compression
// http://en.wikipedia.org/wiki/DEFLATE#Encoder.2Fcompressor
// Changes the time spent trying to compress
TIFFSetField(output, TIFFTAG_ZIPQUALITY, config.zlevel);
}
}
template <typename T1, typename T2>
void save_as_tiff(T1 & file, T2 const& image, tiff_config & config)
{
using pixel_type = typename T2::pixel_type;
const int width = image.width();
const int height = image.height();
TIFF* output = RealTIFFOpen("mapnik_tiff_stream",
"wm",
(thandle_t)&file,
tiff_dummy_read_proc,
tiff_write_proc,
tiff_seek_proc,
tiff_close_proc,
tiff_size_proc,
tiff_dummy_map_proc,
tiff_dummy_unmap_proc);
if (! output)
{
throw ImageWriterException("Could not write TIFF");
}
TIFFSetField(output, TIFFTAG_IMAGEWIDTH, width);
TIFFSetField(output, TIFFTAG_IMAGELENGTH, height);
TIFFSetField(output, TIFFTAG_IMAGEDEPTH, 1);
set_tiff_config(output, config);
// Set tags that vary based on the type of data being provided.
tag_setter set(output, config);
set(image);
//util::apply_visitor(set, image);
// If the image is greater then 8MB uncompressed, then lets use scanline rather then
// tile. TIFF also requires that all TIFFTAG_TILEWIDTH and TIFF_TILELENGTH all be
// a multiple of 16, if they are not we will use scanline.
if (image.getSize() > 8 * 32 * 1024 * 1024
|| width % 16 != 0
|| height % 16 != 0
|| config.scanline)
{
// Process Scanline
TIFFSetField(output, TIFFTAG_ROWSPERSTRIP, 1);
int next_scanline = 0;
std::unique_ptr<pixel_type[]> row (new pixel_type[image.getRowSize()]);
while (next_scanline < height)
{
memcpy(row.get(), image.getRow(next_scanline), image.getRowSize());
//typename T2::pixel_type * row = const_cast<typename T2::pixel_type *>(image.getRow(next_scanline));
TIFFWriteScanline(output, row.get(), next_scanline, 0);
++next_scanline;
}
}
else
{
TIFFSetField(output, TIFFTAG_TILEWIDTH, width);
TIFFSetField(output, TIFFTAG_TILELENGTH, height);
TIFFSetField(output, TIFFTAG_TILEDEPTH, 1);
// Process as tiles
std::unique_ptr<pixel_type[]> image_data (new pixel_type[image.getSize()]);
memcpy(image_data.get(), image.getData(), image.getSize());
//typename T2::pixel_type * image_data = const_cast<typename T2::pixel_type *>(image.getData());
TIFFWriteTile(output, image_data.get(), 0, 0, 0, 0);
}
// TODO - handle palette images
// std::vector<mapnik::rgb> const& palette
// unsigned short r[256], g[256], b[256];
// for (int i = 0; i < (1 << 24); ++i)
// {
// r[i] = (unsigned short)palette[i * 3 + 0] << 8;
// g[i] = (unsigned short)palette[i * 3 + 1] << 8;
// b[i] = (unsigned short)palette[i * 3 + 2] << 8;
// }
// TIFFSetField(output, TIFFTAG_PHOTOMETRIC, PHOTOMETRIC_PALETTE);
// TIFFSetField(output, TIFFTAG_COLORMAP, r, g, b);
RealTIFFClose(output);
}
}
#endif // MAPNIK_TIFF_IO_HPP
<commit_msg>correct alloc size + prefer std::copy over memcpy<commit_after>/*****************************************************************************
*
* This file is part of Mapnik (c++ mapping toolkit)
*
* Copyright (C) 2014 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_TIFF_IO_HPP
#define MAPNIK_TIFF_IO_HPP
#include <mapnik/global.hpp>
#include <mapnik/image_util.hpp>
#include <mapnik/image_data_any.hpp>
#include <mapnik/util/variant.hpp>
extern "C"
{
#include <tiffio.h>
#define RealTIFFOpen TIFFClientOpen
#define RealTIFFClose TIFFClose
}
namespace mapnik {
static inline tsize_t tiff_write_proc(thandle_t fd, tdata_t buf, tsize_t size)
{
std::ostream* out = reinterpret_cast<std::ostream*>(fd);
std::ios::pos_type pos = out->tellp();
std::streamsize request_size = size;
if (static_cast<tsize_t>(request_size) != size)
return static_cast<tsize_t>(-1);
out->write(reinterpret_cast<const char*>(buf), size);
if( static_cast<std::streamsize>(pos) == -1 )
{
return size;
}
else
{
return static_cast<tsize_t>(out->tellp()-pos);
}
}
static inline toff_t tiff_seek_proc(thandle_t fd, toff_t off, int whence)
{
std::ostream* out = reinterpret_cast<std::ostream*>(fd);
if( out->fail() )
return static_cast<toff_t>(-1);
if( static_cast<std::streamsize>(out->tellp()) == -1)
return static_cast< toff_t >( 0 );
switch(whence)
{
case SEEK_SET:
out->seekp(off, std::ios_base::beg);
break;
case SEEK_CUR:
out->seekp(off, std::ios_base::cur);
break;
case SEEK_END:
out->seekp(off, std::ios_base::end);
break;
}
// grow std::stringstream buffer (re: libtiff/tif_stream.cxx)
std::ios::pos_type pos = out->tellp();
// second check needed for clang (libcxx doesn't set failbit when seeking beyond the current buffer size
if( out->fail() || static_cast<std::streamoff>(off) != pos)
{
std::ios::iostate old_state;
std::ios::pos_type origin;
old_state = out->rdstate();
// reset the fail bit or else tellp() won't work below
out->clear(out->rdstate() & ~std::ios::failbit);
switch( whence )
{
case SEEK_SET:
default:
origin = 0L;
break;
case SEEK_CUR:
origin = out->tellp();
break;
case SEEK_END:
out->seekp(0, std::ios::end);
origin = out->tellp();
break;
}
// restore original stream state
out->clear(old_state);
// only do something if desired seek position is valid
if( (static_cast<uint64_t>(origin) + off) > 0L)
{
uint64_t num_fill;
// clear the fail bit
out->clear(out->rdstate() & ~std::ios::failbit);
// extend the stream to the expected size
out->seekp(0, std::ios::end);
num_fill = (static_cast<uint64_t>(origin)) + off - out->tellp();
for( uint64_t i = 0; i < num_fill; ++i)
out->put('\0');
// retry the seek
out->seekp(static_cast<std::ios::off_type>(static_cast<uint64_t>(origin) + off), std::ios::beg);
}
}
return static_cast<toff_t>(out->tellp());
}
static inline int tiff_close_proc(thandle_t fd)
{
std::ostream* out = (std::ostream*)fd;
out->flush();
return 0;
}
static inline toff_t tiff_size_proc(thandle_t fd)
{
std::ostream* out = reinterpret_cast<std::ostream*>(fd);
std::ios::pos_type pos = out->tellp();
out->seekp(0, std::ios::end);
std::ios::pos_type len = out->tellp();
out->seekp(pos);
return static_cast<toff_t>(len);
}
static inline tsize_t tiff_dummy_read_proc(thandle_t , tdata_t , tsize_t)
{
return 0;
}
static inline void tiff_dummy_unmap_proc(thandle_t , tdata_t , toff_t) {}
static inline int tiff_dummy_map_proc(thandle_t , tdata_t*, toff_t* )
{
return 0;
}
struct tiff_config
{
tiff_config()
: compression(COMPRESSION_ADOBE_DEFLATE),
zlevel(4),
scanline(false) {}
int compression;
int zlevel;
bool scanline;
};
struct tag_setter : public mapnik::util::static_visitor<>
{
tag_setter(TIFF * output, tiff_config & config)
: output_(output),
config_(config) {}
template <typename T>
void operator() (T const&) const
{
// Assume this would be null type
throw ImageWriterException("Could not write TIFF - unknown image type provided");
}
inline void operator() (image_data_rgba8 const&) const
{
TIFFSetField(output_, TIFFTAG_PHOTOMETRIC, PHOTOMETRIC_RGB);
TIFFSetField(output_, TIFFTAG_SAMPLEFORMAT, SAMPLEFORMAT_UINT);
TIFFSetField(output_, TIFFTAG_BITSPERSAMPLE, 8);
TIFFSetField(output_, TIFFTAG_SAMPLESPERPIXEL, 4);
uint16 extras[] = { EXTRASAMPLE_UNASSALPHA };
TIFFSetField(output_, TIFFTAG_EXTRASAMPLES, 1, extras);
if (config_.compression == COMPRESSION_DEFLATE
|| config_.compression == COMPRESSION_ADOBE_DEFLATE
|| config_.compression == COMPRESSION_LZW)
{
TIFFSetField(output_, TIFFTAG_PREDICTOR, PREDICTOR_HORIZONTAL);
}
}
inline void operator() (image_data_gray32f const&) const
{
TIFFSetField(output_, TIFFTAG_PHOTOMETRIC, PHOTOMETRIC_MINISBLACK);
TIFFSetField(output_, TIFFTAG_SAMPLEFORMAT, SAMPLEFORMAT_IEEEFP);
TIFFSetField(output_, TIFFTAG_BITSPERSAMPLE, 32);
TIFFSetField(output_, TIFFTAG_SAMPLESPERPIXEL, 1);
if (config_.compression == COMPRESSION_DEFLATE
|| config_.compression == COMPRESSION_ADOBE_DEFLATE
|| config_.compression == COMPRESSION_LZW)
{
TIFFSetField(output_, TIFFTAG_PREDICTOR, PREDICTOR_FLOATINGPOINT);
}
}
inline void operator() (image_data_gray16 const&) const
{
TIFFSetField(output_, TIFFTAG_PHOTOMETRIC, PHOTOMETRIC_MINISBLACK);
TIFFSetField(output_, TIFFTAG_SAMPLEFORMAT, SAMPLEFORMAT_UINT);
TIFFSetField(output_, TIFFTAG_BITSPERSAMPLE, 16);
TIFFSetField(output_, TIFFTAG_SAMPLESPERPIXEL, 1);
if (config_.compression == COMPRESSION_DEFLATE
|| config_.compression == COMPRESSION_ADOBE_DEFLATE
|| config_.compression == COMPRESSION_LZW)
{
TIFFSetField(output_, TIFFTAG_PREDICTOR, PREDICTOR_HORIZONTAL);
}
}
inline void operator() (image_data_gray8 const&) const
{
TIFFSetField(output_, TIFFTAG_PHOTOMETRIC, PHOTOMETRIC_MINISBLACK);
TIFFSetField(output_, TIFFTAG_SAMPLEFORMAT, SAMPLEFORMAT_UINT);
TIFFSetField(output_, TIFFTAG_BITSPERSAMPLE, 8);
TIFFSetField(output_, TIFFTAG_SAMPLESPERPIXEL, 1);
if (config_.compression == COMPRESSION_DEFLATE
|| config_.compression == COMPRESSION_ADOBE_DEFLATE
|| config_.compression == COMPRESSION_LZW)
{
TIFFSetField(output_, TIFFTAG_PREDICTOR, PREDICTOR_HORIZONTAL);
}
}
inline void operator() (image_data_null const&) const
{
// Assume this would be null type
throw ImageWriterException("Could not write TIFF - Null image provided");
}
private:
TIFF * output_;
tiff_config config_;
};
void set_tiff_config(TIFF* output, tiff_config & config)
{
// Set some constant tiff information that doesn't vary based on type of data
// or image size
TIFFSetField(output, TIFFTAG_PLANARCONFIG, PLANARCONFIG_CONTIG);
// Set the compression for the TIFF
TIFFSetField(output, TIFFTAG_COMPRESSION, config.compression);
if (COMPRESSION_ADOBE_DEFLATE == config.compression || COMPRESSION_DEFLATE == config.compression)
{
// Set the zip level for the compression
// http://en.wikipedia.org/wiki/DEFLATE#Encoder.2Fcompressor
// Changes the time spent trying to compress
TIFFSetField(output, TIFFTAG_ZIPQUALITY, config.zlevel);
}
}
template <typename T1, typename T2>
void save_as_tiff(T1 & file, T2 const& image, tiff_config & config)
{
using pixel_type = typename T2::pixel_type;
const int width = image.width();
const int height = image.height();
TIFF* output = RealTIFFOpen("mapnik_tiff_stream",
"wm",
(thandle_t)&file,
tiff_dummy_read_proc,
tiff_write_proc,
tiff_seek_proc,
tiff_close_proc,
tiff_size_proc,
tiff_dummy_map_proc,
tiff_dummy_unmap_proc);
if (! output)
{
throw ImageWriterException("Could not write TIFF");
}
TIFFSetField(output, TIFFTAG_IMAGEWIDTH, width);
TIFFSetField(output, TIFFTAG_IMAGELENGTH, height);
TIFFSetField(output, TIFFTAG_IMAGEDEPTH, 1);
set_tiff_config(output, config);
// Set tags that vary based on the type of data being provided.
tag_setter set(output, config);
set(image);
//util::apply_visitor(set, image);
// If the image is greater then 8MB uncompressed, then lets use scanline rather then
// tile. TIFF also requires that all TIFFTAG_TILEWIDTH and TIFF_TILELENGTH all be
// a multiple of 16, if they are not we will use scanline.
if (image.getSize() > 8 * 32 * 1024 * 1024
|| width % 16 != 0
|| height % 16 != 0
|| config.scanline)
{
// Process Scanline
TIFFSetField(output, TIFFTAG_ROWSPERSTRIP, 1);
int next_scanline = 0;
std::unique_ptr<pixel_type[]> row (new pixel_type[image.width()]);
while (next_scanline < height)
{
std::copy(image.getRow(next_scanline), image.getRow(next_scanline) + image.width(), row.get());
//typename T2::pixel_type * row = const_cast<typename T2::pixel_type *>(image.getRow(next_scanline));
TIFFWriteScanline(output, row.get(), next_scanline, 0);
++next_scanline;
}
}
else
{
TIFFSetField(output, TIFFTAG_TILEWIDTH, width);
TIFFSetField(output, TIFFTAG_TILELENGTH, height);
TIFFSetField(output, TIFFTAG_TILEDEPTH, 1);
// Process as tiles
std::size_t tile_size = width * height;
pixel_type const * image_data_in = image.getData();
std::unique_ptr<pixel_type[]> image_data_out (new pixel_type[tile_size]);
std::copy(image_data_in, image_data_in + tile_size, image_data_out.get());
//typename T2::pixel_type * image_data = const_cast<typename T2::pixel_type *>(image.getData());
TIFFWriteTile(output, image_data_out.get(), 0, 0, 0, 0);
}
// TODO - handle palette images
// std::vector<mapnik::rgb> const& palette
// unsigned short r[256], g[256], b[256];
// for (int i = 0; i < (1 << 24); ++i)
// {
// r[i] = (unsigned short)palette[i * 3 + 0] << 8;
// g[i] = (unsigned short)palette[i * 3 + 1] << 8;
// b[i] = (unsigned short)palette[i * 3 + 2] << 8;
// }
// TIFFSetField(output, TIFFTAG_PHOTOMETRIC, PHOTOMETRIC_PALETTE);
// TIFFSetField(output, TIFFTAG_COLORMAP, r, g, b);
RealTIFFClose(output);
}
}
#endif // MAPNIK_TIFF_IO_HPP
<|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_VERSION_HPP
#define MAPNIK_VERSION_HPP
#define MAPNIK_VERSION_IS_RELEASE 0
#define MAPNIK_MAJOR_VERSION 2
#define MAPNIK_MINOR_VERSION 3
#define MAPNIK_PATCH_VERSION 0
// translates to 300000
#define MAPNIK_VERSION (MAPNIK_MAJOR_VERSION*100000) + (MAPNIK_MINOR_VERSION*100) + (MAPNIK_PATCH_VERSION)
#ifndef MAPNIK_STRINGIFY
#define MAPNIK_STRINGIFY(n) MAPNIK_STRINGIFY_HELPER(n)
#define MAPNIK_STRINGIFY_HELPER(n) #n
#endif
#if MAPNIK_VERSION_IS_RELEASE
#define MAPNIK_VERSION_STRING MAPNIK_STRINGIFY(MAPNIK_MAJOR_VERSION) "." \
MAPNIK_STRINGIFY(MAPNIK_MINOR_VERSION) "." \
MAPNIK_STRINGIFY(MAPNIK_PATCH_VERSION)
#else
#define MAPNIK_VERSION_STRING MAPNIK_STRINGIFY(MAPNIK_MAJOR_VERSION) "." \
MAPNIK_STRINGIFY(MAPNIK_MINOR_VERSION) "." \
MAPNIK_STRINGIFY(MAPNIK_PATCH_VERSION) "-pre"
#endif
#endif // MAPNIK_VERSION_HPP
<commit_msg>fix version in code comment<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_VERSION_HPP
#define MAPNIK_VERSION_HPP
#define MAPNIK_VERSION_IS_RELEASE 0
#define MAPNIK_MAJOR_VERSION 2
#define MAPNIK_MINOR_VERSION 3
#define MAPNIK_PATCH_VERSION 0
// translates to 200300
#define MAPNIK_VERSION (MAPNIK_MAJOR_VERSION*100000) + (MAPNIK_MINOR_VERSION*100) + (MAPNIK_PATCH_VERSION)
#ifndef MAPNIK_STRINGIFY
#define MAPNIK_STRINGIFY(n) MAPNIK_STRINGIFY_HELPER(n)
#define MAPNIK_STRINGIFY_HELPER(n) #n
#endif
#if MAPNIK_VERSION_IS_RELEASE
#define MAPNIK_VERSION_STRING MAPNIK_STRINGIFY(MAPNIK_MAJOR_VERSION) "." \
MAPNIK_STRINGIFY(MAPNIK_MINOR_VERSION) "." \
MAPNIK_STRINGIFY(MAPNIK_PATCH_VERSION)
#else
#define MAPNIK_VERSION_STRING MAPNIK_STRINGIFY(MAPNIK_MAJOR_VERSION) "." \
MAPNIK_STRINGIFY(MAPNIK_MINOR_VERSION) "." \
MAPNIK_STRINGIFY(MAPNIK_PATCH_VERSION) "-pre"
#endif
#endif // MAPNIK_VERSION_HPP
<|endoftext|>
|
<commit_before>//Create by Christine Nattrass, Rebecca Scott, Irakli Martashvili
//University of Tennessee at Knoxville
//by default this runs locally
//With the argument true this submits jobs to the grid
//As written this requires an xml script tag.xml in the ~/et directory on the grid to submit jobs
void runHadEt(bool submit = false, bool data = false, bool PbPb = true) {
TStopwatch timer;
timer.Start();
gSystem->Load("libTree.so");
gSystem->Load("libGeom.so");
gSystem->Load("libVMC.so");
gSystem->Load("libXMLIO.so");
gSystem->Load("libSTEERBase.so");
gSystem->Load("libESD.so");
gSystem->Load("libAOD.so");
gSystem->Load("libANALYSIS");
gSystem->Load("libANALYSISalice");
gSystem->AddIncludePath("-I$ALICE_ROOT/include");
gROOT->ProcessLine(".L AliAnalysisEtCuts.cxx+g");
gROOT->ProcessLine(".L AliAnalysisHadEtCorrections.cxx+g");
gROOT->ProcessLine(".L AliAnalysisEtCommon.cxx+g");
gROOT->ProcessLine(".L AliAnalysisHadEt.cxx+g");
gROOT->ProcessLine(".L AliAnalysisHadEtMonteCarlo.cxx+g");
gROOT->ProcessLine(".L AliAnalysisHadEtReconstructed.cxx+g");
gROOT->ProcessLine(".L AliAnalysisEtSelectionContainer.cxx+g");
gROOT->ProcessLine(".L AliAnalysisEtSelectionHandler.cxx+g");
gROOT->ProcessLine(".L AliAnalysisTaskTransverseEnergy.cxx+g");
gROOT->ProcessLine(".L AliAnalysisTaskHadEt.cxx+g");
char *kTreeName = "esdTree" ;
TChain * chain = new TChain(kTreeName,"myESDTree") ;
if(submit){
gSystem->Load("libNetx.so") ;
gSystem->Load("libgapiUI.so");
gSystem->Load("libRAliEn.so");
TGrid::Connect("alien://") ;
}
chain->Add("/data/LHC10h8/137161/999/AliESDs.root");//Hijing Pb+Pb
//chain->Add("/data/LHC11a4_bis/137161/999/AliESDs.root");//Hijing Pb+Pb
//chain->Add("/data/LHC10h12/999/AliESDs.root");//Hijing Pb+Pb
//chain->Add("/data/LHC10d15/1821/AliESDs.root");//simulation p+p
//chain->Add("/data/LHC10dpass2/10000126403050.70/AliESDs.root");//data
// Make the analysis manager
AliAnalysisManager *mgr = new AliAnalysisManager("TotEtManager");
if(submit){
if(PbPb){
gROOT->LoadMacro("CreateAlienHandlerHadEtSimPbPb.C");
AliAnalysisGrid *alienHandler = CreateAlienHandlerHadEtSimPbPb();
}
else{
gROOT->LoadMacro("CreateAlienHandlerHadEtSim.C");
AliAnalysisGrid *alienHandler = CreateAlienHandlerHadEtSim();
}
if (!alienHandler) return;
mgr->SetGridHandler(alienHandler);
}
AliVEventHandler* esdH = new AliESDInputHandler;
mgr->SetInputEventHandler(esdH);
AliMCEventHandler* handler = new AliMCEventHandler;
if(!data){
handler->SetReadTR(kFALSE);
mgr->SetMCtruthEventHandler(handler);
}
AliAnalysisDataContainer *cinput1 = mgr->GetCommonInputContainer();
bool isMc = true;
if(data) isMC = false;
gROOT->LoadMacro("$ALICE_ROOT/ANALYSIS/macros/AddTaskPhysicsSelection.C");
AliPhysicsSelectionTask *physSelTask = AddTaskPhysicsSelection(isMc);
gROOT->LoadMacro("$ALICE_ROOT/ANALYSIS/macros/AddTaskCentrality.C");
AliCentralitySelectionTask *centTask;
if(PbPb){
AliCentralitySelectionTask *centTask = AddTaskCentrality();
if(isMc){
cout<<"Setting up centrality for MC"<<endl;
centTask->SetMCInput();
}
}
AliAnalysisTaskHadEt *task2 = new AliAnalysisTaskHadEt("TaskHadEt");
if(isMc) task2->SetMcData();
mgr->AddTask(task2);
AliAnalysisDataContainer *coutput2 = mgr->CreateContainer("out2", TList::Class(), AliAnalysisManager::kOutputContainer,"Et.ESD.new.sim.root");
mgr->ConnectInput(task2,0,cinput1);
mgr->ConnectOutput(task2,1,coutput2);
mgr->SetDebugLevel(0);
if (!mgr->InitAnalysis()) return;
mgr->PrintStatus();
if(submit){
mgr->StartAnalysis("grid");
}
else{
mgr->StartAnalysis("local",chain);
}
timer.Stop();
timer.Print();
}
<commit_msg>Adding options to pass macros for running different jobs<commit_after>//Create by Christine Nattrass, Rebecca Scott, Irakli Martashvili
//University of Tennessee at Knoxville
//by default this runs locally
//With the argument true this submits jobs to the grid
//As written this requires an xml script tag.xml in the ~/et directory on the grid to submit jobs
void runHadEt(bool submit = false, bool data = false, Int_t dataset = 20100, Bool_t test = kTRUE) {
TStopwatch timer;
timer.Start();
gSystem->Load("libTree.so");
gSystem->Load("libGeom.so");
gSystem->Load("libVMC.so");
gSystem->Load("libXMLIO.so");
gSystem->Load("libSTEERBase.so");
gSystem->Load("libESD.so");
gSystem->Load("libAOD.so");
gSystem->Load("libANALYSIS");
gSystem->Load("libANALYSISalice");
gSystem->AddIncludePath("-I$ALICE_ROOT/include");
gROOT->ProcessLine(".L AliAnalysisEtCuts.cxx+g");
gROOT->ProcessLine(".L AliAnalysisHadEtCorrections.cxx+g");
gROOT->ProcessLine(".L AliAnalysisEtCommon.cxx+g");
gROOT->ProcessLine(".L AliAnalysisHadEt.cxx+g");
gROOT->ProcessLine(".L AliAnalysisHadEtMonteCarlo.cxx+g");
gROOT->ProcessLine(".L AliAnalysisHadEtReconstructed.cxx+g");
gROOT->ProcessLine(".L AliAnalysisEtSelectionContainer.cxx+g");
gROOT->ProcessLine(".L AliAnalysisEtSelectionHandler.cxx+g");
gROOT->ProcessLine(".L AliAnalysisTaskTransverseEnergy.cxx+g");
gROOT->ProcessLine(".L AliAnalysisTaskHadEt.cxx+g");
char *kTreeName = "esdTree" ;
TChain * chain = new TChain(kTreeName,"myESDTree") ;
if(submit){
gSystem->Load("libNetx.so") ;
gSystem->Load("libgapiUI.so");
gSystem->Load("libRAliEn.so");
TGrid::Connect("alien://") ;
}
bool PbPb = false;
if(dataset ==20100){
bool PbPb = true;
if(data){
chain->Add("/data/LHC10h/pass2_rev15/10000137366041.860/AliESDs.root");//Data Pb+Pb
chain->Add("/data/LHC10h/pass2_rev15/10000137366041.870/AliESDs.root");//Data Pb+Pb
chain->Add("/data/LHC10h/pass2_rev15/10000137366041.880/AliESDs.root");//Data Pb+Pb
chain->Add("/data/LHC10h/pass2_rev15/10000137366041.890/AliESDs.root");//Data Pb+Pb
chain->Add("/data/LHC10h/pass2_rev15/10000137366041.900/AliESDs.root");//Data Pb+Pb
}
else{
chain->Add("/data/LHC10h8/137161/999/AliESDs.root");//Hijing Pb+Pb
chain->Add("/data/LHC10h8/137161/111/AliESDs.root");//Hijing Pb+Pb
chain->Add("/data/LHC10h8/137161/222/AliESDs.root");//Hijing Pb+Pb
//chain->Add("/data/LHC11a4_bis/137161/999/AliESDs.root");//Hijing Pb+Pb
//chain->Add("/data/LHC10h12/999/AliESDs.root");//Hijing Pb+Pb
}
}
else{
if(data){
chain->Add("/data/LHC10dpass2/10000126403050.70/AliESDs.root");//data
}
else{
chain->Add("/data/LHC10d15/1821/AliESDs.root");//simulation p+p
}
}
// Make the analysis manager
AliAnalysisManager *mgr = new AliAnalysisManager("TotEtManager");
if(submit){
gROOT->LoadMacro("CreateAlienHandlerHadEt.C");
AliAnalysisGrid *alienHandler = CreateAlienHandlerHadEt(dataset,data,test);//integer dataset, boolean isData, bool submit-in-test-mode
if (!alienHandler) return;
mgr->SetGridHandler(alienHandler);
}
AliVEventHandler* esdH = new AliESDInputHandler;
mgr->SetInputEventHandler(esdH);
AliMCEventHandler* handler = new AliMCEventHandler;
if(!data){
handler->SetReadTR(kFALSE);
mgr->SetMCtruthEventHandler(handler);
}
AliAnalysisDataContainer *cinput1 = mgr->GetCommonInputContainer();
gROOT->LoadMacro("$ALICE_ROOT/ANALYSIS/macros/AddTaskPhysicsSelection.C");
AliPhysicsSelectionTask *physSelTask = AddTaskPhysicsSelection(!data);
gROOT->LoadMacro("$ALICE_ROOT/ANALYSIS/macros/AddTaskCentrality.C");
AliCentralitySelectionTask *centTask;
if(PbPb){
AliCentralitySelectionTask *centTask = AddTaskCentrality();
if(!data){
cout<<"Setting up centrality for MC"<<endl;
centTask->SetMCInput();
}
else{
cout<<"Setting up centrality for data"<<endl;
}
}
if(dataset==20100){//PbPb 2.76 TeV
if(data){gSystem->CopyFile("rootFiles/corrections/corrections.LHC11a4_bis.PbPb.ForData.root","corrections.root",kTRUE);}
else{gSystem->CopyFile("rootFiles/corrections/corrections.LHC11a4_bis.PbPb.ForSimulations.root","corrections.root",kTRUE);}
}
else{
if(dataset==2009){//pp 900 GeV
cout<<"Warning! You are using 7 TeV corrections for 900 GeV data!"<<endl;}
if(dataset==20111){//pp 2.76 TeV
cout<<"Warning! You are using 7 TeV corrections for 2.76eV data!"<<endl;}
if(data){gSystem->CopyFile("rootFiles/corrections/corrections.LHC10d4.pp.ForData.root","corrections.root",kTRUE);}
else{gSystem->CopyFile("rootFiles/corrections/corrections.LHC10d4.pp.ForSimulations.root","corrections.root",kTRUE);}
}
TString recoFile;
TString mcFile;
if(dataset==20100){
recoFile = "ConfigHadEtReconstructedPbPb.C";
mcFile = "ConfigHadEtMonteCarloPbPb.C";
}
if(dataset==2009){
recoFile = "ConfigHadEtReconstructedpp900GeV.C";
mcFile = "ConfigHadEtMonteCarlopp900GeV.C";
}
if(dataset==20111){
recoFile = "ConfigHadEtReconstructedpp276TeV.C";
mcFile = "ConfigHadEtMonteCarlopp276TeV.C";
}
if(dataset==2010){
recoFile = "ConfigHadEtReconstructedpp7TeV.C";
mcFile = "ConfigHadEtMonteCarlopp7TeV.C";
}
AliAnalysisTaskHadEt *task2 = new AliAnalysisTaskHadEt("TaskHadEt",!data,recoFile,mcFile);
if(!data) task2->SetMcData();
mgr->AddTask(task2);
AliAnalysisDataContainer *coutput2 = mgr->CreateContainer("out2", TList::Class(), AliAnalysisManager::kOutputContainer,"Et.ESD.new.sim.root");
mgr->ConnectInput(task2,0,cinput1);
mgr->ConnectOutput(task2,1,coutput2);
mgr->SetDebugLevel(0);
if (!mgr->InitAnalysis()) return;
mgr->PrintStatus();
if(submit){
mgr->StartAnalysis("grid");
}
else{
mgr->StartAnalysis("local",chain);
}
timer.Stop();
timer.Print();
}
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* $RCSfile: b2ipoint.hxx,v $
*
* $Revision: 1.3 $
*
* last change: $Author: thb $ $Date: 2004-02-16 17:03:05 $
*
* 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 _BGFX_POINT_B2IPOINT_HXX
#define _BGFX_POINT_B2IPOINT_HXX
#ifndef _BGFX_TUPLE_B2ITUPLE_HXX
#include <basegfx/tuple/b2ituple.hxx>
#endif
namespace basegfx
{
// predeclaration
class B2DHomMatrix;
/** Base Point class with two sal_Int32 values
This class derives all operators and common handling for
a 2D data class from B2ITuple. All necessary extensions
which are special for points will be added here.
@see B2ITuple
*/
class B2IPoint : public ::basegfx::B2ITuple
{
public:
/** Create a 2D Point
The point is initialized to (0, 0)
*/
B2IPoint()
: B2ITuple()
{}
/** Create a 2D Point
@param nX
This parameter is used to initialize the X-coordinate
of the 2D Point.
@param nY
This parameter is used to initialize the Y-coordinate
of the 2D Point.
*/
B2IPoint(sal_Int32 nX, sal_Int32 nY)
: B2ITuple(nX, nY)
{}
/** Create a copy of a 2D Point
@param rPoint
The 2D Point which will be copied.
*/
B2IPoint(const B2IPoint& rPoint)
: B2ITuple(rPoint)
{}
/** constructor with tuple to allow copy-constructing
from B2ITuple-based classes
*/
B2IPoint(const ::basegfx::B2ITuple& rTuple)
: B2ITuple(rTuple)
{}
~B2IPoint()
{}
/** *=operator to allow usage from B2IPoint, too
*/
B2IPoint& operator*=( const B2IPoint& rPnt )
{
mnX *= rPnt.mnX;
mnY *= rPnt.mnY;
return *this;
}
/** *=operator to allow usage from B2IPoint, too
*/
B2IPoint& operator*=(sal_Int32 t)
{
mnX *= t;
mnY *= t;
return *this;
}
/** assignment operator to allow assigning the results
of B2ITuple calculations
*/
B2IPoint& operator=( const ::basegfx::B2ITuple& rPoint );
/** Transform point by given transformation matrix.
The translational components of the matrix are, in
contrast to B2DVector, applied.
*/
B2IPoint& operator*=( const ::basegfx::B2DHomMatrix& rMat );
static const B2IPoint& getEmptyPoint()
{
return (const B2IPoint&) ::basegfx::B2ITuple::getEmptyTuple();
}
};
} // end of namespace basegfx
#endif /* _BGFX_POINT_B2IPOINT_HXX */
<commit_msg>INTEGRATION: CWS ooo19126 (1.3.62); FILE MERGED 2005/09/05 17:38:21 rt 1.3.62.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: b2ipoint.hxx,v $
*
* $Revision: 1.4 $
*
* last change: $Author: rt $ $Date: 2005-09-07 20:26:28 $
*
* 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 _BGFX_POINT_B2IPOINT_HXX
#define _BGFX_POINT_B2IPOINT_HXX
#ifndef _BGFX_TUPLE_B2ITUPLE_HXX
#include <basegfx/tuple/b2ituple.hxx>
#endif
namespace basegfx
{
// predeclaration
class B2DHomMatrix;
/** Base Point class with two sal_Int32 values
This class derives all operators and common handling for
a 2D data class from B2ITuple. All necessary extensions
which are special for points will be added here.
@see B2ITuple
*/
class B2IPoint : public ::basegfx::B2ITuple
{
public:
/** Create a 2D Point
The point is initialized to (0, 0)
*/
B2IPoint()
: B2ITuple()
{}
/** Create a 2D Point
@param nX
This parameter is used to initialize the X-coordinate
of the 2D Point.
@param nY
This parameter is used to initialize the Y-coordinate
of the 2D Point.
*/
B2IPoint(sal_Int32 nX, sal_Int32 nY)
: B2ITuple(nX, nY)
{}
/** Create a copy of a 2D Point
@param rPoint
The 2D Point which will be copied.
*/
B2IPoint(const B2IPoint& rPoint)
: B2ITuple(rPoint)
{}
/** constructor with tuple to allow copy-constructing
from B2ITuple-based classes
*/
B2IPoint(const ::basegfx::B2ITuple& rTuple)
: B2ITuple(rTuple)
{}
~B2IPoint()
{}
/** *=operator to allow usage from B2IPoint, too
*/
B2IPoint& operator*=( const B2IPoint& rPnt )
{
mnX *= rPnt.mnX;
mnY *= rPnt.mnY;
return *this;
}
/** *=operator to allow usage from B2IPoint, too
*/
B2IPoint& operator*=(sal_Int32 t)
{
mnX *= t;
mnY *= t;
return *this;
}
/** assignment operator to allow assigning the results
of B2ITuple calculations
*/
B2IPoint& operator=( const ::basegfx::B2ITuple& rPoint );
/** Transform point by given transformation matrix.
The translational components of the matrix are, in
contrast to B2DVector, applied.
*/
B2IPoint& operator*=( const ::basegfx::B2DHomMatrix& rMat );
static const B2IPoint& getEmptyPoint()
{
return (const B2IPoint&) ::basegfx::B2ITuple::getEmptyTuple();
}
};
} // end of namespace basegfx
#endif /* _BGFX_POINT_B2IPOINT_HXX */
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: dinfedt.cxx,v $
*
* $Revision: 1.7 $
*
* last change: $Author: hr $ $Date: 2007-06-27 23:11:03 $
*
* 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_sfx2.hxx"
#ifndef GCC
#endif
#include "dinfedt.hxx"
#include "sfxresid.hxx"
#include <sfx2/sfx.hrc>
#include "dinfedt.hrc"
// class InfoEdit_Impl ---------------------------------------------------
void InfoEdit_Impl::KeyInput( const KeyEvent& rKEvent )
{
if ( rKEvent.GetCharCode() != '~' )
Edit::KeyInput( rKEvent );
}
// class SfxDocInfoEditDlg -----------------------------------------------
SfxDocInfoEditDlg::SfxDocInfoEditDlg( Window* pParent ) :
ModalDialog( pParent, SfxResId( DLG_DOCINFO_EDT ) ),
aInfoFL ( this, SfxResId( FL_INFO ) ),
aInfo1ED ( this, SfxResId( ED_INFO1 ) ),
aInfo2ED ( this, SfxResId( ED_INFO2 ) ),
aInfo3ED ( this, SfxResId( ED_INFO3 ) ),
aInfo4ED ( this, SfxResId( ED_INFO4 ) ),
aOkBT ( this, SfxResId( BT_OK ) ),
aCancelBT ( this, SfxResId( BT_CANCEL ) ),
aHelpBtn ( this, SfxResId( BTN_HELP ) )
{
FreeResource();
}
<commit_msg>INTEGRATION: CWS changefileheader (1.7.216); FILE MERGED 2008/03/31 13:38:13 rt 1.7.216.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: dinfedt.cxx,v $
* $Revision: 1.8 $
*
* This file is part of OpenOffice.org.
*
* OpenOffice.org is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* only, as published by the Free Software Foundation.
*
* OpenOffice.org is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License version 3 for more details
* (a copy is included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with OpenOffice.org. If not, see
* <http://www.openoffice.org/license.html>
* for a copy of the LGPLv3 License.
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_sfx2.hxx"
#ifndef GCC
#endif
#include "dinfedt.hxx"
#include "sfxresid.hxx"
#include <sfx2/sfx.hrc>
#include "dinfedt.hrc"
// class InfoEdit_Impl ---------------------------------------------------
void InfoEdit_Impl::KeyInput( const KeyEvent& rKEvent )
{
if ( rKEvent.GetCharCode() != '~' )
Edit::KeyInput( rKEvent );
}
// class SfxDocInfoEditDlg -----------------------------------------------
SfxDocInfoEditDlg::SfxDocInfoEditDlg( Window* pParent ) :
ModalDialog( pParent, SfxResId( DLG_DOCINFO_EDT ) ),
aInfoFL ( this, SfxResId( FL_INFO ) ),
aInfo1ED ( this, SfxResId( ED_INFO1 ) ),
aInfo2ED ( this, SfxResId( ED_INFO2 ) ),
aInfo3ED ( this, SfxResId( ED_INFO3 ) ),
aInfo4ED ( this, SfxResId( ED_INFO4 ) ),
aOkBT ( this, SfxResId( BT_OK ) ),
aCancelBT ( this, SfxResId( BT_CANCEL ) ),
aHelpBtn ( this, SfxResId( BTN_HELP ) )
{
FreeResource();
}
<|endoftext|>
|
<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
* This file is part of the LibreOffice project.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
#include <basegfx/polygon/b2dpolygon.hxx>
#include <drawinglayer/primitive2d/polygonprimitive2d.hxx>
#include <drawinglayer/primitive2d/polypolygonprimitive2d.hxx>
#include <drawinglayer/processor2d/baseprocessor2d.hxx>
#include <drawinglayer/processor2d/processorfromoutputdevice.hxx>
#include <sfx2/bindings.hxx>
#include <sfx2/dispatch.hxx>
#include <sfx2/infobar.hxx>
#include <sfx2/objsh.hxx>
#include <sfx2/sfx.hrc>
#include <sfx2/viewsh.hxx>
#include <vcl/svapp.hxx>
#include <vcl/settings.hxx>
using namespace std;
using namespace drawinglayer::geometry;
using namespace drawinglayer::processor2d;
using namespace drawinglayer::primitive2d;
using namespace drawinglayer::attribute;
using namespace drawinglayer::geometry;
namespace
{
class SfxCloseButton : public PushButton
{
public:
SfxCloseButton( vcl::Window* pParent ) : PushButton( pParent, 0 )
{
}
virtual ~SfxCloseButton( ) { }
virtual void Paint( const Rectangle& rRect ) SAL_OVERRIDE;
};
void SfxCloseButton::Paint( const Rectangle& )
{
const ViewInformation2D aNewViewInfos;
const unique_ptr<BaseProcessor2D> pProcessor(
createBaseProcessor2DFromOutputDevice(*this, aNewViewInfos));
const Rectangle aRect(Point(0, 0), PixelToLogic(GetSizePixel()));
Primitive2DSequence aSeq(2);
basegfx::BColor aLightColor(1.0, 1.0, 191.0 / 255.0);
basegfx::BColor aDarkColor(217.0 / 255.0, 217.0 / 255.0, 78.0 / 255.0);
const StyleSettings& rSettings = Application::GetSettings().GetStyleSettings();
if ( rSettings.GetHighContrastMode() )
{
aLightColor = rSettings.GetLightColor( ).getBColor( );
aDarkColor = rSettings.GetDialogTextColor( ).getBColor( );
}
// Light background
basegfx::B2DPolygon aPolygon;
aPolygon.append( basegfx::B2DPoint( aRect.Left( ), aRect.Top( ) ) );
aPolygon.append( basegfx::B2DPoint( aRect.Right( ), aRect.Top( ) ) );
aPolygon.append( basegfx::B2DPoint( aRect.Right( ), aRect.Bottom( ) ) );
aPolygon.append( basegfx::B2DPoint( aRect.Left( ), aRect.Bottom( ) ) );
aPolygon.setClosed( true );
PolyPolygonColorPrimitive2D* pBack = new PolyPolygonColorPrimitive2D(
basegfx::B2DPolyPolygon( aPolygon ), aLightColor );
aSeq[0] = pBack;
LineAttribute aLineAttribute(aDarkColor, 2.0);
// Cross
basegfx::B2DPolyPolygon aCross;
basegfx::B2DPolygon aLine1;
aLine1.append( basegfx::B2DPoint( aRect.Left(), aRect.Top( ) ) );
aLine1.append( basegfx::B2DPoint( aRect.Right(), aRect.Bottom( ) ) );
aCross.append( aLine1 );
basegfx::B2DPolygon aLine2;
aLine2.append( basegfx::B2DPoint( aRect.Right(), aRect.Top( ) ) );
aLine2.append( basegfx::B2DPoint( aRect.Left(), aRect.Bottom( ) ) );
aCross.append( aLine2 );
PolyPolygonStrokePrimitive2D * pCross =
new PolyPolygonStrokePrimitive2D(aCross, aLineAttribute, StrokeAttribute());
aSeq[1] = pCross;
pProcessor->process(aSeq);
}
}
SfxInfoBarWindow::SfxInfoBarWindow( vcl::Window* pParent, const OUString& sId,
const OUString& sMessage, vector<PushButton*> aButtons ) :
Window(pParent, 0),
m_sId(sId),
m_pMessage(new FixedText(this, 0)),
m_pCloseBtn(new SfxCloseButton(this)),
m_aActionBtns()
{
long nWidth = pParent->GetSizePixel().getWidth();
SetPosSizePixel(Point(0, 0), Size(nWidth, 40));
m_pMessage->SetText(sMessage);
m_pMessage->SetBackground(Wallpaper(Color(255, 255, 191)));
m_pMessage->Show();
m_pCloseBtn->SetClickHdl(LINK(this, SfxInfoBarWindow, CloseHandler));
m_pCloseBtn->Show();
// Reparent the buttons and place them on the right of the bar
vector<PushButton*>::iterator it;
for (it = aButtons.begin(); it != aButtons.end(); ++it)
{
PushButton* pButton = *it;
pButton->SetParent(this);
pButton->Show();
m_aActionBtns.push_back(pButton);
}
Resize();
}
SfxInfoBarWindow::~SfxInfoBarWindow()
{}
void SfxInfoBarWindow::Paint(const Rectangle& rPaintRect)
{
const ViewInformation2D aNewViewInfos;
const unique_ptr<BaseProcessor2D> pProcessor(
createBaseProcessor2DFromOutputDevice(*this, aNewViewInfos));
const Rectangle aRect(Point(0, 0), PixelToLogic(GetSizePixel()));
Primitive2DSequence aSeq(2);
basegfx::BColor aLightColor(1.0, 1.0, 191.0 / 255.0);
basegfx::BColor aDarkColor(217.0 / 255.0, 217.0 / 255.0, 78.0 / 255.0);
const StyleSettings& rSettings = Application::GetSettings().GetStyleSettings();
if (rSettings.GetHighContrastMode())
{
aLightColor = rSettings.GetLightColor().getBColor();
aDarkColor = rSettings.GetDialogTextColor().getBColor();
}
// Update the label background color
m_pMessage->SetBackground(Wallpaper(Color(aLightColor)));
// Light background
basegfx::B2DPolygon aPolygon;
aPolygon.append( basegfx::B2DPoint( aRect.Left( ), aRect.Top( ) ) );
aPolygon.append( basegfx::B2DPoint( aRect.Right( ), aRect.Top( ) ) );
aPolygon.append( basegfx::B2DPoint( aRect.Right( ), aRect.Bottom( ) ) );
aPolygon.append( basegfx::B2DPoint( aRect.Left( ), aRect.Bottom( ) ) );
aPolygon.setClosed(true);
PolyPolygonColorPrimitive2D* pBack =
new PolyPolygonColorPrimitive2D(basegfx::B2DPolyPolygon(aPolygon), aLightColor);
aSeq[0] = pBack;
LineAttribute aLineAttribute(aDarkColor, 1.0);
// Bottom dark line
basegfx::B2DPolygon aPolygonBottom;
aPolygonBottom.append( basegfx::B2DPoint( aRect.Left(), aRect.Bottom( ) ) );
aPolygonBottom.append( basegfx::B2DPoint( aRect.Right(), aRect.Bottom( ) ) );
PolygonStrokePrimitive2D * pLineBottom =
new PolygonStrokePrimitive2D (aPolygonBottom, aLineAttribute);
aSeq[1] = pLineBottom;
pProcessor->process(aSeq);
Window::Paint(rPaintRect);
}
void SfxInfoBarWindow::Resize()
{
long nWidth = GetSizePixel().getWidth();
m_pCloseBtn->SetPosSizePixel(Point( nWidth - 25, 15), Size(10, 10));
// Reparent the buttons and place them on the right of the bar
long nX = m_pCloseBtn->GetPosPixel().getX() - 15;
long nBtnGap = 5;
boost::ptr_vector<PushButton>::iterator it;
for (it = m_aActionBtns.begin(); it != m_aActionBtns.end(); ++it)
{
long nBtnWidth = it->GetSizePixel().getWidth();
nX -= nBtnWidth;
it->SetPosSizePixel(Point(nX, 5), Size(nBtnWidth, 30));
nX -= nBtnGap;
}
m_pMessage->SetPosSizePixel(Point(10, 10), Size(nX - 20, 20));
}
IMPL_LINK_NOARG(SfxInfoBarWindow, CloseHandler)
{
static_cast<SfxInfoBarContainerWindow*>(GetParent())->removeInfoBar(this);
return 0;
}
SfxInfoBarContainerWindow::SfxInfoBarContainerWindow(SfxInfoBarContainerChild* pChildWin ) :
Window(pChildWin->GetParent(), 0),
m_pChildWin(pChildWin),
m_pInfoBars()
{
}
SfxInfoBarContainerWindow::~SfxInfoBarContainerWindow()
{
}
void SfxInfoBarContainerWindow::appendInfoBar(const OUString& sId, const OUString& sMessage, vector<PushButton*> aButtons)
{
Size aSize = GetSizePixel( );
SfxInfoBarWindow* pInfoBar = new SfxInfoBarWindow(this, sId, sMessage, aButtons);
pInfoBar->SetPosPixel(Point( 0, aSize.getHeight()));
pInfoBar->Show();
m_pInfoBars.push_back(pInfoBar);
long nHeight = pInfoBar->GetSizePixel().getHeight();
aSize.setHeight(aSize.getHeight() + nHeight);
SetSizePixel(aSize);
}
SfxInfoBarWindow* SfxInfoBarContainerWindow::getInfoBar(const OUString& sId)
{
boost::ptr_vector<SfxInfoBarWindow>::iterator it;
for (it = m_pInfoBars.begin(); it != m_pInfoBars.end(); ++it)
{
if (it->getId() == sId)
return &(*it);
}
return NULL;
}
void SfxInfoBarContainerWindow::removeInfoBar(SfxInfoBarWindow* pInfoBar)
{
boost::ptr_vector<SfxInfoBarWindow>::iterator it;
for (it = m_pInfoBars.begin(); it != m_pInfoBars.end(); ++it)
{
if (pInfoBar == &(*it))
{
m_pInfoBars.erase(it);
break;
}
}
long nY = 0;
for (it = m_pInfoBars.begin(); it != m_pInfoBars.end(); ++it)
{
it->SetPosPixel( Point( 0, nY ) );
nY += it->GetSizePixel( ).getHeight( );
}
Size aSize = GetSizePixel( );
aSize.setHeight(nY);
SetSizePixel(aSize);
m_pChildWin->Update();
}
void SfxInfoBarContainerWindow::Resize()
{
// Only need to change the width of the infobars
long nWidth = GetSizePixel().getWidth();
boost::ptr_vector<SfxInfoBarWindow>::iterator it;
for (it = m_pInfoBars.begin(); it != m_pInfoBars.end(); ++it)
{
Size aSize = it->GetSizePixel();
aSize.setWidth(nWidth);
it->SetSizePixel(aSize);
it->Resize();
}
}
SFX_IMPL_POS_CHILDWINDOW_WITHID(SfxInfoBarContainerChild, SID_INFOBAR, SFX_OBJECTBAR_OBJECT);
SfxInfoBarContainerChild::SfxInfoBarContainerChild( vcl::Window* _pParent, sal_uInt16 nId, SfxBindings* pBindings, SfxChildWinInfo* ) :
SfxChildWindow(_pParent, nId),
m_pBindings(pBindings)
{
pWindow = new SfxInfoBarContainerWindow(this);
pWindow->SetPosSizePixel(Point(0, 0), Size(_pParent->GetSizePixel().getWidth(), 0));
pWindow->Show();
eChildAlignment = SFX_ALIGN_LOWESTTOP;
}
SfxInfoBarContainerChild::~SfxInfoBarContainerChild()
{
}
SfxChildWinInfo SfxInfoBarContainerChild::GetInfo() const
{
SfxChildWinInfo aInfo = SfxChildWindow::GetInfo();
return aInfo;
}
void SfxInfoBarContainerChild::Update()
{
// Refresh the frame to take the infobars container height change into account
const sal_uInt16 nId = GetChildWindowId();
SfxViewFrame* pVFrame = m_pBindings->GetDispatcher()->GetFrame();
pVFrame->ShowChildWindow(nId);
// Give the focus to the document view
pVFrame->GetWindow().GrabFocusToDocument();
}
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<commit_msg>Further cleanup style in infobar, remove basegfx namespace in code<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
* This file is part of the LibreOffice project.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
#include <basegfx/polygon/b2dpolygon.hxx>
#include <drawinglayer/primitive2d/polygonprimitive2d.hxx>
#include <drawinglayer/primitive2d/polypolygonprimitive2d.hxx>
#include <drawinglayer/processor2d/baseprocessor2d.hxx>
#include <drawinglayer/processor2d/processorfromoutputdevice.hxx>
#include <sfx2/bindings.hxx>
#include <sfx2/dispatch.hxx>
#include <sfx2/infobar.hxx>
#include <sfx2/objsh.hxx>
#include <sfx2/sfx.hrc>
#include <sfx2/viewsh.hxx>
#include <vcl/svapp.hxx>
#include <vcl/settings.hxx>
using namespace std;
using namespace drawinglayer::geometry;
using namespace drawinglayer::processor2d;
using namespace drawinglayer::primitive2d;
using namespace drawinglayer::attribute;
using namespace drawinglayer::geometry;
using namespace basegfx;
namespace
{
class SfxCloseButton : public PushButton
{
public:
SfxCloseButton(vcl::Window* pParent) : PushButton(pParent, 0)
{
}
virtual ~SfxCloseButton() {}
virtual void Paint(const Rectangle& rRect) SAL_OVERRIDE;
};
void SfxCloseButton::Paint(const Rectangle&)
{
const ViewInformation2D aNewViewInfos;
const unique_ptr<BaseProcessor2D> pProcessor(
createBaseProcessor2DFromOutputDevice(*this, aNewViewInfos));
const Rectangle aRect(Point(0, 0), PixelToLogic(GetSizePixel()));
Primitive2DSequence aSeq(2);
BColor aLightColor(1.0, 1.0, 191.0 / 255.0);
BColor aDarkColor(217.0 / 255.0, 217.0 / 255.0, 78.0 / 255.0);
const StyleSettings& rSettings = Application::GetSettings().GetStyleSettings();
if (rSettings.GetHighContrastMode())
{
aLightColor = rSettings.GetLightColor().getBColor();
aDarkColor = rSettings.GetDialogTextColor().getBColor();
}
// Light background
B2DPolygon aPolygon;
aPolygon.append(B2DPoint(aRect.Left(), aRect.Top()));
aPolygon.append(B2DPoint(aRect.Right(), aRect.Top()));
aPolygon.append(B2DPoint(aRect.Right(), aRect.Bottom()));
aPolygon.append(B2DPoint(aRect.Left(), aRect.Bottom()));
aPolygon.setClosed(true);
PolyPolygonColorPrimitive2D* pBack =
new PolyPolygonColorPrimitive2D(B2DPolyPolygon(aPolygon), aLightColor);
aSeq[0] = pBack;
LineAttribute aLineAttribute(aDarkColor, 2.0);
// Cross
B2DPolyPolygon aCross;
B2DPolygon aLine1;
aLine1.append(B2DPoint(aRect.Left(), aRect.Top()));
aLine1.append(B2DPoint(aRect.Right(), aRect.Bottom()));
aCross.append(aLine1);
B2DPolygon aLine2;
aLine2.append(B2DPoint(aRect.Right(), aRect.Top()));
aLine2.append(B2DPoint(aRect.Left(), aRect.Bottom()));
aCross.append(aLine2);
PolyPolygonStrokePrimitive2D* pCross =
new PolyPolygonStrokePrimitive2D(aCross, aLineAttribute, StrokeAttribute());
aSeq[1] = pCross;
pProcessor->process(aSeq);
}
}
SfxInfoBarWindow::SfxInfoBarWindow(vcl::Window* pParent, const OUString& sId,
const OUString& sMessage, vector<PushButton*> aButtons) :
Window(pParent, 0),
m_sId(sId),
m_pMessage(new FixedText(this, 0)),
m_pCloseBtn(new SfxCloseButton(this)),
m_aActionBtns()
{
long nWidth = pParent->GetSizePixel().getWidth();
SetPosSizePixel(Point(0, 0), Size(nWidth, 40));
m_pMessage->SetText(sMessage);
m_pMessage->SetBackground(Wallpaper(Color(255, 255, 191)));
m_pMessage->Show();
m_pCloseBtn->SetClickHdl(LINK(this, SfxInfoBarWindow, CloseHandler));
m_pCloseBtn->Show();
// Reparent the buttons and place them on the right of the bar
vector<PushButton*>::iterator it;
for (it = aButtons.begin(); it != aButtons.end(); ++it)
{
PushButton* pButton = *it;
pButton->SetParent(this);
pButton->Show();
m_aActionBtns.push_back(pButton);
}
Resize();
}
SfxInfoBarWindow::~SfxInfoBarWindow()
{}
void SfxInfoBarWindow::Paint(const Rectangle& rPaintRect)
{
const ViewInformation2D aNewViewInfos;
const unique_ptr<BaseProcessor2D> pProcessor(
createBaseProcessor2DFromOutputDevice(*this, aNewViewInfos));
const Rectangle aRect(Point(0, 0), PixelToLogic(GetSizePixel()));
Primitive2DSequence aSeq(2);
BColor aLightColor(1.0, 1.0, 191.0 / 255.0);
BColor aDarkColor(217.0 / 255.0, 217.0 / 255.0, 78.0 / 255.0);
const StyleSettings& rSettings = Application::GetSettings().GetStyleSettings();
if (rSettings.GetHighContrastMode())
{
aLightColor = rSettings.GetLightColor().getBColor();
aDarkColor = rSettings.GetDialogTextColor().getBColor();
}
// Update the label background color
m_pMessage->SetBackground(Wallpaper(Color(aLightColor)));
// Light background
B2DPolygon aPolygon;
aPolygon.append(B2DPoint(aRect.Left(), aRect.Top()));
aPolygon.append(B2DPoint(aRect.Right(), aRect.Top()));
aPolygon.append(B2DPoint(aRect.Right(), aRect.Bottom()));
aPolygon.append(B2DPoint(aRect.Left(), aRect.Bottom()));
aPolygon.setClosed(true);
PolyPolygonColorPrimitive2D* pBack =
new PolyPolygonColorPrimitive2D(B2DPolyPolygon(aPolygon), aLightColor);
aSeq[0] = pBack;
LineAttribute aLineAttribute(aDarkColor, 1.0);
// Bottom dark line
B2DPolygon aPolygonBottom;
aPolygonBottom.append(B2DPoint(aRect.Left(), aRect.Bottom()));
aPolygonBottom.append(B2DPoint(aRect.Right(), aRect.Bottom()));
PolygonStrokePrimitive2D* pLineBottom =
new PolygonStrokePrimitive2D (aPolygonBottom, aLineAttribute);
aSeq[1] = pLineBottom;
pProcessor->process(aSeq);
Window::Paint(rPaintRect);
}
void SfxInfoBarWindow::Resize()
{
long nWidth = GetSizePixel().getWidth();
m_pCloseBtn->SetPosSizePixel(Point(nWidth - 25, 15), Size(10, 10));
// Reparent the buttons and place them on the right of the bar
long nX = m_pCloseBtn->GetPosPixel().getX() - 15;
long nBtnGap = 5;
boost::ptr_vector<PushButton>::iterator it;
for (it = m_aActionBtns.begin(); it != m_aActionBtns.end(); ++it)
{
long nBtnWidth = it->GetSizePixel().getWidth();
nX -= nBtnWidth;
it->SetPosSizePixel(Point(nX, 5), Size(nBtnWidth, 30));
nX -= nBtnGap;
}
m_pMessage->SetPosSizePixel(Point(10, 10), Size(nX - 20, 20));
}
IMPL_LINK_NOARG(SfxInfoBarWindow, CloseHandler)
{
static_cast<SfxInfoBarContainerWindow*>(GetParent())->removeInfoBar(this);
return 0;
}
SfxInfoBarContainerWindow::SfxInfoBarContainerWindow(SfxInfoBarContainerChild* pChildWin ) :
Window(pChildWin->GetParent(), 0),
m_pChildWin(pChildWin),
m_pInfoBars()
{
}
SfxInfoBarContainerWindow::~SfxInfoBarContainerWindow()
{
}
void SfxInfoBarContainerWindow::appendInfoBar(const OUString& sId, const OUString& sMessage, vector<PushButton*> aButtons)
{
Size aSize = GetSizePixel( );
SfxInfoBarWindow* pInfoBar = new SfxInfoBarWindow(this, sId, sMessage, aButtons);
pInfoBar->SetPosPixel(Point( 0, aSize.getHeight()));
pInfoBar->Show();
m_pInfoBars.push_back(pInfoBar);
long nHeight = pInfoBar->GetSizePixel().getHeight();
aSize.setHeight(aSize.getHeight() + nHeight);
SetSizePixel(aSize);
}
SfxInfoBarWindow* SfxInfoBarContainerWindow::getInfoBar(const OUString& sId)
{
boost::ptr_vector<SfxInfoBarWindow>::iterator it;
for (it = m_pInfoBars.begin(); it != m_pInfoBars.end(); ++it)
{
if (it->getId() == sId)
return &(*it);
}
return NULL;
}
void SfxInfoBarContainerWindow::removeInfoBar(SfxInfoBarWindow* pInfoBar)
{
boost::ptr_vector<SfxInfoBarWindow>::iterator it;
for (it = m_pInfoBars.begin(); it != m_pInfoBars.end(); ++it)
{
if (pInfoBar == &(*it))
{
m_pInfoBars.erase(it);
break;
}
}
long nY = 0;
for (it = m_pInfoBars.begin(); it != m_pInfoBars.end(); ++it)
{
it->SetPosPixel(Point(0, nY));
nY += it->GetSizePixel().getHeight();
}
Size aSize = GetSizePixel();
aSize.setHeight(nY);
SetSizePixel(aSize);
m_pChildWin->Update();
}
void SfxInfoBarContainerWindow::Resize()
{
// Only need to change the width of the infobars
long nWidth = GetSizePixel().getWidth();
boost::ptr_vector<SfxInfoBarWindow>::iterator it;
for (it = m_pInfoBars.begin(); it != m_pInfoBars.end(); ++it)
{
Size aSize = it->GetSizePixel();
aSize.setWidth(nWidth);
it->SetSizePixel(aSize);
it->Resize();
}
}
SFX_IMPL_POS_CHILDWINDOW_WITHID(SfxInfoBarContainerChild, SID_INFOBAR, SFX_OBJECTBAR_OBJECT);
SfxInfoBarContainerChild::SfxInfoBarContainerChild( vcl::Window* _pParent, sal_uInt16 nId, SfxBindings* pBindings, SfxChildWinInfo* ) :
SfxChildWindow(_pParent, nId),
m_pBindings(pBindings)
{
pWindow = new SfxInfoBarContainerWindow(this);
pWindow->SetPosSizePixel(Point(0, 0), Size(_pParent->GetSizePixel().getWidth(), 0));
pWindow->Show();
eChildAlignment = SFX_ALIGN_LOWESTTOP;
}
SfxInfoBarContainerChild::~SfxInfoBarContainerChild()
{
}
SfxChildWinInfo SfxInfoBarContainerChild::GetInfo() const
{
SfxChildWinInfo aInfo = SfxChildWindow::GetInfo();
return aInfo;
}
void SfxInfoBarContainerChild::Update()
{
// Refresh the frame to take the infobars container height change into account
const sal_uInt16 nId = GetChildWindowId();
SfxViewFrame* pVFrame = m_pBindings->GetDispatcher()->GetFrame();
pVFrame->ShowChildWindow(nId);
// Give the focus to the document view
pVFrame->GetWindow().GrabFocusToDocument();
}
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<|endoftext|>
|
<commit_before>/* LiteSQL - Common routines for backends
*
* The list of contributors at http://litesql.sf.net/
*
* See LICENSE for copyright information. */
#include <map>
#include "compatibility.hpp"
#include "litesql/backend.hpp"
#include "litesql/string.hpp"
#include "litesql/types.hpp"
#ifdef HAVE_LIBMYSQLCLIENT
#include "mysql.hpp"
#endif
#ifdef HAVE_LIBPQ
#include "postgresql.hpp"
#endif
#ifdef HAVE_LIBSQLITE3
#include "sqlite3.hpp"
#endif
#ifdef HAVE_ODBC
#include "odbc_backend.hpp"
#endif
#ifdef HAVE_OCILIB
#include "ocilib_backend.hpp"
#endif
using namespace litesql;
using namespace std;
string Backend::getCreateSequenceSQL(const string& name) const
{
return "CREATE SEQUENCE " + name + " START 1 INCREMENT 1";
}
string Backend::getSeqSQL(const string& sname) const
{
string ret="SELECT nextval('"+ sname + "');";
return ret;
}
string Backend::groupInsert(Record tables, Records fields, Records values,
const string& sequence) const {
string id = values[0][0];
if (supportsSequences() && values[0][0] == "NULL") {
Result * r = execute(getSeqSQL(sequence));
id = r->records()[0][0];
delete r;
}
for (int i = tables.size()-1; i >= 0; i--) {
string fieldString = Split::join(fields[i],",");
string valueString;
if (!values[i].empty())
values[i][0] = id;
Split valueSplit(values[i]);
for (size_t i2 = 0; i2 < valueSplit.size(); i2++)
valueSplit[i2] = escapeSQL(valueSplit[i2]);
valueString = valueSplit.join(",");
string query = "INSERT INTO " + tables[i] + " (" + fieldString
+ ") VALUES (" + valueString + ");";
delete execute(query);
if (!supportsSequences() && id == "NULL")
id = getInsertID();
}
return id;
}
Backend* Backend::getBackend(const string & backendType,const string& connInfo)
{
Backend* backend;
#ifdef HAVE_LIBMYSQLCLIENT
if (backendType == "mysql") {
backend = new MySQL(connInfo);
} else
#endif
#ifdef HAVE_LIBPQ
if (backendType == "postgresql") {
backend = new PostgreSQL(connInfo);
} else
#endif
#ifdef HAVE_ODBC
if (backendType == "odbc") {
backend = new ODBCBackend(connInfo);
} else
#endif
#ifdef HAVE_LIBSQLITE3
if (backendType == "sqlite3") {
backend = new SQLite3(connInfo);
} else
#endif
#ifdef HAVE_OCILIB
if (backendType == "oracle") {
backend = new OCILib(connInfo);
} else
#endif
{
backend = NULL;
};
return backend;
}
<commit_msg>added getSQLType(type) as a first step to get backend specific field types in future versions<commit_after>/* LiteSQL - Common routines for backends
*
* The list of contributors at http://litesql.sf.net/
*
* See LICENSE for copyright information. */
#include <map>
#include "compatibility.hpp"
#include "litesql/backend.hpp"
#include "litesql/string.hpp"
#include "litesql/types.hpp"
#ifdef HAVE_LIBMYSQLCLIENT
#include "mysql.hpp"
#endif
#ifdef HAVE_LIBPQ
#include "postgresql.hpp"
#endif
#ifdef HAVE_LIBSQLITE3
#include "sqlite3.hpp"
#endif
#ifdef HAVE_ODBC
#include "odbc_backend.hpp"
#endif
#ifdef HAVE_OCILIB
#include "ocilib_backend.hpp"
#endif
using namespace litesql;
using namespace std;
string Backend::getSQLType(AT_field_type fieldType) const
{
switch(fieldType) {
case A_field_type_integer: return "INTEGER";
case A_field_type_bigint: return "BIGINT";
case A_field_type_string: return "TEXT";
case A_field_type_float: return "FLOAT";
case A_field_type_double: return "DOUBLE";
case A_field_type_boolean: return "INTEGER";
case A_field_type_date: return "INTEGER";
case A_field_type_time: return "INTEGER";
case A_field_type_datetime: return "INTEGER";
case A_field_type_blob: return "BLOB";
default: return "";
}
}
string Backend::getCreateSequenceSQL(const string& name) const
{
return "CREATE SEQUENCE " + name + " START 1 INCREMENT 1";
}
string Backend::getSeqSQL(const string& sname) const
{
string ret="SELECT nextval('"+ sname + "');";
return ret;
}
string Backend::groupInsert(Record tables, Records fields, Records values,
const string& sequence) const {
string id = values[0][0];
if (supportsSequences() && values[0][0] == "NULL") {
Result * r = execute(getSeqSQL(sequence));
id = r->records()[0][0];
delete r;
}
for (int i = tables.size()-1; i >= 0; i--) {
string fieldString = Split::join(fields[i],",");
string valueString;
if (!values[i].empty())
values[i][0] = id;
Split valueSplit(values[i]);
for (size_t i2 = 0; i2 < valueSplit.size(); i2++)
valueSplit[i2] = escapeSQL(valueSplit[i2]);
valueString = valueSplit.join(",");
string query = "INSERT INTO " + tables[i] + " (" + fieldString
+ ") VALUES (" + valueString + ");";
delete execute(query);
if (!supportsSequences() && id == "NULL")
id = getInsertID();
}
return id;
}
Backend* Backend::getBackend(const string & backendType,const string& connInfo)
{
Backend* backend;
#ifdef HAVE_LIBMYSQLCLIENT
if (backendType == "mysql") {
backend = new MySQL(connInfo);
} else
#endif
#ifdef HAVE_LIBPQ
if (backendType == "postgresql") {
backend = new PostgreSQL(connInfo);
} else
#endif
#ifdef HAVE_ODBC
if (backendType == "odbc") {
backend = new ODBCBackend(connInfo);
} else
#endif
#ifdef HAVE_LIBSQLITE3
if (backendType == "sqlite3") {
backend = new SQLite3(connInfo);
} else
#endif
#ifdef HAVE_OCILIB
if (backendType == "oracle") {
backend = new OCILib(connInfo);
} else
#endif
{
backend = NULL;
};
return backend;
}
<|endoftext|>
|
<commit_before>/*=========================================================================
Program: Visualization Toolkit
Module: vtkCommunicator.cxx
Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
All rights reserved.
See Copyright.txt or http://www.kitware.com/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notice for more information.
=========================================================================*/
#include "vtkCommunicator.h"
#include "vtkCharArray.h"
#include "vtkDataSetReader.h"
#include "vtkDataSetWriter.h"
#include "vtkDoubleArray.h"
#include "vtkFloatArray.h"
#include "vtkIdTypeArray.h"
#include "vtkImageClip.h"
#include "vtkIntArray.h"
#include "vtkStructuredPoints.h"
#include "vtkStructuredPointsReader.h"
#include "vtkStructuredPointsWriter.h"
#include "vtkUnsignedCharArray.h"
#include "vtkUnsignedLongArray.h"
vtkCxxRevisionMacro(vtkCommunicator, "1.26");
template <class T>
int SendDataArray(T* data, int length, int handle, int tag, vtkCommunicator *self)
{
self->Send(data, length, handle, tag);
return 1;
}
vtkCommunicator::vtkCommunicator()
{
this->MarshalString = 0;
this->MarshalStringLength = 0;
this->MarshalDataLength = 0;
}
vtkCommunicator::~vtkCommunicator()
{
this->DeleteAndSetMarshalString(0, 0);
}
int vtkCommunicator::UseCopy = 0;
void vtkCommunicator::SetUseCopy(int useCopy)
{
vtkCommunicator::UseCopy = useCopy;
}
void vtkCommunicator::PrintSelf(ostream& os, vtkIndent indent)
{
this->Superclass::PrintSelf(os, indent);
os << indent << "Marshal string: ";
if ( this->MarshalString )
{
os << this->MarshalString << endl;
}
else
{
os << "(None)" << endl;
}
os << indent << "Marshal string length: " << this->MarshalStringLength
<< endl;
os << indent << "Marshal data length: " << this->MarshalDataLength
<< endl;
}
//----------------------------------------------------------------------------
// Internal method. Assumes responsibility for deleting the string
void vtkCommunicator::DeleteAndSetMarshalString(char *str, int strLength)
{
// delete any previous string
if (this->MarshalString)
{
delete [] this->MarshalString;
this->MarshalString = 0;
this->MarshalStringLength = 0;
this->MarshalDataLength = 0;
}
this->MarshalString = str;
this->MarshalStringLength = strLength;
}
// Need to add better error checking
int vtkCommunicator::Send(vtkDataObject* data, int remoteHandle,
int tag)
{
if (data == NULL)
{
this->MarshalDataLength = 0;
this->Send( &this->MarshalDataLength, 1,
remoteHandle, tag);
return 1;
}
if (this->WriteObject(data))
{
this->Send( &this->MarshalDataLength, 1,
remoteHandle, tag);
// then send the string.
this->Send( this->MarshalString, this->MarshalDataLength,
remoteHandle, tag);
return 1;
}
// could not marshal data
return 0;
}
int vtkCommunicator::Send(vtkDataArray* data, int remoteHandle, int tag)
{
int type = -1;
if (data == NULL)
{
this->MarshalDataLength = 0;
this->Send( &type, 1, remoteHandle, tag);
return 1;
}
// send array type
type = data->GetDataType();
this->Send( &type, 1, remoteHandle, tag);
// send array size
vtkIdType size = data->GetSize();
this->Send( &size, 1, remoteHandle, tag);
// send number of components in array
int numComponents = data->GetNumberOfComponents();
this->Send( &numComponents, 1, remoteHandle, tag);
const char* name = data->GetName();
int len = 0;
if (name)
{
len = static_cast<int>(strlen(name)) + 1;
}
// send length of name
this->Send( &len, 1, remoteHandle, tag);
if (len > 0)
{
// send name
this->Send( const_cast<char*>(name), len, remoteHandle, tag);
}
// now send the raw array
switch (type)
{
case VTK_CHAR:
return SendDataArray(static_cast<char*>(data->GetVoidPointer(0)),
size, remoteHandle, tag, this);
case VTK_UNSIGNED_CHAR:
return SendDataArray(static_cast<unsigned char*>(data->GetVoidPointer(0)),
size, remoteHandle, tag, this);
case VTK_INT:
return SendDataArray(static_cast<int*>(data->GetVoidPointer(0)),
size, remoteHandle, tag, this);
case VTK_UNSIGNED_LONG:
return SendDataArray(static_cast<unsigned long*>(data->GetVoidPointer(0)),
size, remoteHandle, tag, this);
case VTK_FLOAT:
return SendDataArray(static_cast<float*>(data->GetVoidPointer(0)),
size, remoteHandle, tag, this);
case VTK_DOUBLE:
return SendDataArray(static_cast<double*>(data->GetVoidPointer(0)),
size, remoteHandle, tag, this);
case VTK_ID_TYPE:
return SendDataArray(static_cast<vtkIdType*>(data->GetVoidPointer(0)),
size, remoteHandle, tag, this);
default:
vtkErrorMacro(<<"Unsupported data type!");
return 0; // could not marshal data
}
}
int vtkCommunicator::Receive(vtkDataObject* data, int remoteHandle,
int tag)
{
int dataLength;
// First receive the data length.
if (!this->Receive( &dataLength, 1, remoteHandle, tag))
{
vtkErrorMacro("Could not receive data!");
return 0;
}
if (dataLength < 0)
{
vtkErrorMacro("Bad data length");
return 0;
}
if (dataLength == 0)
{ // This indicates a NULL object was sent. Do nothing.
return 1;
}
// if we cannot reuse the string, allocate a new one.
if (dataLength > this->MarshalStringLength)
{
char *str = new char[dataLength + 10]; // maybe a little extra?
this->DeleteAndSetMarshalString(str, dataLength + 10);
}
// Receive the string
this->Receive(this->MarshalString, dataLength,
remoteHandle, tag);
this->MarshalDataLength = dataLength;
this->ReadObject(data);
// we should really look at status to determine success
return 1;
}
int vtkCommunicator::Receive(vtkDataArray* data, int remoteHandle,
int tag)
{
vtkIdType size;
int type;
int numComponents;
int nameLength;
char *c = 0;
unsigned char *uc = 0;
int *i = 0;
unsigned long *ul = 0;
float *f = 0;
double *d = 0;
vtkIdType *idt = 0;
// First receive the data type.
if (!this->Receive( &type, 1, remoteHandle, tag))
{
vtkErrorMacro("Could not receive data!");
return 0;
}
if (type == -1)
{ // This indicates a NULL object was sent. Do nothing.
return 1;
}
// Next receive the data length.
if (!this->Receive( &size, 1, remoteHandle, tag))
{
vtkErrorMacro("Could not receive data!");
return 0;
}
// Next receive the number of components.
this->Receive( &numComponents, 1, remoteHandle, tag);
// Next receive the length of the name.
this->Receive( &nameLength, 1, remoteHandle, tag);
if ( nameLength > 0 )
{
char *str = new char[nameLength];
this->DeleteAndSetMarshalString(str, nameLength);
// Receive the name
this->Receive(this->MarshalString, nameLength, remoteHandle, tag);
this->MarshalDataLength = nameLength;
}
if (size < 0)
{
vtkErrorMacro("Bad data length");
return 0;
}
if (size == 0)
{ // This indicates a NULL object was sent. Do nothing.
return 1;
}
// Receive the raw data array
switch (type)
{
case VTK_CHAR:
c = new char[size];
this->Receive(c, size, remoteHandle, tag);
static_cast<vtkCharArray*>(data)->SetArray(c, size, 0);
break;
case VTK_UNSIGNED_CHAR:
uc = new unsigned char[size];
this->Receive(uc, size, remoteHandle, tag);
static_cast<vtkUnsignedCharArray*>(data)->SetArray(uc, size, 0);
break;
case VTK_INT:
i = new int[size];
this->Receive(i, size, remoteHandle, tag);
static_cast<vtkIntArray*>(data)->SetArray(i, size, 0);
break;
case VTK_UNSIGNED_LONG:
ul = new unsigned long[size];
this->Receive(ul, size, remoteHandle, tag);
static_cast<vtkUnsignedLongArray*>(data)->SetArray(ul, size, 0);
break;
case VTK_FLOAT:
f = new float[size];
this->Receive(f, size, remoteHandle, tag);
static_cast<vtkFloatArray*>(data)->SetArray(f, size, 0);
break;
case VTK_DOUBLE:
d = new double[size];
this->Receive(d, size, remoteHandle, tag);
static_cast<vtkDoubleArray*>(data)->SetArray(d, size, 0);
break;
case VTK_ID_TYPE:
idt = new vtkIdType[size];
this->Receive(idt, size, remoteHandle, tag);
static_cast<vtkIdTypeArray*>(data)->SetArray(idt, size, 0);
break;
default:
vtkErrorMacro(<<"Unsupported data type!");
return 0; // could not marshal data
}
if (nameLength > 0)
{
data->SetName(this->MarshalString);
}
else
{
data->SetName(0);
}
data->SetNumberOfComponents(numComponents);
return 1;
}
int vtkCommunicator::WriteObject(vtkDataObject *data)
{
if (strcmp(data->GetClassName(), "vtkPolyData") == 0 ||
strcmp(data->GetClassName(), "vtkUnstructuredGrid") == 0 ||
strcmp(data->GetClassName(), "vtkStructuredGrid") == 0 ||
strcmp(data->GetClassName(), "vtkRectilinearGrid") == 0 ||
strcmp(data->GetClassName(), "vtkStructuredPoints") == 0)
{
return this->WriteDataSet((vtkDataSet*)data);
}
if (strcmp(data->GetClassName(), "vtkImageData") == 0)
{
return this->WriteImageData((vtkImageData*)data);
}
vtkErrorMacro("Cannot marshal object of type "
<< data->GetClassName());
return 0;
}
int vtkCommunicator::ReadObject(vtkDataObject *data)
{
if (strcmp(data->GetClassName(), "vtkPolyData") == 0 ||
strcmp(data->GetClassName(), "vtkUnstructuredGrid") == 0 ||
strcmp(data->GetClassName(), "vtkStructuredGrid") == 0 ||
strcmp(data->GetClassName(), "vtkRectilinearGrid") == 0 ||
strcmp(data->GetClassName(), "vtkStructuredPoints") == 0)
{
return this->ReadDataSet((vtkDataSet*)data);
}
if (strcmp(data->GetClassName(), "vtkImageData") == 0)
{
return this->ReadImageData((vtkImageData*)data);
}
vtkErrorMacro("Cannot marshal object of type "
<< data->GetClassName());
return 1;
}
int vtkCommunicator::WriteImageData(vtkImageData *data)
{
vtkImageClip *clip;
vtkStructuredPointsWriter *writer;
int size;
// keep Update from propagating
vtkImageData *tmp = vtkImageData::New();
tmp->ShallowCopy(data);
tmp->SetUpdateExtent(data->GetUpdateExtent());
clip = vtkImageClip::New();
clip->SetInput(tmp);
clip->SetOutputWholeExtent(data->GetExtent());
writer = vtkStructuredPointsWriter::New();
writer->SetFileTypeToBinary();
writer->WriteToOutputStringOn();
writer->SetInput(clip->GetOutput());
writer->Write();
size = writer->GetOutputStringLength();
this->DeleteAndSetMarshalString(writer->RegisterAndGetOutputString(), size);
this->MarshalDataLength = size;
clip->Delete();
writer->Delete();
tmp->Delete();
return 1;
}
int vtkCommunicator::ReadImageData(vtkImageData *object)
{
vtkStructuredPointsReader *reader = vtkStructuredPointsReader::New();
if (this->MarshalString == NULL || this->MarshalStringLength <= 0)
{
return 0;
}
reader->ReadFromInputStringOn();
vtkCharArray* mystring = vtkCharArray::New();
// mystring should not delete the string when it's done,
// that's our job.
mystring->SetArray(this->MarshalString, this->MarshalDataLength, 1);
reader->SetInputArray(mystring);
mystring->Delete();
reader->GetOutput()->Update();
object->ShallowCopy(reader->GetOutput());
object->SetUpdateExtent(reader->GetOutput()->GetUpdateExtent());
reader->Delete();
return 1;
}
int vtkCommunicator::WriteDataSet(vtkDataSet *data)
{
vtkDataSet *copy;
unsigned long size;
vtkDataSetWriter *writer = vtkDataSetWriter::New();
copy = data->NewInstance();
copy->ShallowCopy(data);
// There is a problem with binary files with no data.
if (copy->GetNumberOfCells() + copy->GetNumberOfPoints() > 0)
{
writer->SetFileTypeToBinary();
}
writer->WriteToOutputStringOn();
writer->SetInput(copy);
writer->Write();
size = writer->GetOutputStringLength();
this->DeleteAndSetMarshalString(writer->RegisterAndGetOutputString(), size);
this->MarshalDataLength = size;
writer->Delete();
copy->Delete();
return 1;
}
int vtkCommunicator::ReadDataSet(vtkDataSet *object)
{
vtkDataSetReader *reader = vtkDataSetReader::New();
if (this->MarshalString == NULL || this->MarshalStringLength <= 0)
{
return 0;
}
reader->ReadFromInputStringOn();
vtkCharArray* mystring = vtkCharArray::New();
// mystring should not delete the string when it's done,
// that's our job.
mystring->SetArray(this->MarshalString, this->MarshalDataLength, 1);
reader->SetInputArray(mystring);
mystring->Delete();
reader->Update();
object->ShallowCopy(reader->GetOutput());
reader->Delete();
return 1;
}
<commit_msg>BUG: Should not set update extent. This can cause numerous problems<commit_after>/*=========================================================================
Program: Visualization Toolkit
Module: vtkCommunicator.cxx
Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
All rights reserved.
See Copyright.txt or http://www.kitware.com/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notice for more information.
=========================================================================*/
#include "vtkCommunicator.h"
#include "vtkCharArray.h"
#include "vtkDataSetReader.h"
#include "vtkDataSetWriter.h"
#include "vtkDoubleArray.h"
#include "vtkFloatArray.h"
#include "vtkIdTypeArray.h"
#include "vtkImageClip.h"
#include "vtkIntArray.h"
#include "vtkStructuredPoints.h"
#include "vtkStructuredPointsReader.h"
#include "vtkStructuredPointsWriter.h"
#include "vtkUnsignedCharArray.h"
#include "vtkUnsignedLongArray.h"
vtkCxxRevisionMacro(vtkCommunicator, "1.27");
template <class T>
int SendDataArray(T* data, int length, int handle, int tag, vtkCommunicator *self)
{
self->Send(data, length, handle, tag);
return 1;
}
vtkCommunicator::vtkCommunicator()
{
this->MarshalString = 0;
this->MarshalStringLength = 0;
this->MarshalDataLength = 0;
}
vtkCommunicator::~vtkCommunicator()
{
this->DeleteAndSetMarshalString(0, 0);
}
int vtkCommunicator::UseCopy = 0;
void vtkCommunicator::SetUseCopy(int useCopy)
{
vtkCommunicator::UseCopy = useCopy;
}
void vtkCommunicator::PrintSelf(ostream& os, vtkIndent indent)
{
this->Superclass::PrintSelf(os, indent);
os << indent << "Marshal string: ";
if ( this->MarshalString )
{
os << this->MarshalString << endl;
}
else
{
os << "(None)" << endl;
}
os << indent << "Marshal string length: " << this->MarshalStringLength
<< endl;
os << indent << "Marshal data length: " << this->MarshalDataLength
<< endl;
}
//----------------------------------------------------------------------------
// Internal method. Assumes responsibility for deleting the string
void vtkCommunicator::DeleteAndSetMarshalString(char *str, int strLength)
{
// delete any previous string
if (this->MarshalString)
{
delete [] this->MarshalString;
this->MarshalString = 0;
this->MarshalStringLength = 0;
this->MarshalDataLength = 0;
}
this->MarshalString = str;
this->MarshalStringLength = strLength;
}
// Need to add better error checking
int vtkCommunicator::Send(vtkDataObject* data, int remoteHandle,
int tag)
{
if (data == NULL)
{
this->MarshalDataLength = 0;
this->Send( &this->MarshalDataLength, 1,
remoteHandle, tag);
return 1;
}
if (this->WriteObject(data))
{
this->Send( &this->MarshalDataLength, 1,
remoteHandle, tag);
// then send the string.
this->Send( this->MarshalString, this->MarshalDataLength,
remoteHandle, tag);
return 1;
}
// could not marshal data
return 0;
}
int vtkCommunicator::Send(vtkDataArray* data, int remoteHandle, int tag)
{
int type = -1;
if (data == NULL)
{
this->MarshalDataLength = 0;
this->Send( &type, 1, remoteHandle, tag);
return 1;
}
// send array type
type = data->GetDataType();
this->Send( &type, 1, remoteHandle, tag);
// send array size
vtkIdType size = data->GetSize();
this->Send( &size, 1, remoteHandle, tag);
// send number of components in array
int numComponents = data->GetNumberOfComponents();
this->Send( &numComponents, 1, remoteHandle, tag);
const char* name = data->GetName();
int len = 0;
if (name)
{
len = static_cast<int>(strlen(name)) + 1;
}
// send length of name
this->Send( &len, 1, remoteHandle, tag);
if (len > 0)
{
// send name
this->Send( const_cast<char*>(name), len, remoteHandle, tag);
}
// now send the raw array
switch (type)
{
case VTK_CHAR:
return SendDataArray(static_cast<char*>(data->GetVoidPointer(0)),
size, remoteHandle, tag, this);
case VTK_UNSIGNED_CHAR:
return SendDataArray(static_cast<unsigned char*>(data->GetVoidPointer(0)),
size, remoteHandle, tag, this);
case VTK_INT:
return SendDataArray(static_cast<int*>(data->GetVoidPointer(0)),
size, remoteHandle, tag, this);
case VTK_UNSIGNED_LONG:
return SendDataArray(static_cast<unsigned long*>(data->GetVoidPointer(0)),
size, remoteHandle, tag, this);
case VTK_FLOAT:
return SendDataArray(static_cast<float*>(data->GetVoidPointer(0)),
size, remoteHandle, tag, this);
case VTK_DOUBLE:
return SendDataArray(static_cast<double*>(data->GetVoidPointer(0)),
size, remoteHandle, tag, this);
case VTK_ID_TYPE:
return SendDataArray(static_cast<vtkIdType*>(data->GetVoidPointer(0)),
size, remoteHandle, tag, this);
default:
vtkErrorMacro(<<"Unsupported data type!");
return 0; // could not marshal data
}
}
int vtkCommunicator::Receive(vtkDataObject* data, int remoteHandle,
int tag)
{
int dataLength;
// First receive the data length.
if (!this->Receive( &dataLength, 1, remoteHandle, tag))
{
vtkErrorMacro("Could not receive data!");
return 0;
}
if (dataLength < 0)
{
vtkErrorMacro("Bad data length");
return 0;
}
if (dataLength == 0)
{ // This indicates a NULL object was sent. Do nothing.
return 1;
}
// if we cannot reuse the string, allocate a new one.
if (dataLength > this->MarshalStringLength)
{
char *str = new char[dataLength + 10]; // maybe a little extra?
this->DeleteAndSetMarshalString(str, dataLength + 10);
}
// Receive the string
this->Receive(this->MarshalString, dataLength,
remoteHandle, tag);
this->MarshalDataLength = dataLength;
this->ReadObject(data);
// we should really look at status to determine success
return 1;
}
int vtkCommunicator::Receive(vtkDataArray* data, int remoteHandle,
int tag)
{
vtkIdType size;
int type;
int numComponents;
int nameLength;
char *c = 0;
unsigned char *uc = 0;
int *i = 0;
unsigned long *ul = 0;
float *f = 0;
double *d = 0;
vtkIdType *idt = 0;
// First receive the data type.
if (!this->Receive( &type, 1, remoteHandle, tag))
{
vtkErrorMacro("Could not receive data!");
return 0;
}
if (type == -1)
{ // This indicates a NULL object was sent. Do nothing.
return 1;
}
// Next receive the data length.
if (!this->Receive( &size, 1, remoteHandle, tag))
{
vtkErrorMacro("Could not receive data!");
return 0;
}
// Next receive the number of components.
this->Receive( &numComponents, 1, remoteHandle, tag);
// Next receive the length of the name.
this->Receive( &nameLength, 1, remoteHandle, tag);
if ( nameLength > 0 )
{
char *str = new char[nameLength];
this->DeleteAndSetMarshalString(str, nameLength);
// Receive the name
this->Receive(this->MarshalString, nameLength, remoteHandle, tag);
this->MarshalDataLength = nameLength;
}
if (size < 0)
{
vtkErrorMacro("Bad data length");
return 0;
}
if (size == 0)
{ // This indicates a NULL object was sent. Do nothing.
return 1;
}
// Receive the raw data array
switch (type)
{
case VTK_CHAR:
c = new char[size];
this->Receive(c, size, remoteHandle, tag);
static_cast<vtkCharArray*>(data)->SetArray(c, size, 0);
break;
case VTK_UNSIGNED_CHAR:
uc = new unsigned char[size];
this->Receive(uc, size, remoteHandle, tag);
static_cast<vtkUnsignedCharArray*>(data)->SetArray(uc, size, 0);
break;
case VTK_INT:
i = new int[size];
this->Receive(i, size, remoteHandle, tag);
static_cast<vtkIntArray*>(data)->SetArray(i, size, 0);
break;
case VTK_UNSIGNED_LONG:
ul = new unsigned long[size];
this->Receive(ul, size, remoteHandle, tag);
static_cast<vtkUnsignedLongArray*>(data)->SetArray(ul, size, 0);
break;
case VTK_FLOAT:
f = new float[size];
this->Receive(f, size, remoteHandle, tag);
static_cast<vtkFloatArray*>(data)->SetArray(f, size, 0);
break;
case VTK_DOUBLE:
d = new double[size];
this->Receive(d, size, remoteHandle, tag);
static_cast<vtkDoubleArray*>(data)->SetArray(d, size, 0);
break;
case VTK_ID_TYPE:
idt = new vtkIdType[size];
this->Receive(idt, size, remoteHandle, tag);
static_cast<vtkIdTypeArray*>(data)->SetArray(idt, size, 0);
break;
default:
vtkErrorMacro(<<"Unsupported data type!");
return 0; // could not marshal data
}
if (nameLength > 0)
{
data->SetName(this->MarshalString);
}
else
{
data->SetName(0);
}
data->SetNumberOfComponents(numComponents);
return 1;
}
int vtkCommunicator::WriteObject(vtkDataObject *data)
{
if (strcmp(data->GetClassName(), "vtkPolyData") == 0 ||
strcmp(data->GetClassName(), "vtkUnstructuredGrid") == 0 ||
strcmp(data->GetClassName(), "vtkStructuredGrid") == 0 ||
strcmp(data->GetClassName(), "vtkRectilinearGrid") == 0 ||
strcmp(data->GetClassName(), "vtkStructuredPoints") == 0)
{
return this->WriteDataSet((vtkDataSet*)data);
}
if (strcmp(data->GetClassName(), "vtkImageData") == 0)
{
return this->WriteImageData((vtkImageData*)data);
}
vtkErrorMacro("Cannot marshal object of type "
<< data->GetClassName());
return 0;
}
int vtkCommunicator::ReadObject(vtkDataObject *data)
{
if (strcmp(data->GetClassName(), "vtkPolyData") == 0 ||
strcmp(data->GetClassName(), "vtkUnstructuredGrid") == 0 ||
strcmp(data->GetClassName(), "vtkStructuredGrid") == 0 ||
strcmp(data->GetClassName(), "vtkRectilinearGrid") == 0 ||
strcmp(data->GetClassName(), "vtkStructuredPoints") == 0)
{
return this->ReadDataSet((vtkDataSet*)data);
}
if (strcmp(data->GetClassName(), "vtkImageData") == 0)
{
return this->ReadImageData((vtkImageData*)data);
}
vtkErrorMacro("Cannot marshal object of type "
<< data->GetClassName());
return 1;
}
int vtkCommunicator::WriteImageData(vtkImageData *data)
{
vtkImageClip *clip;
vtkStructuredPointsWriter *writer;
int size;
// keep Update from propagating
vtkImageData *tmp = vtkImageData::New();
tmp->ShallowCopy(data);
tmp->SetUpdateExtent(data->GetUpdateExtent());
clip = vtkImageClip::New();
clip->SetInput(tmp);
clip->SetOutputWholeExtent(data->GetExtent());
writer = vtkStructuredPointsWriter::New();
writer->SetFileTypeToBinary();
writer->WriteToOutputStringOn();
writer->SetInput(clip->GetOutput());
writer->Write();
size = writer->GetOutputStringLength();
this->DeleteAndSetMarshalString(writer->RegisterAndGetOutputString(), size);
this->MarshalDataLength = size;
clip->Delete();
writer->Delete();
tmp->Delete();
return 1;
}
int vtkCommunicator::ReadImageData(vtkImageData *object)
{
vtkStructuredPointsReader *reader = vtkStructuredPointsReader::New();
if (this->MarshalString == NULL || this->MarshalStringLength <= 0)
{
return 0;
}
reader->ReadFromInputStringOn();
vtkCharArray* mystring = vtkCharArray::New();
// mystring should not delete the string when it's done,
// that's our job.
mystring->SetArray(this->MarshalString, this->MarshalDataLength, 1);
reader->SetInputArray(mystring);
mystring->Delete();
reader->GetOutput()->Update();
object->ShallowCopy(reader->GetOutput());
reader->Delete();
return 1;
}
int vtkCommunicator::WriteDataSet(vtkDataSet *data)
{
vtkDataSet *copy;
unsigned long size;
vtkDataSetWriter *writer = vtkDataSetWriter::New();
copy = data->NewInstance();
copy->ShallowCopy(data);
// There is a problem with binary files with no data.
if (copy->GetNumberOfCells() + copy->GetNumberOfPoints() > 0)
{
writer->SetFileTypeToBinary();
}
writer->WriteToOutputStringOn();
writer->SetInput(copy);
writer->Write();
size = writer->GetOutputStringLength();
this->DeleteAndSetMarshalString(writer->RegisterAndGetOutputString(), size);
this->MarshalDataLength = size;
writer->Delete();
copy->Delete();
return 1;
}
int vtkCommunicator::ReadDataSet(vtkDataSet *object)
{
vtkDataSetReader *reader = vtkDataSetReader::New();
if (this->MarshalString == NULL || this->MarshalStringLength <= 0)
{
return 0;
}
reader->ReadFromInputStringOn();
vtkCharArray* mystring = vtkCharArray::New();
// mystring should not delete the string when it's done,
// that's our job.
mystring->SetArray(this->MarshalString, this->MarshalDataLength, 1);
reader->SetInputArray(mystring);
mystring->Delete();
reader->Update();
object->ShallowCopy(reader->GetOutput());
reader->Delete();
return 1;
}
<|endoftext|>
|
<commit_before>#include <iostream>
#include <stdexcept>
const bool BLACK = 1;
const bool RED = 0;
template<typename T>
struct Node
{
T value;
bool color;
Node* leftNode;
Node* rightNode;
Node* parNode;
};
template<typename T>
class RedBlackTree
{
private:
Node<T>* root;
Node<T>* NIL;
public:
RedBlackTree();
~RedBlackTree();
bool _color(const T& value) const;
Node<T>* _root() const;
Node<T>* _NIL() const;
void left_rotate(Node<T>* currNode);
void right_rotate(Node<T>* currNode);
void insertFix(Node<T>* currNode);
void insert(const T& value);
void destroyTree(Node<T>* node);
void print(const Node<T>* tempNode, int level) const;
Node<T>* findElement(const T& value) const;
};
template <typename T>
RedBlackTree<T>::RedBlackTree()
{
NIL = new Node<T>;
NIL->leftNode = NIL->parNode = NIL->rightNode = nullptr;
NIL->color = BLACK;
root = NIL;
}
template <typename T>
bool RedBlackTree<T>::_color(const T& value) const
{
return findElement(value)->color;
}
template <typename T>
Node<T>* RedBlackTree<T>::_root() const
{
return root;
}
template <typename T>
Node<T>* RedBlackTree<T>::_NIL()const
{
return NIL;
}
template <typename T>
void RedBlackTree<T>::left_rotate(Node<T>* currNode)
{
Node<T>* tempNode= currNode->rightNode;
currNode->rightNode = tempNode->leftNode;
if (tempNode->leftNode != NIL)
tempNode->leftNode->parNode = currNode;
if (tempNode!= NIL)
tempNode->parNode = currNode->parNode;
if (currNode->parNode != NIL)
{
if (currNode == currNode->parNode->leftNode)
currNode->parNode->leftNode = tempNode;
else
currNode->parNode->rightNode = tempNode;
}
else
{
root = tempNode;
}
tempNode->leftNode = currNode;
if (currNode != NIL)
currNode->parNode = tempNode;
}
template <typename T>
void RedBlackTree<T>::right_rotate(Node<T> *currNode)
{
Node<T> *tempNode= currNode->leftNode;
currNode->leftNode = tempNode->rightNode;
if (tempNode->rightNode != NIL)
tempNode->rightNode->parNode = currNode;
if (tempNode!= NIL)
tempNode->parNode = currNode->parNode;
if (currNode->parNode != NIL)
{
if (currNode == currNode->parNode->rightNode)
currNode->parNode->rightNode = tempNode;
else
currNode->parNode->leftNode = tempNode;
}
else
{
root = tempNode;
}
tempNode->rightNode = currNode;
if (currNode != NIL)
currNode->parNode = tempNode;
}
template <typename T>
void RedBlackTree<T>::insertFix(Node<T>* currNode)
{
while (currNode != root && currNode->parNode->color == RED)
{
if (currNode->parNode == currNode->parNode->parNode->leftNode)
{
Node<T>* tempNode= currNode->parNode->parNode->rightNode;
if (tempNode->color == RED)
{
currNode->parNode->color = BLACK;
tempNode->color = BLACK;
currNode->parNode->parNode->color = RED;
currNode = currNode->parNode->parNode;
}
else
{
if (currNode == currNode->parNode->rightNode)
{
currNode = currNode->parNode;
left_rotate(currNode);
}
currNode->parNode->color = BLACK;
currNode->parNode->parNode->color = RED;
right_rotate(currNode->parNode->parNode);
}
}
else
{
Node<T>* tempNode= currNode->parNode->parNode->leftNode;
if (tempNode->color == RED)
{
currNode->parNode->color = BLACK;
tempNode->color = BLACK;
currNode->parNode->parNode->color = RED;
currNode = currNode->parNode->parNode;
}
else
{
if (currNode == currNode->parNode->leftNode)
{
currNode = currNode->parNode;
right_rotate(currNode);
}
currNode->parNode->color = BLACK;
currNode->parNode->parNode->color = RED;
left_rotate(currNode->parNode->parNode);
}
}
}
root->color = BLACK;
}
template <typename T>
void RedBlackTree<T>::insert(const T& value)
{
if (findElement(value))
{
throw std::logic_error("This value is already added!\n");
}
Node<T>* child = new Node<T>;
child->value = value;
child->color = RED;
child->leftNode = child->rightNode = child->parNode = NIL;
Node<T>* parNode = NIL;
Node<T>* tempNode= root;
if (root == NIL)
{
root = child;
root->color = BLACK;
return;
}
while (tempNode!= NIL)
{
if (child->value == tempNode->value)
return;
parNode = tempNode;
if (value < tempNode->value)
tempNode= tempNode->leftNode;
else
tempNode= tempNode->rightNode;
}
if (value < parNode->value)
{
parNode->leftNode = child;
}
else
{
parNode->rightNode = child;
}
child->parNode = parNode;
insertFix(child);
}
template <typename T>
void RedBlackTree<T>::print(const Node<T>* tempNode, int level)const
{
if (root == NIL)
{
throw std::logic_error("Error! The tree is empty!\n");
}
if (tempNode!= NIL)
{
print(tempNode->leftNode, level + 1);
for (int i = 0; i < level; i++)
std::cout << "\t";
std::cout << "(" << tempNode->color << ")";
std::cout << tempNode->value << "\n";
print(tempNode->rightNode, level + 1);
}
}
template <typename T>
Node<T>* RedBlackTree<T>::findElement(const T& value) const
{
Node<T>* currNode = root;
while (currNode != NIL)
{
if (value == currNode->value)
return currNode;
else
{
if (value < currNode->value)
currNode = currNode->leftNode;
else currNode = currNode->rightNode;
}
}
return 0;
}
<commit_msg>Update red_black_tree.hpp<commit_after>#include <iostream>
#include <stdexcept>
const bool BLACK = 1;
const bool RED = 0;
template<typename T>
struct Node
{
T value;
bool color;
Node* leftNode;
Node* rightNode;
Node* parNode;
};
template<typename T>
class RedBlackTree
{
private:
Node<T>* root;
Node<T>* NIL;
public:
RedBlackTree();
bool _color(const T& value) const;
Node<T>* _root() const;
Node<T>* _NIL() const;
void left_rotate(Node<T>* currNode);
void right_rotate(Node<T>* currNode);
void insertFix(Node<T>* currNode);
void insert(const T& value);
void print(const Node<T>* tempNode, int level) const;
Node<T>* findElement(const T& value) const;
};
template <typename T>
RedBlackTree<T>::RedBlackTree()
{
NIL = new Node<T>;
NIL->leftNode = NIL->parNode = NIL->rightNode = nullptr;
NIL->color = BLACK;
root = NIL;
}
template <typename T>
bool RedBlackTree<T>::_color(const T& value) const
{
return findElement(value)->color;
}
template <typename T>
Node<T>* RedBlackTree<T>::_root() const
{
return root;
}
template <typename T>
Node<T>* RedBlackTree<T>::_NIL()const
{
return NIL;
}
template <typename T>
void RedBlackTree<T>::left_rotate(Node<T>* currNode)
{
Node<T>* tempNode= currNode->rightNode;
currNode->rightNode = tempNode->leftNode;
if (tempNode->leftNode != NIL)
tempNode->leftNode->parNode = currNode;
if (tempNode!= NIL)
tempNode->parNode = currNode->parNode;
if (currNode->parNode != NIL)
{
if (currNode == currNode->parNode->leftNode)
currNode->parNode->leftNode = tempNode;
else
currNode->parNode->rightNode = tempNode;
}
else
{
root = tempNode;
}
tempNode->leftNode = currNode;
if (currNode != NIL)
currNode->parNode = tempNode;
}
template <typename T>
void RedBlackTree<T>::right_rotate(Node<T> *currNode)
{
Node<T> *tempNode= currNode->leftNode;
currNode->leftNode = tempNode->rightNode;
if (tempNode->rightNode != NIL)
tempNode->rightNode->parNode = currNode;
if (tempNode!= NIL)
tempNode->parNode = currNode->parNode;
if (currNode->parNode != NIL)
{
if (currNode == currNode->parNode->rightNode)
currNode->parNode->rightNode = tempNode;
else
currNode->parNode->leftNode = tempNode;
}
else
{
root = tempNode;
}
tempNode->rightNode = currNode;
if (currNode != NIL)
currNode->parNode = tempNode;
}
template <typename T>
void RedBlackTree<T>::insertFix(Node<T>* currNode)
{
while (currNode != root && currNode->parNode->color == RED)
{
if (currNode->parNode == currNode->parNode->parNode->leftNode)
{
Node<T>* tempNode= currNode->parNode->parNode->rightNode;
if (tempNode->color == RED)
{
currNode->parNode->color = BLACK;
tempNode->color = BLACK;
currNode->parNode->parNode->color = RED;
currNode = currNode->parNode->parNode;
}
else
{
if (currNode == currNode->parNode->rightNode)
{
currNode = currNode->parNode;
left_rotate(currNode);
}
currNode->parNode->color = BLACK;
currNode->parNode->parNode->color = RED;
right_rotate(currNode->parNode->parNode);
}
}
else
{
Node<T>* tempNode= currNode->parNode->parNode->leftNode;
if (tempNode->color == RED)
{
currNode->parNode->color = BLACK;
tempNode->color = BLACK;
currNode->parNode->parNode->color = RED;
currNode = currNode->parNode->parNode;
}
else
{
if (currNode == currNode->parNode->leftNode)
{
currNode = currNode->parNode;
right_rotate(currNode);
}
currNode->parNode->color = BLACK;
currNode->parNode->parNode->color = RED;
left_rotate(currNode->parNode->parNode);
}
}
}
root->color = BLACK;
}
template <typename T>
void RedBlackTree<T>::insert(const T& value)
{
if (findElement(value))
{
throw std::logic_error("This value is already added!\n");
}
Node<T>* child = new Node<T>;
child->value = value;
child->color = RED;
child->leftNode = child->rightNode = child->parNode = NIL;
Node<T>* parNode = NIL;
Node<T>* tempNode= root;
if (root == NIL)
{
root = child;
root->color = BLACK;
return;
}
while (tempNode!= NIL)
{
if (child->value == tempNode->value)
return;
parNode = tempNode;
if (value < tempNode->value)
tempNode= tempNode->leftNode;
else
tempNode= tempNode->rightNode;
}
if (value < parNode->value)
{
parNode->leftNode = child;
}
else
{
parNode->rightNode = child;
}
child->parNode = parNode;
insertFix(child);
}
template <typename T>
void RedBlackTree<T>::print(const Node<T>* tempNode, int level)const
{
if (root == NIL)
{
throw std::logic_error("Error! The tree is empty!\n");
}
if (tempNode!= NIL)
{
print(tempNode->leftNode, level + 1);
for (int i = 0; i < level; i++)
std::cout << "\t";
std::cout << "(" << tempNode->color << ")";
std::cout << tempNode->value << "\n";
print(tempNode->rightNode, level + 1);
}
}
template <typename T>
Node<T>* RedBlackTree<T>::findElement(const T& value) const
{
Node<T>* currNode = root;
while (currNode != NIL)
{
if (value == currNode->value)
return currNode;
else
{
if (value < currNode->value)
currNode = currNode->leftNode;
else currNode = currNode->rightNode;
}
}
return 0;
}
<|endoftext|>
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.