text stringlengths 54 60.6k |
|---|
<commit_before>#include "musicapplication.h"
#include "musicruntimemanager.h"
#include "musicnumberdefine.h"
#include "ttkdumper.h"
#include <QTimer>
#include <QTranslator>
#include <QApplication>
#define MUSIC_DEBUG
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
#if !defined MUSIC_DEBUG && !defined Q_OS_UNIX
if(argc <= 1 || QString(argv[1]) != APPNAME)
{
return -1;
}
#endif
///////////////////////////////////////////////////////
QCoreApplication::setOrganizationName(APPNAME);
QCoreApplication::setOrganizationDomain(APPCOME);
QCoreApplication::setApplicationName(APPNAME);
TTKDumper dumper;
dumper.run();
MusicRunTimeManager manager;
manager.run();
QTranslator translator;
translator.load(manager.translator());
a.installTranslator(&translator);
MusicApplication w;
w.show();
///////////////////////////////////////////////////////
if(argc == 4)
{
if( QString(argv[1]) == "-Open" )
{
w.musicImportSongsSettingPath(QStringList() << argv[2]);
QTimer::singleShot(MT_MS, &w, SLOT(musicImportPlay()));
}
if( QString(argv[1]) == "-List" )
{
w.musicImportSongsSettingPath(QStringList() << argv[2]);
}
}
return a.exec();
}
<commit_msg>#68 High dpi supported[945220]<commit_after>#include "musicapplication.h"
#include "musicruntimemanager.h"
#include "musicnumberdefine.h"
#include "ttkdumper.h"
#include <QTimer>
#include <QScreen>
#include <QTranslator>
#include <QApplication>
#define MUSIC_DEBUG
void loadDXcbPlugin(int argc, char *argv[])
{
#if QT_VERSION >= QT_VERSION_CHECK(5, 4, 0)
#if QT_VERSION >= QT_VERSION_CHECK(5, 6, 0)
Q_UNUSED(argc);
Q_UNUSED(argv);
QApplication::setAttribute(Qt::AA_EnableHighDpiScaling);
#else
QApplication a(argc, argv);
qputenv("QT_DEVICE_PIXEL_RATIO", "auto");
QScreen *screen = QApplication::primaryScreen();
qreal dpi = screen->logicalDotsPerInch()/96;
qputenv("QT_SCALE_FACTOR", QByteArray::number(dpi));
Q_UNUSED(a);
#endif
#endif
}
int main(int argc, char *argv[])
{
loadDXcbPlugin(argc, argv);
QApplication a(argc, argv);
#if !defined MUSIC_DEBUG && !defined Q_OS_UNIX
if(argc <= 1 || QString(argv[1]) != APPNAME)
{
return -1;
}
#endif
///////////////////////////////////////////////////////
QCoreApplication::setOrganizationName(APPNAME);
QCoreApplication::setOrganizationDomain(APPCOME);
QCoreApplication::setApplicationName(APPNAME);
TTKDumper dumper;
dumper.run();
MusicRunTimeManager manager;
manager.run();
QTranslator translator;
translator.load(manager.translator());
a.installTranslator(&translator);
MusicApplication w;
w.show();
///////////////////////////////////////////////////////
if(argc == 4)
{
if( QString(argv[1]) == "-Open" )
{
w.musicImportSongsSettingPath(QStringList() << argv[2]);
QTimer::singleShot(MT_MS, &w, SLOT(musicImportPlay()));
}
if( QString(argv[1]) == "-List" )
{
w.musicImportSongsSettingPath(QStringList() << argv[2]);
}
}
return a.exec();
}
<|endoftext|> |
<commit_before>//===- CallingConvEmitter.cpp - Generate calling conventions --------------===//
//
// The LLVM Compiler Infrastructure
//
// This file was developed by Chris Lattner and is distributed under
// the University of Illinois Open Source License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This tablegen backend is responsible for emitting descriptions of the calling
// conventions supported by this target.
//
//===----------------------------------------------------------------------===//
#include "CallingConvEmitter.h"
#include "Record.h"
#include "CodeGenTarget.h"
using namespace llvm;
void CallingConvEmitter::run(std::ostream &O) {
EmitSourceFileHeader("Calling Convention Implementation Fragment", O);
std::vector<Record*> CCs = Records.getAllDerivedDefinitions("CallingConv");
// Emit prototypes for all of the CC's so that they can forward ref each
// other.
for (unsigned i = 0, e = CCs.size(); i != e; ++i) {
O << "static bool " << CCs[i]->getName()
<< "(unsigned ValNo, MVT::ValueType ValVT,\n"
<< std::string(CCs[i]->getName().size()+13, ' ')
<< "MVT::ValueType LocVT, CCValAssign::LocInfo LocInfo,\n"
<< std::string(CCs[i]->getName().size()+13, ' ')
<< "unsigned ArgFlags, CCState &State);\n";
}
// Emit each calling convention description in full.
for (unsigned i = 0, e = CCs.size(); i != e; ++i)
EmitCallingConv(CCs[i], O);
}
void CallingConvEmitter::EmitCallingConv(Record *CC, std::ostream &O) {
ListInit *CCActions = CC->getValueAsListInit("Actions");
Counter = 0;
O << "\n\nstatic bool " << CC->getName()
<< "(unsigned ValNo, MVT::ValueType ValVT,\n"
<< std::string(CC->getName().size()+13, ' ')
<< "MVT::ValueType LocVT, CCValAssign::LocInfo LocInfo,\n"
<< std::string(CC->getName().size()+13, ' ')
<< "unsigned ArgFlags, CCState &State) {\n";
// Emit all of the actions, in order.
for (unsigned i = 0, e = CCActions->getSize(); i != e; ++i) {
O << "\n";
EmitAction(CCActions->getElementAsRecord(i), 2, O);
}
O << "\n return true; // CC didn't match.\n";
O << "}\n";
}
void CallingConvEmitter::EmitAction(Record *Action,
unsigned Indent, std::ostream &O) {
std::string IndentStr = std::string(Indent, ' ');
if (Action->isSubClassOf("CCPredicateAction")) {
O << IndentStr << "if (";
if (Action->isSubClassOf("CCMatchType")) {
ListInit *VTs = Action->getValueAsListInit("VTs");
for (unsigned i = 0, e = VTs->getSize(); i != e; ++i) {
Record *VT = VTs->getElementAsRecord(i);
if (i != 0) O << " ||\n " << IndentStr;
O << "LocVT == " << getEnumName(getValueType(VT));
}
} else if (Action->isSubClassOf("CCMatchIf")) {
O << Action->getValueAsString("Predicate");
} else {
Action->dump();
throw "Unknown CCPredicateAction!";
}
O << ") {\n";
EmitAction(Action->getValueAsDef("SubAction"), Indent+2, O);
O << IndentStr << "}\n";
} else {
if (Action->isSubClassOf("CCDelegateTo")) {
Record *CC = Action->getValueAsDef("CC");
O << IndentStr << "if (!" << CC->getName()
<< "(ValNo, ValVT, LocVT, LocInfo, ArgFlags, State))\n"
<< IndentStr << " return false;\n";
} else if (Action->isSubClassOf("CCAssignToReg")) {
ListInit *RegList = Action->getValueAsListInit("RegList");
if (RegList->getSize() == 1) {
O << IndentStr << "if (unsigned Reg = State.AllocateReg(";
O << getQualifiedName(RegList->getElementAsRecord(0)) << ")) {\n";
} else {
O << IndentStr << "static const unsigned RegList" << ++Counter
<< "[] = {\n";
O << IndentStr << " ";
for (unsigned i = 0, e = RegList->getSize(); i != e; ++i) {
if (i != 0) O << ", ";
O << getQualifiedName(RegList->getElementAsRecord(i));
}
O << "\n" << IndentStr << "};\n";
O << IndentStr << "if (unsigned Reg = State.AllocateReg(RegList"
<< Counter << ", " << RegList->getSize() << ")) {\n";
}
O << IndentStr << " State.addLoc(CCValAssign::getReg(ValNo, ValVT, "
<< "Reg, LocVT, LocInfo));\n";
O << IndentStr << " return false;\n";
O << IndentStr << "}\n";
} else if (Action->isSubClassOf("CCAssignToStack")) {
int Size = Action->getValueAsInt("Size");
int Align = Action->getValueAsInt("Align");
O << IndentStr << "unsigned Offset" << ++Counter
<< " = State.AllocateStack(" << Size << ", " << Align << ");\n";
O << IndentStr << "State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset"
<< Counter << ", LocVT, LocInfo));\n";
O << IndentStr << "return false;\n";
} else if (Action->isSubClassOf("CCPromoteToType")) {
Record *DestTy = Action->getValueAsDef("DestTy");
O << IndentStr << "LocVT = " << getEnumName(getValueType(DestTy)) <<";\n";
O << IndentStr << "LocInfo = (ArgFlags & 1) ? CCValAssign::SExt"
<< " : CCValAssign::ZExt;\n";
} else {
Action->dump();
throw "Unknown CCAction!";
}
}
}
<commit_msg>rename some CCActions<commit_after>//===- CallingConvEmitter.cpp - Generate calling conventions --------------===//
//
// The LLVM Compiler Infrastructure
//
// This file was developed by Chris Lattner and is distributed under
// the University of Illinois Open Source License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This tablegen backend is responsible for emitting descriptions of the calling
// conventions supported by this target.
//
//===----------------------------------------------------------------------===//
#include "CallingConvEmitter.h"
#include "Record.h"
#include "CodeGenTarget.h"
using namespace llvm;
void CallingConvEmitter::run(std::ostream &O) {
EmitSourceFileHeader("Calling Convention Implementation Fragment", O);
std::vector<Record*> CCs = Records.getAllDerivedDefinitions("CallingConv");
// Emit prototypes for all of the CC's so that they can forward ref each
// other.
for (unsigned i = 0, e = CCs.size(); i != e; ++i) {
O << "static bool " << CCs[i]->getName()
<< "(unsigned ValNo, MVT::ValueType ValVT,\n"
<< std::string(CCs[i]->getName().size()+13, ' ')
<< "MVT::ValueType LocVT, CCValAssign::LocInfo LocInfo,\n"
<< std::string(CCs[i]->getName().size()+13, ' ')
<< "unsigned ArgFlags, CCState &State);\n";
}
// Emit each calling convention description in full.
for (unsigned i = 0, e = CCs.size(); i != e; ++i)
EmitCallingConv(CCs[i], O);
}
void CallingConvEmitter::EmitCallingConv(Record *CC, std::ostream &O) {
ListInit *CCActions = CC->getValueAsListInit("Actions");
Counter = 0;
O << "\n\nstatic bool " << CC->getName()
<< "(unsigned ValNo, MVT::ValueType ValVT,\n"
<< std::string(CC->getName().size()+13, ' ')
<< "MVT::ValueType LocVT, CCValAssign::LocInfo LocInfo,\n"
<< std::string(CC->getName().size()+13, ' ')
<< "unsigned ArgFlags, CCState &State) {\n";
// Emit all of the actions, in order.
for (unsigned i = 0, e = CCActions->getSize(); i != e; ++i) {
O << "\n";
EmitAction(CCActions->getElementAsRecord(i), 2, O);
}
O << "\n return true; // CC didn't match.\n";
O << "}\n";
}
void CallingConvEmitter::EmitAction(Record *Action,
unsigned Indent, std::ostream &O) {
std::string IndentStr = std::string(Indent, ' ');
if (Action->isSubClassOf("CCPredicateAction")) {
O << IndentStr << "if (";
if (Action->isSubClassOf("CCIfType")) {
ListInit *VTs = Action->getValueAsListInit("VTs");
for (unsigned i = 0, e = VTs->getSize(); i != e; ++i) {
Record *VT = VTs->getElementAsRecord(i);
if (i != 0) O << " ||\n " << IndentStr;
O << "LocVT == " << getEnumName(getValueType(VT));
}
} else if (Action->isSubClassOf("CCIf")) {
O << Action->getValueAsString("Predicate");
} else {
Action->dump();
throw "Unknown CCPredicateAction!";
}
O << ") {\n";
EmitAction(Action->getValueAsDef("SubAction"), Indent+2, O);
O << IndentStr << "}\n";
} else {
if (Action->isSubClassOf("CCDelegateTo")) {
Record *CC = Action->getValueAsDef("CC");
O << IndentStr << "if (!" << CC->getName()
<< "(ValNo, ValVT, LocVT, LocInfo, ArgFlags, State))\n"
<< IndentStr << " return false;\n";
} else if (Action->isSubClassOf("CCAssignToReg")) {
ListInit *RegList = Action->getValueAsListInit("RegList");
if (RegList->getSize() == 1) {
O << IndentStr << "if (unsigned Reg = State.AllocateReg(";
O << getQualifiedName(RegList->getElementAsRecord(0)) << ")) {\n";
} else {
O << IndentStr << "static const unsigned RegList" << ++Counter
<< "[] = {\n";
O << IndentStr << " ";
for (unsigned i = 0, e = RegList->getSize(); i != e; ++i) {
if (i != 0) O << ", ";
O << getQualifiedName(RegList->getElementAsRecord(i));
}
O << "\n" << IndentStr << "};\n";
O << IndentStr << "if (unsigned Reg = State.AllocateReg(RegList"
<< Counter << ", " << RegList->getSize() << ")) {\n";
}
O << IndentStr << " State.addLoc(CCValAssign::getReg(ValNo, ValVT, "
<< "Reg, LocVT, LocInfo));\n";
O << IndentStr << " return false;\n";
O << IndentStr << "}\n";
} else if (Action->isSubClassOf("CCAssignToStack")) {
int Size = Action->getValueAsInt("Size");
int Align = Action->getValueAsInt("Align");
O << IndentStr << "unsigned Offset" << ++Counter
<< " = State.AllocateStack(" << Size << ", " << Align << ");\n";
O << IndentStr << "State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset"
<< Counter << ", LocVT, LocInfo));\n";
O << IndentStr << "return false;\n";
} else if (Action->isSubClassOf("CCPromoteToType")) {
Record *DestTy = Action->getValueAsDef("DestTy");
O << IndentStr << "LocVT = " << getEnumName(getValueType(DestTy)) <<";\n";
O << IndentStr << "LocInfo = (ArgFlags & 1) ? CCValAssign::SExt"
<< " : CCValAssign::ZExt;\n";
} else {
Action->dump();
throw "Unknown CCAction!";
}
}
}
<|endoftext|> |
<commit_before>/*
Copyright (c) 2006 Volker Krause <volker.krause@rwth-aachen.de>
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 "collection.h"
#include "collectionselectjob.h"
#include "imapparser.h"
#include "messagefetchjob.h"
#include "kmime_message.h"
#include <QDebug>
using namespace PIM;
class PIM::MessageFetchJobPrivate
{
public:
QByteArray path;
DataReference uid;
Message::List messages;
QByteArray tag;
};
PIM::MessageFetchJob::MessageFetchJob( const QByteArray & path, QObject * parent ) :
Job( parent ),
d( new MessageFetchJobPrivate )
{
d->path = path;
}
PIM::MessageFetchJob::MessageFetchJob( const DataReference & ref, QObject * parent ) :
Job( parent ),
d( new MessageFetchJobPrivate )
{
d->path = Collection::root();
d->uid = ref;
}
PIM::MessageFetchJob::~ MessageFetchJob( )
{
delete d;
}
void PIM::MessageFetchJob::doStart()
{
QByteArray selectPath;
if ( d->uid.isNull() ) // collection content listing
selectPath = d->path;
else // message fetching
selectPath = /*Collection::root()*/ "res1/foo"; // ### just until the server is fixed
CollectionSelectJob *job = new CollectionSelectJob( selectPath, this );
connect( job, SIGNAL(done(PIM::Job*)), SLOT(selectDone(PIM::Job*)) );
job->start();
}
void PIM::MessageFetchJob::handleResponse( const QByteArray & tag, const QByteArray & data )
{
if ( tag == d->tag ) {
if ( !data.startsWith( "OK" ) )
setError( Unknown );
emit done( this );
return;
}
if ( tag == "*" ) {
int begin = data.indexOf( "FETCH" );
if ( begin >= 0 ) {
// split fetch response into key/value pairs
QList<QByteArray> fetch;
ImapParser::parseParentheziedList( data, fetch, begin + 6 );
// create a new message object
DataReference ref = parseUid( fetch );
if ( ref.isNull() ) {
qWarning() << "No UID found in fetch response - skipping";
return;
}
Message* msg = new Message( ref );
KMime::Message* mime = new KMime::Message();
msg->setMime( mime );
d->messages.append( msg );
// parse fetch response fields
for ( int i = 0; i < fetch.count() - 1; i += 2 ) {
// flags
if ( fetch[i] == "FLAGS" ) {
QList<QByteArray> flags;
ImapParser::parseParentheziedList( fetch[i + 1], flags );
foreach ( const QByteArray flag, flags )
msg->setFlag( flag );
}
// envelope
else if ( fetch[i] == "ENVELOPE" ) {
QList<QByteArray> env;
ImapParser::parseParentheziedList( fetch[i + 1], env );
Q_ASSERT( env.count() >= 10 );
// date
mime->date()->from7BitString( env[0] );
// subject
mime->subject()->from7BitString( env[1] );
// from
QList<QByteArray> addrList;
ImapParser::parseParentheziedList( env[2], addrList );
if ( addrList.count() >= 1 ) {
QList<QByteArray> addr;
ImapParser::parseParentheziedList( addrList[0], addr );
Q_ASSERT( addr.count() == 4 );
mime->from()->setName( addr[0] );
mime->from()->setEmail( addr[2] + "@" + addr[3] );
}
// sender
// not supported by kmime, skipp it
// reply-to
ImapParser::parseParentheziedList( env[4], addrList );
if ( addrList.count() >= 1 ) {
QList<QByteArray> addr;
ImapParser::parseParentheziedList( addrList[0], addr );
Q_ASSERT( addr.count() == 4 );
mime->replyTo()->setNameFrom7Bit( addr[0] );
mime->replyTo()->setEmail( addr[2] + "@" + addr[3] );
}
// to
ImapParser::parseParentheziedList( env[5], addrList );
foreach ( const QByteArray ba, addrList ) {
QList<QByteArray> addr;
ImapParser::parseParentheziedList( ba, addr );
Q_ASSERT( addr.count() == 4 );
KMime::Headers::AddressField addrField;
addrField.setNameFrom7Bit( addr[0] );
addrField.setEmail( addr[2] + "@" + addr[3] );
mime->to()->addAddress( addrField );
}
// cc
ImapParser::parseParentheziedList( env[6], addrList );
foreach ( const QByteArray ba, addrList ) {
QList<QByteArray> addr;
ImapParser::parseParentheziedList( ba, addr );
Q_ASSERT( addr.count() == 4 );
KMime::Headers::AddressField addrField;
addrField.setNameFrom7Bit( addr[0] );
addrField.setEmail( addr[2] + "@" + addr[3] );
mime->cc()->addAddress( addrField );
}
// bcc
ImapParser::parseParentheziedList( env[7], addrList );
foreach ( const QByteArray ba, addrList ) {
QList<QByteArray> addr;
ImapParser::parseParentheziedList( ba, addr );
Q_ASSERT( addr.count() == 4 );
KMime::Headers::AddressField addrField;
addrField.setNameFrom7Bit( addr[0] );
addrField.setEmail( addr[2] + "@" + addr[3] );
mime->bcc()->addAddress( addrField );
}
// in-reply-to
// not yet supported by KMime
// message id
mime->messageID()->from7BitString( env[9] );
}
// rfc822 body
else if ( fetch[i] == "RFC822" ) {
mime->setContent( fetch[i + 1] );
}
}
Q_ASSERT( msg );
return;
}
}
qDebug() << "Unhandled response in message fetch job: " << tag << data;
}
Message::List PIM::MessageFetchJob::messages() const
{
return d->messages;
}
void PIM::MessageFetchJob::selectDone( PIM::Job * job )
{
if ( job->error() ) {
setError( job->error() );
emit done( this );
} else {
job->deleteLater();
// the collection is now selected, fetch the message(s)
d->tag = newTag();
QByteArray command = d->tag;
if ( d->uid.isNull() )
command += " FETCH 1:* (UID FLAGS ENVELOPE)";
else
command += " UID FETCH " + d->uid.persistanceID().toLatin1() + " (UID FLAGS RFC822)";
writeData( command );
}
}
DataReference PIM::MessageFetchJob::parseUid( const QList< QByteArray > & fetchResponse )
{
int index = fetchResponse.indexOf( "UID" );
if ( index < 0 ) {
qWarning() << "Fetch response doesn't contain a UID field!";
return DataReference();
}
if ( index == fetchResponse.count() - 1 ) {
qWarning() << "Broken fetch response: No value for UID field!";
return DataReference();
}
return DataReference( fetchResponse[index + 1], QString() );
}
#include "messagefetchjob.moc"
<commit_msg>Refactor envelope parsing and don't use asserts for error handling anymore.<commit_after>/*
Copyright (c) 2006 Volker Krause <volker.krause@rwth-aachen.de>
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 "collection.h"
#include "collectionselectjob.h"
#include "imapparser.h"
#include "messagefetchjob.h"
#include "kmime_message.h"
#include "kmime_headers.h"
#include <QDebug>
using namespace PIM;
class PIM::MessageFetchJobPrivate
{
public:
QByteArray path;
DataReference uid;
Message::List messages;
QByteArray tag;
public:
void parseAddrField( const QList<QByteArray> &addrField, KMime::Headers::AddressField *hdr )
{
if ( addrField.count() != 1 ) {
qWarning() << "Error parsing envelope - address field does not contains exactly one entry: " << addrField;
return;
}
QList<QByteArray> addr;
ImapParser::parseParentheziedList( addrField[0], addr );
if ( addr.count() != 4 ) {
qWarning() << "Error parsing envelope address field: " << addr;
return;
}
hdr->setName( addr[0] );
hdr->setEmail( addr[2] + "@" + addr[3] );
}
void parseAddrList( const QList<QByteArray> &addrList, KMime::Headers::To *hdr )
{
foreach ( const QByteArray ba, addrList ) {
QList<QByteArray> addr;
ImapParser::parseParentheziedList( ba, addr );
if ( addr.count() != 4 ) {
qWarning() << "Error parsing envelope address field: " << addr;
continue;
}
KMime::Headers::AddressField addrField;
addrField.setNameFrom7Bit( addr[0] );
addrField.setEmail( addr[2] + "@" + addr[3] );
hdr->addAddress( addrField );
}
}
};
PIM::MessageFetchJob::MessageFetchJob( const QByteArray & path, QObject * parent ) :
Job( parent ),
d( new MessageFetchJobPrivate )
{
d->path = path;
}
PIM::MessageFetchJob::MessageFetchJob( const DataReference & ref, QObject * parent ) :
Job( parent ),
d( new MessageFetchJobPrivate )
{
d->path = Collection::root();
d->uid = ref;
}
PIM::MessageFetchJob::~ MessageFetchJob( )
{
delete d;
}
void PIM::MessageFetchJob::doStart()
{
QByteArray selectPath;
if ( d->uid.isNull() ) // collection content listing
selectPath = d->path;
else // message fetching
selectPath = /*Collection::root()*/ "res1/foo"; // ### just until the server is fixed
CollectionSelectJob *job = new CollectionSelectJob( selectPath, this );
connect( job, SIGNAL(done(PIM::Job*)), SLOT(selectDone(PIM::Job*)) );
job->start();
}
void PIM::MessageFetchJob::handleResponse( const QByteArray & tag, const QByteArray & data )
{
if ( tag == d->tag ) {
if ( !data.startsWith( "OK" ) )
setError( Unknown );
emit done( this );
return;
}
if ( tag == "*" ) {
int begin = data.indexOf( "FETCH" );
if ( begin >= 0 ) {
// split fetch response into key/value pairs
QList<QByteArray> fetch;
ImapParser::parseParentheziedList( data, fetch, begin + 6 );
// create a new message object
DataReference ref = parseUid( fetch );
if ( ref.isNull() ) {
qWarning() << "No UID found in fetch response - skipping";
return;
}
Message* msg = new Message( ref );
KMime::Message* mime = new KMime::Message();
msg->setMime( mime );
d->messages.append( msg );
// parse fetch response fields
for ( int i = 0; i < fetch.count() - 1; i += 2 ) {
// flags
if ( fetch[i] == "FLAGS" ) {
QList<QByteArray> flags;
ImapParser::parseParentheziedList( fetch[i + 1], flags );
foreach ( const QByteArray flag, flags )
msg->setFlag( flag );
}
// envelope
else if ( fetch[i] == "ENVELOPE" ) {
QList<QByteArray> env;
ImapParser::parseParentheziedList( fetch[i + 1], env );
Q_ASSERT( env.count() >= 10 );
// date
mime->date()->from7BitString( env[0] );
// subject
mime->subject()->from7BitString( env[1] );
// from
QList<QByteArray> addrList;
ImapParser::parseParentheziedList( env[2], addrList );
d->parseAddrField( addrList, mime->from() );
// sender
// not supported by kmime, skipp it
// reply-to
ImapParser::parseParentheziedList( env[4], addrList );
d->parseAddrField( addrList, mime->replyTo() );
// to
ImapParser::parseParentheziedList( env[5], addrList );
if ( !addrList.isEmpty() )
d->parseAddrList( addrList, mime->to() );
// cc
ImapParser::parseParentheziedList( env[6], addrList );
if ( !addrList.isEmpty() )
d->parseAddrList( addrList, mime->cc() );
// bcc
ImapParser::parseParentheziedList( env[7], addrList );
if ( !addrList.isEmpty() )
d->parseAddrList( addrList, mime->bcc() );
// in-reply-to
// not yet supported by KMime
// message id
mime->messageID()->from7BitString( env[9] );
}
// rfc822 body
else if ( fetch[i] == "RFC822" ) {
mime->setContent( fetch[i + 1] );
}
}
Q_ASSERT( msg );
return;
}
}
qDebug() << "Unhandled response in message fetch job: " << tag << data;
}
Message::List PIM::MessageFetchJob::messages() const
{
return d->messages;
}
void PIM::MessageFetchJob::selectDone( PIM::Job * job )
{
if ( job->error() ) {
setError( job->error() );
emit done( this );
} else {
job->deleteLater();
// the collection is now selected, fetch the message(s)
d->tag = newTag();
QByteArray command = d->tag;
if ( d->uid.isNull() )
command += " FETCH 1:* (UID FLAGS ENVELOPE)";
else
command += " UID FETCH " + d->uid.persistanceID().toLatin1() + " (UID FLAGS RFC822)";
writeData( command );
}
}
DataReference PIM::MessageFetchJob::parseUid( const QList< QByteArray > & fetchResponse )
{
int index = fetchResponse.indexOf( "UID" );
if ( index < 0 ) {
qWarning() << "Fetch response doesn't contain a UID field!";
return DataReference();
}
if ( index == fetchResponse.count() - 1 ) {
qWarning() << "Broken fetch response: No value for UID field!";
return DataReference();
}
return DataReference( fetchResponse[index + 1], QString() );
}
#include "messagefetchjob.moc"
<|endoftext|> |
<commit_before>//===- Parser.cpp - Main dispatch module for the Parser library -------------===
//
// This library implements the functionality defined in llvm/assembly/parser.h
//
//===------------------------------------------------------------------------===
#include "llvm/Analysis/Verifier.h"
#include "llvm/Module.h"
#include "ParserInternals.h"
#include <stdio.h> // for sprintf
using std::string;
// The useful interface defined by this file... Parse an ascii file, and return
// the internal representation in a nice slice'n'dice'able representation.
//
Module *ParseAssemblyFile(const string &Filename) { // throw (ParseException)
FILE *F = stdin;
if (Filename != "-")
F = fopen(Filename.c_str(), "r");
if (F == 0) {
throw ParseException(Filename, string("Could not open file '") +
Filename + "'");
}
// TODO: If this throws an exception, F is not closed.
Module *Result = RunVMAsmParser(Filename, F);
if (F != stdin)
fclose(F);
if (Result) { // Check to see that it is valid...
if (verifyModule(Result)) {
delete Result;
throw ParseException(Filename, "Source file is not well formed LLVM!");
}
}
return Result;
}
//===------------------------------------------------------------------------===
// ParseException Class
//===------------------------------------------------------------------------===
ParseException::ParseException(const string &filename, const string &message,
int lineNo, int colNo)
: Filename(filename), Message(message) {
LineNo = lineNo; ColumnNo = colNo;
}
ParseException::ParseException(const ParseException &E)
: Filename(E.Filename), Message(E.Message) {
LineNo = E.LineNo;
ColumnNo = E.ColumnNo;
}
const string ParseException::getMessage() const { // Includes info from options
string Result;
char Buffer[10];
if (Filename == "-")
Result += "<stdin>";
else
Result += Filename;
if (LineNo != -1) {
sprintf(Buffer, "%d", LineNo);
Result += string(":") + Buffer;
if (ColumnNo != -1) {
sprintf(Buffer, "%d", ColumnNo);
Result += string(",") + Buffer;
}
}
return Result + ": " + Message;
}
<commit_msg>Close input file if exception is thrown<commit_after>//===- Parser.cpp - Main dispatch module for the Parser library -------------===
//
// This library implements the functionality defined in llvm/assembly/parser.h
//
//===------------------------------------------------------------------------===
#include "llvm/Analysis/Verifier.h"
#include "llvm/Module.h"
#include "ParserInternals.h"
#include <stdio.h> // for sprintf
using std::string;
// The useful interface defined by this file... Parse an ascii file, and return
// the internal representation in a nice slice'n'dice'able representation.
//
Module *ParseAssemblyFile(const string &Filename) { // throw (ParseException)
FILE *F = stdin;
if (Filename != "-") {
F = fopen(Filename.c_str(), "r");
if (F == 0)
throw ParseException(Filename, "Could not open file '" + Filename + "'");
}
Module *Result;
try {
Result = RunVMAsmParser(Filename, F);
} catch (...) {
if (F != stdin) fclose(F); // Make sure to close file descriptor if an
throw; // exception is thrown
}
if (F != stdin)
fclose(F);
if (Result) { // Check to see that it is valid...
if (verifyModule(Result)) {
delete Result;
throw ParseException(Filename, "Source file is not well formed LLVM!");
}
}
return Result;
}
//===------------------------------------------------------------------------===
// ParseException Class
//===------------------------------------------------------------------------===
ParseException::ParseException(const string &filename, const string &message,
int lineNo, int colNo)
: Filename(filename), Message(message) {
LineNo = lineNo; ColumnNo = colNo;
}
ParseException::ParseException(const ParseException &E)
: Filename(E.Filename), Message(E.Message) {
LineNo = E.LineNo;
ColumnNo = E.ColumnNo;
}
const string ParseException::getMessage() const { // Includes info from options
string Result;
char Buffer[10];
if (Filename == "-")
Result += "<stdin>";
else
Result += Filename;
if (LineNo != -1) {
sprintf(Buffer, "%d", LineNo);
Result += string(":") + Buffer;
if (ColumnNo != -1) {
sprintf(Buffer, "%d", ColumnNo);
Result += string(",") + Buffer;
}
}
return Result + ": " + Message;
}
<|endoftext|> |
<commit_before>////////////////////////////////////////////////////////////////////////////////
/// @brief debugging helpers
///
/// @file
///
/// DISCLAIMER
///
/// Copyright 2014 ArangoDB GmbH, Cologne, Germany
/// Copyright 2004-2014 triAGENS GmbH, Cologne, Germany
///
/// Licensed under the Apache License, Version 2.0 (the "License");
/// you may not use this file except in compliance with the License.
/// You may obtain a copy of the License at
///
/// http://www.apache.org/licenses/LICENSE-2.0
///
/// Unless required by applicable law or agreed to in writing, software
/// distributed under the License is distributed on an "AS IS" BASIS,
/// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
/// See the License for the specific language governing permissions and
/// limitations under the License.
///
/// Copyright holder is ArangoDB GmbH, Cologne, Germany
///
/// @author Jan Steemann
/// @author Copyright 2014, ArangoDB GmbH, Cologne, Germany
/// @author Copyright 2011-2013, triAGENS GmbH, Cologne, Germany
////////////////////////////////////////////////////////////////////////////////
#include "Basics/Common.h"
#include "Basics/locks.h"
#include "Basics/logging.h"
#ifdef TRI_ENABLE_MAINTAINER_MODE
#if HAVE_BACKTRACE
#ifdef _WIN32
#include <DbgHelp.h>
#else
#include <execinfo.h>
#include <cxxabi.h>
#endif
#endif
#endif
// -----------------------------------------------------------------------------
// --SECTION-- private variables
// -----------------------------------------------------------------------------
////////////////////////////////////////////////////////////////////////////////
/// @brief a global string containing the currently registered failure points
/// the string is a comma-separated list of point names
////////////////////////////////////////////////////////////////////////////////
static char* FailurePoints;
////////////////////////////////////////////////////////////////////////////////
/// @brief a read-write lock for thread-safe access to the failure-points list
////////////////////////////////////////////////////////////////////////////////
TRI_read_write_lock_t FailurePointsLock;
#ifdef TRI_ENABLE_FAILURE_TESTS
// -----------------------------------------------------------------------------
// --SECTION-- private functions
// -----------------------------------------------------------------------------
////////////////////////////////////////////////////////////////////////////////
/// @brief make a delimited value from a string, so we can unambigiously
/// search for it (e.g. searching for just "foo" would find "foo" and "foobar",
/// so we'll be putting the value inside some delimiter: ",foo,")
////////////////////////////////////////////////////////////////////////////////
static char* MakeValue (char const* value) {
if (value == nullptr || strlen(value) == 0) {
return nullptr;
}
char* delimited = static_cast<char*>(TRI_Allocate(TRI_CORE_MEM_ZONE, strlen(value) + 3, false));
if (delimited != nullptr) {
memcpy(delimited + 1, value, strlen(value));
delimited[0] = ',';
delimited[strlen(value) + 1] = ',';
delimited[strlen(value) + 2] = '\0';
}
return delimited;
}
// -----------------------------------------------------------------------------
// --SECTION-- public functions
// -----------------------------------------------------------------------------
////////////////////////////////////////////////////////////////////////////////
/// @brief cause a segmentation violation
/// this is used for crash and recovery tests
////////////////////////////////////////////////////////////////////////////////
void TRI_SegfaultDebugging (char const* message) {
LOG_WARNING("%s: summon Baal!", message);
// make sure the latest log messages are flushed
TRI_ShutdownLogging(true);
// and now crash
#ifndef __APPLE__
// on MacOS, the following statement makes the server hang but not crash
*((char*) -1) = '!';
#endif
// ensure the process is terminated
abort();
}
////////////////////////////////////////////////////////////////////////////////
/// @brief check whether we should fail at a specific failure point
////////////////////////////////////////////////////////////////////////////////
bool TRI_ShouldFailDebugging (char const* value) {
char* found = nullptr;
// try without the lock first (to speed things up)
if (FailurePoints == nullptr) {
return false;
}
TRI_ReadLockReadWriteLock(&FailurePointsLock);
if (FailurePoints != nullptr) {
char* checkValue = MakeValue(value);
if (checkValue != nullptr) {
found = strstr(FailurePoints, checkValue);
TRI_Free(TRI_CORE_MEM_ZONE, checkValue);
}
}
TRI_ReadUnlockReadWriteLock(&FailurePointsLock);
return (found != nullptr);
}
////////////////////////////////////////////////////////////////////////////////
/// @brief add a failure point
////////////////////////////////////////////////////////////////////////////////
void TRI_AddFailurePointDebugging (char const* value) {
char* found;
char* checkValue;
checkValue = MakeValue(value);
if (checkValue == nullptr) {
return;
}
TRI_WriteLockReadWriteLock(&FailurePointsLock);
if (FailurePoints == nullptr) {
found = nullptr;
}
else {
found = strstr(FailurePoints, checkValue);
}
if (found == nullptr) {
// not yet found. so add it
char* copy;
size_t n;
LOG_WARNING("activating intentional failure point '%s'. the server will misbehave!", value);
n = strlen(checkValue);
if (FailurePoints == nullptr) {
copy = static_cast<char*>(TRI_Allocate(TRI_CORE_MEM_ZONE, n + 1, false));
if (copy == nullptr) {
TRI_WriteUnlockReadWriteLock(&FailurePointsLock);
TRI_Free(TRI_CORE_MEM_ZONE, checkValue);
return;
}
memcpy(copy, checkValue, n);
copy[n] = '\0';
}
else {
copy = static_cast<char*>(TRI_Allocate(TRI_CORE_MEM_ZONE, n + strlen(FailurePoints), false));
if (copy == nullptr) {
TRI_WriteUnlockReadWriteLock(&FailurePointsLock);
TRI_Free(TRI_CORE_MEM_ZONE, checkValue);
return;
}
memcpy(copy, FailurePoints, strlen(FailurePoints));
memcpy(copy + strlen(FailurePoints) - 1, checkValue, n);
copy[strlen(FailurePoints) + n - 1] = '\0';
}
FailurePoints = copy;
}
TRI_WriteUnlockReadWriteLock(&FailurePointsLock);
TRI_Free(TRI_CORE_MEM_ZONE, checkValue);
}
////////////////////////////////////////////////////////////////////////////////
/// @brief remove a failure points
////////////////////////////////////////////////////////////////////////////////
void TRI_RemoveFailurePointDebugging (char const* value) {
char* checkValue;
TRI_WriteLockReadWriteLock(&FailurePointsLock);
if (FailurePoints == nullptr) {
TRI_WriteUnlockReadWriteLock(&FailurePointsLock);
return;
}
checkValue = MakeValue(value);
if (checkValue != nullptr) {
char* found;
char* copy;
size_t n;
found = strstr(FailurePoints, checkValue);
if (found == nullptr) {
TRI_WriteUnlockReadWriteLock(&FailurePointsLock);
TRI_Free(TRI_CORE_MEM_ZONE, checkValue);
return;
}
if (strlen(FailurePoints) - strlen(checkValue) <= 2) {
TRI_Free(TRI_CORE_MEM_ZONE, FailurePoints);
FailurePoints = nullptr;
TRI_WriteUnlockReadWriteLock(&FailurePointsLock);
TRI_Free(TRI_CORE_MEM_ZONE, checkValue);
return;
}
copy = static_cast<char*>(TRI_Allocate(TRI_CORE_MEM_ZONE, strlen(FailurePoints) - strlen(checkValue) + 2, false));
if (copy == nullptr) {
TRI_WriteUnlockReadWriteLock(&FailurePointsLock);
TRI_Free(TRI_CORE_MEM_ZONE, checkValue);
return;
}
// copy start of string
n = found - FailurePoints;
memcpy(copy, FailurePoints, n);
// copy remainder of string
memcpy(copy + n, found + strlen(checkValue) - 1, strlen(FailurePoints) - strlen(checkValue) - n + 1);
copy[strlen(FailurePoints) - strlen(checkValue) + 1] = '\0';
TRI_Free(TRI_CORE_MEM_ZONE, FailurePoints);
FailurePoints = copy;
TRI_WriteUnlockReadWriteLock(&FailurePointsLock);
TRI_Free(TRI_CORE_MEM_ZONE, checkValue);
}
}
////////////////////////////////////////////////////////////////////////////////
/// @brief clear all failure points
////////////////////////////////////////////////////////////////////////////////
void TRI_ClearFailurePointsDebugging () {
TRI_WriteLockReadWriteLock(&FailurePointsLock);
if (FailurePoints != nullptr) {
TRI_Free(TRI_CORE_MEM_ZONE, FailurePoints);
}
FailurePoints = nullptr;
TRI_WriteUnlockReadWriteLock(&FailurePointsLock);
}
#endif
////////////////////////////////////////////////////////////////////////////////
/// @brief initialise the debugging
////////////////////////////////////////////////////////////////////////////////
void TRI_InitialiseDebugging () {
FailurePoints = nullptr;
TRI_InitReadWriteLock(&FailurePointsLock);
}
////////////////////////////////////////////////////////////////////////////////
/// @brief shutdown the debugging
////////////////////////////////////////////////////////////////////////////////
void TRI_ShutdownDebugging () {
if (FailurePoints != nullptr) {
TRI_Free(TRI_CORE_MEM_ZONE, FailurePoints);
}
FailurePoints = nullptr;
TRI_DestroyReadWriteLock(&FailurePointsLock);
}
////////////////////////////////////////////////////////////////////////////////
/// @brief appends a backtrace to the string provided
////////////////////////////////////////////////////////////////////////////////
void TRI_GetBacktrace (std::string& btstr) {
#if HAVE_BACKTRACE
#ifdef _WIN32
void * stack[100];
unsigned short frames;
SYMBOL_INFO * symbol;
HANDLE process;
process = GetCurrentProcess();
SymInitialize(process, nullptr, true);
frames = CaptureStackBackTrace(0, 100, stack, nullptr);
symbol = (SYMBOL_INFO*) calloc(sizeof(SYMBOL_INFO) + 256 * sizeof(char), 1);
if (symbol == nullptr) {
// cannot allocate memory
return;
}
symbol->MaxNameLen = 255;
symbol->SizeOfStruct = sizeof(SYMBOL_INFO);
for (unsigned int i = 0; i < frames; i++) {
char address[64];
SymFromAddr(process, (DWORD64) stack[i], 0, symbol);
snprintf(address, sizeof(address), "0x%0X", (unsigned int) symbol->Address);
btstr += std::to_string(frames - i - 1) + std::string(": ") + symbol->Name + std::string(" [") + address + std::string("]\n");
}
TRI_SystemFree(symbol);
#else
void* stack_frames[50];
size_t size, i;
char** strings;
size = backtrace(stack_frames, sizeof(stack_frames) / sizeof(void*));
strings = backtrace_symbols(stack_frames, size);
for (i = 0; i < size; i++) {
std::stringstream ss;
if (strings != nullptr) {
char *mangled_name = nullptr, *offset_begin = nullptr, *offset_end = nullptr;
// find parantheses and +address offset surrounding mangled name
for (char *p = strings[i]; *p; ++p) {
if (*p == '(') {
mangled_name = p;
}
else if (*p == '+') {
offset_begin = p;
}
else if (*p == ')') {
offset_end = p;
break;
}
}
// TODO: osx demangling works a little bit different.
// http://oroboro.com/stack-trace-on-crash/
// says it should look like that:
//#ifdef DARWIN
// // OSX style stack trace
// for ( char *p = symbollist[i]; *p; ++p )
// {
// if (( *p == '_' ) && ( *(p-1) == ' ' ))
// begin_name = p-1;
// else if ( *p == '+' )
// begin_offset = p-1;
// }
//
// if ( begin_name && begin_offset && ( begin_name < begin_offset ))
// {
// *begin_name++ = '\0';
// *begin_offset++ = '\0';
//
// // mangled name is now in [begin_name, begin_offset) and caller
// // offset in [begin_offset, end_offset). now apply
// // __cxa_demangle():
// int status;
// char* ret = abi::__cxa_demangle( begin_name, &funcname[0],
// &funcnamesize, &status );
// if ( status == 0 )
// {
// funcname = ret; // use possibly realloc()-ed string
// fprintf( out, " %-30s %-40s %s\n",
// symbollist[i], funcname, begin_offset );
// } else {
// // demangling failed. Output function name as a C function with
// // no arguments.
// fprintf( out, " %-30s %-38s() %s\n",
// symbollist[i], begin_name, begin_offset );
// }
//
//#else // !DARWIN - but is posix
// if the line could be processed, attempt to demangle the symbol
if (mangled_name && offset_begin && offset_end &&
mangled_name < offset_begin) {
*mangled_name++ = '\0';
*offset_begin++ = '\0';
*offset_end++ = '\0';
int status = 0;
char * demangled_name = abi::__cxa_demangle(mangled_name, 0, 0, &status);
if (demangled_name != nullptr) {
if (status == 0) {
ss << stack_frames[i];
btstr += strings[i] +
std::string("() [") +
ss.str() +
std::string("] ") +
demangled_name +
std::string("\n");
}
else {
btstr += strings[i] +
std::string("\n");
}
TRI_SystemFree(demangled_name);
}
}
else {
btstr += strings[i] +
std::string("\n");
}
}
else {
ss << stack_frames[i];
btstr += ss.str() +
std::string("\n");
}
}
if (strings != nullptr) {
TRI_SystemFree(strings);
}
#endif
#endif
}
////////////////////////////////////////////////////////////////////////////////
/// @brief prints a backtrace on stderr
////////////////////////////////////////////////////////////////////////////////
void TRI_PrintBacktrace () {
#if HAVE_BACKTRACE
std::string out;
TRI_GetBacktrace(out);
fprintf(stderr, "%s", out.c_str());
#endif
}
// -----------------------------------------------------------------------------
// --SECTION-- END-OF-FILE
// -----------------------------------------------------------------------------
// Local Variables:
// mode: outline-minor
// outline-regexp: "/// @brief\\|/// {@inheritDoc}\\|/// @page\\|// --SECTION--\\|/// @\\}"
// End:
<commit_msg>use ReadWriteLocker<commit_after>////////////////////////////////////////////////////////////////////////////////
/// @brief debugging helpers
///
/// @file
///
/// DISCLAIMER
///
/// Copyright 2014 ArangoDB GmbH, Cologne, Germany
/// Copyright 2004-2014 triAGENS GmbH, Cologne, Germany
///
/// Licensed under the Apache License, Version 2.0 (the "License");
/// you may not use this file except in compliance with the License.
/// You may obtain a copy of the License at
///
/// http://www.apache.org/licenses/LICENSE-2.0
///
/// Unless required by applicable law or agreed to in writing, software
/// distributed under the License is distributed on an "AS IS" BASIS,
/// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
/// See the License for the specific language governing permissions and
/// limitations under the License.
///
/// Copyright holder is ArangoDB GmbH, Cologne, Germany
///
/// @author Jan Steemann
/// @author Copyright 2014, ArangoDB GmbH, Cologne, Germany
/// @author Copyright 2011-2013, triAGENS GmbH, Cologne, Germany
////////////////////////////////////////////////////////////////////////////////
#include "Basics/Common.h"
#include "Basics/logging.h"
#include "Basics/ReadLocker.h"
#include "Basics/ReadWriteLock.h"
#include "Basics/WriteLocker.h"
#ifdef TRI_ENABLE_MAINTAINER_MODE
#if HAVE_BACKTRACE
#ifdef _WIN32
#include <DbgHelp.h>
#else
#include <execinfo.h>
#include <cxxabi.h>
#endif
#endif
#endif
// -----------------------------------------------------------------------------
// --SECTION-- private variables
// -----------------------------------------------------------------------------
////////////////////////////////////////////////////////////////////////////////
/// @brief a global string containing the currently registered failure points
/// the string is a comma-separated list of point names
////////////////////////////////////////////////////////////////////////////////
static char* FailurePoints = nullptr;
////////////////////////////////////////////////////////////////////////////////
/// @brief a read-write lock for thread-safe access to the failure-points list
////////////////////////////////////////////////////////////////////////////////
triagens::basics::ReadWriteLock FailurePointsLock;
#ifdef TRI_ENABLE_FAILURE_TESTS
// -----------------------------------------------------------------------------
// --SECTION-- private functions
// -----------------------------------------------------------------------------
////////////////////////////////////////////////////////////////////////////////
/// @brief make a delimited value from a string, so we can unambigiously
/// search for it (e.g. searching for just "foo" would find "foo" and "foobar",
/// so we'll be putting the value inside some delimiter: ",foo,")
////////////////////////////////////////////////////////////////////////////////
static char* MakeValue (char const* value) {
if (value == nullptr || strlen(value) == 0) {
return nullptr;
}
char* delimited = static_cast<char*>(TRI_Allocate(TRI_CORE_MEM_ZONE, strlen(value) + 3, false));
if (delimited != nullptr) {
memcpy(delimited + 1, value, strlen(value));
delimited[0] = ',';
delimited[strlen(value) + 1] = ',';
delimited[strlen(value) + 2] = '\0';
}
return delimited;
}
// -----------------------------------------------------------------------------
// --SECTION-- public functions
// -----------------------------------------------------------------------------
////////////////////////////////////////////////////////////////////////////////
/// @brief cause a segmentation violation
/// this is used for crash and recovery tests
////////////////////////////////////////////////////////////////////////////////
void TRI_SegfaultDebugging (char const* message) {
LOG_WARNING("%s: summon Baal!", message);
// make sure the latest log messages are flushed
TRI_ShutdownLogging(true);
// and now crash
#ifndef __APPLE__
// on MacOS, the following statement makes the server hang but not crash
*((char*) -1) = '!';
#endif
// ensure the process is terminated
abort();
}
////////////////////////////////////////////////////////////////////////////////
/// @brief check whether we should fail at a specific failure point
////////////////////////////////////////////////////////////////////////////////
bool TRI_ShouldFailDebugging (char const* value) {
char* found = nullptr;
// try without the lock first (to speed things up)
if (FailurePoints == nullptr) {
return false;
}
READ_LOCKER(FailurePointsLock);
if (FailurePoints != nullptr) {
char* checkValue = MakeValue(value);
if (checkValue != nullptr) {
found = strstr(FailurePoints, checkValue);
TRI_Free(TRI_CORE_MEM_ZONE, checkValue);
}
}
return (found != nullptr);
}
////////////////////////////////////////////////////////////////////////////////
/// @brief add a failure point
////////////////////////////////////////////////////////////////////////////////
void TRI_AddFailurePointDebugging (char const* value) {
char* found;
char* checkValue = MakeValue(value);
if (checkValue == nullptr) {
return;
}
WRITE_LOCKER(FailurePointsLock);
if (FailurePoints == nullptr) {
found = nullptr;
}
else {
found = strstr(FailurePoints, checkValue);
}
if (found == nullptr) {
// not yet found. so add it
char* copy;
LOG_WARNING("activating intentional failure point '%s'. the server will misbehave!", value);
size_t n = strlen(checkValue);
if (FailurePoints == nullptr) {
copy = static_cast<char*>(TRI_Allocate(TRI_CORE_MEM_ZONE, n + 1, false));
if (copy == nullptr) {
TRI_Free(TRI_CORE_MEM_ZONE, checkValue);
return;
}
memcpy(copy, checkValue, n);
copy[n] = '\0';
}
else {
copy = static_cast<char*>(TRI_Allocate(TRI_CORE_MEM_ZONE, n + strlen(FailurePoints), false));
if (copy == nullptr) {
TRI_Free(TRI_CORE_MEM_ZONE, checkValue);
return;
}
memcpy(copy, FailurePoints, strlen(FailurePoints));
memcpy(copy + strlen(FailurePoints) - 1, checkValue, n);
copy[strlen(FailurePoints) + n - 1] = '\0';
}
FailurePoints = copy;
}
TRI_Free(TRI_CORE_MEM_ZONE, checkValue);
}
////////////////////////////////////////////////////////////////////////////////
/// @brief remove a failure points
////////////////////////////////////////////////////////////////////////////////
void TRI_RemoveFailurePointDebugging (char const* value) {
WRITE_LOCKER(FailurePointsLock);
if (FailurePoints == nullptr) {
return;
}
char* checkValue = MakeValue(value);
if (checkValue != nullptr) {
char* found;
char* copy;
size_t n;
found = strstr(FailurePoints, checkValue);
if (found == nullptr) {
TRI_Free(TRI_CORE_MEM_ZONE, checkValue);
return;
}
if (strlen(FailurePoints) - strlen(checkValue) <= 2) {
TRI_Free(TRI_CORE_MEM_ZONE, FailurePoints);
FailurePoints = nullptr;
TRI_Free(TRI_CORE_MEM_ZONE, checkValue);
return;
}
copy = static_cast<char*>(TRI_Allocate(TRI_CORE_MEM_ZONE, strlen(FailurePoints) - strlen(checkValue) + 2, false));
if (copy == nullptr) {
TRI_Free(TRI_CORE_MEM_ZONE, checkValue);
return;
}
// copy start of string
n = found - FailurePoints;
memcpy(copy, FailurePoints, n);
// copy remainder of string
memcpy(copy + n, found + strlen(checkValue) - 1, strlen(FailurePoints) - strlen(checkValue) - n + 1);
copy[strlen(FailurePoints) - strlen(checkValue) + 1] = '\0';
TRI_Free(TRI_CORE_MEM_ZONE, FailurePoints);
FailurePoints = copy;
TRI_Free(TRI_CORE_MEM_ZONE, checkValue);
}
}
////////////////////////////////////////////////////////////////////////////////
/// @brief clear all failure points
////////////////////////////////////////////////////////////////////////////////
void TRI_ClearFailurePointsDebugging () {
WRITE_LOCKER(FailurePointsLock);
if (FailurePoints != nullptr) {
TRI_Free(TRI_CORE_MEM_ZONE, FailurePoints);
}
FailurePoints = nullptr;
}
#endif
////////////////////////////////////////////////////////////////////////////////
/// @brief initialise the debugging
////////////////////////////////////////////////////////////////////////////////
void TRI_InitialiseDebugging () {
}
////////////////////////////////////////////////////////////////////////////////
/// @brief shutdown the debugging
////////////////////////////////////////////////////////////////////////////////
void TRI_ShutdownDebugging () {
if (FailurePoints != nullptr) {
TRI_Free(TRI_CORE_MEM_ZONE, FailurePoints);
}
FailurePoints = nullptr;
}
////////////////////////////////////////////////////////////////////////////////
/// @brief appends a backtrace to the string provided
////////////////////////////////////////////////////////////////////////////////
void TRI_GetBacktrace (std::string& btstr) {
#if HAVE_BACKTRACE
#ifdef _WIN32
void * stack[100];
unsigned short frames;
SYMBOL_INFO * symbol;
HANDLE process;
process = GetCurrentProcess();
SymInitialize(process, nullptr, true);
frames = CaptureStackBackTrace(0, 100, stack, nullptr);
symbol = (SYMBOL_INFO*) calloc(sizeof(SYMBOL_INFO) + 256 * sizeof(char), 1);
if (symbol == nullptr) {
// cannot allocate memory
return;
}
symbol->MaxNameLen = 255;
symbol->SizeOfStruct = sizeof(SYMBOL_INFO);
for (unsigned int i = 0; i < frames; i++) {
char address[64];
SymFromAddr(process, (DWORD64) stack[i], 0, symbol);
snprintf(address, sizeof(address), "0x%0X", (unsigned int) symbol->Address);
btstr += std::to_string(frames - i - 1) + std::string(": ") + symbol->Name + std::string(" [") + address + std::string("]\n");
}
TRI_SystemFree(symbol);
#else
void* stack_frames[50];
size_t size, i;
char** strings;
size = backtrace(stack_frames, sizeof(stack_frames) / sizeof(void*));
strings = backtrace_symbols(stack_frames, size);
for (i = 0; i < size; i++) {
std::stringstream ss;
if (strings != nullptr) {
char *mangled_name = nullptr, *offset_begin = nullptr, *offset_end = nullptr;
// find parantheses and +address offset surrounding mangled name
for (char *p = strings[i]; *p; ++p) {
if (*p == '(') {
mangled_name = p;
}
else if (*p == '+') {
offset_begin = p;
}
else if (*p == ')') {
offset_end = p;
break;
}
}
// TODO: osx demangling works a little bit different.
// http://oroboro.com/stack-trace-on-crash/
// says it should look like that:
//#ifdef DARWIN
// // OSX style stack trace
// for ( char *p = symbollist[i]; *p; ++p )
// {
// if (( *p == '_' ) && ( *(p-1) == ' ' ))
// begin_name = p-1;
// else if ( *p == '+' )
// begin_offset = p-1;
// }
//
// if ( begin_name && begin_offset && ( begin_name < begin_offset ))
// {
// *begin_name++ = '\0';
// *begin_offset++ = '\0';
//
// // mangled name is now in [begin_name, begin_offset) and caller
// // offset in [begin_offset, end_offset). now apply
// // __cxa_demangle():
// int status;
// char* ret = abi::__cxa_demangle( begin_name, &funcname[0],
// &funcnamesize, &status );
// if ( status == 0 )
// {
// funcname = ret; // use possibly realloc()-ed string
// fprintf( out, " %-30s %-40s %s\n",
// symbollist[i], funcname, begin_offset );
// } else {
// // demangling failed. Output function name as a C function with
// // no arguments.
// fprintf( out, " %-30s %-38s() %s\n",
// symbollist[i], begin_name, begin_offset );
// }
//
//#else // !DARWIN - but is posix
// if the line could be processed, attempt to demangle the symbol
if (mangled_name && offset_begin && offset_end &&
mangled_name < offset_begin) {
*mangled_name++ = '\0';
*offset_begin++ = '\0';
*offset_end++ = '\0';
int status = 0;
char * demangled_name = abi::__cxa_demangle(mangled_name, 0, 0, &status);
if (demangled_name != nullptr) {
if (status == 0) {
ss << stack_frames[i];
btstr += strings[i] +
std::string("() [") +
ss.str() +
std::string("] ") +
demangled_name +
std::string("\n");
}
else {
btstr += strings[i] +
std::string("\n");
}
TRI_SystemFree(demangled_name);
}
}
else {
btstr += strings[i] +
std::string("\n");
}
}
else {
ss << stack_frames[i];
btstr += ss.str() +
std::string("\n");
}
}
if (strings != nullptr) {
TRI_SystemFree(strings);
}
#endif
#endif
}
////////////////////////////////////////////////////////////////////////////////
/// @brief prints a backtrace on stderr
////////////////////////////////////////////////////////////////////////////////
void TRI_PrintBacktrace () {
#if HAVE_BACKTRACE
std::string out;
TRI_GetBacktrace(out);
fprintf(stderr, "%s", out.c_str());
#endif
}
// -----------------------------------------------------------------------------
// --SECTION-- END-OF-FILE
// -----------------------------------------------------------------------------
// Local Variables:
// mode: outline-minor
// outline-regexp: "/// @brief\\|/// {@inheritDoc}\\|/// @page\\|// --SECTION--\\|/// @\\}"
// End:
<|endoftext|> |
<commit_before>// {{{ GPL License
// This file is part of gringo - a grounder for logic programs.
// Copyright (C) 2013 Roland Kaminski
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
// }}}
#include "gringo/output/output.hh"
#include "gringo/logger.hh"
#include "gringo/output/aggregates.hh"
#include "gringo/output/backends.hh"
#include <cstring>
namespace Gringo { namespace Output {
// {{{1 internal functions and classes
namespace {
// {{{2 definition of DelayedStatement
class DelayedStatement : public Statement {
public:
DelayedStatement(LiteralId lit)
: lit_(lit)
{ }
void output(DomainData &, Backend &) const override { }
void print(PrintPlain out, char const *prefix) const override {
auto lit = call(out.domain, lit_, &Literal::delayedLit).first;
out << prefix;
call(out.domain, lit, &Literal::printPlain, out);
out << " <=> ";
call(out.domain, lit_, &Literal::printPlain, out);
out << "\n";
}
void translate(DomainData &data, Translator &trans) override {
trans.output(data, *this);
call(data, lit_, &Literal::translate, trans);
}
void replaceDelayed(DomainData &, LitVec &) override { }
virtual ~DelayedStatement() noexcept = default;
private:
LiteralId lit_;
};
// {{{2 definition of TranslateStatement
template <class T>
class TranslateStatement : public Statement {
public:
TranslateStatement(T const &lambda)
: lambda_(lambda)
{ }
void output(DomainData &, Backend &) const override { }
void print(PrintPlain, char const *) const override { }
void translate(DomainData &data, Translator &trans) override {
trans.output(data, *this);
lambda_(data, trans);
}
void replaceDelayed(DomainData &, LitVec &) override { }
virtual ~TranslateStatement() { }
private:
T const &lambda_;
};
template <class T>
void translateLambda(DomainData &data, AbstractOutput &out, T const &lambda) {
TranslateStatement<T>(lambda).passTo(data, out);
}
// {{{2 definition of EndStepStatement
class EndStepStatement : public Statement {
public:
EndStepStatement(OutputPredicates const &outPreds, bool solve, Logger &log)
: outPreds_(outPreds), log_(log), solve_(solve) { }
void output(DomainData &, Backend &out) const override {
if (solve_) {
out.endStep();
}
}
void print(PrintPlain out, char const *prefix) const override {
for (auto &x : outPreds_) {
if (std::get<1>(x).match("", 0)) { out << prefix << "#show " << (std::get<2>(x) ? "$" : "") << std::get<1>(x) << ".\n"; }
else { out << prefix << "#show.\n"; }
}
}
void translate(DomainData &data, Translator &trans) override {
trans.translate(data, outPreds_, log_);
trans.output(data, *this);
}
void replaceDelayed(DomainData &, LitVec &) override { }
virtual ~EndStepStatement() { }
private:
OutputPredicates const &outPreds_;
Logger &log_;
bool solve_;
};
// }}}2
} // namespace
// {{{1 definition of TranslatorOutput
TranslatorOutput::TranslatorOutput(UAbstractOutput &&out)
: trans_(std::move(out)) { }
void TranslatorOutput::output(DomainData &data, Statement &stm) {
stm.translate(data, trans_);
}
// {{{1 definition of TextOutput
TextOutput::TextOutput(std::string prefix, std::ostream &stream, UAbstractOutput &&out)
: prefix_(prefix)
, stream_(stream)
, out_(std::move(out)) { }
void TextOutput::TextOutput::output(DomainData &data, Statement &stm) {
stm.print({data, stream_}, prefix_.c_str());
if (out_) {
out_->output(data, stm);
}
}
// {{{1 definition of BackendOutput
BackendOutput::BackendOutput(UBackend &&out)
: out_(std::move(out)) { }
void BackendOutput::output(DomainData &data, Statement &stm) {
stm.output(data, *out_);
}
// {{{1 definition of OutputBase
OutputBase::OutputBase(Potassco::TheoryData &data, OutputPredicates &&outPreds, std::ostream &out, OutputFormat format, OutputDebug debug)
: outPreds(std::move(outPreds))
, data(data)
, out_(fromFormat(out, format, debug))
{ }
OutputBase::OutputBase(Potassco::TheoryData &data, OutputPredicates &&outPreds, UBackend &&out, OutputDebug debug)
: outPreds(std::move(outPreds))
, data(data)
, out_(fromBackend(std::move(out), debug))
{ }
OutputBase::OutputBase(Potassco::TheoryData &data, OutputPredicates &&outPreds, UAbstractOutput &&out)
: outPreds(std::move(outPreds))
, data(data)
, out_(std::move(out))
{ }
UAbstractOutput OutputBase::fromFormat(std::ostream &stream, OutputFormat format, OutputDebug debug) {
if (format == OutputFormat::TEXT) {
UAbstractOutput out;
out = gringo_make_unique<TextOutput>("", stream);
if (debug == OutputDebug::TEXT) {
out = gringo_make_unique<TextOutput>("% ", std::cerr, std::move(out));
}
return out;
}
else {
UBackend backend;
switch (format) {
case OutputFormat::REIFY: {
throw std::logic_error("implement reified format");
}
case OutputFormat::INTERMEDIATE: {
backend = gringo_make_unique<IntermediateFormatBackend>(stream);
break;
}
case OutputFormat::SMODELS: {
backend = gringo_make_unique<SmodelsFormatBackend>(stream, true);
break;
}
case OutputFormat::TEXT: {
throw std::logic_error("cannot happen");
}
}
return fromBackend(std::move(backend), debug);
}
}
UAbstractOutput OutputBase::fromBackend(UBackend &&backend, OutputDebug debug) {
UAbstractOutput out;
out = gringo_make_unique<BackendOutput>(std::move(backend));
if (debug == OutputDebug::TRANSLATE || debug == OutputDebug::ALL) {
out = gringo_make_unique<TextOutput>("%% ", std::cerr, std::move(out));
}
out = gringo_make_unique<TranslatorOutput>(std::move(out));
if (debug == OutputDebug::TEXT || debug == OutputDebug::ALL) {
out = gringo_make_unique<TextOutput>("% ", std::cerr, std::move(out));
}
return out;
}
void OutputBase::init(bool incremental) {
backendLambda(data, *out_, [incremental](DomainData &, Backend &out) { out.initProgram(incremental); });
}
void OutputBase::output(Statement &x) {
x.replaceDelayed(data, delayed_);
out_->output(data, x);
}
void OutputBase::flush() {
for (auto &lit : delayed_) { DelayedStatement(lit).passTo(data, *out_); }
delayed_.clear();
backendLambda(data, *out_, [](DomainData &data, Backend &out) {
auto getCond = [&data](Id_t elem) {
TheoryData &td = data.theory();
BackendLitVec bc;
for (auto &lit : td.getCondition(elem)) {
bc.emplace_back(call(data, lit, &Literal::uid));
}
return bc;
};
Gringo::output(data.theory().data(), out, getCond);
});
}
void OutputBase::beginStep() {
backendLambda(data, *out_, [](DomainData &, Backend &out) { out.beginStep(); });
}
void OutputBase::endStep(bool solve, Logger &log) {
if (!outPreds.empty()) {
std::move(outPredsForce.begin(), outPredsForce.end(), std::back_inserter(outPreds));
outPredsForce.clear();
}
EndStepStatement(outPreds, solve, log).passTo(data, *out_);
// TODO: get rid of such things #d domains should be stored somewhere else
std::set<Sig> rm;
for (auto &x : predDoms()) {
if (x->sig().name().startsWith("#d")) {
rm.emplace(x->sig());
}
}
if (!rm.empty()) {
predDoms().erase([&rm](UPredDom const &dom) {
return rm.find(dom->sig()) != rm.end();
});
}
}
void OutputBase::reset() {
data.reset();
translateLambda(data, *out_, [](DomainData &, Translator &x) { x.reset(); });
}
void OutputBase::checkOutPreds(Logger &log) {
auto le = [](OutputPredicates::value_type const &x, OutputPredicates::value_type const &y) -> bool {
if (std::get<1>(x) != std::get<1>(y)) { return std::get<1>(x) < std::get<1>(y); }
return std::get<2>(x) < std::get<2>(y);
};
auto eq = [](OutputPredicates::value_type const &x, OutputPredicates::value_type const &y) {
return std::get<1>(x) == std::get<1>(y) && std::get<2>(x) == std::get<2>(y);
};
std::sort(outPreds.begin(), outPreds.end(), le);
outPreds.erase(std::unique(outPreds.begin(), outPreds.end(), eq), outPreds.end());
for (auto &x : outPreds) {
if (!std::get<1>(x).match("", 0) && !std::get<2>(x)) {
auto it(predDoms().find(std::get<1>(x)));
if (it == predDoms().end()) {
GRINGO_REPORT(log, clingo_warning_atom_undefined)
<< std::get<0>(x) << ": info: no atoms over signature occur in program:\n"
<< " " << std::get<1>(x) << "\n";
}
}
}
}
SymVec OutputBase::atoms(unsigned atomset, IsTrueLookup isTrue) const {
SymVec atoms;
translateLambda(const_cast<DomainData&>(data), *out_, [&](DomainData &data, Translator &trans) {
trans.atoms(data, atomset, isTrue, atoms, outPreds);
});
return atoms;
}
std::pair<PredicateDomain::ConstIterator, PredicateDomain const *> OutputBase::find(Symbol val) const {
return const_cast<OutputBase*>(this)->find(val);
}
std::pair<PredicateDomain::Iterator, PredicateDomain*> OutputBase::find(Symbol val) {
if (val.type() == SymbolType::Fun) {
auto it = predDoms().find(val.sig());
if (it != predDoms().end()) {
auto jt = (*it)->find(val);
if (jt != (*it)->end() && jt->defined()) {
return {jt, it->get()};
}
}
}
return {PredicateDomain::Iterator(), nullptr};
}
std::pair<Id_t, Id_t> OutputBase::simplify(AssignmentLookup assignment) {
Id_t facts = 0;
Id_t deleted = 0;
if (true) {
if (data.canSimplify()) {
std::vector<Mapping> mappings;
for (auto &dom : data.predDoms()) {
mappings.emplace_back();
auto ret = dom->cleanup(assignment, mappings.back());
facts+= ret.first;
deleted+= ret.second;
}
translateLambda(data, *out_, [&](DomainData &data, Translator &trans) { trans.simplify(data, mappings, assignment); });
}
}
return {facts, deleted};
}
Backend *OutputBase::backend() {
Backend *backend = nullptr;
backendLambda(data, *out_, [&backend](DomainData &, Backend &out) { backend = &out; });
return backend;
}
// }}}1
} } // namespace Output Gringo
<commit_msg>fix textoutput of #show statements<commit_after>// {{{ GPL License
// This file is part of gringo - a grounder for logic programs.
// Copyright (C) 2013 Roland Kaminski
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
// }}}
#include "gringo/output/output.hh"
#include "gringo/logger.hh"
#include "gringo/output/aggregates.hh"
#include "gringo/output/backends.hh"
#include <cstring>
namespace Gringo { namespace Output {
// {{{1 internal functions and classes
namespace {
// {{{2 definition of DelayedStatement
class DelayedStatement : public Statement {
public:
DelayedStatement(LiteralId lit)
: lit_(lit)
{ }
void output(DomainData &, Backend &) const override { }
void print(PrintPlain out, char const *prefix) const override {
auto lit = call(out.domain, lit_, &Literal::delayedLit).first;
out << prefix;
call(out.domain, lit, &Literal::printPlain, out);
out << " <=> ";
call(out.domain, lit_, &Literal::printPlain, out);
out << "\n";
}
void translate(DomainData &data, Translator &trans) override {
trans.output(data, *this);
call(data, lit_, &Literal::translate, trans);
}
void replaceDelayed(DomainData &, LitVec &) override { }
virtual ~DelayedStatement() noexcept = default;
private:
LiteralId lit_;
};
// {{{2 definition of TranslateStatement
template <class T>
class TranslateStatement : public Statement {
public:
TranslateStatement(T const &lambda)
: lambda_(lambda)
{ }
void output(DomainData &, Backend &) const override { }
void print(PrintPlain, char const *) const override { }
void translate(DomainData &data, Translator &trans) override {
trans.output(data, *this);
lambda_(data, trans);
}
void replaceDelayed(DomainData &, LitVec &) override { }
virtual ~TranslateStatement() { }
private:
T const &lambda_;
};
template <class T>
void translateLambda(DomainData &data, AbstractOutput &out, T const &lambda) {
TranslateStatement<T>(lambda).passTo(data, out);
}
// {{{2 definition of EndStepStatement
class EndStepStatement : public Statement {
public:
EndStepStatement(OutputPredicates const &outPreds, bool solve, Logger &log)
: outPreds_(outPreds), log_(log), solve_(solve) { }
void output(DomainData &, Backend &out) const override {
if (solve_) {
out.endStep();
}
}
void print(PrintPlain out, char const *prefix) const override {
for (auto &x : outPreds_) {
if (std::get<1>(x).match("", 0)) { out << prefix << "#show.\n"; }
else { out << prefix << "#show " << (std::get<2>(x) ? "$" : "") << std::get<1>(x) << ".\n"; }
}
}
void translate(DomainData &data, Translator &trans) override {
trans.translate(data, outPreds_, log_);
trans.output(data, *this);
}
void replaceDelayed(DomainData &, LitVec &) override { }
virtual ~EndStepStatement() { }
private:
OutputPredicates const &outPreds_;
Logger &log_;
bool solve_;
};
// }}}2
} // namespace
// {{{1 definition of TranslatorOutput
TranslatorOutput::TranslatorOutput(UAbstractOutput &&out)
: trans_(std::move(out)) { }
void TranslatorOutput::output(DomainData &data, Statement &stm) {
stm.translate(data, trans_);
}
// {{{1 definition of TextOutput
TextOutput::TextOutput(std::string prefix, std::ostream &stream, UAbstractOutput &&out)
: prefix_(prefix)
, stream_(stream)
, out_(std::move(out)) { }
void TextOutput::TextOutput::output(DomainData &data, Statement &stm) {
stm.print({data, stream_}, prefix_.c_str());
if (out_) {
out_->output(data, stm);
}
}
// {{{1 definition of BackendOutput
BackendOutput::BackendOutput(UBackend &&out)
: out_(std::move(out)) { }
void BackendOutput::output(DomainData &data, Statement &stm) {
stm.output(data, *out_);
}
// {{{1 definition of OutputBase
OutputBase::OutputBase(Potassco::TheoryData &data, OutputPredicates &&outPreds, std::ostream &out, OutputFormat format, OutputDebug debug)
: outPreds(std::move(outPreds))
, data(data)
, out_(fromFormat(out, format, debug))
{ }
OutputBase::OutputBase(Potassco::TheoryData &data, OutputPredicates &&outPreds, UBackend &&out, OutputDebug debug)
: outPreds(std::move(outPreds))
, data(data)
, out_(fromBackend(std::move(out), debug))
{ }
OutputBase::OutputBase(Potassco::TheoryData &data, OutputPredicates &&outPreds, UAbstractOutput &&out)
: outPreds(std::move(outPreds))
, data(data)
, out_(std::move(out))
{ }
UAbstractOutput OutputBase::fromFormat(std::ostream &stream, OutputFormat format, OutputDebug debug) {
if (format == OutputFormat::TEXT) {
UAbstractOutput out;
out = gringo_make_unique<TextOutput>("", stream);
if (debug == OutputDebug::TEXT) {
out = gringo_make_unique<TextOutput>("% ", std::cerr, std::move(out));
}
return out;
}
else {
UBackend backend;
switch (format) {
case OutputFormat::REIFY: {
throw std::logic_error("implement reified format");
}
case OutputFormat::INTERMEDIATE: {
backend = gringo_make_unique<IntermediateFormatBackend>(stream);
break;
}
case OutputFormat::SMODELS: {
backend = gringo_make_unique<SmodelsFormatBackend>(stream, true);
break;
}
case OutputFormat::TEXT: {
throw std::logic_error("cannot happen");
}
}
return fromBackend(std::move(backend), debug);
}
}
UAbstractOutput OutputBase::fromBackend(UBackend &&backend, OutputDebug debug) {
UAbstractOutput out;
out = gringo_make_unique<BackendOutput>(std::move(backend));
if (debug == OutputDebug::TRANSLATE || debug == OutputDebug::ALL) {
out = gringo_make_unique<TextOutput>("%% ", std::cerr, std::move(out));
}
out = gringo_make_unique<TranslatorOutput>(std::move(out));
if (debug == OutputDebug::TEXT || debug == OutputDebug::ALL) {
out = gringo_make_unique<TextOutput>("% ", std::cerr, std::move(out));
}
return out;
}
void OutputBase::init(bool incremental) {
backendLambda(data, *out_, [incremental](DomainData &, Backend &out) { out.initProgram(incremental); });
}
void OutputBase::output(Statement &x) {
x.replaceDelayed(data, delayed_);
out_->output(data, x);
}
void OutputBase::flush() {
for (auto &lit : delayed_) { DelayedStatement(lit).passTo(data, *out_); }
delayed_.clear();
backendLambda(data, *out_, [](DomainData &data, Backend &out) {
auto getCond = [&data](Id_t elem) {
TheoryData &td = data.theory();
BackendLitVec bc;
for (auto &lit : td.getCondition(elem)) {
bc.emplace_back(call(data, lit, &Literal::uid));
}
return bc;
};
Gringo::output(data.theory().data(), out, getCond);
});
}
void OutputBase::beginStep() {
backendLambda(data, *out_, [](DomainData &, Backend &out) { out.beginStep(); });
}
void OutputBase::endStep(bool solve, Logger &log) {
if (!outPreds.empty()) {
std::move(outPredsForce.begin(), outPredsForce.end(), std::back_inserter(outPreds));
outPredsForce.clear();
}
EndStepStatement(outPreds, solve, log).passTo(data, *out_);
// TODO: get rid of such things #d domains should be stored somewhere else
std::set<Sig> rm;
for (auto &x : predDoms()) {
if (x->sig().name().startsWith("#d")) {
rm.emplace(x->sig());
}
}
if (!rm.empty()) {
predDoms().erase([&rm](UPredDom const &dom) {
return rm.find(dom->sig()) != rm.end();
});
}
}
void OutputBase::reset() {
data.reset();
translateLambda(data, *out_, [](DomainData &, Translator &x) { x.reset(); });
}
void OutputBase::checkOutPreds(Logger &log) {
auto le = [](OutputPredicates::value_type const &x, OutputPredicates::value_type const &y) -> bool {
if (std::get<1>(x) != std::get<1>(y)) { return std::get<1>(x) < std::get<1>(y); }
return std::get<2>(x) < std::get<2>(y);
};
auto eq = [](OutputPredicates::value_type const &x, OutputPredicates::value_type const &y) {
return std::get<1>(x) == std::get<1>(y) && std::get<2>(x) == std::get<2>(y);
};
std::sort(outPreds.begin(), outPreds.end(), le);
outPreds.erase(std::unique(outPreds.begin(), outPreds.end(), eq), outPreds.end());
for (auto &x : outPreds) {
if (!std::get<1>(x).match("", 0) && !std::get<2>(x)) {
auto it(predDoms().find(std::get<1>(x)));
if (it == predDoms().end()) {
GRINGO_REPORT(log, clingo_warning_atom_undefined)
<< std::get<0>(x) << ": info: no atoms over signature occur in program:\n"
<< " " << std::get<1>(x) << "\n";
}
}
}
}
SymVec OutputBase::atoms(unsigned atomset, IsTrueLookup isTrue) const {
SymVec atoms;
translateLambda(const_cast<DomainData&>(data), *out_, [&](DomainData &data, Translator &trans) {
trans.atoms(data, atomset, isTrue, atoms, outPreds);
});
return atoms;
}
std::pair<PredicateDomain::ConstIterator, PredicateDomain const *> OutputBase::find(Symbol val) const {
return const_cast<OutputBase*>(this)->find(val);
}
std::pair<PredicateDomain::Iterator, PredicateDomain*> OutputBase::find(Symbol val) {
if (val.type() == SymbolType::Fun) {
auto it = predDoms().find(val.sig());
if (it != predDoms().end()) {
auto jt = (*it)->find(val);
if (jt != (*it)->end() && jt->defined()) {
return {jt, it->get()};
}
}
}
return {PredicateDomain::Iterator(), nullptr};
}
std::pair<Id_t, Id_t> OutputBase::simplify(AssignmentLookup assignment) {
Id_t facts = 0;
Id_t deleted = 0;
if (true) {
if (data.canSimplify()) {
std::vector<Mapping> mappings;
for (auto &dom : data.predDoms()) {
mappings.emplace_back();
auto ret = dom->cleanup(assignment, mappings.back());
facts+= ret.first;
deleted+= ret.second;
}
translateLambda(data, *out_, [&](DomainData &data, Translator &trans) { trans.simplify(data, mappings, assignment); });
}
}
return {facts, deleted};
}
Backend *OutputBase::backend() {
Backend *backend = nullptr;
backendLambda(data, *out_, [&backend](DomainData &, Backend &out) { backend = &out; });
return backend;
}
// }}}1
} } // namespace Output Gringo
<|endoftext|> |
<commit_before>/* Copyright 2011 Alexander Potashev <aspotashev@gmail.com>
This library is free software; you can redistribute it and/or modify
it under the terms of the GNU Library General Public License as published
by the Free Software Foundation; either version 2 of the License or
( at your option ) version 3 or, at the discretion of KDE e.V.
( which shall act as a proxy as in section 14 of the GPLv3 ), 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 <qjson/parser.h>
#include <KIO/Job>
#include <KDebug>
#include <KLocale>
#include "photopostjob.h"
#include "mpform.h"
PhotoPostJob::PhotoPostJob(const QString &url, const QStringList &files)
: m_url(url)
, m_files(files)
{
setCapabilities(KJob::Killable);
m_ok = true;
if (files.size() <= 0 || files.size() > 5)
m_ok = false;
}
void PhotoPostJob::handleError(const QVariant& data)
{
const QVariantMap errorMap = data.toMap();
int error_code = errorMap["error_code"].toInt();
const QString error_msg = errorMap["error_msg"].toString();
kWarning() << "An error of type" << error_code << "occurred:" << error_msg;
setError(KJob::UserDefinedError);
setErrorText(i18n(
"The VKontakte server returned an error "
"of type <i>%1</i> in reply to uploading to URL %2: <i>%3</i>",
error_code, m_url, error_msg));
}
void PhotoPostJob::start()
{
if (!m_ok)
{
setError(UserDefinedError);
setErrorText("Internal error");
emitResult();
}
MPForm form;
// file1 .. file5
for (int i = 0; i < m_files.size(); i ++)
if (!form.addFile(QString("file%1").arg(i + 1), m_files[i]))
{
m_ok = false;
break;
}
form.finish();
if (!m_ok)
{
setError(UserDefinedError);
setErrorText("Could not attach file");
emitResult();
}
KUrl url(m_url);
kDebug() << "Starting request" << url;
KIO::StoredTransferJob *job = KIO::storedHttpPost(form.formData(), url, KIO::HideProgressInfo);
job->addMetaData("content-type", form.contentType());
m_job = job;
connect(job, SIGNAL(result(KJob*)), this, SLOT(jobFinished(KJob*)));
job->start();
}
void PhotoPostJob::jobFinished(KJob *job)
{
KIO::StoredTransferJob *transferJob = dynamic_cast<KIO::StoredTransferJob *>(job);
Q_ASSERT(transferJob);
if (transferJob->error()) {
setError( transferJob->error() );
setErrorText(KIO::buildErrorString( error(), transferJob->errorText()));
kWarning() << "Job error: " << transferJob->errorString();
} else {
kDebug() << "Got data: " << QString::fromAscii(transferJob->data().data());
QJson::Parser parser;
bool ok;
const QVariant data = parser.parse( transferJob->data(), &ok );
if ( ok ) {
const QVariant error = data.toMap()["error"];
if ( error.isValid() ) {
handleError( error );
} else {
handleData( data.toMap()["response"] );
}
} else {
kWarning() << "Unable to parse JSON data: " << QString::fromAscii( transferJob->data().data() );
setError( KJob::UserDefinedError );
setErrorText( i18n( "Unable to parse data returned by the VKontakte server: %1", parser.errorString() ) );
}
}
emitResult();
m_job = 0;
}
void PhotoPostJob::handleData(const QVariant &data)
{
m_response = data.toMap();
}
QMap<QString, QVariant> PhotoPostJob::response() const
{
return m_response;
}
<commit_msg>Fix PhotoPostJob<commit_after>/* Copyright 2011 Alexander Potashev <aspotashev@gmail.com>
This library is free software; you can redistribute it and/or modify
it under the terms of the GNU Library General Public License as published
by the Free Software Foundation; either version 2 of the License or
( at your option ) version 3 or, at the discretion of KDE e.V.
( which shall act as a proxy as in section 14 of the GPLv3 ), 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 <qjson/parser.h>
#include <KIO/Job>
#include <KDebug>
#include <KLocale>
#include "photopostjob.h"
#include "mpform.h"
PhotoPostJob::PhotoPostJob(const QString &url, const QStringList &files)
: m_url(url)
, m_files(files)
{
setCapabilities(KJob::Killable);
m_ok = true;
if (files.size() <= 0 || files.size() > 5)
m_ok = false;
}
void PhotoPostJob::handleError(const QVariant& data)
{
const QVariantMap errorMap = data.toMap();
int error_code = errorMap["error_code"].toInt();
const QString error_msg = errorMap["error_msg"].toString();
kWarning() << "An error of type" << error_code << "occurred:" << error_msg;
setError(KJob::UserDefinedError);
setErrorText(i18n(
"The VKontakte server returned an error "
"of type <i>%1</i> in reply to uploading to URL %2: <i>%3</i>",
error_code, m_url, error_msg));
}
void PhotoPostJob::start()
{
if (!m_ok)
{
setError(UserDefinedError);
setErrorText("Internal error");
emitResult();
}
MPForm form;
// file1 .. file5
for (int i = 0; i < m_files.size(); i ++)
if (!form.addFile(QString("file%1").arg(i + 1), m_files[i]))
{
m_ok = false;
break;
}
form.finish();
if (!m_ok)
{
setError(UserDefinedError);
setErrorText("Could not attach file");
emitResult();
}
KUrl url(m_url);
kDebug() << "Starting request" << url;
KIO::StoredTransferJob *job = KIO::storedHttpPost(form.formData(), url, KIO::HideProgressInfo);
job->addMetaData("content-type", form.contentType());
m_job = job;
connect(job, SIGNAL(result(KJob*)), this, SLOT(jobFinished(KJob*)));
job->start();
}
void PhotoPostJob::jobFinished(KJob *job)
{
KIO::StoredTransferJob *transferJob = dynamic_cast<KIO::StoredTransferJob *>(job);
Q_ASSERT(transferJob);
if (transferJob->error()) {
setError( transferJob->error() );
setErrorText(KIO::buildErrorString( error(), transferJob->errorText()));
kWarning() << "Job error: " << transferJob->errorString();
} else {
kDebug() << "Got data: " << QString::fromAscii(transferJob->data().data());
QJson::Parser parser;
bool ok;
const QVariant data = parser.parse( transferJob->data(), &ok );
if ( ok ) {
const QVariant error = data.toMap()["error"];
if ( error.isValid() ) {
handleError( error );
} else {
handleData(data);
}
} else {
kWarning() << "Unable to parse JSON data: " << QString::fromAscii( transferJob->data().data() );
setError( KJob::UserDefinedError );
setErrorText( i18n( "Unable to parse data returned by the VKontakte server: %1", parser.errorString() ) );
}
}
emitResult();
m_job = 0;
}
void PhotoPostJob::handleData(const QVariant &data)
{
m_response = data.toMap();
}
QMap<QString, QVariant> PhotoPostJob::response() const
{
return m_response;
}
<|endoftext|> |
<commit_before>
/**************************************************************************
* Copyright(c) 1998-2000, ALICE Experiment at CERN, All rights reserved. *
* *
* Author: The ALICE Off-line Project. *
* Contributors are mentioned in the code where appropriate. *
* *
* Permission to use, copy, modify and distribute this software and its *
* documentation strictly for non-commercial purposes is hereby granted *
* without fee, provided that the above copyright notice appears in all *
* copies and that both the copyright notice and this permission notice *
* appear in the supporting documentation. The authors make no claims *
* about the suitability of this software for any purpose. It is *
* provided "as is" without express or implied warranty. *
**************************************************************************/
#include <TTree.h>
#include <TFile.h>
#include <TDirectory.h>
#include <TRandom.h>
#include <TArrayI.h>
#include <TError.h>
#include <TH1F.h>
#include "AliLog.h"
#include "AliSTARTDigitizer.h"
#include "AliSTART.h"
#include "AliSTARThit.h"
#include "AliSTARTdigit.h"
#include "AliRunDigitizer.h"
#include <AliDetector.h>
#include "AliRun.h"
#include <AliLoader.h>
#include <AliRunLoader.h>
#include <stdlib.h>
#include <Riostream.h>
#include <Riostream.h>
ClassImp(AliSTARTDigitizer)
//___________________________________________
AliSTARTDigitizer::AliSTARTDigitizer() :AliDigitizer()
{
// Default ctor - don't use it
;
}
//___________________________________________
AliSTARTDigitizer::AliSTARTDigitizer(AliRunDigitizer* manager)
:AliDigitizer(manager),
fSTART(0),
fHits(0),
fdigits(0),
ftimeTDC(0),
fADC(0),
ftimeTDCAmp(0),
fADCAmp(0),
fSumMult(0),
fEff(0)
{
// cout<<"AliSTARTDigitizer::AliSTARTDigitizer"<<endl;
// ctor which should be used
AliDebug(1,"processed");
fSTART = 0;
fHits = 0;
fdigits = 0;
ftimeTDC = new TArrayI(24);
fADC = new TArrayI(24);
ftimeTDCAmp = new TArrayI(24);
fADCAmp = new TArrayI(24);
fSumMult = new TArrayI(6);
TFile* file = TFile::Open("$ALICE_ROOT/START/PMTefficiency.root");
fEff = (TH1F*) file->Get("hEff")->Clone();
fEff->SetDirectory(NULL);
file->Close();
delete file;
}
//------------------------------------------------------------------------
AliSTARTDigitizer::~AliSTARTDigitizer()
{
// Destructor
AliDebug(1,"START");
delete ftimeTDC;
delete fADC;
delete fEff;
delete ftimeTDCAmp;
delete fADCAmp;
delete fSumMult;
}
//------------------------------------------------------------------------
Bool_t AliSTARTDigitizer::Init()
{
// Initialization
AliDebug(1," Init");
return kTRUE;
}
//---------------------------------------------------------------------
void AliSTARTDigitizer::Exec(Option_t* /*option*/)
{
/*
Produde digits from hits
digits is TObject and includes
We are writing array if left & right TDC
left & right ADC (will need for slow simulation)
TOF first particle left & right
mean time and time difference (vertex position)
*/
//output loader
AliRunLoader *outRL = AliRunLoader::GetRunLoader(fManager->GetOutputFolderName());
AliLoader * pOutStartLoader = outRL->GetLoader("STARTLoader");
AliSTART *fSTART = (AliSTART*)outRL ->GetAliRun()->GetDetector("START");
AliDebug(1,"start...");
cout<<" AliSTARTDigitizer::Exec "<<endl;
//input loader
//
// From hits to digits
//
Int_t hit, nhits;
Int_t countE[24], sumMult[3];
Int_t volume,pmt,tr,qt,qtAmp;
Int_t bestRightTDC,bestLeftTDC;
Float_t time[24],besttime[24], timeGaus[24] ;
Float_t channelWidth=25.; //ps
//Q->T-> coefficients !!!! should be asked!!!
Float_t ph2mV = 150./500.;
Int_t threshold =50; //photoelectrons
Int_t mV2channel=200000/(25*25); //5V -> 200ns
AliSTARThit *startHit;
TBranch *brHits=0;
Int_t nFiles=fManager->GetNinputs();
for (Int_t inputFile=0; inputFile<nFiles; inputFile++) {
if (inputFile < nFiles-1) {
AliWarning(Form("ignoring input stream %d", inputFile));
continue;
}
Float_t besttimeright=99999.;
Float_t besttimeleft=99999.;
Int_t timeDiff, meanTime;
for (Int_t i0=0; i0<24; i0++)
{
time[i0]=99999; besttime[i0]=99999; countE[i0]=0;
}
for ( Int_t imu=0; imu<3; imu++) sumMult[imu]=0;
AliRunLoader * inRL = AliRunLoader::GetRunLoader(fManager->GetInputFolderName(inputFile));
AliLoader * pInStartLoader = inRL->GetLoader("STARTLoader");
if (!inRL->GetAliRun()) inRL->LoadgAlice();
//read Hits
pInStartLoader->LoadHits("READ");//probably it is necessary to load them before
TClonesArray *fHits = fSTART->Hits ();
TTree *th = pInStartLoader->TreeH();
brHits = th->GetBranch("START");
if (brHits) {
fSTART->SetHitsAddressBranch(brHits);
}else{
AliError("Branch START hit not found");
exit(111);
}
Int_t ntracks = (Int_t) th->GetEntries();
if (ntracks<=0) return;
// Start loop on tracks in the hits containers
for (Int_t track=0; track<ntracks;track++) {
brHits->GetEntry(track);
nhits = fHits->GetEntriesFast();
for (hit=0;hit<nhits;hit++)
{
startHit = (AliSTARThit*) fHits->UncheckedAt(hit);
if (!startHit) {
AliError("The unchecked hit doesn't exist");
break;
}
pmt=startHit->Pmt();
Int_t numpmt=pmt-1;
Double_t e=startHit->Etot();
volume = startHit->Volume();
if(e>0 && RegisterPhotoE(e)) {
countE[numpmt]++;
besttime[numpmt] = startHit->Time();
if(besttime[numpmt]<time[numpmt])
{
time[numpmt]=besttime[numpmt];
}
}
} //hits loop
} //track loop
//spread time right&left by 25ps && besttime
for (Int_t ipmt=0; ipmt<12; ipmt++){
if(countE[ipmt] > threshold) {
timeGaus[ipmt]=gRandom->Gaus(time[ipmt],25);
if(timeGaus[ipmt]<besttimeleft) besttimeleft=timeGaus[ipmt]; //timeleft
sumMult[0] += countE[ipmt];
sumMult[1] += countE[ipmt];
}
}
for ( Int_t ipmt=12; ipmt<24; ipmt++){
if(countE[ipmt] > threshold) {
timeGaus[ipmt]=gRandom->Gaus(time[ipmt],25);
if(timeGaus[ipmt]<besttimeright) besttimeright=timeGaus[ipmt]; //timeright
sumMult[0] += countE[ipmt];
sumMult[2] += countE[ipmt];
}
}
//ADC features fill digits
//folding with experimental time distribution
Float_t c = 0.0299792; // cm/ps
Float_t koef=(350.-69.7)/c;
Float_t besttimeleftR= besttimeleft;
besttimeleft=koef+besttimeleft;
bestLeftTDC=Int_t (besttimeleftR/channelWidth);
bestRightTDC=Int_t (besttimeright/channelWidth);
timeDiff=Int_t ((besttimeright-besttimeleftR)/channelWidth);
meanTime=Int_t (((besttimeright+besttimeleft)/2.)/channelWidth);
AliDebug(2,Form(" time in ns %f ", besttimeleft));
for (Int_t i=0; i<24; i++)
{
// fill TDC
tr= Int_t (timeGaus[i]/channelWidth);
if(timeGaus[i]>50000) tr=0;
//fill ADC
Int_t al= countE[i];
// QTC procedure:
// phe -> mV 0.3; 1MIP ->500phe -> ln (amp (mV)) = 5;
// max 200ns, HIJING mean 50000phe -> 15000mv -> ln = 15 (s zapasom)
// channel 25ps
if (al>threshold) {
qt=Int_t (TMath::Log(al*ph2mV) * mV2channel);
qtAmp=Int_t (TMath::Log(al*10*ph2mV) * mV2channel);
cout<<i<<" "<<qt<<" "<<qtAmp<<endl;
fADC->AddAt(qt,i);
ftimeTDC->AddAt(tr,i);
fADCAmp->AddAt(qtAmp,i);
ftimeTDCAmp->AddAt(tr,i); //now is the same as non-amplified but will be change
}
} //pmt loop
for (Int_t im=0; im<3; im++)
{
if (sumMult[im]>threshold){
Int_t sum=Int_t (TMath::Log(sumMult[im]*ph2mV) * mV2channel);
Int_t sumAmp=Int_t (TMath::Log(10*sumMult[im]*ph2mV) * mV2channel);
fSumMult->AddAt(sum,im);
fSumMult->AddAt(sumAmp,im+3);
}
}
fSTART->AddDigit(bestRightTDC,bestLeftTDC,meanTime,timeDiff,fSumMult,
ftimeTDC,fADC,ftimeTDCAmp,fADCAmp);
pOutStartLoader->UnloadHits();
} //input streams loop
//load digits
pOutStartLoader->LoadDigits("UPDATE");
TTree *treeD = pOutStartLoader->TreeD();
if (treeD == 0x0) {
pOutStartLoader->MakeTree("D");
treeD = pOutStartLoader->TreeD();
}
fSTART->MakeBranch("D");
treeD->Reset();
treeD->Fill();
pOutStartLoader->WriteDigits("OVERWRITE");
fSTART->ResetDigits();
pOutStartLoader->UnloadDigits();
}
//------------------------------------------------------------------------
Bool_t AliSTARTDigitizer::RegisterPhotoE(Double_t energy)
{
// Float_t hc=197.326960*1.e6; //mev*nm
Double_t hc=1.973*1.e-6; //gev*nm
// cout<<"AliSTARTDigitizer::RegisterPhotoE >> energy "<<energy<<endl;
Float_t lambda=hc/energy;
Int_t bin= fEff->GetXaxis()->FindBin(lambda);
Float_t eff=fEff->GetBinContent(bin);
Double_t p = gRandom->Rndm();
if (p > eff)
return kFALSE;
return kTRUE;
}
//----------------------------------------------------------------------------
<commit_msg>Corrected switching between the input and output streams<commit_after>
/**************************************************************************
* Copyright(c) 1998-2000, ALICE Experiment at CERN, All rights reserved. *
* *
* Author: The ALICE Off-line Project. *
* Contributors are mentioned in the code where appropriate. *
* *
* Permission to use, copy, modify and distribute this software and its *
* documentation strictly for non-commercial purposes is hereby granted *
* without fee, provided that the above copyright notice appears in all *
* copies and that both the copyright notice and this permission notice *
* appear in the supporting documentation. The authors make no claims *
* about the suitability of this software for any purpose. It is *
* provided "as is" without express or implied warranty. *
**************************************************************************/
#include <TTree.h>
#include <TFile.h>
#include <TDirectory.h>
#include <TRandom.h>
#include <TArrayI.h>
#include <TError.h>
#include <TH1F.h>
#include "AliLog.h"
#include "AliSTARTDigitizer.h"
#include "AliSTART.h"
#include "AliSTARThit.h"
#include "AliSTARTdigit.h"
#include "AliRunDigitizer.h"
#include <AliDetector.h>
#include "AliRun.h"
#include <AliLoader.h>
#include <AliRunLoader.h>
#include <stdlib.h>
#include <Riostream.h>
#include <Riostream.h>
ClassImp(AliSTARTDigitizer)
//___________________________________________
AliSTARTDigitizer::AliSTARTDigitizer() :AliDigitizer()
{
// Default ctor - don't use it
;
}
//___________________________________________
AliSTARTDigitizer::AliSTARTDigitizer(AliRunDigitizer* manager)
:AliDigitizer(manager),
fSTART(0),
fHits(0),
fdigits(0),
ftimeTDC(0),
fADC(0),
ftimeTDCAmp(0),
fADCAmp(0),
fSumMult(0),
fEff(0)
{
// cout<<"AliSTARTDigitizer::AliSTARTDigitizer"<<endl;
// ctor which should be used
AliDebug(1,"processed");
fSTART = 0;
fHits = 0;
fdigits = 0;
ftimeTDC = new TArrayI(24);
fADC = new TArrayI(24);
ftimeTDCAmp = new TArrayI(24);
fADCAmp = new TArrayI(24);
fSumMult = new TArrayI(6);
TFile* file = TFile::Open("$ALICE_ROOT/START/PMTefficiency.root");
fEff = (TH1F*) file->Get("hEff")->Clone();
fEff->SetDirectory(NULL);
file->Close();
delete file;
}
//------------------------------------------------------------------------
AliSTARTDigitizer::~AliSTARTDigitizer()
{
// Destructor
AliDebug(1,"START");
delete ftimeTDC;
delete fADC;
delete fEff;
delete ftimeTDCAmp;
delete fADCAmp;
delete fSumMult;
}
//------------------------------------------------------------------------
Bool_t AliSTARTDigitizer::Init()
{
// Initialization
AliDebug(1," Init");
return kTRUE;
}
//---------------------------------------------------------------------
void AliSTARTDigitizer::Exec(Option_t* /*option*/)
{
/*
Produde digits from hits
digits is TObject and includes
We are writing array if left & right TDC
left & right ADC (will need for slow simulation)
TOF first particle left & right
mean time and time difference (vertex position)
*/
//output loader
AliRunLoader *outRL = AliRunLoader::GetRunLoader(fManager->GetOutputFolderName());
AliLoader * pOutStartLoader = outRL->GetLoader("STARTLoader");
AliDebug(1,"start...");
cout<<" AliSTARTDigitizer::Exec "<<endl;
//input loader
//
// From hits to digits
//
Int_t hit, nhits;
Int_t countE[24], sumMult[3];
Int_t volume,pmt,tr,qt,qtAmp;
Int_t bestRightTDC,bestLeftTDC;
Float_t time[24],besttime[24], timeGaus[24] ;
Float_t channelWidth=25.; //ps
//Q->T-> coefficients !!!! should be asked!!!
Float_t ph2mV = 150./500.;
Int_t threshold =50; //photoelectrons
Int_t mV2channel=200000/(25*25); //5V -> 200ns
AliSTARThit *startHit;
TBranch *brHits=0;
Int_t nFiles=fManager->GetNinputs();
for (Int_t inputFile=0; inputFile<nFiles; inputFile++) {
if (inputFile < nFiles-1) {
AliWarning(Form("ignoring input stream %d", inputFile));
continue;
}
Float_t besttimeright=99999.;
Float_t besttimeleft=99999.;
Int_t timeDiff, meanTime;
for (Int_t i0=0; i0<24; i0++)
{
time[i0]=99999; besttime[i0]=99999; countE[i0]=0;
}
for ( Int_t imu=0; imu<3; imu++) sumMult[imu]=0;
AliRunLoader * inRL = AliRunLoader::GetRunLoader(fManager->GetInputFolderName(inputFile));
AliLoader * pInStartLoader = inRL->GetLoader("STARTLoader");
if (!inRL->GetAliRun()) inRL->LoadgAlice();
AliSTART *fSTART = (AliSTART*)inRL ->GetAliRun()->GetDetector("START");
//read Hits
pInStartLoader->LoadHits("READ");//probably it is necessary to load them before
TClonesArray *fHits = fSTART->Hits ();
TTree *th = pInStartLoader->TreeH();
brHits = th->GetBranch("START");
if (brHits) {
fSTART->SetHitsAddressBranch(brHits);
}else{
AliError("Branch START hit not found");
exit(111);
}
Int_t ntracks = (Int_t) th->GetEntries();
if (ntracks<=0) return;
// Start loop on tracks in the hits containers
for (Int_t track=0; track<ntracks;track++) {
brHits->GetEntry(track);
nhits = fHits->GetEntriesFast();
for (hit=0;hit<nhits;hit++)
{
startHit = (AliSTARThit*) fHits->UncheckedAt(hit);
if (!startHit) {
AliError("The unchecked hit doesn't exist");
break;
}
pmt=startHit->Pmt();
Int_t numpmt=pmt-1;
Double_t e=startHit->Etot();
volume = startHit->Volume();
if(e>0 && RegisterPhotoE(e)) {
countE[numpmt]++;
besttime[numpmt] = startHit->Time();
if(besttime[numpmt]<time[numpmt])
{
time[numpmt]=besttime[numpmt];
}
}
} //hits loop
} //track loop
//spread time right&left by 25ps && besttime
for (Int_t ipmt=0; ipmt<12; ipmt++){
if(countE[ipmt] > threshold) {
timeGaus[ipmt]=gRandom->Gaus(time[ipmt],25);
if(timeGaus[ipmt]<besttimeleft) besttimeleft=timeGaus[ipmt]; //timeleft
sumMult[0] += countE[ipmt];
sumMult[1] += countE[ipmt];
}
}
for ( Int_t ipmt=12; ipmt<24; ipmt++){
if(countE[ipmt] > threshold) {
timeGaus[ipmt]=gRandom->Gaus(time[ipmt],25);
if(timeGaus[ipmt]<besttimeright) besttimeright=timeGaus[ipmt]; //timeright
sumMult[0] += countE[ipmt];
sumMult[2] += countE[ipmt];
}
}
//ADC features fill digits
//folding with experimental time distribution
Float_t c = 0.0299792; // cm/ps
Float_t koef=(350.-69.7)/c;
Float_t besttimeleftR= besttimeleft;
besttimeleft=koef+besttimeleft;
bestLeftTDC=Int_t (besttimeleftR/channelWidth);
bestRightTDC=Int_t (besttimeright/channelWidth);
timeDiff=Int_t ((besttimeright-besttimeleftR)/channelWidth);
meanTime=Int_t (((besttimeright+besttimeleft)/2.)/channelWidth);
AliDebug(2,Form(" time in ns %f ", besttimeleft));
for (Int_t i=0; i<24; i++)
{
// fill TDC
tr= Int_t (timeGaus[i]/channelWidth);
if(timeGaus[i]>50000) tr=0;
//fill ADC
Int_t al= countE[i];
// QTC procedure:
// phe -> mV 0.3; 1MIP ->500phe -> ln (amp (mV)) = 5;
// max 200ns, HIJING mean 50000phe -> 15000mv -> ln = 15 (s zapasom)
// channel 25ps
if (al>threshold) {
qt=Int_t (TMath::Log(al*ph2mV) * mV2channel);
qtAmp=Int_t (TMath::Log(al*10*ph2mV) * mV2channel);
cout<<i<<" "<<qt<<" "<<qtAmp<<endl;
fADC->AddAt(qt,i);
ftimeTDC->AddAt(tr,i);
fADCAmp->AddAt(qtAmp,i);
ftimeTDCAmp->AddAt(tr,i); //now is the same as non-amplified but will be change
}
} //pmt loop
for (Int_t im=0; im<3; im++)
{
if (sumMult[im]>threshold){
Int_t sum=Int_t (TMath::Log(sumMult[im]*ph2mV) * mV2channel);
Int_t sumAmp=Int_t (TMath::Log(10*sumMult[im]*ph2mV) * mV2channel);
fSumMult->AddAt(sum,im);
fSumMult->AddAt(sumAmp,im+3);
}
}
fSTART->AddDigit(bestRightTDC,bestLeftTDC,meanTime,timeDiff,fSumMult,
ftimeTDC,fADC,ftimeTDCAmp,fADCAmp);
pOutStartLoader->UnloadHits();
} //input streams loop
//load digits
pOutStartLoader->LoadDigits("UPDATE");
TTree *treeD = pOutStartLoader->TreeD();
if (treeD == 0x0) {
pOutStartLoader->MakeTree("D");
treeD = pOutStartLoader->TreeD();
}
AliSTART *fSTART = (AliSTART*)outRL ->GetAliRun()->GetDetector("START");
fSTART->MakeBranch("D");
treeD->Reset();
treeD->Fill();
pOutStartLoader->WriteDigits("OVERWRITE");
fSTART->ResetDigits();
pOutStartLoader->UnloadDigits();
}
//------------------------------------------------------------------------
Bool_t AliSTARTDigitizer::RegisterPhotoE(Double_t energy)
{
// Float_t hc=197.326960*1.e6; //mev*nm
Double_t hc=1.973*1.e-6; //gev*nm
// cout<<"AliSTARTDigitizer::RegisterPhotoE >> energy "<<energy<<endl;
Float_t lambda=hc/energy;
Int_t bin= fEff->GetXaxis()->FindBin(lambda);
Float_t eff=fEff->GetBinContent(bin);
Double_t p = gRandom->Rndm();
if (p > eff)
return kFALSE;
return kTRUE;
}
//----------------------------------------------------------------------------
<|endoftext|> |
<commit_before>/**************************************************************************
* Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *
* *
* Author: The ALICE Off-line Project. *
* Contributors are mentioned in the code where appropriate. *
* *
* Permission to use, copy, modify and distribute this software and its *
* documentation strictly for non-commercial purposes is hereby granted *
* without fee, provided that the above copyright notice appears in all *
* copies and that both the copyright notice and this permission notice *
* appear in the supporting documentation. The authors make no claims *
* about the suitability of this software for any purpose. It is *
* provided "as is" without express or implied warranty. *
**************************************************************************/
//-------------------------------------------------------------------------
// Implementation of the AliESDfriendTrack class
// This class keeps complementary to the AliESDtrack information
// Origin: Iouri Belikov, CERN, Jouri.Belikov@cern.ch
//-------------------------------------------------------------------------
#include "AliTrackPointArray.h"
#include "AliESDfriendTrack.h"
#include "TObjArray.h"
#include "AliKalmanTrack.h"
ClassImp(AliESDfriendTrack)
AliESDfriendTrack::AliESDfriendTrack():
TObject(),
f1P(0),
fPoints(0),
fCalibContainer(0),
fITStrack(0),
fTRDtrack(0)
{
//
// Default constructor
//
Int_t i;
for (i=0; i<kMaxITScluster; i++) fITSindex[i]=-2;
for (i=0; i<kMaxTPCcluster; i++) fTPCindex[i]=-2;
for (i=0; i<kMaxTRDcluster; i++) fTRDindex[i]=-2;
}
AliESDfriendTrack::AliESDfriendTrack(const AliESDfriendTrack &t):
TObject(t),
f1P(t.f1P),
fPoints(0),
fCalibContainer(0),
fITStrack(0),
fTRDtrack(0)
{
//
// Copy constructor
//
Int_t i;
for (i=0; i<kMaxITScluster; i++) fITSindex[i]=t.fITSindex[i];
for (i=0; i<kMaxTPCcluster; i++) fTPCindex[i]=t.fTPCindex[i];
for (i=0; i<kMaxTRDcluster; i++) fTRDindex[i]=t.fTRDindex[i];
if (t.fPoints) fPoints=new AliTrackPointArray(*t.fPoints);
if (t.fCalibContainer) fCalibContainer = new TObjArray(*(t.fCalibContainer));
}
AliESDfriendTrack::~AliESDfriendTrack() {
//
// Simple destructor
//
delete fPoints;
if (fCalibContainer) {
fCalibContainer->Delete();
delete fCalibContainer;
}
delete fITStrack;
delete fTRDtrack;
}
void AliESDfriendTrack::AddCalibObject(TObject * calibObject){
//
// add calibration object to array -
// track is owner of the objects in the container
//
if (!fCalibContainer) fCalibContainer = new TObjArray(5);
fCalibContainer->AddLast(calibObject);
}
TObject * AliESDfriendTrack::GetCalibObject(Int_t index){
//
//
//
if (!fCalibContainer) return 0;
if (index>=fCalibContainer->GetEntriesFast()) return 0;
return fCalibContainer->At(index);
}
<commit_msg>One cannot delete the objects from fCalibContainer, because they are used outside the AliESDfriendTrack<commit_after>/**************************************************************************
* Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *
* *
* Author: The ALICE Off-line Project. *
* Contributors are mentioned in the code where appropriate. *
* *
* Permission to use, copy, modify and distribute this software and its *
* documentation strictly for non-commercial purposes is hereby granted *
* without fee, provided that the above copyright notice appears in all *
* copies and that both the copyright notice and this permission notice *
* appear in the supporting documentation. The authors make no claims *
* about the suitability of this software for any purpose. It is *
* provided "as is" without express or implied warranty. *
**************************************************************************/
//-------------------------------------------------------------------------
// Implementation of the AliESDfriendTrack class
// This class keeps complementary to the AliESDtrack information
// Origin: Iouri Belikov, CERN, Jouri.Belikov@cern.ch
//-------------------------------------------------------------------------
#include "AliTrackPointArray.h"
#include "AliESDfriendTrack.h"
#include "TObjArray.h"
#include "AliKalmanTrack.h"
ClassImp(AliESDfriendTrack)
AliESDfriendTrack::AliESDfriendTrack():
TObject(),
f1P(0),
fPoints(0),
fCalibContainer(0),
fITStrack(0),
fTRDtrack(0)
{
//
// Default constructor
//
Int_t i;
for (i=0; i<kMaxITScluster; i++) fITSindex[i]=-2;
for (i=0; i<kMaxTPCcluster; i++) fTPCindex[i]=-2;
for (i=0; i<kMaxTRDcluster; i++) fTRDindex[i]=-2;
}
AliESDfriendTrack::AliESDfriendTrack(const AliESDfriendTrack &t):
TObject(t),
f1P(t.f1P),
fPoints(0),
fCalibContainer(0),
fITStrack(0),
fTRDtrack(0)
{
//
// Copy constructor
//
Int_t i;
for (i=0; i<kMaxITScluster; i++) fITSindex[i]=t.fITSindex[i];
for (i=0; i<kMaxTPCcluster; i++) fTPCindex[i]=t.fTPCindex[i];
for (i=0; i<kMaxTRDcluster; i++) fTRDindex[i]=t.fTRDindex[i];
if (t.fPoints) fPoints=new AliTrackPointArray(*t.fPoints);
if (t.fCalibContainer) fCalibContainer = new TObjArray(*(t.fCalibContainer));
}
AliESDfriendTrack::~AliESDfriendTrack() {
//
// Simple destructor
//
delete fPoints;
delete fCalibContainer;
delete fITStrack;
delete fTRDtrack;
}
void AliESDfriendTrack::AddCalibObject(TObject * calibObject){
//
// add calibration object to array -
// track is owner of the objects in the container
//
if (!fCalibContainer) fCalibContainer = new TObjArray(5);
fCalibContainer->AddLast(calibObject);
}
TObject * AliESDfriendTrack::GetCalibObject(Int_t index){
//
//
//
if (!fCalibContainer) return 0;
if (index>=fCalibContainer->GetEntriesFast()) return 0;
return fCalibContainer->At(index);
}
<|endoftext|> |
<commit_before>// [standard includes]
#include <vector>
#include <set>
#include <queue>
#include <algorithm>
#include <fstream>
#include <sstream>
#include <iostream>
#include <thread>
#include <mutex>
#include <condition_variable>
#include <atomic>
#include <memory>
#include <cstdio>
#include <typeinfo>
// [external includes]
#include <opencl_utils.h>
// [local includes]
#include "options.h"
#include "run.h"
template<typename T>
using Matrix = std::vector<T>;
template<typename T>
struct MVRun : public Run {
// input matrix size
std::size_t size;
// list of additional buffers to allocate
std::vector<int> extra_buffer_size;
std::vector<cl::Buffer> extra_args;
// list of additional local buffers to allocate
std::vector<int> extra_local_buffer_size;
std::vector<cl::LocalSpaceArg> extra_local_args;
/**
* Deserialize a line from the CSV
*/
MVRun(const std::vector<std::string>& values) {
assert(values.size() > 8 && "Bad CSV format");
// input size
size = Csv::readInt(values[0]);
// global NDRange
glob1 = Csv::readInt(values[1]);
glob2 = Csv::readInt(values[2]);
glob3 = Csv::readInt(values[3]);
// local NDRange
loc1 = Csv::readInt(values[4]);
loc2 = Csv::readInt(values[5]);
loc3 = Csv::readInt(values[6]);
// source hash
hash = values[7];
hash.erase(std::remove_if(std::begin(hash), std::end(hash), isspace), std::end(hash));
// number of temporary buffers to allocate and their sizes
auto num_buf = Csv::readInt(values[8]);
for(unsigned i = 9+3; i < 9+3 + num_buf; ++i) {
extra_buffer_size.push_back((int)Csv::readInt(values[i]));
}
// number of local buffers to allocate and their sizes
auto num_local = Csv::readInt(values[12+num_buf]);
for (unsigned i = 13 + (unsigned) num_buf; i < 13 + num_buf + num_local; ++i) {
extra_local_buffer_size.push_back((int)Csv::readInt(values[i]));
}
}
void setup(cl::Context context) override {
// Allocate extra buffers
for(auto &size: extra_buffer_size)
extra_args.push_back({context, CL_MEM_READ_WRITE, (size_t) size});
for (auto &size: extra_local_buffer_size)
extra_local_args.push_back({(size_t) size});
// Skip the first 3 to compensate for the csv (forgot a drop(3) in scala)
for(unsigned i = 0; i < extra_args.size(); ++i)
kernel.setArg(3+i, extra_args[i]);
for (unsigned i = 0; i < extra_local_args.size(); ++i)
kernel.setArg((unsigned) extra_args.size() + 3 + i, extra_local_args[i]);
kernel.setArg((unsigned)extra_local_args.size()+(unsigned)extra_args.size()+3, (int)size);
kernel.setArg((unsigned)extra_local_args.size()+(unsigned)extra_args.size()+4, (int)size);
}
void cleanup() override {
extra_buffer_size.clear();
kernel = cl::Kernel();
}
};
/**
* FIXME: This is a lazy copy paste of the old main with a template switch for single and double precision
*/
template<typename Float>
void run_harness(
std::vector<std::shared_ptr<Run>>& all_run,
const unsigned N,
const std::string& mat_file,
const std::string& vec_file,
const std::string& gold_file,
const bool force,
const bool transposeIn,
const bool threaded,
const bool binary
)
{
using namespace std;
if(binary)
std::cout << "Using precompiled binaries" << std::endl;
// Compute input and output
Matrix<Float> mat(N*N);
std::vector<Float> vec(N);
std::vector<Float> gold(N);
if(File::is_file_exist(gold_file) && File::is_file_exist(mat_file) && File::is_file_exist(vec_file) && !force ) {
File::load_input(gold, gold_file);
File::load_input(mat, mat_file);
File::load_input(vec, vec_file);
} else {
for(unsigned y = 0; y < N; ++y) {
for (unsigned x = 0; x < N; ++x) {
mat[y * N + x] = (((y * 3 + x * 2) % 10) + 1) * 1.0f;
}
vec[y] = (y%10)*0.5f;
}
// compute gold
for (int i=0; i<N; i++) {
Float Result=0.0;
for (int j=0; j<N; j++)
Result+=mat[i*N+j]*vec[j];
gold[i]=Result;
}
if (transposeIn) {
std::vector<Float> Tmat(N*N);
for(unsigned y = 0; y < N; ++y)
for(unsigned x = 0; x < N; ++x)
Tmat[y*N+x] = mat[x*N+y];
std::swap(Tmat, mat);
}
File::save_input(gold, gold_file);
File::save_input(mat, mat_file);
File::save_input(vec, vec_file);
}
// validation function
auto validate = [&](const std::vector<Float> &output) {
if(gold.size() != output.size()) return false;
for(unsigned i = 0; i < gold.size(); ++i) {
auto x = gold[i];
auto y = output[i];
if(abs(x - y) > 0.001f * max(abs(x), abs(y))) {
cout << "at " << i << ": " << x << "=/=" << y <<std::endl;
return false;
}
}
return true;
};
// Allocating buffers
const size_t buf_size = mat.size() * sizeof(Float);
cl::Buffer mat_dev = OpenCL::alloc( CL_MEM_READ_ONLY | CL_MEM_COPY_HOST_PTR,
buf_size, static_cast<void*>(mat.data()) );
cl::Buffer vec_dev = OpenCL::alloc( CL_MEM_READ_ONLY | CL_MEM_COPY_HOST_PTR,
N*sizeof(Float), static_cast<void*>(vec.data()) );
cl::Buffer output_dev = OpenCL::alloc( CL_MEM_READ_WRITE, N*sizeof(Float) );
// multi-threaded exec
if(threaded) {
std::mutex m;
std::condition_variable cv;
bool done = false;
bool ready = false;
std::queue<Run*> ready_queue;
// compilation thread
auto compilation_thread = std::thread([&] {
for (auto &r: all_run) {
if (r->compile(binary)) {
std::unique_lock<std::mutex> locker(m);
ready_queue.push(&*r);
ready = true;
cv.notify_one();
}
}
});
auto execute_thread = std::thread([&] {
Run *r = nullptr;
while (!done) {
{
std::unique_lock<std::mutex> locker(m);
while (!ready && !done) cv.wait(locker);
}
while (!ready_queue.empty()) {
{
std::unique_lock<std::mutex> locker(m);
r = ready_queue.front();
ready_queue.pop();
}
r->getKernel().setArg(0, mat_dev);
r->getKernel().setArg(1, vec_dev);
r->getKernel().setArg(2, output_dev);
OpenCL::executeRun<Float>(*r, output_dev, N, validate);
}
}
});
compilation_thread.join();
done = true;
cv.notify_one();
execute_thread.join();
}
// single threaded exec
else {
for (auto &r: all_run) {
if (r->compile(binary)) {
r->getKernel().setArg(0, mat_dev);
r->getKernel().setArg(1, vec_dev);
r->getKernel().setArg(2, output_dev);
OpenCL::executeRun<Float>(*r, output_dev, N, validate);
}
}
}
};
int main(int argc, char *argv[]) {
OptParser op("Harness for simple matrix-matrix multiply.");
auto opt_platform = op.addOption<unsigned>({'p', "platform", "OpenCL platform index (default 0).", 0});
auto opt_device = op.addOption<unsigned>({'d', "device", "OpenCL device index (default 0).", 0});
auto opt_size = op.addOption<std::size_t>({'s', "size", "Matrix size (default 1024).", 1024});
auto opt_transpose = op.addOption<bool>({0, "transpose-in", "Transpose the input matrix before computation.", false});
auto opt_binary = op.addOption<bool>({'b', "binary", "Load programs as binaries instead of compiling OpenCL-C source.", false});
auto opt_timeout = op.addOption<float>({'t', "timeout", "Timeout to avoid multiple executions (default 100ms).", 100.0f});
auto opt_double = op.addOption<bool>({0, "double", "Use double precision.", false});
auto opt_threaded = op.addOption<bool>({'t', "threaded", "Use a separate thread for compilation and execution (default true).", true});
auto opt_force = op.addOption<bool>({'f', "force", "Override cached cross validation files.", false});
auto opt_clean = op.addOption<bool>({'c', "clean", "Clean temporary files and exit.", false});
op.parse(argc, argv);
using namespace std;
// Option handling
const size_t N = opt_size->get();
File::setSize(opt_size->get());
OpenCL::timeout = opt_timeout->get();
// temporary files
std::string gold_file = "/tmp/apart_mv_gold_" + std::to_string(N);
std::string mat_file = "/tmp/apart_mv_mat_" + std::to_string(N);
std::string vec_file = "/tmp/apart_mv_vec_" + std::to_string(N);
if(opt_clean->get()) {
std::cout << "Cleaning..." << std::endl;
for(const auto& file: {gold_file, mat_file, vec_file})
std::remove(file.data());
return 0;
}
// === Loading CSV file ===
auto all_run = Csv::init(
[&](const std::vector<std::string>& values) -> std::shared_ptr<Run> {
return (opt_double->get() ?
std::shared_ptr<Run>(new MVRun<double>(values)) :
std::shared_ptr<Run>(new MVRun<float>(values)));
});
if (all_run.size() == 0) return 0;
// === OpenCL init ===
OpenCL::init(opt_platform->get(), opt_device->get());
// run the harness
if (opt_double->get())
run_harness<double>(
all_run, N,
mat_file, vec_file, gold_file,
opt_force->get(),
opt_transpose->get(),
opt_threaded->get(), opt_binary->get()
);
else
run_harness<float>(
all_run, N,
mat_file, vec_file, gold_file,
opt_force->get(),
opt_transpose->get(),
opt_threaded->get(), opt_binary->get()
);
}
<commit_msg>Update mv harness for the new csv format<commit_after>// [standard includes]
#include <vector>
#include <set>
#include <queue>
#include <algorithm>
#include <fstream>
#include <sstream>
#include <iostream>
#include <thread>
#include <mutex>
#include <condition_variable>
#include <atomic>
#include <memory>
#include <cstdio>
#include <typeinfo>
// [external includes]
#include <opencl_utils.h>
// [local includes]
#include "options.h"
#include "run.h"
template<typename T>
using Matrix = std::vector<T>;
template<typename T>
struct MVRun : public Run {
// input matrix size
std::size_t size;
// list of additional buffers to allocate
std::vector<int> extra_buffer_size;
std::vector<cl::Buffer> extra_args;
// list of additional local buffers to allocate
std::vector<int> extra_local_buffer_size;
std::vector<cl::LocalSpaceArg> extra_local_args;
/**
* Deserialize a line from the CSV
*/
MVRun(const std::vector<std::string>& values) {
assert(values.size() > 8 && "Bad CSV format");
// input size
size = Csv::readInt(values[0]);
// global NDRange
glob1 = Csv::readInt(values[1]);
glob2 = Csv::readInt(values[2]);
glob3 = Csv::readInt(values[3]);
// local NDRange
loc1 = Csv::readInt(values[4]);
loc2 = Csv::readInt(values[5]);
loc3 = Csv::readInt(values[6]);
// source hash
hash = values[7];
hash.erase(std::remove_if(std::begin(hash), std::end(hash), isspace), std::end(hash));
// number of temporary buffers to allocate and their sizes
auto num_buf = Csv::readInt(values[8]);
for(unsigned i = 9; i < 9 + num_buf; ++i) {
extra_buffer_size.push_back((int)Csv::readInt(values[i]));
}
// number of local buffers to allocate and their sizes
auto num_local = Csv::readInt(values[9+num_buf]);
for (unsigned i = 10 + (unsigned) num_buf; i < 10 + num_buf + num_local; ++i) {
extra_local_buffer_size.push_back((int)Csv::readInt(values[i]));
}
}
void setup(cl::Context context) override {
// Allocate extra buffers
for(auto &size: extra_buffer_size)
extra_args.push_back({context, CL_MEM_READ_WRITE, (size_t) size});
for (auto &size: extra_local_buffer_size)
extra_local_args.push_back({(size_t) size});
// Skip the first 3 to compensate for the csv (forgot a drop(3) in scala)
for(unsigned i = 0; i < extra_args.size(); ++i)
kernel.setArg(3+i, extra_args[i]);
for (unsigned i = 0; i < extra_local_args.size(); ++i)
kernel.setArg((unsigned) extra_args.size() + 3 + i, extra_local_args[i]);
kernel.setArg((unsigned)extra_local_args.size()+(unsigned)extra_args.size()+3, (int)size);
kernel.setArg((unsigned)extra_local_args.size()+(unsigned)extra_args.size()+4, (int)size);
}
void cleanup() override {
extra_buffer_size.clear();
kernel = cl::Kernel();
}
};
/**
* FIXME: This is a lazy copy paste of the old main with a template switch for single and double precision
*/
template<typename Float>
void run_harness(
std::vector<std::shared_ptr<Run>>& all_run,
const unsigned N,
const std::string& mat_file,
const std::string& vec_file,
const std::string& gold_file,
const bool force,
const bool transposeIn,
const bool threaded,
const bool binary
)
{
using namespace std;
if(binary)
std::cout << "Using precompiled binaries" << std::endl;
// Compute input and output
Matrix<Float> mat(N*N);
std::vector<Float> vec(N);
std::vector<Float> gold(N);
if(File::is_file_exist(gold_file) && File::is_file_exist(mat_file) && File::is_file_exist(vec_file) && !force ) {
File::load_input(gold, gold_file);
File::load_input(mat, mat_file);
File::load_input(vec, vec_file);
} else {
for(unsigned y = 0; y < N; ++y) {
for (unsigned x = 0; x < N; ++x) {
mat[y * N + x] = (((y * 3 + x * 2) % 10) + 1) * 1.0f;
}
vec[y] = (y%10)*0.5f;
}
// compute gold
for (int i=0; i<N; i++) {
Float Result=0.0;
for (int j=0; j<N; j++)
Result+=mat[i*N+j]*vec[j];
gold[i]=Result;
}
if (transposeIn) {
std::vector<Float> Tmat(N*N);
for(unsigned y = 0; y < N; ++y)
for(unsigned x = 0; x < N; ++x)
Tmat[y*N+x] = mat[x*N+y];
std::swap(Tmat, mat);
}
File::save_input(gold, gold_file);
File::save_input(mat, mat_file);
File::save_input(vec, vec_file);
}
// validation function
auto validate = [&](const std::vector<Float> &output) {
if(gold.size() != output.size()) return false;
for(unsigned i = 0; i < gold.size(); ++i) {
auto x = gold[i];
auto y = output[i];
if(abs(x - y) > 0.001f * max(abs(x), abs(y))) {
cout << "at " << i << ": " << x << "=/=" << y <<std::endl;
return false;
}
}
return true;
};
// Allocating buffers
const size_t buf_size = mat.size() * sizeof(Float);
cl::Buffer mat_dev = OpenCL::alloc( CL_MEM_READ_ONLY | CL_MEM_COPY_HOST_PTR,
buf_size, static_cast<void*>(mat.data()) );
cl::Buffer vec_dev = OpenCL::alloc( CL_MEM_READ_ONLY | CL_MEM_COPY_HOST_PTR,
N*sizeof(Float), static_cast<void*>(vec.data()) );
cl::Buffer output_dev = OpenCL::alloc( CL_MEM_READ_WRITE, N*sizeof(Float) );
// multi-threaded exec
if(threaded) {
std::mutex m;
std::condition_variable cv;
bool done = false;
bool ready = false;
std::queue<Run*> ready_queue;
// compilation thread
auto compilation_thread = std::thread([&] {
for (auto &r: all_run) {
if (r->compile(binary)) {
std::unique_lock<std::mutex> locker(m);
ready_queue.push(&*r);
ready = true;
cv.notify_one();
}
}
});
auto execute_thread = std::thread([&] {
Run *r = nullptr;
while (!done) {
{
std::unique_lock<std::mutex> locker(m);
while (!ready && !done) cv.wait(locker);
}
while (!ready_queue.empty()) {
{
std::unique_lock<std::mutex> locker(m);
r = ready_queue.front();
ready_queue.pop();
}
r->getKernel().setArg(0, mat_dev);
r->getKernel().setArg(1, vec_dev);
r->getKernel().setArg(2, output_dev);
OpenCL::executeRun<Float>(*r, output_dev, N, validate);
}
}
});
compilation_thread.join();
done = true;
cv.notify_one();
execute_thread.join();
}
// single threaded exec
else {
for (auto &r: all_run) {
if (r->compile(binary)) {
r->getKernel().setArg(0, mat_dev);
r->getKernel().setArg(1, vec_dev);
r->getKernel().setArg(2, output_dev);
OpenCL::executeRun<Float>(*r, output_dev, N, validate);
}
}
}
};
int main(int argc, char *argv[]) {
OptParser op("Harness for simple matrix-matrix multiply.");
auto opt_platform = op.addOption<unsigned>({'p', "platform", "OpenCL platform index (default 0).", 0});
auto opt_device = op.addOption<unsigned>({'d', "device", "OpenCL device index (default 0).", 0});
auto opt_size = op.addOption<std::size_t>({'s', "size", "Matrix size (default 1024).", 1024});
auto opt_transpose = op.addOption<bool>({0, "transpose-in", "Transpose the input matrix before computation.", false});
auto opt_binary = op.addOption<bool>({'b', "binary", "Load programs as binaries instead of compiling OpenCL-C source.", false});
auto opt_timeout = op.addOption<float>({'t', "timeout", "Timeout to avoid multiple executions (default 100ms).", 100.0f});
auto opt_double = op.addOption<bool>({0, "double", "Use double precision.", false});
auto opt_threaded = op.addOption<bool>({'t', "threaded", "Use a separate thread for compilation and execution (default true).", true});
auto opt_force = op.addOption<bool>({'f', "force", "Override cached cross validation files.", false});
auto opt_clean = op.addOption<bool>({'c', "clean", "Clean temporary files and exit.", false});
op.parse(argc, argv);
using namespace std;
// Option handling
const size_t N = opt_size->get();
File::setSize(opt_size->get());
OpenCL::timeout = opt_timeout->get();
// temporary files
std::string gold_file = "/tmp/apart_mv_gold_" + std::to_string(N);
std::string mat_file = "/tmp/apart_mv_mat_" + std::to_string(N);
std::string vec_file = "/tmp/apart_mv_vec_" + std::to_string(N);
if(opt_clean->get()) {
std::cout << "Cleaning..." << std::endl;
for(const auto& file: {gold_file, mat_file, vec_file})
std::remove(file.data());
return 0;
}
// === Loading CSV file ===
auto all_run = Csv::init(
[&](const std::vector<std::string>& values) -> std::shared_ptr<Run> {
return (opt_double->get() ?
std::shared_ptr<Run>(new MVRun<double>(values)) :
std::shared_ptr<Run>(new MVRun<float>(values)));
});
if (all_run.size() == 0) return 0;
// === OpenCL init ===
OpenCL::init(opt_platform->get(), opt_device->get());
// run the harness
if (opt_double->get())
run_harness<double>(
all_run, N,
mat_file, vec_file, gold_file,
opt_force->get(),
opt_transpose->get(),
opt_threaded->get(), opt_binary->get()
);
else
run_harness<float>(
all_run, N,
mat_file, vec_file, gold_file,
opt_force->get(),
opt_transpose->get(),
opt_threaded->get(), opt_binary->get()
);
}
<|endoftext|> |
<commit_before>/**
* \file dcs/testbed/dummy_application_manager.hpp
*
* \brief A 'do-nothing' Application Manager component.
*
* \author Marco Guazzone (marco.guazzone@gmail.com)
*
* <hr/>
*
* Copyright 2014 Marco Guazzone (marco.guazzone@gmail.com)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef DCS_TESTBED_DUMMY_APPLICATION_MANAGER_HPP
#define DCS_TESTBED_DUMMY_APPLICATION_MANAGER_HPP
#include <boost/smart_ptr.hpp>
#include <cstddef>
#include <dcs/debug.hpp>
#include <dcs/exception.hpp>
#include <dcs/testbed/application_performance_category.hpp>
#include <dcs/testbed/base_application_manager.hpp>
#include <fstream>
#include <map>
#include <sstream>
#include <stdexcept>
#include <vector>
namespace dcs { namespace testbed {
template <typename TraitsT>
class dummy_application_manager: public base_application_manager<TraitsT>
{
private: typedef base_application_manager<TraitsT> base_type;
public: typedef typename base_type::traits_type traits_type;
public: typedef typename traits_type::real_type real_type;
private: typedef typename base_type::app_type app_type;
private: typedef typename base_type::app_pointer app_pointer;
private: typedef typename app_type::sensor_type sensor_type;
private: typedef typename app_type::sensor_pointer sensor_pointer;
private: typedef ::std::map<application_performance_category,sensor_pointer> out_sensor_map;
private: static const real_type default_sampling_time;
private: static const real_type default_control_time;
public: dummy_application_manager()
: ctl_count_(0),
ctl_skip_count_(0),
ctl_fail_count_(0)
{
}
public: void export_data_to(::std::string const& fname)
{
dat_fname_ = fname;
}
private: void do_reset()
{
typedef typename base_type::target_value_map::const_iterator target_iterator;
typedef typename app_type::vm_pointer vm_pointer;
const ::std::vector<vm_pointer> vms = this->app().vms();
// Reset output sensors
out_sensors_.clear();
const target_iterator tgt_end_it = this->target_values().end();
for (target_iterator tgt_it = this->target_values().begin();
tgt_it != tgt_end_it;
++tgt_it)
{
const application_performance_category cat = tgt_it->first;
out_sensors_[cat] = this->app().sensor(cat);
}
// Reset counters
ctl_count_ = ctl_skip_count_
= ctl_fail_count_
= 0;
// Reset output data file
if (p_dat_ofs_ && p_dat_ofs_->is_open())
{
p_dat_ofs_->close();
}
p_dat_ofs_.reset();
if (!dat_fname_.empty())
{
p_dat_ofs_ = ::boost::make_shared< ::std::ofstream >(dat_fname_.c_str());
if (!p_dat_ofs_->good())
{
::std::ostringstream oss;
oss << "Cannot open output data file '" << dat_fname_ << "'";
DCS_EXCEPTION_THROW(::std::runtime_error, oss.str());
}
*p_dat_ofs_ << "\"ts\"";
const ::std::size_t nvms = this->app().num_vms();
for (::std::size_t i = 0; i < nvms; ++i)
{
*p_dat_ofs_ << ",\"Cap_{" << i << "}\",\"Share_{" << i << "}\"";
}
for (target_iterator tgt_it = this->target_values().begin();
tgt_it != tgt_end_it;
++tgt_it)
{
const application_performance_category cat = tgt_it->first;
*p_dat_ofs_ << ",\"y_{" << cat << "}\",\"yn_{" << cat << "}\",\"r_{" << cat << "}\"";
}
*p_dat_ofs_ << ",\"# Controls\",\"# Skip Controls\",\"# Fail Controls\"";
*p_dat_ofs_ << ::std::endl;
}
}
private: void do_sample()
{
typedef typename out_sensor_map::const_iterator out_sensor_iterator;
typedef ::std::vector<typename sensor_type::observation_type> obs_container;
typedef typename obs_container::const_iterator obs_iterator;
DCS_DEBUG_TRACE("(" << this << ") BEGIN Do SAMPLE - Count: " << ctl_count_ << "/" << ctl_skip_count_ << "/" << ctl_fail_count_);
// Collect output values
const out_sensor_iterator out_sens_end_it = out_sensors_.end();
for (out_sensor_iterator out_sens_it = out_sensors_.begin();
out_sens_it != out_sens_end_it;
++out_sens_it)
{
const application_performance_category cat = out_sens_it->first;
sensor_pointer p_sens = out_sens_it->second;
// check: p_sens != null
DCS_DEBUG_ASSERT( p_sens );
p_sens->sense();
if (p_sens->has_observations())
{
const obs_container obs = p_sens->observations();
const obs_iterator end_it = obs.end();
for (obs_iterator it = obs.begin();
it != end_it;
++it)
{
this->data_estimator(cat).collect(it->value());
this->data_estimator(cat).collect(it->value());
}
}
}
DCS_DEBUG_TRACE("(" << this << ") END Do SAMPLE - Count: " << ctl_count_ << "/" << ctl_skip_count_ << "/" << ctl_fail_count_);
}
private: void do_control()
{
typedef typename base_type::target_value_map::const_iterator target_iterator;
typedef typename app_type::vm_pointer vm_pointer;
DCS_DEBUG_TRACE("(" << this << ") BEGIN Do CONTROL - Count: " << ctl_count_ << "/" << ctl_skip_count_ << "/" << ctl_fail_count_);
++ctl_count_;
bool skip_ctl = false;
::std::map<virtual_machine_performance_category,::std::vector<real_type> > cress;
::std::map<application_performance_category,real_type> rgains;
::std::vector<vm_pointer> vms = this->app().vms();
const ::std::size_t nvms = vms.size();
const target_iterator tgt_end_it = this->target_values().end();
for (target_iterator tgt_it = this->target_values().begin();
tgt_it != tgt_end_it;
++tgt_it)
{
const application_performance_category cat(tgt_it->first);
// Compute a summary statistics of collected observation
if (this->data_estimator(cat).count() > 0)
{
const real_type yh = this->data_estimator(cat).estimate();
const real_type yr = this->target_value(cat);
switch (cat)
{
case response_time_application_performance:
rgains[cat] = (yr-yh)/yr;
break;
case throughput_application_performance:
rgains[cat] = (yh-yr)/yr;
break;
}
DCS_DEBUG_TRACE("APP Performance Category: " << cat << " - Yhat(k): " << yh << " - R: " << yr << " -> Rgain(k+1): " << rgains.at(cat));//XXX
}
else
{
// No observation collected during the last control interval
DCS_DEBUG_TRACE("No output observation collected during the last control interval -> Skip control");
skip_ctl = true;
break;
}
#ifdef DCSXX_TESTBED_EXP_APP_MGR_RESET_ESTIMATION_EVERY_INTERVAL
this->data_estimator(cat).reset();
#endif // DCSXX_TESTBED_EXP_APP_MGR_RESET_ESTIMATION_EVERY_INTERVAL
}
if (skip_ctl)
{
++ctl_skip_count_;
}
// Export to file
if (p_dat_ofs_)
{
*p_dat_ofs_ << ::std::time(0) << ",";
for (::std::size_t i = 0; i < nvms; ++i)
{
const vm_pointer p_vm = vms[i];
// check: p_vm != null
DCS_DEBUG_ASSERT( p_vm );
if (i != 0)
{
*p_dat_ofs_ << ",";
}
*p_dat_ofs_ << p_vm->cpu_cap() << "," << p_vm->cpu_share();
}
*p_dat_ofs_ << ",";
const target_iterator tgt_end_it = this->target_values().end();
for (target_iterator tgt_it = this->target_values().begin();
tgt_it != tgt_end_it;
++tgt_it)
{
const application_performance_category cat = tgt_it->first;
if (tgt_it != this->target_values().begin())
{
*p_dat_ofs_ << ",";
}
const real_type yh = this->data_estimator(cat).estimate();
const real_type yr = tgt_it->second;
const real_type yn = yh/yr;
*p_dat_ofs_ << yh << "," << yn << "," << yr;
}
*p_dat_ofs_ << "," << ctl_count_ << "," << ctl_skip_count_ << "," << ctl_fail_count_;
*p_dat_ofs_ << ::std::endl;
}
DCS_DEBUG_TRACE("(" << this << ") END Do CONTROL - Count: " << ctl_count_ << "/" << ctl_skip_count_ << "/" << ctl_fail_count_);
}
private: ::std::size_t ctl_count_; ///< Number of times control function has been invoked
private: ::std::size_t ctl_skip_count_; ///< Number of times control has been skipped
private: ::std::size_t ctl_fail_count_; ///< Number of times control has failed
private: out_sensor_map out_sensors_;
private: ::std::string dat_fname_;
private: ::boost::shared_ptr< ::std::ofstream > p_dat_ofs_;
}; // dummy_application_manager
}} // Namespace dcs::testbed
#endif // DCS_TESTBED_DUMMY_APPLICATION_MANAGER_HPP
<commit_msg>Dummy application manager: dump statistics for CPU and RAM utilization. Other cosmetic changes.<commit_after>/**
* \file dcs/testbed/dummy_application_manager.hpp
*
* \brief A 'do-nothing' Application Manager component.
*
* \author Marco Guazzone (marco.guazzone@gmail.com)
*
* <hr/>
*
* Copyright 2014 Marco Guazzone (marco.guazzone@gmail.com)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef DCS_TESTBED_DUMMY_APPLICATION_MANAGER_HPP
#define DCS_TESTBED_DUMMY_APPLICATION_MANAGER_HPP
#include <boost/smart_ptr.hpp>
#include <cstddef>
#include <dcs/debug.hpp>
#include <dcs/exception.hpp>
#include <dcs/testbed/application_performance_category.hpp>
#include <dcs/testbed/base_application_manager.hpp>
#include <fstream>
#include <map>
#include <sstream>
#include <stdexcept>
#include <vector>
namespace dcs { namespace testbed {
/**
* \brief A do-nothing application manager.
*
* This application does not act on the application.
* It only observes the behavior of the monitored application, together with
* its resource usage, and dump statistics.
*
* \author Marco Guazzone (marco.guazzone@gmail.com)
*/
template <typename TraitsT>
class dummy_application_manager: public base_application_manager<TraitsT>
{
private: typedef base_application_manager<TraitsT> base_type;
public: typedef typename base_type::traits_type traits_type;
public: typedef typename traits_type::real_type real_type;
private: typedef typename base_type::app_type app_type;
private: typedef typename base_type::app_pointer app_pointer;
private: typedef typename base_type::vm_identifier_type vm_identifier_type;
private: typedef typename app_type::sensor_type sensor_type;
private: typedef typename app_type::sensor_pointer sensor_pointer;
private: typedef ::std::map<application_performance_category,sensor_pointer> out_sensor_map;
private: typedef std::map<virtual_machine_performance_category,std::map<vm_identifier_type,sensor_pointer> > in_sensor_map;
private: static const real_type default_sampling_time;
private: static const real_type default_control_time;
public: dummy_application_manager()
: beta_(0.9),
ctl_count_(0),
ctl_skip_count_(0),
ctl_fail_count_(0)
{
}
public: void smoothing_factor(real_type value)
{
beta_ = value;
}
public: real_type smoothing_factor() const
{
return beta_;
}
public: void export_data_to(::std::string const& fname)
{
dat_fname_ = fname;
}
private: void do_reset()
{
typedef typename base_type::target_value_map::const_iterator target_iterator;
typedef typename app_type::vm_pointer vm_pointer;
const ::std::vector<vm_pointer> vms = this->app().vms();
const std::size_t nvms = this->app().num_vms();
// Reset output sensors
out_sensors_.clear();
for (target_iterator tgt_it = this->target_values().begin(),
tgt_end_it = this->target_values().end();
tgt_it != tgt_end_it;
++tgt_it)
{
const application_performance_category cat = tgt_it->first;
out_sensors_[cat] = this->app().sensor(cat);
}
// Reset input sensors
in_sensors_.clear();
for (::std::size_t i = 0; i < nvms; ++i)
{
vm_pointer p_vm = vms[i];
in_sensors_[cpu_util_virtual_machine_performance][p_vm->id()] = p_vm->sensor(cpu_util_virtual_machine_performance);
in_sensors_[memory_util_virtual_machine_performance][p_vm->id()] = p_vm->sensor(memory_util_virtual_machine_performance);
}
// Reset resource utilization smoothers
for (::std::size_t i = 0; i < nvms; ++i)
{
this->data_smoother(cpu_util_virtual_machine_performance, vms[i]->id(), ::boost::make_shared< testbed::brown_single_exponential_smoother<real_type> >(beta_));
this->data_smoother(memory_util_virtual_machine_performance, vms[i]->id(), ::boost::make_shared< testbed::brown_single_exponential_smoother<real_type> >(beta_));
}
// Reset counters
ctl_count_ = ctl_skip_count_
= ctl_fail_count_
= 0;
// Reset output data file
if (p_dat_ofs_ && p_dat_ofs_->is_open())
{
p_dat_ofs_->close();
}
p_dat_ofs_.reset();
if (!dat_fname_.empty())
{
p_dat_ofs_ = ::boost::make_shared< ::std::ofstream >(dat_fname_.c_str());
if (!p_dat_ofs_->good())
{
::std::ostringstream oss;
oss << "Cannot open output data file '" << dat_fname_ << "'";
DCS_EXCEPTION_THROW(::std::runtime_error, oss.str());
}
*p_dat_ofs_ << "\"ts\"";
const ::std::size_t nvms = this->app().num_vms();
for (::std::size_t i = 0; i < nvms; ++i)
{
*p_dat_ofs_ << ",\"CPUCap_{" << i << "}(k)\",\"CPUShare_{" << i << "}(k)\""
<< ",\"MemCap_{" << i << "}(k)\",\"MemShare_{" << i << "}(k)\"";
}
for (::std::size_t i = 0; i < nvms; ++i)
{
*p_dat_ofs_ << ",\"CPUShare_{" << vms[i]->id() << "}(k-1)\",\"MemShare_{" << vms[i]->id() << "}(k-1)\"";
}
for (::std::size_t i = 0; i < nvms; ++i)
{
*p_dat_ofs_ << ",\"CPUUtil_{" << vms[i]->id() << "}(k-1)\",\"MemUtil_{" << vms[i]->id() << "}(k-1)\"";
}
for (target_iterator tgt_it = this->target_values().begin(),
tgt_end_it = this->target_values().end();
tgt_it != tgt_end_it;
++tgt_it)
{
const application_performance_category cat = tgt_it->first;
*p_dat_ofs_ << ",\"ReferenceOutput_{" << cat << "}(k-1)\",\"MeasuredOutput_{" << cat << "}(k-1)\",\"RelativeOutputError_{" << cat << "}(k-1)\"";
}
*p_dat_ofs_ << ",\"# Controls\",\"# Skip Controls\",\"# Fail Controls\"";
*p_dat_ofs_ << ",\"Elapsed Time\"";
*p_dat_ofs_ << ::std::endl;
}
}
private: void do_sample()
{
typedef typename in_sensor_map::const_iterator in_sensor_iterator;
typedef typename out_sensor_map::const_iterator out_sensor_iterator;
typedef ::std::vector<typename sensor_type::observation_type> obs_container;
typedef typename obs_container::const_iterator obs_iterator;
DCS_DEBUG_TRACE("(" << this << ") BEGIN Do SAMPLE - Count: " << ctl_count_ << "/" << ctl_skip_count_ << "/" << ctl_fail_count_);
// Collect input values
for (in_sensor_iterator in_sens_it = in_sensors_.begin(),
in_sens_end_it = in_sensors_.end();
in_sens_it != in_sens_end_it;
++in_sens_it)
{
const virtual_machine_performance_category cat = in_sens_it->first;
for (typename in_sensor_map::mapped_type::const_iterator vm_it = in_sens_it->second.begin(),
vm_end_it = in_sens_it->second.end();
vm_it != vm_end_it;
++vm_it)
{
const vm_identifier_type vm_id = vm_it->first;
sensor_pointer p_sens = vm_it->second;
// check: p_sens != null
DCS_DEBUG_ASSERT( p_sens );
p_sens->sense();
if (p_sens->has_observations())
{
const obs_container obs = p_sens->observations();
const obs_iterator end_it = obs.end();
for (obs_iterator it = obs.begin();
it != end_it;
++it)
{
//this->data_estimator(cat, vm_id).collect(it->value());
this->data_smoother(cat, vm_id).smooth(it->value());
}
}
}
}
// Collect output values
for (out_sensor_iterator out_sens_it = out_sensors_.begin(),
out_sens_end_it = out_sensors_.end();
out_sens_it != out_sens_end_it;
++out_sens_it)
{
const application_performance_category cat = out_sens_it->first;
sensor_pointer p_sens = out_sens_it->second;
// check: p_sens != null
DCS_DEBUG_ASSERT( p_sens );
p_sens->sense();
if (p_sens->has_observations())
{
const obs_container obs = p_sens->observations();
const obs_iterator end_it = obs.end();
for (obs_iterator it = obs.begin();
it != end_it;
++it)
{
this->data_estimator(cat).collect(it->value());
}
}
}
DCS_DEBUG_TRACE("(" << this << ") END Do SAMPLE - Count: " << ctl_count_ << "/" << ctl_skip_count_ << "/" << ctl_fail_count_);
}
private: void do_control()
{
typedef typename base_type::target_value_map::const_iterator target_iterator;
typedef typename app_type::vm_pointer vm_pointer;
DCS_DEBUG_TRACE("(" << this << ") BEGIN Do CONTROL - Count: " << ctl_count_ << "/" << ctl_skip_count_ << "/" << ctl_fail_count_);
boost::timer::cpu_timer cpu_timer;
++ctl_count_;
bool skip_ctl = false;
::std::map<virtual_machine_performance_category,::std::vector<real_type> > xshares;
::std::map<virtual_machine_performance_category,::std::vector<real_type> > xutils;
::std::map<application_performance_category,real_type> perf_errs;
::std::vector<vm_pointer> vms = this->app().vms();
const ::std::size_t nvms = vms.size();
for (::std::size_t i = 0; i < nvms; ++i)
{
const virtual_machine_performance_category cat = cpu_util_virtual_machine_performance;
const vm_pointer p_vm = vms[i];
const real_type uh = this->data_smoother(cat, p_vm->id()).forecast(0);
const real_type c = p_vm->cpu_share();
xshares[cat].push_back(c);
xutils[cat].push_back(uh);
DCS_DEBUG_TRACE("VM " << p_vm->id() << " - Performance Category: " << cat << " - Uhat(k): " << uh << " - C(k): " << c);//XXX
}
if (!skip_ctl)
{
for (target_iterator tgt_it = this->target_values().begin(),
tgt_end_it = this->target_values().end();
tgt_it != tgt_end_it;
++tgt_it)
{
const application_performance_category cat(tgt_it->first);
// Compute a summary statistics of collected observation
if (this->data_estimator(cat).count() > 0)
{
const real_type yh = this->data_estimator(cat).estimate();
const real_type yr = this->target_value(cat);
switch (cat)
{
case response_time_application_performance:
perf_errs[cat] = (yr-yh)/yr;
break;
case throughput_application_performance:
perf_errs[cat] = (yh-yr)/yr;
break;
}
DCS_DEBUG_TRACE("APP Performance Category: " << cat << " - Yhat(k): " << yh << " - R: " << yr << " -> RelatiiveError(k+1): " << perf_errs.at(cat));//XXX
}
else
{
// No observation collected during the last control interval
DCS_DEBUG_TRACE("No output observation collected during the last control interval -> Skip control");
skip_ctl = true;
break;
}
#ifdef DCSXX_TESTBED_EXP_APP_MGR_RESET_ESTIMATION_EVERY_INTERVAL
this->data_estimator(cat).reset();
#endif // DCSXX_TESTBED_EXP_APP_MGR_RESET_ESTIMATION_EVERY_INTERVAL
}
}
if (skip_ctl)
{
++ctl_skip_count_;
}
cpu_timer.stop();
// Export to file
if (p_dat_ofs_)
{
if (xshares.size() == 0)
{
for (::std::size_t i = 0; i < nvms; ++i)
{
const vm_pointer p_vm = vms[i];
// check: p_vm != null
DCS_DEBUG_ASSERT( p_vm );
xshares[cpu_util_virtual_machine_performance].push_back(p_vm->cpu_share());
xshares[memory_util_virtual_machine_performance].push_back(p_vm->memory_share());
}
}
if (xutils.size() == 0)
{
xutils[cpu_util_virtual_machine_performance].assign(nvms, std::numeric_limits<real_type>::quiet_NaN());
xutils[memory_util_virtual_machine_performance].assign(nvms, std::numeric_limits<real_type>::quiet_NaN());
}
*p_dat_ofs_ << ::std::time(0) << ",";
for (::std::size_t i = 0; i < nvms; ++i)
{
const vm_pointer p_vm = vms[i];
// check: p_vm != null
DCS_DEBUG_ASSERT( p_vm );
if (i != 0)
{
*p_dat_ofs_ << ",";
}
*p_dat_ofs_ << p_vm->cpu_cap() << "," << p_vm->cpu_share()
<< "," << p_vm->memory_cap() << "," << p_vm->memory_share();
}
*p_dat_ofs_ << ",";
for (std::size_t i = 0; i < nvms; ++i)
{
if (i != 0)
{
*p_dat_ofs_ << ",";
}
*p_dat_ofs_ << xshares.at(cpu_util_virtual_machine_performance)[i]
<< "," << xshares.at(memory_util_virtual_machine_performance)[i];
}
*p_dat_ofs_ << ",";
for (std::size_t i = 0; i < nvms; ++i)
{
const vm_pointer p_vm = vms[i];
// check: p_vm != null
DCS_DEBUG_ASSERT( p_vm );
if (i != 0)
{
*p_dat_ofs_ << ",";
}
*p_dat_ofs_ << xutils.at(cpu_util_virtual_machine_performance)[i]
<< "," << xutils.at(memory_util_virtual_machine_performance)[i];
}
*p_dat_ofs_ << ",";
for (target_iterator tgt_it = this->target_values().begin(),
tgt_end_it = this->target_values().end();
tgt_it != tgt_end_it;
++tgt_it)
{
const application_performance_category cat = tgt_it->first;
if (tgt_it != this->target_values().begin())
{
*p_dat_ofs_ << ",";
}
const real_type yh = this->data_estimator(cat).estimate();
const real_type yr = tgt_it->second;
*p_dat_ofs_ << yr << "," << yh << "," << perf_errs.at(cat);
}
*p_dat_ofs_ << "," << ctl_count_ << "," << ctl_skip_count_ << "," << ctl_fail_count_;
*p_dat_ofs_ << "," << (cpu_timer.elapsed().user+cpu_timer.elapsed().system);
*p_dat_ofs_ << ::std::endl;
}
DCS_DEBUG_TRACE("(" << this << ") END Do CONTROL - Count: " << ctl_count_ << "/" << ctl_skip_count_ << "/" << ctl_fail_count_);
}
private: real_type beta_; ///< The EWMA smoothing factor for resource utilization
private: ::std::size_t ctl_count_; ///< Number of times control function has been invoked
private: ::std::size_t ctl_skip_count_; ///< Number of times control has been skipped
private: ::std::size_t ctl_fail_count_; ///< Number of times control has failed
private: in_sensor_map in_sensors_;
private: out_sensor_map out_sensors_;
private: ::std::string dat_fname_;
private: ::boost::shared_ptr< ::std::ofstream > p_dat_ofs_;
}; // dummy_application_manager
}} // Namespace dcs::testbed
#endif // DCS_TESTBED_DUMMY_APPLICATION_MANAGER_HPP
<|endoftext|> |
<commit_before>/*
* The Apache Software License, Version 1.1
*
*
* Copyright (c) 1999-2001 The Apache Software Foundation. All rights
* reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution,
* if any, must include the following acknowledgment:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowledgment may appear in the software itself,
* if and wherever such third-party acknowledgments normally appear.
*
* 4. The names "Xalan" and "Apache Software Foundation" must
* not be used to endorse or promote products derived from this
* software without prior written permission. For written
* permission, please contact apache@apache.org.
*
* 5. Products derived from this software may not be called "Apache",
* nor may "Apache" appear in their name, without prior written
* permission of the Apache Software Foundation.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (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.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation and was
* originally based on software copyright (c) 1999, International
* Business Machines, Inc., http://www.ibm.com. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*/
#include <iostream>
#include <strstream>
#include <stdio.h>
#include <direct.h>
#if !defined(XALAN_NO_NAMESPACES)
using std::cerr;
using std::cout;
using std::cin;
using std::endl;
using std::ifstream;
using std::ios_base;
using std::ostrstream;
using std::string;
#endif
// XERCES HEADERS...
// Are included by HarnessInit.hpp
// XALAN HEADERS...
// Are included by FileUtility.hpp
// HARNESS HEADERS...
#include <XMLFileReporter.hpp>
#include <FileUtility.hpp>
#include <HarnessInit.hpp>
#if defined(XALAN_NO_NAMESPACES)
typedef map<XalanDOMString, XalanDOMString, less<XalanDOMString> > Hashtable;
#else
typedef std::map<XalanDOMString, XalanDOMString> Hashtable;
#endif
// This is here for memory leak testing.
#if !defined(NDEBUG) && defined(_MSC_VER)
#include <crtdbg.h>
#endif
const char* const excludeStylesheets[] =
{
"sorterr06.xsl",
0
};
FileUtility h;
void
setHelp()
{
h.args.help << endl
<< "errortests dir [-sub -out]"
<< endl
<< endl
<< "dir (location of conformance directory)"
<< endl
<< "-sub dir (specific directory)"
<< endl
<< "-out dir (base directory for output)"
<< endl;
}
inline bool
checkForExclusion(XalanDOMString currentFile)
{
for (int i=0; excludeStylesheets[i] != 0; i++)
{
if (equals(currentFile, XalanDOMString(excludeStylesheets[i])))
{
return true;
}
}
return false;
}
int
main(int argc,
const char* argv[])
{
#if !defined(NDEBUG) && defined(_MSC_VER)
_CrtSetDbgFlag(_CrtSetDbgFlag(_CRTDBG_REPORT_FLAG) | _CRTDBG_LEAK_CHECK_DF);
_CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE);
_CrtSetReportFile(_CRT_WARN, _CRTDBG_FILE_STDERR);
#endif
HarnessInit xmlPlatformUtils;
XalanTransformer::initialize();
{
int theResult;
bool setGold = false;
// Set the program help string, then get the command line parameters.
//
setHelp();
if (h.getParams(argc, argv, "ERR-RESULTS", setGold) == true)
{
//
// Call the static initializers for xerces and xalan, and create a transformer
//
XalanTransformer xalan;
XalanSourceTreeDOMSupport domSupport;
XalanSourceTreeParserLiaison parserLiaison(domSupport);
domSupport.setParserLiaison(&parserLiaison);
// Generate Unique Run id and processor info
const XalanDOMString UniqRunid = h.generateUniqRunid();
// Defined basic constants for file manipulation and open results file
const XalanDOMString resultFilePrefix("cpperr");
const XalanDOMString resultsFile(h.args.output + resultFilePrefix + UniqRunid + XMLSuffix);
XMLFileReporter logFile(resultsFile);
logFile.logTestFileInit("Error Testing:");
// Get the list of Directories that are below conf
bool foundDir = false; // Flag indicates directory found. Used in conjunction with -sub cmd-line arg.
const FileNameVectorType dirs = h.getDirectoryNames(h.args.base);
for(FileNameVectorType::size_type j = 0; j < dirs.size(); ++j)
{
// If conformance directory structure does not exist, it needs to be created.
const XalanDOMString confSubdir = h.args.output + dirs[j];
h.checkAndCreateDir(confSubdir);
// Set up to get files from the associated error directories
const XalanDOMString currentDir(dirs[j] + XalanDOMString("\\err"));
const XalanDOMString subErrDir(h.args.sub + XalanDOMString("\\err"));
// Run specific category of files from given directory
if (length(h.args.sub) > 0 && !equals(currentDir, subErrDir))
{
continue;
}
// Check that output directory is there.
const XalanDOMString theOutputDir = h.args.output + currentDir;
h.checkAndCreateDir(theOutputDir);
// Indicate that directory was processed and get test files from the directory
foundDir = true;
logFile.logTestCaseInit(currentDir);
const FileNameVectorType files = h.getTestFileNames(h.args.base, currentDir, false);
for(FileNameVectorType::size_type i = 0; i < files.size(); i++)
{
Hashtable attrs;
const XalanDOMString currentFile(files[i]);
h.data.testOrFile = currentFile;
if (checkForExclusion(currentFile))
continue;
const XalanDOMString theXSLFile= h.args.base + currentDir + pathSep + currentFile;
const XalanDOMString theXMLFile = h.generateFileName(theXSLFile,"xml");
XalanDOMString theGoldFile = h.args.gold + currentDir + pathSep + currentFile;
theGoldFile = h.generateFileName(theGoldFile, "out");
const XalanDOMString outbase = h.args.output + currentDir + pathSep + currentFile;
const XalanDOMString theOutputFile = h.generateFileName(outbase, "out");
const XSLTInputSource xslInputSource(c_wstr(theXSLFile));
const XSLTInputSource xmlInputSource(c_wstr(theXMLFile));
const XSLTInputSource goldInputSource(c_wstr(theGoldFile));
const XSLTResultTarget resultFile(theOutputFile);
// Parsing(compile) the XSL stylesheet and report the results..
//
const XalanCompiledStylesheet* compiledSS = 0;
try
{
cout << endl << "PARSING STYLESHEET FOR: " << currentFile << endl;
xalan.compileStylesheet(xslInputSource, compiledSS);
if (compiledSS == 0 )
{
cout << "FAILED to parse stylesheet for " << currentFile << endl;
cout << "Reason: " << xalan.getLastError() << endl;
logFile.logErrorResult(currentFile, XalanDOMString(xalan.getLastError()));
continue;
}
}
catch(...)
{
cerr << "Exception caught!!!" << endl << endl;
}
// Parsing the input XML and report the results..
//
cout << "PARSING SOURCE XML FOR: " << currentFile << endl;
const XalanParsedSource* parsedSource = 0;
xalan.parseSource(xmlInputSource, parsedSource);
if (parsedSource == 0)
{
cout << "Failed to PARSE source document for " << currentFile << endl;
continue;
}
// Perform One transform using parsed stylesheet and parsed xml source, report results...
//
theResult = 0;
cout << "TRANSFORMING: " << currentFile << endl;
theResult = xalan.transform(*parsedSource, compiledSS, resultFile);
if (theResult != 0)
{
cout << "FAILED to transform stylesheet for " << currentFile << endl;
cout << "Reason: " << xalan.getLastError() << endl;
logFile.logErrorResult(currentFile, XalanDOMString(xalan.getLastError()));
}
else
{
logFile.logCheckPass(currentFile);
}
parserLiaison.reset();
xalan.destroyParsedSource(parsedSource);
xalan.destroyStylesheet(compiledSS);
}
logFile.logTestCaseClose("Done", "Pass");
}
// Check to see if -sub cmd-line directory was processed correctly.
if (!foundDir)
{
cout << "Specified test directory: \"" << c_str(TranscodeToLocalCodePage(h.args.sub)) << "\" not found" << endl;
}
h.reportPassFail(logFile, UniqRunid);
logFile.logTestFileClose("Conformance ", "Done");
logFile.close();
}
}
XalanTransformer::terminate();
return 0;
}
<commit_msg>Updated to run from new directory conferr.<commit_after>/*
* The Apache Software License, Version 1.1
*
*
* Copyright (c) 1999-2001 The Apache Software Foundation. All rights
* reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution,
* if any, must include the following acknowledgment:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowledgment may appear in the software itself,
* if and wherever such third-party acknowledgments normally appear.
*
* 4. The names "Xalan" and "Apache Software Foundation" must
* not be used to endorse or promote products derived from this
* software without prior written permission. For written
* permission, please contact apache@apache.org.
*
* 5. Products derived from this software may not be called "Apache",
* nor may "Apache" appear in their name, without prior written
* permission of the Apache Software Foundation.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (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.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation and was
* originally based on software copyright (c) 1999, International
* Business Machines, Inc., http://www.ibm.com. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*/
#include <iostream>
#include <strstream>
#include <stdio.h>
#include <direct.h>
#if !defined(XALAN_NO_NAMESPACES)
using std::cerr;
using std::cout;
using std::cin;
using std::endl;
using std::ifstream;
using std::ios_base;
using std::ostrstream;
using std::string;
#endif
// XERCES HEADERS...
// Are included by HarnessInit.hpp
// XALAN HEADERS...
// Are included by FileUtility.hpp
// HARNESS HEADERS...
#include <XMLFileReporter.hpp>
#include <FileUtility.hpp>
#include <HarnessInit.hpp>
#if defined(XALAN_NO_NAMESPACES)
typedef map<XalanDOMString, XalanDOMString, less<XalanDOMString> > Hashtable;
#else
typedef std::map<XalanDOMString, XalanDOMString> Hashtable;
#endif
// This is here for memory leak testing.
#if !defined(NDEBUG) && defined(_MSC_VER)
#include <crtdbg.h>
#endif
const char* const excludeStylesheets[] =
{
"sorterr06.xsl",
0
};
FileUtility h;
void
setHelp()
{
h.args.help << endl
<< "errortests dir [-sub -out]"
<< endl
<< endl
<< "dir (location of conformance directory)"
<< endl
<< "-sub dir (specific directory)"
<< endl
<< "-out dir (base directory for output)"
<< endl;
}
inline bool
checkForExclusion(XalanDOMString currentFile)
{
for (int i=0; excludeStylesheets[i] != 0; i++)
{
if (equals(currentFile, XalanDOMString(excludeStylesheets[i])))
{
return true;
}
}
return false;
}
int
main(int argc,
const char* argv[])
{
#if !defined(NDEBUG) && defined(_MSC_VER)
_CrtSetDbgFlag(_CrtSetDbgFlag(_CRTDBG_REPORT_FLAG) | _CRTDBG_LEAK_CHECK_DF);
_CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE);
_CrtSetReportFile(_CRT_WARN, _CRTDBG_FILE_STDERR);
#endif
HarnessInit xmlPlatformUtils;
XalanTransformer::initialize();
{
int theResult;
bool setGold = false;
// Set the program help string, then get the command line parameters.
//
setHelp();
if (h.getParams(argc, argv, "ERR-RESULTS", setGold) == true)
{
//
// Call the static initializers for xerces and xalan, and create a transformer
//
XalanTransformer xalan;
XalanSourceTreeDOMSupport domSupport;
XalanSourceTreeParserLiaison parserLiaison(domSupport);
domSupport.setParserLiaison(&parserLiaison);
// Generate Unique Run id and processor info
const XalanDOMString UniqRunid = h.generateUniqRunid();
// Defined basic constants for file manipulation and open results file
const XalanDOMString resultFilePrefix("cpperr");
const XalanDOMString resultsFile(h.args.output + resultFilePrefix + UniqRunid + XMLSuffix);
XMLFileReporter logFile(resultsFile);
logFile.logTestFileInit("Error Testing:");
// Get the list of Directories that are below conf
bool foundDir = false; // Flag indicates directory found. Used in conjunction with -sub cmd-line arg.
const FileNameVectorType dirs = h.getDirectoryNames(h.args.base);
for(FileNameVectorType::size_type j = 0; j < dirs.size(); ++j)
{
// If conformance directory structure does not exist, it needs to be created.
const XalanDOMString confSubdir = h.args.output + dirs[j];
h.checkAndCreateDir(confSubdir);
// Set up to get files from the associated error directories
const XalanDOMString currentDir(dirs[j]);
const XalanDOMString subErrDir(h.args.sub);
// Run specific category of files from given directory
if (length(h.args.sub) > 0 && !equals(currentDir, subErrDir))
{
continue;
}
// Check that output directory is there.
const XalanDOMString theOutputDir = h.args.output + currentDir;
h.checkAndCreateDir(theOutputDir);
// Indicate that directory was processed and get test files from the directory
foundDir = true;
logFile.logTestCaseInit(currentDir);
const FileNameVectorType files = h.getTestFileNames(h.args.base, currentDir, false);
for(FileNameVectorType::size_type i = 0; i < files.size(); i++)
{
Hashtable attrs;
const XalanDOMString currentFile(files[i]);
h.data.testOrFile = currentFile;
if (checkForExclusion(currentFile))
continue;
const XalanDOMString theXSLFile= h.args.base + currentDir + pathSep + currentFile;
const XalanDOMString theXMLFile = h.generateFileName(theXSLFile,"xml");
XalanDOMString theGoldFile = h.args.gold + currentDir + pathSep + currentFile;
theGoldFile = h.generateFileName(theGoldFile, "out");
const XalanDOMString outbase = h.args.output + currentDir + pathSep + currentFile;
const XalanDOMString theOutputFile = h.generateFileName(outbase, "out");
const XSLTInputSource xslInputSource(c_wstr(theXSLFile));
const XSLTInputSource xmlInputSource(c_wstr(theXMLFile));
const XSLTInputSource goldInputSource(c_wstr(theGoldFile));
const XSLTResultTarget resultFile(theOutputFile);
// Parsing(compile) the XSL stylesheet and report the results..
//
const XalanCompiledStylesheet* compiledSS = 0;
try
{
cout << endl << "PARSING STYLESHEET FOR: " << currentFile << endl;
xalan.compileStylesheet(xslInputSource, compiledSS);
if (compiledSS == 0 )
{
cout << "FAILED to parse stylesheet for " << currentFile << endl;
cout << "Reason: " << xalan.getLastError() << endl;
logFile.logErrorResult(currentFile, XalanDOMString(xalan.getLastError()));
continue;
}
}
catch(...)
{
cerr << "Exception caught!!!" << endl << endl;
}
// Parsing the input XML and report the results..
//
cout << "PARSING SOURCE XML FOR: " << currentFile << endl;
const XalanParsedSource* parsedSource = 0;
xalan.parseSource(xmlInputSource, parsedSource);
if (parsedSource == 0)
{
cout << "Failed to PARSE source document for " << currentFile << endl;
continue;
}
// Perform One transform using parsed stylesheet and parsed xml source, report results...
//
theResult = 0;
cout << "TRANSFORMING: " << currentFile << endl;
theResult = xalan.transform(*parsedSource, compiledSS, resultFile);
if (theResult != 0)
{
cout << "FAILED to transform stylesheet for " << currentFile << endl;
cout << "Reason: " << xalan.getLastError() << endl;
logFile.logErrorResult(currentFile, XalanDOMString(xalan.getLastError()));
}
else
{
logFile.logCheckPass(currentFile);
}
parserLiaison.reset();
xalan.destroyParsedSource(parsedSource);
xalan.destroyStylesheet(compiledSS);
}
logFile.logTestCaseClose("Done", "Pass");
}
// Check to see if -sub cmd-line directory was processed correctly.
if (!foundDir)
{
cout << "Specified test directory: \"" << c_str(TranscodeToLocalCodePage(h.args.sub)) << "\" not found" << endl;
}
h.reportPassFail(logFile, UniqRunid);
logFile.logTestFileClose("Conformance ", "Done");
logFile.close();
}
}
XalanTransformer::terminate();
return 0;
}
<|endoftext|> |
<commit_before>/*
* Eos - A 3D Morphable Model fitting library written in modern C++11/14.
*
* File: include/eos/morphablemodel/MorphableModel.hpp
*
* Copyright 2014, 2015 Patrik Huber
*
* 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.
*/
#pragma once
#ifndef MORPHABLEMODEL_HPP_
#define MORPHABLEMODEL_HPP_
#include "eos/morphablemodel/PcaModel.hpp"
#include "eos/render/Mesh.hpp"
#include "eos/morphablemodel/io/mat_cerealisation.hpp"
#include "cereal/cereal.hpp"
#include "cereal/access.hpp"
#include "cereal/types/vector.hpp"
#include "cereal/archives/binary.hpp"
#include <vector>
#include <array>
#include <cstdint>
// Forward declaration of an internal function
namespace eos { namespace morphablemodel { namespace detail {
eos::render::Mesh sample_to_mesh(cv::Mat shape, cv::Mat color, std::vector<std::array<int, 3>> tvi, std::vector<std::array<int, 3>> tci, std::vector<cv::Vec2f> texture_coordinates = std::vector<cv::Vec2f>());
} } }
namespace eos {
namespace morphablemodel {
/**
* @brief A class representing a 3D Morphable Model, consisting
* of a shape- and colour (albedo) PCA model.
*
* For the general idea of 3DMMs see T. Vetter, V. Blanz,
* 'A Morphable Model for the Synthesis of 3D Faces', SIGGRAPH 1999.
*/
class MorphableModel
{
public:
MorphableModel() = default;
/**
* Create a Morphable Model from a shape and a color PCA model, and optional
* texture coordinates.
*
* @param[in] shape_model A PCA model over the shape.
* @param[in] color_model A PCA model over the colour (albedo).
* @param[in] texture_coordinates Optional texture coordinates for every vertex.
*/
MorphableModel(PcaModel shape_model, PcaModel color_model, std::vector<cv::Vec2f> texture_coordinates = std::vector<cv::Vec2f>()) : shape_model(shape_model), color_model(color_model), texture_coordinates(texture_coordinates)
{
};
/**
* Returns the PCA shape model of this Morphable Model.
* as a Mesh.
*
* @return The shape model.
*/
PcaModel get_shape_model() const
{
return shape_model;
};
/**
* Returns the PCA color (albedo) model of this Morphable Model.
*
* @return The color model.
*/
PcaModel get_color_model() const
{
return color_model;
};
/**
* Returns the mean of the shape- and color model as a Mesh.
*
* @return An mesh instance of the mean of the Morphable Model.
*/
render::Mesh get_mean() const
{
assert(shape_model.get_data_dimension() == color_model.get_data_dimension() || !has_color_model()); // The number of vertices (= model.getDataDimension() / 3) has to be equal for both models, or, alternatively, it has to be a shape-only model.
cv::Mat shape = shape_model.get_mean();
cv::Mat color = color_model.get_mean();
render::Mesh mesh;
if (has_texture_coordinates()) {
mesh = detail::sample_to_mesh(shape, color, shape_model.get_triangle_list(), color_model.get_triangle_list(), texture_coordinates);
}
else {
mesh = detail::sample_to_mesh(shape, color, shape_model.get_triangle_list(), color_model.get_triangle_list());
}
return mesh;
};
/**
* Draws a random sample from the model, where the coefficients
* for the shape- and color models are both drawn from a standard
* normal (or with the given standard deviation).
*
* @param[in] shape_sigma The shape model standard deviation.
* @param[in] color_sigma The color model standard deviation.
* @return A random sample from the model.
*/
render::Mesh draw_sample(float shape_sigma = 1.0f, float color_sigma = 1.0f)
{
assert(shape_model.get_data_dimension() == color_model.get_data_dimension()); // The number of vertices (= model.getDataDimension() / 3) has to be equal for both models.
cv::Mat shapeSample = shape_model.draw_sample(shape_sigma);
cv::Mat colorSample = color_model.draw_sample(color_sigma);
render::Mesh mesh;
if (has_texture_coordinates()) {
mesh = detail::sample_to_mesh(shapeSample, colorSample, shape_model.get_triangle_list(), color_model.get_triangle_list(), texture_coordinates);
}
else {
mesh = detail::sample_to_mesh(shapeSample, colorSample, shape_model.get_triangle_list(), color_model.get_triangle_list());
}
return mesh;
};
/**
* Returns a sample from the model with the given shape- and
* colour PCA coefficients.
*
* If one of the given vectors is empty, the mean is used.
* The coefficient vectors should contain normalised, i.e. standard normal distributed coefficients.
* If the Morphable Model is a shape-only model (without colour model), make sure to
* leave \c color_coefficients empty.
*
* @param[in] shape_coefficients The PCA coefficients used to generate the shape sample.
* @param[in] color_coefficients The PCA coefficients used to generate the vertex colouring.
* @return A model instance with given coefficients.
*/
render::Mesh draw_sample(std::vector<float> shape_coefficients, std::vector<float> color_coefficients) const
{
assert(shape_model.get_data_dimension() == color_model.get_data_dimension() || !has_color_model()); // The number of vertices (= model.getDataDimension() / 3) has to be equal for both models, or, alternatively, it has to be a shape-only model.
cv::Mat shape_sample;
cv::Mat color_sample;
if (shape_coefficients.empty()) {
shape_sample = shape_model.get_mean();
}
else {
shape_sample = shape_model.draw_sample(shape_coefficients);
}
if (color_coefficients.empty()) {
color_sample = color_model.get_mean();
}
else {
color_sample = color_model.draw_sample(color_coefficients);
}
render::Mesh mesh;
if (has_texture_coordinates()) {
mesh = detail::sample_to_mesh(shape_sample, color_sample, shape_model.get_triangle_list(), color_model.get_triangle_list(), texture_coordinates);
}
else {
mesh = detail::sample_to_mesh(shape_sample, color_sample, shape_model.get_triangle_list(), color_model.get_triangle_list());
}
return mesh;
};
/**
* Returns true if this Morphable Model contains a colour
* model. Returns false if it is a shape-only model.
*
* @return True if the Morphable Model has a colour model (i.e. is not a shape-only model).
*/
bool has_color_model() const
{
return !color_model.get_mean().empty();
};
/**
* Returns the texture coordinates for all the vertices in the model.
*
* @return The texture coordinates for the model vertices.
*/
std::vector<cv::Vec2f> get_texture_coordinates() const
{
return texture_coordinates;
};
private:
PcaModel shape_model; ///< A PCA model of the shape
PcaModel color_model; ///< A PCA model of vertex color information
std::vector<cv::Vec2f> texture_coordinates; ///< uv-coordinates for every vertex
/**
* Returns whether the model has texture mapping coordinates, i.e.
* coordinates for every vertex.
*
* @return True if the model contains texture mapping coordinates.
*/
bool has_texture_coordinates() const {
return texture_coordinates.size() > 0 ? true : false;
};
friend class cereal::access;
/**
* Serialises this class using cereal.
*
* @param[in] ar The archive to serialise to (or to serialise from).
*/
template<class Archive>
void serialize(Archive& archive, const std::uint32_t version)
{
archive(shape_model, color_model, texture_coordinates);
};
};
/**
* Helper method to load a Morphable Model from
* a cereal::BinaryInputArchive from the harddisk.
*
* @param[in] filename Filename to a model.
* @return The loaded Morphable Model.
* @throw std::runtime_error When the file given in \c filename fails to be opened (most likely because the file doesn't exist).
*/
MorphableModel load_model(std::string filename)
{
MorphableModel model;
std::ifstream file(filename, std::ios::binary);
if (file.fail()) {
throw std::runtime_error("Error opening given file: " + filename);
}
cereal::BinaryInputArchive input_archive(file);
input_archive(model);
return model;
};
/**
* Helper method to save a Morphable Model to the
* harddrive as cereal::BinaryInputArchive.
*
* @param[in] model The model to be saved.
* @param[in] filename Filename for the model.
*/
void save_model(MorphableModel model, std::string filename)
{
std::ofstream file(filename, std::ios::binary);
cereal::BinaryOutputArchive output_archive(file);
output_archive(model);
};
namespace detail { /* eos::morphablemodel::detail */
/**
* Internal helper function that creates a Mesh from given shape and colour
* PCA instances. Needs the vertex index lists as well to assemble the mesh -
* and optional texture coordinates.
*
* If \c color is empty, it will create a mesh without vertex colouring.
*
* @param[in] shape PCA shape model instance.
* @param[in] color PCA color model instance.
* @param[in] tvi Triangle vertex indices.
* @param[in] tci Triangle color indices (usually identical to the vertex indices).
* @param[in] texture_coordinates Optional texture coordinates for each vertex.
* @return A mesh created from given parameters.
*/
eos::render::Mesh sample_to_mesh(cv::Mat shape, cv::Mat color, std::vector<std::array<int, 3>> tvi, std::vector<std::array<int, 3>> tci, std::vector<cv::Vec2f> texture_coordinates /* = std::vector<cv::Vec2f>() */)
{
assert(shape.rows == color.rows || color.empty()); // The number of vertices (= model.getDataDimension() / 3) has to be equal for both models, or, alternatively, it has to be a shape-only model.
auto num_vertices = shape.rows / 3;
eos::render::Mesh mesh;
// Construct the mesh vertices:
mesh.vertices.resize(num_vertices);
for (auto i = 0; i < num_vertices; ++i) {
mesh.vertices[i] = cv::Vec4f(shape.at<float>(i * 3 + 0), shape.at<float>(i * 3 + 1), shape.at<float>(i * 3 + 2), 1.0f);
}
// Assign the vertex color information if it's not a shape-only model:
if (!color.empty()) {
mesh.colors.resize(num_vertices);
for (auto i = 0; i < num_vertices; ++i) {
mesh.colors[i] = cv::Vec3f(color.at<float>(i * 3 + 0), color.at<float>(i * 3 + 1), color.at<float>(i * 3 + 2)); // order in hdf5: RGB. Order in OCV: BGR. But order in vertex.color: RGB
}
}
// Assign the triangle lists:
mesh.tvi = tvi;
mesh.tci = tci; // tci will be empty in case of a shape-only model
// Texture coordinates, if the model has them:
if (!texture_coordinates.empty()) {
mesh.texcoords.resize(num_vertices);
for (auto i = 0; i < num_vertices; ++i) {
mesh.texcoords[i] = texture_coordinates[i];
}
}
return mesh;
};
} /* namespace eos::morphablemodel::detail */
} /* namespace morphablemodel */
} /* namespace eos */
CEREAL_CLASS_VERSION(eos::morphablemodel::MorphableModel, 0);
#endif /* MORPHABLEMODEL_HPP_ */
<commit_msg>Clarified documentation of draw_sample() when a partial vector is given<commit_after>/*
* Eos - A 3D Morphable Model fitting library written in modern C++11/14.
*
* File: include/eos/morphablemodel/MorphableModel.hpp
*
* Copyright 2014, 2015 Patrik Huber
*
* 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.
*/
#pragma once
#ifndef MORPHABLEMODEL_HPP_
#define MORPHABLEMODEL_HPP_
#include "eos/morphablemodel/PcaModel.hpp"
#include "eos/render/Mesh.hpp"
#include "eos/morphablemodel/io/mat_cerealisation.hpp"
#include "cereal/cereal.hpp"
#include "cereal/access.hpp"
#include "cereal/types/vector.hpp"
#include "cereal/archives/binary.hpp"
#include <vector>
#include <array>
#include <cstdint>
// Forward declaration of an internal function
namespace eos { namespace morphablemodel { namespace detail {
eos::render::Mesh sample_to_mesh(cv::Mat shape, cv::Mat color, std::vector<std::array<int, 3>> tvi, std::vector<std::array<int, 3>> tci, std::vector<cv::Vec2f> texture_coordinates = std::vector<cv::Vec2f>());
} } }
namespace eos {
namespace morphablemodel {
/**
* @brief A class representing a 3D Morphable Model, consisting
* of a shape- and colour (albedo) PCA model.
*
* For the general idea of 3DMMs see T. Vetter, V. Blanz,
* 'A Morphable Model for the Synthesis of 3D Faces', SIGGRAPH 1999.
*/
class MorphableModel
{
public:
MorphableModel() = default;
/**
* Create a Morphable Model from a shape and a color PCA model, and optional
* texture coordinates.
*
* @param[in] shape_model A PCA model over the shape.
* @param[in] color_model A PCA model over the colour (albedo).
* @param[in] texture_coordinates Optional texture coordinates for every vertex.
*/
MorphableModel(PcaModel shape_model, PcaModel color_model, std::vector<cv::Vec2f> texture_coordinates = std::vector<cv::Vec2f>()) : shape_model(shape_model), color_model(color_model), texture_coordinates(texture_coordinates)
{
};
/**
* Returns the PCA shape model of this Morphable Model.
* as a Mesh.
*
* @return The shape model.
*/
PcaModel get_shape_model() const
{
return shape_model;
};
/**
* Returns the PCA color (albedo) model of this Morphable Model.
*
* @return The color model.
*/
PcaModel get_color_model() const
{
return color_model;
};
/**
* Returns the mean of the shape- and color model as a Mesh.
*
* @return An mesh instance of the mean of the Morphable Model.
*/
render::Mesh get_mean() const
{
assert(shape_model.get_data_dimension() == color_model.get_data_dimension() || !has_color_model()); // The number of vertices (= model.getDataDimension() / 3) has to be equal for both models, or, alternatively, it has to be a shape-only model.
cv::Mat shape = shape_model.get_mean();
cv::Mat color = color_model.get_mean();
render::Mesh mesh;
if (has_texture_coordinates()) {
mesh = detail::sample_to_mesh(shape, color, shape_model.get_triangle_list(), color_model.get_triangle_list(), texture_coordinates);
}
else {
mesh = detail::sample_to_mesh(shape, color, shape_model.get_triangle_list(), color_model.get_triangle_list());
}
return mesh;
};
/**
* Draws a random sample from the model, where the coefficients
* for the shape- and color models are both drawn from a standard
* normal (or with the given standard deviation).
*
* @param[in] shape_sigma The shape model standard deviation.
* @param[in] color_sigma The color model standard deviation.
* @return A random sample from the model.
*/
render::Mesh draw_sample(float shape_sigma = 1.0f, float color_sigma = 1.0f)
{
assert(shape_model.get_data_dimension() == color_model.get_data_dimension()); // The number of vertices (= model.getDataDimension() / 3) has to be equal for both models.
cv::Mat shapeSample = shape_model.draw_sample(shape_sigma);
cv::Mat colorSample = color_model.draw_sample(color_sigma);
render::Mesh mesh;
if (has_texture_coordinates()) {
mesh = detail::sample_to_mesh(shapeSample, colorSample, shape_model.get_triangle_list(), color_model.get_triangle_list(), texture_coordinates);
}
else {
mesh = detail::sample_to_mesh(shapeSample, colorSample, shape_model.get_triangle_list(), color_model.get_triangle_list());
}
return mesh;
};
/**
* Returns a sample from the model with the given shape- and
* colour PCA coefficients.
*
* If one of the given vectors is empty, the mean is used.
* The coefficient vectors should contain normalised, i.e. standard normal distributed coefficients.
* If the Morphable Model is a shape-only model (without colour model), make sure to
* leave \c color_coefficients empty.
* If a partial coefficient vector is given, it is filled with zeros up to the end.
*
* @param[in] shape_coefficients The PCA coefficients used to generate the shape sample.
* @param[in] color_coefficients The PCA coefficients used to generate the vertex colouring.
* @return A model instance with given coefficients.
*/
render::Mesh draw_sample(std::vector<float> shape_coefficients, std::vector<float> color_coefficients) const
{
assert(shape_model.get_data_dimension() == color_model.get_data_dimension() || !has_color_model()); // The number of vertices (= model.getDataDimension() / 3) has to be equal for both models, or, alternatively, it has to be a shape-only model.
cv::Mat shape_sample;
cv::Mat color_sample;
if (shape_coefficients.empty()) {
shape_sample = shape_model.get_mean();
}
else {
shape_sample = shape_model.draw_sample(shape_coefficients);
}
if (color_coefficients.empty()) {
color_sample = color_model.get_mean();
}
else {
color_sample = color_model.draw_sample(color_coefficients);
}
render::Mesh mesh;
if (has_texture_coordinates()) {
mesh = detail::sample_to_mesh(shape_sample, color_sample, shape_model.get_triangle_list(), color_model.get_triangle_list(), texture_coordinates);
}
else {
mesh = detail::sample_to_mesh(shape_sample, color_sample, shape_model.get_triangle_list(), color_model.get_triangle_list());
}
return mesh;
};
/**
* Returns true if this Morphable Model contains a colour
* model. Returns false if it is a shape-only model.
*
* @return True if the Morphable Model has a colour model (i.e. is not a shape-only model).
*/
bool has_color_model() const
{
return !color_model.get_mean().empty();
};
/**
* Returns the texture coordinates for all the vertices in the model.
*
* @return The texture coordinates for the model vertices.
*/
std::vector<cv::Vec2f> get_texture_coordinates() const
{
return texture_coordinates;
};
private:
PcaModel shape_model; ///< A PCA model of the shape
PcaModel color_model; ///< A PCA model of vertex colour information
std::vector<cv::Vec2f> texture_coordinates; ///< uv-coordinates for every vertex
/**
* Returns whether the model has texture mapping coordinates, i.e.
* coordinates for every vertex.
*
* @return True if the model contains texture mapping coordinates.
*/
bool has_texture_coordinates() const {
return texture_coordinates.size() > 0 ? true : false;
};
friend class cereal::access;
/**
* Serialises this class using cereal.
*
* @param[in] ar The archive to serialise to (or to serialise from).
*/
template<class Archive>
void serialize(Archive& archive, const std::uint32_t version)
{
archive(shape_model, color_model, texture_coordinates);
};
};
/**
* Helper method to load a Morphable Model from
* a cereal::BinaryInputArchive from the harddisk.
*
* @param[in] filename Filename to a model.
* @return The loaded Morphable Model.
* @throw std::runtime_error When the file given in \c filename fails to be opened (most likely because the file doesn't exist).
*/
MorphableModel load_model(std::string filename)
{
MorphableModel model;
std::ifstream file(filename, std::ios::binary);
if (file.fail()) {
throw std::runtime_error("Error opening given file: " + filename);
}
cereal::BinaryInputArchive input_archive(file);
input_archive(model);
return model;
};
/**
* Helper method to save a Morphable Model to the
* harddrive as cereal::BinaryInputArchive.
*
* @param[in] model The model to be saved.
* @param[in] filename Filename for the model.
*/
void save_model(MorphableModel model, std::string filename)
{
std::ofstream file(filename, std::ios::binary);
cereal::BinaryOutputArchive output_archive(file);
output_archive(model);
};
namespace detail { /* eos::morphablemodel::detail */
/**
* Internal helper function that creates a Mesh from given shape and colour
* PCA instances. Needs the vertex index lists as well to assemble the mesh -
* and optional texture coordinates.
*
* If \c color is empty, it will create a mesh without vertex colouring.
*
* @param[in] shape PCA shape model instance.
* @param[in] color PCA color model instance.
* @param[in] tvi Triangle vertex indices.
* @param[in] tci Triangle color indices (usually identical to the vertex indices).
* @param[in] texture_coordinates Optional texture coordinates for each vertex.
* @return A mesh created from given parameters.
*/
eos::render::Mesh sample_to_mesh(cv::Mat shape, cv::Mat color, std::vector<std::array<int, 3>> tvi, std::vector<std::array<int, 3>> tci, std::vector<cv::Vec2f> texture_coordinates /* = std::vector<cv::Vec2f>() */)
{
assert(shape.rows == color.rows || color.empty()); // The number of vertices (= model.getDataDimension() / 3) has to be equal for both models, or, alternatively, it has to be a shape-only model.
auto num_vertices = shape.rows / 3;
eos::render::Mesh mesh;
// Construct the mesh vertices:
mesh.vertices.resize(num_vertices);
for (auto i = 0; i < num_vertices; ++i) {
mesh.vertices[i] = cv::Vec4f(shape.at<float>(i * 3 + 0), shape.at<float>(i * 3 + 1), shape.at<float>(i * 3 + 2), 1.0f);
}
// Assign the vertex color information if it's not a shape-only model:
if (!color.empty()) {
mesh.colors.resize(num_vertices);
for (auto i = 0; i < num_vertices; ++i) {
mesh.colors[i] = cv::Vec3f(color.at<float>(i * 3 + 0), color.at<float>(i * 3 + 1), color.at<float>(i * 3 + 2)); // order in hdf5: RGB. Order in OCV: BGR. But order in vertex.color: RGB
}
}
// Assign the triangle lists:
mesh.tvi = tvi;
mesh.tci = tci; // tci will be empty in case of a shape-only model
// Texture coordinates, if the model has them:
if (!texture_coordinates.empty()) {
mesh.texcoords.resize(num_vertices);
for (auto i = 0; i < num_vertices; ++i) {
mesh.texcoords[i] = texture_coordinates[i];
}
}
return mesh;
};
} /* namespace eos::morphablemodel::detail */
} /* namespace morphablemodel */
} /* namespace eos */
CEREAL_CLASS_VERSION(eos::morphablemodel::MorphableModel, 0);
#endif /* MORPHABLEMODEL_HPP_ */
<|endoftext|> |
<commit_before>/**
* \file standard_gaussian.hpp
* \date May 2014
* @author Manuel Wuthrich (manuel.wuthrich@gmail.com)
* @author Jan Issac (jan.issac@gmail.com)
*/
#ifndef FL__DISTRIBUTION__STANDARD_GAUSSIAN_HPP
#define FL__DISTRIBUTION__STANDARD_GAUSSIAN_HPP
#include <Eigen/Dense>
#include <random>
#include <type_traits>
#include <fl/util/random.hpp>
#include <fl/util/traits.hpp>
#include <fl/util/math.hpp>
#include <fl/distribution/interface/sampling.hpp>
#include <fl/exception/exception.hpp>
namespace fl
{
/// \todo MISSING DOC. MISSING UTESTS
/**
* \ingroup distributions
*/
template <typename StandardVariate>
class StandardGaussian:
public Sampling<StandardVariate>
{
public:
explicit StandardGaussian(size_t dim = DimensionOf<StandardVariate>())
: dimension_ (dim),
generator_(fl::seed()),
gaussian_distribution_(0.0, 1.0)
{
}
virtual ~StandardGaussian() { }
virtual StandardVariate sample() const
{
StandardVariate gaussian_sample(dimension());
for (int i = 0; i < dimension(); i++)
{
gaussian_sample(i) = gaussian_distribution_(generator_);
}
return gaussian_sample;
}
virtual int dimension() const
{
return dimension_;
}
virtual void dimension(size_t new_dimension)
{
if (dimension_ == new_dimension) return;
if (fl::IsFixed<StandardVariate::SizeAtCompileTime>())
{
fl_throw(
fl::ResizingFixedSizeEntityException(dimension_,
new_dimension,
"Gaussian"));
}
dimension_ = new_dimension;
}
private:
int dimension_;
mutable fl::mt11213b generator_;
mutable std::normal_distribution<> gaussian_distribution_;
};
/** \cond IMPL_DETAILS */
/**
* Floating point implementation for Scalar types float, double and long double
*/
template <typename Scalar>
class StandardGaussianFloatingPointScalarImpl
{
static_assert(
std::is_floating_point<Scalar>::value,
"Scalar must be a floating point (float, double, long double)");
public:
StandardGaussianFloatingPointScalarImpl()
: generator_(fl::seed()),
gaussian_distribution_(Scalar(0.), Scalar(1.))
{ }
Scalar sample_impl() const
{
return gaussian_distribution_(generator_);
}
protected:
mutable fl::mt11213b generator_;
mutable std::normal_distribution<Scalar> gaussian_distribution_;
};
/** \endcond */
/**
* Float floating point StandardGaussian specialization
* \ingroup distributions
*/
template <>
class StandardGaussian<float>
: public Sampling<float>,
public StandardGaussianFloatingPointScalarImpl<float>
{
public:
/**
* \copydoc Sampling::sample
*/
virtual float sample() const
{
return this->sample_impl();
}
};
/**
* Double floating point StandardGaussian specialization
* \ingroup distributions
*/
template <>
class StandardGaussian<double>
: public Sampling<double>,
public StandardGaussianFloatingPointScalarImpl<double>
{
public:
/**
* \copydoc Sampling::sample
*/
virtual double sample() const
{
return this->sample_impl();
}
};
/**
* Long double floating point StandardGaussian specialization
* \ingroup distributions
*/
template <>
class StandardGaussian<long double>
: public Sampling<long double>,
public StandardGaussianFloatingPointScalarImpl<long double>
{
public:
/**
* \copydoc Sampling::sample
*/
virtual long double sample() const
{
return this->sample_impl();
}
};
}
#endif
<commit_msg>updated doc<commit_after>/**
* \file standard_gaussian.hpp
* \date May 2014
* \author Jan Issac (jan.issac@gmail.com)
* \author Manuel Wuthrich (manuel.wuthrich@gmail.com)
*/
#ifndef FL__DISTRIBUTION__STANDARD_GAUSSIAN_HPP
#define FL__DISTRIBUTION__STANDARD_GAUSSIAN_HPP
#include <Eigen/Dense>
#include <random>
#include <type_traits>
#include <fl/util/random.hpp>
#include <fl/util/traits.hpp>
#include <fl/util/math.hpp>
#include <fl/distribution/interface/sampling.hpp>
#include <fl/exception/exception.hpp>
namespace fl
{
/**
* \ingroup distributions
*/
template <typename StandardVariate>
class StandardGaussian:
public Sampling<StandardVariate>
{
public:
explicit StandardGaussian(size_t dim = DimensionOf<StandardVariate>())
: dimension_ (dim),
generator_(fl::seed()),
gaussian_distribution_(0.0, 1.0)
{
}
virtual ~StandardGaussian() { }
virtual StandardVariate sample() const
{
StandardVariate gaussian_sample(dimension());
for (int i = 0; i < dimension(); i++)
{
gaussian_sample(i) = gaussian_distribution_(generator_);
}
return gaussian_sample;
}
virtual int dimension() const
{
return dimension_;
}
virtual void dimension(size_t new_dimension)
{
if (dimension_ == new_dimension) return;
if (fl::IsFixed<StandardVariate::SizeAtCompileTime>())
{
fl_throw(
fl::ResizingFixedSizeEntityException(dimension_,
new_dimension,
"Gaussian"));
}
dimension_ = new_dimension;
}
private:
int dimension_;
mutable fl::mt11213b generator_;
mutable std::normal_distribution<> gaussian_distribution_;
};
/** \cond IMPL_DETAILS */
/**
* Floating point implementation for Scalar types float, double and long double
*/
template <typename Scalar>
class StandardGaussianFloatingPointScalarImpl
{
static_assert(
std::is_floating_point<Scalar>::value,
"Scalar must be a floating point (float, double, long double)");
public:
StandardGaussianFloatingPointScalarImpl()
: generator_(fl::seed()),
gaussian_distribution_(Scalar(0.), Scalar(1.))
{ }
Scalar sample_impl() const
{
return gaussian_distribution_(generator_);
}
protected:
mutable fl::mt11213b generator_;
mutable std::normal_distribution<Scalar> gaussian_distribution_;
};
/** \endcond */
/**
* Float floating point StandardGaussian specialization
* \ingroup distributions
*/
template <>
class StandardGaussian<float>
: public Sampling<float>,
public StandardGaussianFloatingPointScalarImpl<float>
{
public:
/**
* \copydoc Sampling::sample
*/
virtual float sample() const
{
return this->sample_impl();
}
};
/**
* Double floating point StandardGaussian specialization
* \ingroup distributions
*/
template <>
class StandardGaussian<double>
: public Sampling<double>,
public StandardGaussianFloatingPointScalarImpl<double>
{
public:
/**
* \copydoc Sampling::sample
*/
virtual double sample() const
{
return this->sample_impl();
}
};
/**
* Long double floating point StandardGaussian specialization
* \ingroup distributions
*/
template <>
class StandardGaussian<long double>
: public Sampling<long double>,
public StandardGaussianFloatingPointScalarImpl<long double>
{
public:
/**
* \copydoc Sampling::sample
*/
virtual long double sample() const
{
return this->sample_impl();
}
};
}
#endif
<|endoftext|> |
<commit_before>/*
* This is part of the FL library, a C++ Bayesian filtering library
* (https://github.com/filtering-library)
*
* Copyright (c) 2014 Jan Issac (jan.issac@gmail.com)
* Copyright (c) 2014 Manuel Wuthrich (manuel.wuthrich@gmail.com)
*
* Max-Planck Institute for Intelligent Systems, AMD Lab
* University of Southern California, CLMC Lab
*
* This Source Code Form is subject to the terms of the MIT License (MIT).
* A copy of the license can be found in the LICENSE file distributed with this
* source code.
*/
/**
* \date August 2015
* \author Manuel Wuthrich (manuel.wuthrich@gmail.com)
*/
#ifndef FL__UTIL__MATH__POSE_VELOCITY_VECTOR_HPP
#define FL__UTIL__MATH__POSE_VELOCITY_VECTOR_HPP
#include <Eigen/Dense>
#include <fl/util/types.hpp>
#include <fl/util/math/euler_vector.hpp>
#include <fl/util/math/pose_vector.hpp>
namespace fl
{
/// basic functionality for both vectors and blocks ****************************
template <typename Base>
class PoseVelocityBase: public Base
{
public:
enum
{
POSE_INDEX = 0,
LINEAR_VELOCITY_INDEX = 6,
ANGULAR_VELOCITY_INDEX = 9,
POSE_SIZE = 6,
VELOCITY_SIZE = 3,
};
// types *******************************************************************
typedef Eigen::Matrix<Real, VELOCITY_SIZE, 1> VelocityVector;
typedef Eigen::VectorBlock<Base, VELOCITY_SIZE> VelocityBlock;
// constructor and destructor **********************************************
PoseVelocityBase(const Base& vector): Base(vector) { }
virtual ~PoseVelocityBase() {}
// operators ***************************************************************
template <typename T>
void operator = (const Eigen::MatrixBase<T>& vector)
{
*((Base*)(this)) = vector;
}
// accessors ***************************************************************
virtual PoseVector pose() const
{
return this->template middleRows<POSE_SIZE>(POSE_INDEX);
}
virtual VelocityVector linear_velocity() const
{
return this->template middleRows<VELOCITY_SIZE>(LINEAR_VELOCITY_INDEX);
}
virtual VelocityVector angular_velocity() const
{
return this->template middleRows<VELOCITY_SIZE>(ANGULAR_VELOCITY_INDEX);
}
// mutators ****************************************************************
PoseBlock<Base> pose()
{
return PoseBlock<Base>(*this, POSE_INDEX);
}
VelocityBlock linear_velocity()
{
return VelocityBlock(*this, LINEAR_VELOCITY_INDEX);
}
VelocityBlock angular_velocity()
{
return VelocityBlock(*this, ANGULAR_VELOCITY_INDEX);
}
};
/// implementation for vectors *************************************************
class PoseVelocityVector: public PoseVelocityBase<Eigen::Matrix<Real, 12, 1>>
{
public:
typedef PoseVelocityBase<Eigen::Matrix<Real, 12, 1>> Base;
// constructor and destructor **********************************************
PoseVelocityVector(): Base(Base::Zero()) { }
template <typename T>
PoseVelocityVector(const Eigen::MatrixBase<T>& vector): Base(vector) { }
virtual ~PoseVelocityVector() {}
};
/// implementation for blocks **************************************************
template <typename Vector>
class PoseVelocityBlock: public PoseVelocityBase<Eigen::VectorBlock<Vector, 12>>
{
public:
typedef Eigen::VectorBlock<Vector, 12> Block;
typedef PoseVelocityBase<Block> Base;
using Base::operator=;
// constructor and destructor **********************************************
PoseVelocityBlock(const Block& block): Base(block) { }
PoseVelocityBlock(Vector& vector, int start): Base(Block(vector, start)) { }
virtual ~PoseVelocityBlock() {}
};
}
#endif
<commit_msg>added some functionality to pose_velocity_vector<commit_after>/*
* This is part of the FL library, a C++ Bayesian filtering library
* (https://github.com/filtering-library)
*
* Copyright (c) 2014 Jan Issac (jan.issac@gmail.com)
* Copyright (c) 2014 Manuel Wuthrich (manuel.wuthrich@gmail.com)
*
* Max-Planck Institute for Intelligent Systems, AMD Lab
* University of Southern California, CLMC Lab
*
* This Source Code Form is subject to the terms of the MIT License (MIT).
* A copy of the license can be found in the LICENSE file distributed with this
* source code.
*/
/**
* \date August 2015
* \author Manuel Wuthrich (manuel.wuthrich@gmail.com)
*/
#ifndef FL__UTIL__MATH__POSE_VELOCITY_VECTOR_HPP
#define FL__UTIL__MATH__POSE_VELOCITY_VECTOR_HPP
#include <Eigen/Dense>
#include <fl/util/types.hpp>
#include <fl/util/math/euler_vector.hpp>
#include <fl/util/math/pose_vector.hpp>
namespace fl
{
/// basic functionality for both vectors and blocks ****************************
template <typename Base>
class PoseVelocityBase: public Base
{
public:
enum
{
POSE_INDEX = 0,
LINEAR_VELOCITY_INDEX = 6,
ANGULAR_VELOCITY_INDEX = 9,
POSE_SIZE = 6,
VELOCITY_SIZE = 3,
};
// types *******************************************************************
typedef Eigen::Matrix<Real, VELOCITY_SIZE, 1> VelocityVector;
typedef Eigen::VectorBlock<Base, VELOCITY_SIZE> VelocityBlock;
// constructor and destructor **********************************************
PoseVelocityBase(const Base& vector): Base(vector) { }
virtual ~PoseVelocityBase() {}
// operators ***************************************************************
template <typename T>
void operator = (const Eigen::MatrixBase<T>& vector)
{
*((Base*)(this)) = vector;
}
// accessors ***************************************************************
virtual PoseVector pose() const
{
return this->template middleRows<POSE_SIZE>(POSE_INDEX);
}
virtual PoseVector::Vector position() const
{
return pose().position();
}
virtual EulerVector euler_vector() const
{
return pose().euler_vector();
}
virtual PoseVector::HomogeneousMatrix homogeneous_matrix() const
{
return pose().homogeneous_matrix();
}
virtual VelocityVector linear_velocity() const
{
return this->template middleRows<VELOCITY_SIZE>(LINEAR_VELOCITY_INDEX);
}
virtual VelocityVector angular_velocity() const
{
return this->template middleRows<VELOCITY_SIZE>(ANGULAR_VELOCITY_INDEX);
}
// mutators ****************************************************************
PoseBlock<Base> pose()
{
return PoseBlock<Base>(*this, POSE_INDEX);
}
typename PoseBlock<Base>::PositionBlock position()
{
return pose().position();
}
typename PoseBlock<Base>::OrientationBlock euler_vector()
{
return pose().euler_vector();
}
virtual void homogeneous_matrix(
const typename PoseBlock<Base>::HomogeneousMatrix& H)
{
pose().homogeneous_matrix(H);
}
VelocityBlock linear_velocity()
{
return VelocityBlock(*this, LINEAR_VELOCITY_INDEX);
}
VelocityBlock angular_velocity()
{
return VelocityBlock(*this, ANGULAR_VELOCITY_INDEX);
}
};
/// implementation for vectors *************************************************
class PoseVelocityVector: public PoseVelocityBase<Eigen::Matrix<Real, 12, 1>>
{
public:
typedef PoseVelocityBase<Eigen::Matrix<Real, 12, 1>> Base;
// constructor and destructor **********************************************
PoseVelocityVector(): Base(Base::Zero()) { }
template <typename T>
PoseVelocityVector(const Eigen::MatrixBase<T>& vector): Base(vector) { }
virtual ~PoseVelocityVector() {}
};
/// implementation for blocks **************************************************
template <typename Vector>
class PoseVelocityBlock: public PoseVelocityBase<Eigen::VectorBlock<Vector, 12>>
{
public:
typedef Eigen::VectorBlock<Vector, 12> Block;
typedef PoseVelocityBase<Block> Base;
using Base::operator=;
// constructor and destructor **********************************************
PoseVelocityBlock(const Block& block): Base(block) { }
PoseVelocityBlock(Vector& vector, int start): Base(Block(vector, start)) { }
virtual ~PoseVelocityBlock() {}
};
}
#endif
<|endoftext|> |
<commit_before>/*
Copyright (c) 2015 - present Advanced Micro Devices, Inc. All rights reserved.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
#pragma once
#include <hsa/hsa.h>
#include <algorithm>
#include <cstdint>
#include <istream>
#include <iterator>
#include <string>
#include <utility>
#include <vector>
namespace hip_impl {
inline
__attribute__((visibility("hidden")))
std::string transmogrify_triple(const std::string& triple)
{
static constexpr const char old_prefix[]{"hcc-amdgcn--amdhsa-gfx"};
static constexpr const char new_prefix[]{"hcc-amdgcn-amd-amdhsa--gfx"};
if (triple.find(old_prefix) == 0) {
return new_prefix + triple.substr(sizeof(old_prefix) - 1);
}
return (triple.find(new_prefix) == 0) ? triple : "";
}
inline
__attribute__((visibility("hidden")))
std::string isa_name(std::string triple)
{
static constexpr const char offload_prefix[]{"hcc-"};
triple = transmogrify_triple(triple);
if (triple.empty()) return {};
triple.erase(0, sizeof(offload_prefix) - 1);
return triple;
}
inline
__attribute__((visibility("hidden")))
hsa_isa_t triple_to_hsa_isa(const std::string& triple) {
const std::string isa{isa_name(std::move(triple))};
if (isa.empty()) return hsa_isa_t({});
hsa_isa_t r{};
if(HSA_STATUS_SUCCESS != hsa_isa_from_name(isa.c_str(), &r)) {
r.handle = 0;
}
return r;
}
struct Bundled_code {
union Header {
struct {
std::uint64_t offset;
std::uint64_t bundle_sz;
std::uint64_t triple_sz;
};
char cbuf[sizeof(offset) + sizeof(bundle_sz) + sizeof(triple_sz)];
} header;
std::string triple;
std::vector<char> blob;
};
class Bundled_code_header {
// DATA - STATICS
static constexpr const char magic_string_[] = "__CLANG_OFFLOAD_BUNDLE__";
static constexpr auto magic_string_sz_ = sizeof(magic_string_) - 1;
// DATA
union Header_ {
struct {
char bundler_magic_string_[magic_string_sz_];
std::uint64_t bundle_cnt_;
};
char cbuf_[sizeof(bundler_magic_string_) + sizeof(bundle_cnt_)];
} header_;
std::vector<Bundled_code> bundles_;
// FRIENDS - MANIPULATORS
template <typename RandomAccessIterator>
friend inline bool read(RandomAccessIterator f, RandomAccessIterator l,
Bundled_code_header& x) {
if (f == l) return false;
std::copy_n(f, sizeof(x.header_.cbuf_), x.header_.cbuf_);
if (valid(x)) {
x.bundles_.resize(x.header_.bundle_cnt_);
auto it = f + sizeof(x.header_.cbuf_);
for (auto&& y : x.bundles_) {
std::copy_n(it, sizeof(y.header.cbuf), y.header.cbuf);
it += sizeof(y.header.cbuf);
y.triple.assign(it, it + y.header.triple_sz);
std::copy_n(f + y.header.offset, y.header.bundle_sz, std::back_inserter(y.blob));
it += y.header.triple_sz;
x.bundled_code_size = std::max(x.bundled_code_size,
y.header.offset + y.header.bundle_sz);
}
return true;
}
return false;
}
friend inline bool read(const std::vector<char>& blob, Bundled_code_header& x) {
return read(blob.cbegin(), blob.cend(), x);
}
friend inline bool read(std::istream& is, Bundled_code_header& x) {
return read(
std::vector<char>{std::istreambuf_iterator<char>{is}, std::istreambuf_iterator<char>{}},
x);
}
// FRIENDS - ACCESSORS
friend inline bool valid(const Bundled_code_header& x) {
return std::equal(magic_string_, magic_string_ + magic_string_sz_,
x.header_.bundler_magic_string_);
}
friend inline const std::vector<Bundled_code>& bundles(const Bundled_code_header& x) {
return x.bundles_;
}
public:
// CREATORS
Bundled_code_header() = default;
template <typename RandomAccessIterator>
Bundled_code_header(RandomAccessIterator f, RandomAccessIterator l);
explicit Bundled_code_header(const std::vector<char>& blob);
explicit Bundled_code_header(const void* maybe_blob);
Bundled_code_header(const Bundled_code_header&) = default;
Bundled_code_header(Bundled_code_header&&) = default;
~Bundled_code_header() = default;
// MANIPULATORS
Bundled_code_header& operator=(const Bundled_code_header&) = default;
Bundled_code_header& operator=(Bundled_code_header&&) = default;
size_t bundled_code_size = 0;
};
// CREATORS
template <typename RandomAccessIterator>
Bundled_code_header::Bundled_code_header(RandomAccessIterator f, RandomAccessIterator l)
: Bundled_code_header{} {
read(f, l, *this);
}
} // Namespace hip_impl.
<commit_msg>remove visibility hidden attribute<commit_after>/*
Copyright (c) 2015 - present Advanced Micro Devices, Inc. All rights reserved.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
#pragma once
#include <hsa/hsa.h>
#include <algorithm>
#include <cstdint>
#include <istream>
#include <iterator>
#include <string>
#include <utility>
#include <vector>
namespace hip_impl {
inline
std::string transmogrify_triple(const std::string& triple)
{
static constexpr const char old_prefix[]{"hcc-amdgcn--amdhsa-gfx"};
static constexpr const char new_prefix[]{"hcc-amdgcn-amd-amdhsa--gfx"};
if (triple.find(old_prefix) == 0) {
return new_prefix + triple.substr(sizeof(old_prefix) - 1);
}
return (triple.find(new_prefix) == 0) ? triple : "";
}
inline
std::string isa_name(std::string triple)
{
static constexpr const char offload_prefix[]{"hcc-"};
triple = transmogrify_triple(triple);
if (triple.empty()) return {};
triple.erase(0, sizeof(offload_prefix) - 1);
return triple;
}
inline
hsa_isa_t triple_to_hsa_isa(const std::string& triple) {
const std::string isa{isa_name(std::move(triple))};
if (isa.empty()) return hsa_isa_t({});
hsa_isa_t r{};
if(HSA_STATUS_SUCCESS != hsa_isa_from_name(isa.c_str(), &r)) {
r.handle = 0;
}
return r;
}
struct Bundled_code {
union Header {
struct {
std::uint64_t offset;
std::uint64_t bundle_sz;
std::uint64_t triple_sz;
};
char cbuf[sizeof(offset) + sizeof(bundle_sz) + sizeof(triple_sz)];
} header;
std::string triple;
std::vector<char> blob;
};
class Bundled_code_header {
// DATA - STATICS
static constexpr const char magic_string_[] = "__CLANG_OFFLOAD_BUNDLE__";
static constexpr auto magic_string_sz_ = sizeof(magic_string_) - 1;
// DATA
union Header_ {
struct {
char bundler_magic_string_[magic_string_sz_];
std::uint64_t bundle_cnt_;
};
char cbuf_[sizeof(bundler_magic_string_) + sizeof(bundle_cnt_)];
} header_;
std::vector<Bundled_code> bundles_;
// FRIENDS - MANIPULATORS
template <typename RandomAccessIterator>
friend inline bool read(RandomAccessIterator f, RandomAccessIterator l,
Bundled_code_header& x) {
if (f == l) return false;
std::copy_n(f, sizeof(x.header_.cbuf_), x.header_.cbuf_);
if (valid(x)) {
x.bundles_.resize(x.header_.bundle_cnt_);
auto it = f + sizeof(x.header_.cbuf_);
for (auto&& y : x.bundles_) {
std::copy_n(it, sizeof(y.header.cbuf), y.header.cbuf);
it += sizeof(y.header.cbuf);
y.triple.assign(it, it + y.header.triple_sz);
std::copy_n(f + y.header.offset, y.header.bundle_sz, std::back_inserter(y.blob));
it += y.header.triple_sz;
x.bundled_code_size = std::max(x.bundled_code_size,
y.header.offset + y.header.bundle_sz);
}
return true;
}
return false;
}
friend inline bool read(const std::vector<char>& blob, Bundled_code_header& x) {
return read(blob.cbegin(), blob.cend(), x);
}
friend inline bool read(std::istream& is, Bundled_code_header& x) {
return read(
std::vector<char>{std::istreambuf_iterator<char>{is}, std::istreambuf_iterator<char>{}},
x);
}
// FRIENDS - ACCESSORS
friend inline bool valid(const Bundled_code_header& x) {
return std::equal(magic_string_, magic_string_ + magic_string_sz_,
x.header_.bundler_magic_string_);
}
friend inline const std::vector<Bundled_code>& bundles(const Bundled_code_header& x) {
return x.bundles_;
}
public:
// CREATORS
Bundled_code_header() = default;
template <typename RandomAccessIterator>
Bundled_code_header(RandomAccessIterator f, RandomAccessIterator l);
explicit Bundled_code_header(const std::vector<char>& blob);
explicit Bundled_code_header(const void* maybe_blob);
Bundled_code_header(const Bundled_code_header&) = default;
Bundled_code_header(Bundled_code_header&&) = default;
~Bundled_code_header() = default;
// MANIPULATORS
Bundled_code_header& operator=(const Bundled_code_header&) = default;
Bundled_code_header& operator=(Bundled_code_header&&) = default;
size_t bundled_code_size = 0;
};
// CREATORS
template <typename RandomAccessIterator>
Bundled_code_header::Bundled_code_header(RandomAccessIterator f, RandomAccessIterator l)
: Bundled_code_header{} {
read(f, l, *this);
}
} // Namespace hip_impl.
<|endoftext|> |
<commit_before>/*
Copyright (c) 2006, 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.
*/
#ifndef ROUTING_TABLE_HPP
#define ROUTING_TABLE_HPP
#include <vector>
#include <deque>
#include <boost/cstdint.hpp>
#include <boost/date_time/posix_time/posix_time.hpp>
#include <boost/iterator/iterator_facade.hpp>
#include <boost/iterator/iterator_categories.hpp>
#include <boost/utility.hpp>
#include <boost/tuple/tuple.hpp>
#include <boost/array.hpp>
#include <libtorrent/kademlia/logging.hpp>
#include <libtorrent/kademlia/node_id.hpp>
#include <libtorrent/kademlia/node_entry.hpp>
#include <libtorrent/session_settings.hpp>
namespace pt = boost::posix_time;
namespace libtorrent { namespace dht
{
using asio::ip::udp;
//TORRENT_DECLARE_LOG(table);
typedef std::deque<node_entry> bucket_t;
// differences in the implementation from the description in
// the paper:
//
// * The routing table tree is not allocated dynamically, there
// are always 160 buckets.
// * Nodes are not marked as being stale, they keep a counter
// that tells how many times in a row they have failed. When
// a new node is to be inserted, the node that has failed
// the most times is replaced. If none of the nodes in the
// bucket has failed, then it is put in the replacement
// cache (just like in the paper).
class routing_table;
namespace aux
{
// Iterates over a flattened routing_table structure.
class routing_table_iterator
: public boost::iterator_facade<
routing_table_iterator
, node_entry const
, boost::forward_traversal_tag
>
{
public:
routing_table_iterator()
{
}
private:
friend class libtorrent::dht::routing_table;
friend class boost::iterator_core_access;
typedef boost::array<std::pair<bucket_t, bucket_t>, 160>::const_iterator
bucket_iterator_t;
routing_table_iterator(
bucket_iterator_t begin
, bucket_iterator_t end)
: m_bucket_iterator(begin)
, m_bucket_end(end)
, m_iterator(begin != end ? begin->first.begin() : bucket_t::iterator())
{
if (m_bucket_iterator == m_bucket_end) return;
while (m_iterator == m_bucket_iterator->first.end())
{
if (++m_bucket_iterator == m_bucket_end)
break;
m_iterator = m_bucket_iterator->first.begin();
}
}
bool equal(routing_table_iterator const& other) const
{
return m_bucket_iterator == other.m_bucket_iterator
&& (m_iterator == other.m_iterator
|| m_bucket_iterator == m_bucket_end);
}
void increment()
{
assert(m_bucket_iterator != m_bucket_end);
++m_iterator;
while (m_iterator == m_bucket_iterator->first.end())
{
if (++m_bucket_iterator == m_bucket_end)
break;
m_iterator = m_bucket_iterator->first.begin();
}
}
node_entry const& dereference() const
{
assert(m_bucket_iterator != m_bucket_end);
return *m_iterator;
}
bucket_iterator_t m_bucket_iterator;
bucket_iterator_t m_bucket_end;
bucket_t::const_iterator m_iterator;
};
} // namespace aux
class routing_table
{
public:
typedef aux::routing_table_iterator iterator;
typedef iterator const_iterator;
routing_table(node_id const& id, int bucket_size
, dht_settings const& settings);
void node_failed(node_id const& id);
// this function is called every time the node sees
// a sign of a node being alive. This node will either
// be inserted in the k-buckets or be moved to the top
// of its bucket.
bool node_seen(node_id const& id, udp::endpoint addr);
// returns time when the given bucket needs another refresh.
// if the given bucket is empty but there are nodes
// in a bucket closer to us, or if the bucket is non-empty and
// the time from the last activity is more than 15 minutes
boost::posix_time::ptime next_refresh(int bucket);
// fills the vector with the count nodes from our buckets that
// are nearest to the given id.
void find_node(node_id const& id, std::vector<node_entry>& l
, bool include_self, int count = 0);
// returns true if the given node would be placed in a bucket
// that is not full. If the node already exists in the table
// this function returns false
bool need_node(node_id const& id);
// this will set the given bucket's latest activity
// to the current time
void touch_bucket(int bucket);
int bucket_size(int bucket)
{
assert(bucket >= 0 && bucket < 160);
return (int)m_buckets[bucket].first.size();
}
int bucket_size() const { return m_bucket_size; }
iterator begin() const;
iterator end() const;
boost::tuple<int, int> size() const;
// returns true if there are no working nodes
// in the routing table
bool need_bootstrap() const;
void replacement_cache(bucket_t& nodes) const;
// used for debug and monitoring purposes. This will print out
// the state of the routing table to the given stream
void print_state(std::ostream& os) const;
private:
// constant called k in paper
int m_bucket_size;
dht_settings const& m_settings;
// 160 (k-bucket, replacement cache) pairs
typedef boost::array<std::pair<bucket_t, bucket_t>, 160> table_t;
table_t m_buckets;
// timestamps of the last activity in each bucket
boost::array<boost::posix_time::ptime, 160> m_bucket_activity;
node_id m_id; // our own node id
// this is the lowest bucket index with nodes in it
int m_lowest_active_bucket;
};
} } // namespace libtorrent::dht
#endif // ROUTING_TABLE_HPP
<commit_msg>fixed comparison of invalid iterators<commit_after>/*
Copyright (c) 2006, 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.
*/
#ifndef ROUTING_TABLE_HPP
#define ROUTING_TABLE_HPP
#include <vector>
#include <deque>
#include <boost/cstdint.hpp>
#include <boost/date_time/posix_time/posix_time.hpp>
#include <boost/iterator/iterator_facade.hpp>
#include <boost/iterator/iterator_categories.hpp>
#include <boost/utility.hpp>
#include <boost/tuple/tuple.hpp>
#include <boost/array.hpp>
#include <libtorrent/kademlia/logging.hpp>
#include <libtorrent/kademlia/node_id.hpp>
#include <libtorrent/kademlia/node_entry.hpp>
#include <libtorrent/session_settings.hpp>
namespace pt = boost::posix_time;
namespace libtorrent { namespace dht
{
using asio::ip::udp;
//TORRENT_DECLARE_LOG(table);
typedef std::deque<node_entry> bucket_t;
// differences in the implementation from the description in
// the paper:
//
// * The routing table tree is not allocated dynamically, there
// are always 160 buckets.
// * Nodes are not marked as being stale, they keep a counter
// that tells how many times in a row they have failed. When
// a new node is to be inserted, the node that has failed
// the most times is replaced. If none of the nodes in the
// bucket has failed, then it is put in the replacement
// cache (just like in the paper).
class routing_table;
namespace aux
{
// Iterates over a flattened routing_table structure.
class routing_table_iterator
: public boost::iterator_facade<
routing_table_iterator
, node_entry const
, boost::forward_traversal_tag
>
{
public:
routing_table_iterator()
{
}
private:
friend class libtorrent::dht::routing_table;
friend class boost::iterator_core_access;
typedef boost::array<std::pair<bucket_t, bucket_t>, 160>::const_iterator
bucket_iterator_t;
routing_table_iterator(
bucket_iterator_t begin
, bucket_iterator_t end)
: m_bucket_iterator(begin)
, m_bucket_end(end)
, m_iterator(begin != end ? begin->first.begin() : bucket_t::iterator())
{
if (m_bucket_iterator == m_bucket_end) return;
while (m_iterator == m_bucket_iterator->first.end())
{
if (++m_bucket_iterator == m_bucket_end)
break;
m_iterator = m_bucket_iterator->first.begin();
}
}
bool equal(routing_table_iterator const& other) const
{
return m_bucket_iterator == other.m_bucket_iterator
&& (m_bucket_iterator == m_bucket_end
|| m_iterator == other.m_iterator);
}
void increment()
{
assert(m_bucket_iterator != m_bucket_end);
++m_iterator;
while (m_iterator == m_bucket_iterator->first.end())
{
if (++m_bucket_iterator == m_bucket_end)
break;
m_iterator = m_bucket_iterator->first.begin();
}
}
node_entry const& dereference() const
{
assert(m_bucket_iterator != m_bucket_end);
return *m_iterator;
}
bucket_iterator_t m_bucket_iterator;
bucket_iterator_t m_bucket_end;
bucket_t::const_iterator m_iterator;
};
} // namespace aux
class routing_table
{
public:
typedef aux::routing_table_iterator iterator;
typedef iterator const_iterator;
routing_table(node_id const& id, int bucket_size
, dht_settings const& settings);
void node_failed(node_id const& id);
// this function is called every time the node sees
// a sign of a node being alive. This node will either
// be inserted in the k-buckets or be moved to the top
// of its bucket.
bool node_seen(node_id const& id, udp::endpoint addr);
// returns time when the given bucket needs another refresh.
// if the given bucket is empty but there are nodes
// in a bucket closer to us, or if the bucket is non-empty and
// the time from the last activity is more than 15 minutes
boost::posix_time::ptime next_refresh(int bucket);
// fills the vector with the count nodes from our buckets that
// are nearest to the given id.
void find_node(node_id const& id, std::vector<node_entry>& l
, bool include_self, int count = 0);
// returns true if the given node would be placed in a bucket
// that is not full. If the node already exists in the table
// this function returns false
bool need_node(node_id const& id);
// this will set the given bucket's latest activity
// to the current time
void touch_bucket(int bucket);
int bucket_size(int bucket)
{
assert(bucket >= 0 && bucket < 160);
return (int)m_buckets[bucket].first.size();
}
int bucket_size() const { return m_bucket_size; }
iterator begin() const;
iterator end() const;
boost::tuple<int, int> size() const;
// returns true if there are no working nodes
// in the routing table
bool need_bootstrap() const;
void replacement_cache(bucket_t& nodes) const;
// used for debug and monitoring purposes. This will print out
// the state of the routing table to the given stream
void print_state(std::ostream& os) const;
private:
// constant called k in paper
int m_bucket_size;
dht_settings const& m_settings;
// 160 (k-bucket, replacement cache) pairs
typedef boost::array<std::pair<bucket_t, bucket_t>, 160> table_t;
table_t m_buckets;
// timestamps of the last activity in each bucket
boost::array<boost::posix_time::ptime, 160> m_bucket_activity;
node_id m_id; // our own node id
// this is the lowest bucket index with nodes in it
int m_lowest_active_bucket;
};
} } // namespace libtorrent::dht
#endif // ROUTING_TABLE_HPP
<|endoftext|> |
<commit_before>/*
Copyright 2011 Brain Research Institute, Melbourne, Australia
Written by Robert E. Smith, 2013.
This file is part of MRtrix.
MRtrix 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.
MRtrix 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 MRtrix. If not, see <http://www.gnu.org/licenses/>.
*/
#include "command.h"
#include "ptr.h"
#include "image/buffer.h"
#include "image/info.h"
#include "image/loop.h"
#include "image/nav.h"
#include "image/position.h"
#include "image/voxel.h"
#include "dwi/tractography/ACT/act.h"
using namespace MR;
using namespace App;
void usage ()
{
AUTHOR = "Robert E. Smith (r.smith@brain.org.au)";
DESCRIPTION
+ "manually set the partial volume fractions in an ACT five-tissue-type (5TT) image using mask images";
ARGUMENTS
+ Argument ("input", "the 5TT image to be modified").type_image_in()
+ Argument ("output", "the output modified 5TT image").type_image_out();
OPTIONS
+ Option ("cgm", "provide a mask of voxels that should be set to cortical grey matter")
+ Argument ("image").type_image_in()
+ Option ("sgm", "provide a mask of voxels that should be set to sub-cortical grey matter")
+ Argument ("image").type_image_in()
+ Option ("wm", "provide a mask of voxels that should be set to white matter")
+ Argument ("image").type_image_in()
+ Option ("csf", "provide a mask of voxels that should be set to CSF")
+ Argument ("image").type_image_in()
+ Option ("path", "provide a mask of voxels that should be set to pathological tissue")
+ Argument ("image").type_image_in()
+ Option ("none", "provide a mask of voxels that should be cleared (i.e. are non-brain); note that this will supersede all other provided masks")
+ Argument ("image").type_image_in();
};
class Modifier
{
public:
Modifier (Image::Buffer<float>& input_image, Image::Buffer<float>& output_image) :
v_in (input_image),
v_out (output_image) { }
Modifier (const Modifier& that) :
v_in (that.v_in),
v_out (that.v_out),
buffers (that.buffers)
{
for (size_t index = 0; index != 6; ++index) {
if (buffers[index])
voxels[index] = new Image::Buffer<bool>::voxel_type (*buffers[index]);
}
}
void set_cgm_mask (const std::string& path) { load (path, 0); }
void set_sgm_mask (const std::string& path) { load (path, 1); }
void set_wm_mask (const std::string& path) { load (path, 2); }
void set_csf_mask (const std::string& path) { load (path, 3); }
void set_path_mask (const std::string& path) { load (path, 4); }
void set_none_mask (const std::string& path) { load (path, 5); }
bool operator() (const Image::Iterator& pos)
{
Image::Nav::set_pos (v_out, pos, 0, 3);
bool voxel_nulled = false;
if (buffers[5]) {
Image::Nav::set_pos (*voxels[5], pos, 0, 3);
if (voxels[5]->value()) {
for (v_out[3] = 0; v_out[3] != 5; ++v_out[3])
v_out.value() = 0.0;
voxel_nulled = true;
}
}
if (!voxel_nulled) {
unsigned int count = 0;
memset (values, 0x00, 5 * sizeof (float));
for (size_t tissue = 0; tissue != 5; ++tissue) {
if (buffers[tissue]) {
Image::Nav::set_pos (*voxels[tissue], pos, 0, 3);
if (voxels[tissue]->value()) {
++count;
values[tissue] = 1.0;
}
}
}
if (count) {
if (count > 1) {
const float multiplier = 1.0 / float(count);
for (size_t tissue = 0; tissue != 5; ++tissue)
values[tissue] *= multiplier;
}
for (v_out[3] = 0; v_out[3] != 5; ++v_out[3])
v_out.value() = values[v_out[3]];
} else {
Image::Nav::set_pos (v_in, pos, 0, 3);
for (v_in[3] = v_out[3] = 0; v_out[3] != 5; ++v_in[3], ++v_out[3])
v_out.value() = v_in.value();
}
}
return true;
}
private:
Image::Buffer<float>::voxel_type v_in, v_out;
RefPtr< Image::Buffer<bool> > buffers[6];
Ptr< Image::Buffer<bool>::voxel_type > voxels[6];
float values[5];
void load (const std::string& path, const size_t index)
{
assert (index <= 5);
buffers[index] = new Image::Buffer<bool> (path);
if (!Image::dimensions_match (v_in, *buffers[index], 0, 3))
throw Exception ("Image " + str(path) + " does not match 5TT image dimensions");
voxels[index] = new Image::Buffer<bool>::voxel_type (*buffers[index]);
}
};
void run ()
{
Image::Header H (argument[0]);
DWI::Tractography::ACT::verify_5TT_image (H);
Image::Buffer<float> in (H);
Image::Buffer<float> out (argument[1], H);
Modifier modifier (in, out);
Options
opt = get_options ("cgm"); if (opt.size()) modifier.set_cgm_mask (opt[0][0]);
opt = get_options ("sgm"); if (opt.size()) modifier.set_sgm_mask (opt[0][0]);
opt = get_options ("wm"); if (opt.size()) modifier.set_wm_mask (opt[0][0]);
opt = get_options ("csf"); if (opt.size()) modifier.set_csf_mask (opt[0][0]);
opt = get_options ("path"); if (opt.size()) modifier.set_path_mask (opt[0][0]);
opt = get_options ("none"); if (opt.size()) modifier.set_none_mask (opt[0][0]);
Image::ThreadedLoop loop ("Modifying ACT 5TT image... ", H, 2, 0, 3);
loop.run (modifier);
}
<commit_msg>5ttedit: Fix compilation on clang<commit_after>/*
Copyright 2011 Brain Research Institute, Melbourne, Australia
Written by Robert E. Smith, 2013.
This file is part of MRtrix.
MRtrix 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.
MRtrix 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 MRtrix. If not, see <http://www.gnu.org/licenses/>.
*/
#include "command.h"
#include "ptr.h"
#include "image/buffer.h"
#include "image/info.h"
#include "image/loop.h"
#include "image/nav.h"
#include "image/position.h"
#include "image/voxel.h"
#include "dwi/tractography/ACT/act.h"
using namespace MR;
using namespace App;
void usage ()
{
AUTHOR = "Robert E. Smith (r.smith@brain.org.au)";
DESCRIPTION
+ "manually set the partial volume fractions in an ACT five-tissue-type (5TT) image using mask images";
ARGUMENTS
+ Argument ("input", "the 5TT image to be modified").type_image_in()
+ Argument ("output", "the output modified 5TT image").type_image_out();
OPTIONS
+ Option ("cgm", "provide a mask of voxels that should be set to cortical grey matter")
+ Argument ("image").type_image_in()
+ Option ("sgm", "provide a mask of voxels that should be set to sub-cortical grey matter")
+ Argument ("image").type_image_in()
+ Option ("wm", "provide a mask of voxels that should be set to white matter")
+ Argument ("image").type_image_in()
+ Option ("csf", "provide a mask of voxels that should be set to CSF")
+ Argument ("image").type_image_in()
+ Option ("path", "provide a mask of voxels that should be set to pathological tissue")
+ Argument ("image").type_image_in()
+ Option ("none", "provide a mask of voxels that should be cleared (i.e. are non-brain); note that this will supersede all other provided masks")
+ Argument ("image").type_image_in();
};
class Modifier
{
public:
Modifier (Image::Buffer<float>& input_image, Image::Buffer<float>& output_image) :
v_in (input_image),
v_out (output_image) { }
Modifier (const Modifier& that) :
v_in (that.v_in),
v_out (that.v_out)
{
for (size_t index = 0; index != 6; ++index) {
if (that.buffers[index]) {
buffers[index] = that.buffers[index];
voxels [index] = new Image::Buffer<bool>::voxel_type (*buffers[index]);
}
}
}
void set_cgm_mask (const std::string& path) { load (path, 0); }
void set_sgm_mask (const std::string& path) { load (path, 1); }
void set_wm_mask (const std::string& path) { load (path, 2); }
void set_csf_mask (const std::string& path) { load (path, 3); }
void set_path_mask (const std::string& path) { load (path, 4); }
void set_none_mask (const std::string& path) { load (path, 5); }
bool operator() (const Image::Iterator& pos)
{
Image::Nav::set_pos (v_out, pos, 0, 3);
bool voxel_nulled = false;
if (buffers[5]) {
Image::Nav::set_pos (*voxels[5], pos, 0, 3);
if (voxels[5]->value()) {
for (v_out[3] = 0; v_out[3] != 5; ++v_out[3])
v_out.value() = 0.0;
voxel_nulled = true;
}
}
if (!voxel_nulled) {
unsigned int count = 0;
memset (values, 0x00, 5 * sizeof (float));
for (size_t tissue = 0; tissue != 5; ++tissue) {
if (buffers[tissue]) {
Image::Nav::set_pos (*voxels[tissue], pos, 0, 3);
if (voxels[tissue]->value()) {
++count;
values[tissue] = 1.0;
}
}
}
if (count) {
if (count > 1) {
const float multiplier = 1.0 / float(count);
for (size_t tissue = 0; tissue != 5; ++tissue)
values[tissue] *= multiplier;
}
for (v_out[3] = 0; v_out[3] != 5; ++v_out[3])
v_out.value() = values[v_out[3]];
} else {
Image::Nav::set_pos (v_in, pos, 0, 3);
for (v_in[3] = v_out[3] = 0; v_out[3] != 5; ++v_in[3], ++v_out[3])
v_out.value() = v_in.value();
}
}
return true;
}
private:
Image::Buffer<float>::voxel_type v_in, v_out;
RefPtr< Image::Buffer<bool> > buffers[6];
Ptr< Image::Buffer<bool>::voxel_type > voxels[6];
float values[5];
void load (const std::string& path, const size_t index)
{
assert (index <= 5);
buffers[index] = new Image::Buffer<bool> (path);
if (!Image::dimensions_match (v_in, *buffers[index], 0, 3))
throw Exception ("Image " + str(path) + " does not match 5TT image dimensions");
voxels[index] = new Image::Buffer<bool>::voxel_type (*buffers[index]);
}
};
void run ()
{
Image::Header H (argument[0]);
DWI::Tractography::ACT::verify_5TT_image (H);
Image::Buffer<float> in (H);
Image::Buffer<float> out (argument[1], H);
Modifier modifier (in, out);
Options
opt = get_options ("cgm"); if (opt.size()) modifier.set_cgm_mask (opt[0][0]);
opt = get_options ("sgm"); if (opt.size()) modifier.set_sgm_mask (opt[0][0]);
opt = get_options ("wm"); if (opt.size()) modifier.set_wm_mask (opt[0][0]);
opt = get_options ("csf"); if (opt.size()) modifier.set_csf_mask (opt[0][0]);
opt = get_options ("path"); if (opt.size()) modifier.set_path_mask (opt[0][0]);
opt = get_options ("none"); if (opt.size()) modifier.set_none_mask (opt[0][0]);
Image::ThreadedLoop loop ("Modifying ACT 5TT image... ", H, 2, 0, 3);
loop.run (modifier);
}
<|endoftext|> |
<commit_before>#pragma once
#include<algorithm>
#include<vector>
#include<universal/blas/operators.hpp>
#include<universal/blas/solvers.hpp>
#include<universal/blas/generators.hpp>
#include<universal/include/universal/blas/blas_l1.hpp>
const double EPS = 1E-9;
const double k = 0.0000001;
namespace sw {
namespace universal {
namespace blas {
template<typename Scalar>
size_t find_rank(const matrix<Scalar>& A) {
size_t n = num_rows(A);
size_t m = num_cols(A);
size_t rank = 0;
vector<bool> row(n, false);
for (size_t i = 0; i < m; ++i) {
for (size_t j = 0; j < n; ++j) {
if (abs(A[j][i]) > EPS && row[j]!=Scalar(0)) break;
}
if (j != n) {
++rank;
row[j] = true;
for (size_t p = i + 1; p < m; ++p) A[j][p] /= A[j][i];
for (size_t k = 0; k < n; ++k) {
if (abs(A[k][i]) > EPS && k != j) {
for (size_t p = i + 1; p < m; ++p)
A[k][p] -= A[j][p] * A[k][i];
}
}
}
}
return rank;
}
template<typename Scalar>
inline void qr(const matrix<Scalar>& A, matrix<Scalar>& Q, matrix<Scalar>& R) {
using value_type = typename matrix::value_type;
using size_type = typename matrix::size_type;
using Magnitude<value_type>::type = typename matrix::magnitude_type;
size_type ncols = num_cols(A), nrows = num_rows(A);
mini = ncols == nrows ? ncols - 1 : (nrows >= ncols ? ncols : nrows);
//magnitude_type factor = magnitude_type(2);
static_assert(nrows<ncols,"Required Columns <= Rows");
matrix<Scalar> A_tmp(A),tmp;
vector<matrix<Scalar>> qi(nrows);
for(size_t i=0;i<ncols && i<nrows-1; ++i){
vector<Scalar> e(nrows),x(nrows);
Scalar a;
tmp=minor(A_tmp, i);
get_col(tmp, x, i);
a=norm(x, "two_norm");
if(A[nrows][nrows]>0) a-=a;
for(size_t j=0; j<e.size();++j){
e[j]=(j==nrows) ? 1:0;
}
for(size_t j=0;j<e.size();++j) e[j]=x[j]+a*e[j];
Scalar f=norm(e);
for(size_t j=0;j<e.size();++j) e[j]/=f;
householder_factors(qi[i], e);
A_tmp=qi[i]*tmp;
}
Q=qi[0];
for(size_t i=1;i<ncols && i<nrows-1;++i){
tmp=qi[i]*Q;
Q=tmp;
}
R=Q*A;
Q.transpose();
}//completed QR-decomposition
template<typename Scalar>
std::pair<matrix<Scalar>, matrix<Scalar>>
inline qr(const matrix<Scalar>& A) {
//R is the upper triangular matrix
//Q is the orthogonal matrix
matrix<Scalar> Q(num_rows(A), num_cols(A)), R(A);
qr(A, Q, R);
return std::make_pair(Q, R);
}
template<Scalar, Vector>
void householder_factors(matrix<Scalar>& A, const Vector& v){
Scalar n=num_cols(A);
for(size_t i=0;i<n;++i){
for(size_t j=0;j<n;++j){
A[i][j]=-2*v[i]*v[j];
}
}
for(size_t i=0;i<n;++i) A[i][i]+=1;
}
template<typename Scalar, typename Tolerance>
inline void svd(const matrix<Scalar>& A, matrix<Scalar>& S, matrix<Scalar>& V, matrix<Scalar>& D, Tolerance tol = 10e-10) {
using value_type = typename matrix::value_type;
using size_type = typename matrix::size_type;
size_type ncols = num_cols(A), nrows = num_rows(A);
value_type ref, zero = math::zero(ref), one = math::one(ref);
double err(std::numeric_limits<double>::max()), e, f;
if (nrows != ncols) std::swap(row, col);
matrix<Scalar> Q(nrows, nrows), R(nrows, ncols), VT(nrows, ncols), E(nrows, ncols),QT(ncols, ncols), RT(ncols, nrows);
size_type l = 100 * std::max(nrows, ncols);
S = one; D = one; E = zero;
for (size_type i = 0; err > tol && i < l; ++i) {
std::tie(QT, RT) = qr(V);
S *= QT;
VT = RT.transpose();
std::tie(Q, R) = qr(VT);
D *= Q;
E = triu(R, 1);
V = trans(R);
f=norm(diag(R), "two_norm");
e=norm(E);
if(f==zero) f=1;
err=e/f;
}
{
V= 0;
matrix<Scalar> ins_V(V), ins_S(S);
for (size_type i= 0, end= std::min(nrows, ncols); i < end; i++) {
ins_V[i][i] *= std::abs(R[i][i]);
if (R[i][i] < zero)
for (size_type j= 0; j < nrows; j++)
ins_S[j][i] *= -1;
}
}
}
template<typename Scalar, typename Tolerance>
std::tuple<matrix<Scalar>, matrix<Scalar>, matrix<Scalar>>
inline svd(const matrix<Scalar>& A, Tolerance tol= 10e-10) {
typedef typename Collection<Matrix>::size_type size_type;
size_type ncols = num_cols(A), nrows = num_rows(A);
if (nrows != ncols) std::swap(row, col);
matrix<Scalar> ST(ncols, ncols), V(A), D(nrows, nrows);
svd(A, ST, V, D, tol);
return std::make_tuple(ST, V, D);
}
template<typename Scalar>
std::tuple<matrix<Scalar>,matrix<Scalar>, matrix<Scalar>>
inline randsvd(const matrix<Scalar>& A) {
size_t k = min(num_cols(A), num_rows(A));
size_t n = num_cols(A), m = num_row(A);
matrix<Scalar> omega(n, k),Y(m, k), B(k, n);
gaussian_random(omega);
Y = A * omega;
tie(Q, R) = qr(Y);
Q.transpose();
B = Q * A;
std::tie(S, V, D) = svd(B,k);
return std::make_tuple(S, V, D);
}
}
}
}<commit_msg>Updates<commit_after>#pragma once
#include<algorithm>
#include<vector>
#include<universal/blas/operators.hpp>
#include<universal/blas/solvers.hpp>
#include<universal/blas/generators.hpp>
#include<universal/include/universal/blas/blas_l1.hpp>
const double EPS = 1E-9;
const double k = 0.0000001;
namespace sw {
namespace universal {
namespace blas {
template<typename Scalar>
size_t find_rank(const matrix<Scalar>& A) {
size_t n = num_rows(A);
size_t m = num_cols(A);
size_t rank = 0;
vector<bool> row(n, false);
for (size_t i = 0; i < m; ++i) {
for (size_t j = 0; j < n; ++j) {
if (abs(A[j][i]) > EPS && row[j]!=Scalar(0)) break;
}
if (j != n) {
++rank;
row[j] = true;
for (size_t p = i + 1; p < m; ++p) A[j][p] /= A[j][i];
for (size_t k = 0; k < n; ++k) {
if (abs(A[k][i]) > EPS && k != j) {
for (size_t p = i + 1; p < m; ++p)
A[k][p] -= A[j][p] * A[k][i];
}
}
}
}
return rank;
}
template<typename Scalar>
inline void qr(const matrix<Scalar>& A, matrix<Scalar>& Q, matrix<Scalar>& R) {
using value_type = typename matrix::value_type;
using size_type = typename matrix::size_type;
using Magnitude<value_type>::type = typename matrix::magnitude_type;
size_type ncols = num_cols(A), nrows = num_rows(A);
mini = ncols == nrows ? ncols - 1 : (nrows >= ncols ? ncols : nrows);
//magnitude_type factor = magnitude_type(2);
static_assert(nrows<ncols,"Required Columns <= Rows");
matrix<Scalar> A_tmp(A),tmp;
vector<matrix<Scalar>> qi(nrows);
for(size_t i=0;i<ncols && i<nrows-1; ++i){
vector<Scalar> e(nrows),x(nrows);
Scalar a;
tmp=minor(A_tmp, i);
get_col(tmp, x, i);
a=norm(x, "two_norm");
if(A[nrows][nrows]>0) a-=a;
for(size_t j=0; j<e.size();++j){
e[j]=(j==nrows) ? 1:0;
}
for(size_t j=0;j<e.size();++j) e[j]=x[j]+a*e[j];
Scalar f=norm(e);
for(size_t j=0;j<e.size();++j) e[j]/=f;
householder_factors(qi[i], e);
A_tmp=qi[i]*tmp;
}
Q=qi[0];
for(size_t i=1;i<ncols && i<nrows-1;++i){
tmp=qi[i]*Q;
Q=tmp;
}
R=Q*A;
Q.transpose();
}//completed QR-decomposition
template<typename Scalar>
std::pair<matrix<Scalar>, matrix<Scalar>>
inline qr(const matrix<Scalar>& A) {
//R is the upper triangular matrix
//Q is the orthogonal matrix
matrix<Scalar> Q(num_rows(A), num_cols(A)), R(A);
qr(A, Q, R);
return std::make_pair(Q, R);
}
template<Scalar, Vector>
void householder_factors(matrix<Scalar>& A, const Vector& v){
Scalar n=num_cols(A);
for(size_t i=0;i<n;++i){
for(size_t j=0;j<n;++j){
A[i][j]=-2*v[i]*v[j];
}
}
for(size_t i=0;i<n;++i) A[i][i]+=1;
}
template<typename Scalar, typename Tolerance>
inline void svd(const matrix<Scalar>& A, matrix<Scalar>& S, matrix<Scalar>& V, matrix<Scalar>& D, Tolerance tol = 10e-10) {
using value_type = typename matrix::value_type;
using size_type = typename matrix::size_type;
size_type ncols = num_cols(A), nrows = num_rows(A);
value_type ref, zero = math::zero(ref), one = math::one(ref);
double err(std::numeric_limits<double>::max()), f, e;
if (nrows != ncols) std::swap(row, col);
matrix<Scalar> Q(nrows, nrows), R(nrows, ncols), VT(nrows, ncols), E(nrows, ncols),QT(ncols, ncols), RT(ncols, nrows);
size_type l = 100 * std::max(nrows, ncols);
S= 1; D= 1; E;
for (size_type i = 0; err > tol && i < l; ++i) {
std::tie(QT, RT) = qr(V);
S *= QT;
VT = RT.transpose();
std::tie(Q, R) = qr(VT);
D *= Q;
E = triu(R, 1);
V = trans(R);
f=norm(diag(R), "two_norm");
e=norm(E);
if(f==0) f=1;
err=e/f;
}
{
V= 0;
matrix<Scalar> ins_V(V), ins_S(S);
for (size_type i= 0, end= std::min(nrows, ncols); i < end; ++i) {
ins_V[i][i] *= std::abs(R[i][i]);
if (R[i][i] < Scalar(0))
for (size_type j= 0; j < nrows; ++j)
ins_S[j][i] *= -1;
}
}
}
template<typename Scalar, typename Tolerance>
std::tuple<matrix<Scalar>, matrix<Scalar>, matrix<Scalar>>
inline svd(const matrix<Scalar>& A, Tolerance tol= 10e-10) {
typedef typename Collection<Matrix>::size_type size_type;
size_type ncols = num_cols(A), nrows = num_rows(A);
if (nrows != ncols) std::swap(row, col);
matrix<Scalar> ST(ncols, ncols), V(A), D(nrows, nrows);
svd(A, ST, V, D, tol);
return std::make_tuple (ST, V, D);
}
template<typename Scalar>
std::tuple<matrix<Scalar>,matrix<Scalar>, matrix<Scalar>>
inline randsvd(const matrix<Scalar>& A) {
size_t k = min(num_cols(A), num_rows(A));
size_t n = num_cols(A), m = num_row(A);
matrix<Scalar> omega(n, k),Y(m, k), B(k, n);
gaussian_random(omega);
Y = A * omega;
tie(Q, R) = qr(Y);
Q.transpose();
B = Q * A;
std::tie(S, V, D) = svd(B,k);
return std::make_tuple(S, V, D);
}
}
}
}<|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.
// Tests for Watchdog class.
#include "base/watchdog.h"
#include "base/logging.h"
#include "base/platform_thread.h"
#include "base/spin_wait.h"
#include "base/time.h"
#include "testing/gtest/include/gtest/gtest.h"
using base::TimeDelta;
using base::TimeTicks;
namespace {
//------------------------------------------------------------------------------
// Provide a derived class to facilitate testing.
class WatchdogCounter : public Watchdog {
public:
WatchdogCounter(const TimeDelta& duration,
const std::string& thread_watched_name,
bool enabled)
: Watchdog(duration, thread_watched_name, enabled), alarm_counter_(0) {
}
virtual ~WatchdogCounter() {}
virtual void Alarm() {
alarm_counter_++;
Watchdog::Alarm();
}
int alarm_counter() { return alarm_counter_; }
private:
int alarm_counter_;
DISALLOW_COPY_AND_ASSIGN(WatchdogCounter);
};
class WatchdogTest : public testing::Test {
public:
void SetUp() {
Watchdog::ResetStaticData();
}
};
//------------------------------------------------------------------------------
// Actual tests
// Minimal constructor/destructor test.
TEST_F(WatchdogTest, StartupShutdownTest) {
Watchdog watchdog1(TimeDelta::FromMilliseconds(300), "Disabled", false);
Watchdog watchdog2(TimeDelta::FromMilliseconds(300), "Enabled", true);
}
// Test ability to call Arm and Disarm repeatedly.
TEST_F(WatchdogTest, ArmDisarmTest) {
Watchdog watchdog1(TimeDelta::FromMilliseconds(300), "Disabled", false);
watchdog1.Arm();
watchdog1.Disarm();
watchdog1.Arm();
watchdog1.Disarm();
Watchdog watchdog2(TimeDelta::FromMilliseconds(300), "Enabled", true);
watchdog2.Arm();
watchdog2.Disarm();
watchdog2.Arm();
watchdog2.Disarm();
}
// Make sure a basic alarm fires when the time has expired.
TEST_F(WatchdogTest, AlarmTest) {
WatchdogCounter watchdog(TimeDelta::FromMilliseconds(10), "Enabled", true);
watchdog.Arm();
SPIN_FOR_TIMEDELTA_OR_UNTIL_TRUE(TimeDelta::FromMinutes(5),
watchdog.alarm_counter() > 0);
EXPECT_EQ(1, watchdog.alarm_counter());
}
// Make sure a basic alarm fires when the time has expired.
TEST_F(WatchdogTest, AlarmPriorTimeTest) {
WatchdogCounter watchdog(TimeDelta::TimeDelta(), "Enabled2", true);
// Set a time in the past.
watchdog.ArmSomeTimeDeltaAgo(TimeDelta::FromSeconds(2));
// It should instantly go off, but certainly in less than 5 minutes.
SPIN_FOR_TIMEDELTA_OR_UNTIL_TRUE(TimeDelta::FromMinutes(5),
watchdog.alarm_counter() > 0);
EXPECT_EQ(1, watchdog.alarm_counter());
}
// Make sure a disable alarm does nothing, even if we arm it.
TEST_F(WatchdogTest, ConstructorDisabledTest) {
WatchdogCounter watchdog(TimeDelta::FromMilliseconds(10), "Disabled", false);
watchdog.Arm();
// Alarm should not fire, as it was disabled.
PlatformThread::Sleep(500);
EXPECT_EQ(0, watchdog.alarm_counter());
}
// Make sure Disarming will prevent firing, even after Arming.
TEST_F(WatchdogTest, DisarmTest) {
WatchdogCounter watchdog(TimeDelta::FromSeconds(1), "Enabled3", true);
TimeTicks start = TimeTicks::Now();
watchdog.Arm();
PlatformThread::Sleep(100); // Sleep a bit, but not past the alarm point.
watchdog.Disarm();
TimeTicks end = TimeTicks::Now();
if (end - start > TimeDelta::FromMilliseconds(500)) {
LOG(WARNING) << "100ms sleep took over 500ms, making the results of this "
<< "timing-sensitive test suspicious. Aborting now.";
return;
}
// Alarm should not have fired before it was disarmed.
EXPECT_EQ(0, watchdog.alarm_counter());
// Sleep past the point where it would have fired if it wasn't disarmed,
// and verify that it didn't fire.
PlatformThread::Sleep(1000);
EXPECT_EQ(0, watchdog.alarm_counter());
// ...but even after disarming, we can still use the alarm...
// Set a time greater than the timeout into the past.
watchdog.ArmSomeTimeDeltaAgo(TimeDelta::FromSeconds(10));
// It should almost instantly go off, but certainly in less than 5 minutes.
SPIN_FOR_TIMEDELTA_OR_UNTIL_TRUE(TimeDelta::FromMinutes(5),
watchdog.alarm_counter() > 0);
EXPECT_EQ(1, watchdog.alarm_counter());
}
} // namespace
<commit_msg>[Linux] Fix base_unittests for GCC 4.5.1<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.
// Tests for Watchdog class.
#include "base/watchdog.h"
#include "base/logging.h"
#include "base/platform_thread.h"
#include "base/spin_wait.h"
#include "base/time.h"
#include "testing/gtest/include/gtest/gtest.h"
using base::TimeDelta;
using base::TimeTicks;
namespace {
//------------------------------------------------------------------------------
// Provide a derived class to facilitate testing.
class WatchdogCounter : public Watchdog {
public:
WatchdogCounter(const TimeDelta& duration,
const std::string& thread_watched_name,
bool enabled)
: Watchdog(duration, thread_watched_name, enabled), alarm_counter_(0) {
}
virtual ~WatchdogCounter() {}
virtual void Alarm() {
alarm_counter_++;
Watchdog::Alarm();
}
int alarm_counter() { return alarm_counter_; }
private:
int alarm_counter_;
DISALLOW_COPY_AND_ASSIGN(WatchdogCounter);
};
class WatchdogTest : public testing::Test {
public:
void SetUp() {
Watchdog::ResetStaticData();
}
};
//------------------------------------------------------------------------------
// Actual tests
// Minimal constructor/destructor test.
TEST_F(WatchdogTest, StartupShutdownTest) {
Watchdog watchdog1(TimeDelta::FromMilliseconds(300), "Disabled", false);
Watchdog watchdog2(TimeDelta::FromMilliseconds(300), "Enabled", true);
}
// Test ability to call Arm and Disarm repeatedly.
TEST_F(WatchdogTest, ArmDisarmTest) {
Watchdog watchdog1(TimeDelta::FromMilliseconds(300), "Disabled", false);
watchdog1.Arm();
watchdog1.Disarm();
watchdog1.Arm();
watchdog1.Disarm();
Watchdog watchdog2(TimeDelta::FromMilliseconds(300), "Enabled", true);
watchdog2.Arm();
watchdog2.Disarm();
watchdog2.Arm();
watchdog2.Disarm();
}
// Make sure a basic alarm fires when the time has expired.
TEST_F(WatchdogTest, AlarmTest) {
WatchdogCounter watchdog(TimeDelta::FromMilliseconds(10), "Enabled", true);
watchdog.Arm();
SPIN_FOR_TIMEDELTA_OR_UNTIL_TRUE(TimeDelta::FromMinutes(5),
watchdog.alarm_counter() > 0);
EXPECT_EQ(1, watchdog.alarm_counter());
}
// Make sure a basic alarm fires when the time has expired.
TEST_F(WatchdogTest, AlarmPriorTimeTest) {
WatchdogCounter watchdog(TimeDelta(), "Enabled2", true);
// Set a time in the past.
watchdog.ArmSomeTimeDeltaAgo(TimeDelta::FromSeconds(2));
// It should instantly go off, but certainly in less than 5 minutes.
SPIN_FOR_TIMEDELTA_OR_UNTIL_TRUE(TimeDelta::FromMinutes(5),
watchdog.alarm_counter() > 0);
EXPECT_EQ(1, watchdog.alarm_counter());
}
// Make sure a disable alarm does nothing, even if we arm it.
TEST_F(WatchdogTest, ConstructorDisabledTest) {
WatchdogCounter watchdog(TimeDelta::FromMilliseconds(10), "Disabled", false);
watchdog.Arm();
// Alarm should not fire, as it was disabled.
PlatformThread::Sleep(500);
EXPECT_EQ(0, watchdog.alarm_counter());
}
// Make sure Disarming will prevent firing, even after Arming.
TEST_F(WatchdogTest, DisarmTest) {
WatchdogCounter watchdog(TimeDelta::FromSeconds(1), "Enabled3", true);
TimeTicks start = TimeTicks::Now();
watchdog.Arm();
PlatformThread::Sleep(100); // Sleep a bit, but not past the alarm point.
watchdog.Disarm();
TimeTicks end = TimeTicks::Now();
if (end - start > TimeDelta::FromMilliseconds(500)) {
LOG(WARNING) << "100ms sleep took over 500ms, making the results of this "
<< "timing-sensitive test suspicious. Aborting now.";
return;
}
// Alarm should not have fired before it was disarmed.
EXPECT_EQ(0, watchdog.alarm_counter());
// Sleep past the point where it would have fired if it wasn't disarmed,
// and verify that it didn't fire.
PlatformThread::Sleep(1000);
EXPECT_EQ(0, watchdog.alarm_counter());
// ...but even after disarming, we can still use the alarm...
// Set a time greater than the timeout into the past.
watchdog.ArmSomeTimeDeltaAgo(TimeDelta::FromSeconds(10));
// It should almost instantly go off, but certainly in less than 5 minutes.
SPIN_FOR_TIMEDELTA_OR_UNTIL_TRUE(TimeDelta::FromMinutes(5),
watchdog.alarm_counter() > 0);
EXPECT_EQ(1, watchdog.alarm_counter());
}
} // namespace
<|endoftext|> |
<commit_before>/**
* IFT339 - TP3
* Recherche d’information bi-demensionnelle
*
* Membres de l'équipe :
* - Félix Hamel
* - Nabil Diab
*
* Universite de Sherbrooke, automne 2014
*/
#include "graphe.h"
uint8_t architectureMachine = 2;
#include <chrono>
#include <ctime>
#include <cmath>
#include <thread>
#include <set>
#include <vector>
graphe::graphe(const string& cheminVersFichier)
{
DATA.open(cheminVersFichier.c_str(), ios::in|ios::binary);
if(!DATA.is_open()) {
cout << "Erreur d'ouverture du fichier, celui-ci n'existe pas." << endl;
exit(1);
}
DATA >> nom >> nbNOEUDS >> architecture;
DATA.ignore(1);
DEBUT = DATA.tellg();
// Determiner l'architecture de la machine courante
short int word = 0x0001;
char *byte = (char *) &word;
architectureMachine = (byte[0] ? ___LITTLE_ENDIAN : ___BIG_ENDIAN);
}
graphe::~graphe()
{
// Fermer le fichier à la sortie du programme.
if (DATA.is_open()) {
DATA.close();
}
}
void graphe::lire_noeud(uint32_t noeud)
{
if(noeud < nbNOEUDS) {
// Si le noeud n'a jamais ete lu, alors il va l'être !
if(lesNoeuds[noeud].partieVariable == 0) {
// Lecture des donn.es statiques du noeud
DATA.seekg(DEBUT + (28 * noeud), ios::beg);
this->lire(lesNoeuds[noeud].partieVariable);
this->lire(lesNoeuds[noeud].latitude);
this->lire(lesNoeuds[noeud].longitude);
for(int i = 0; i < 4; ++i) {
this->lire(lesNoeuds[noeud].zone[i]);
}
// Lecture des donnees variable du noeud
DATA.seekg(lesNoeuds[noeud].partieVariable);
this->lire(lesNoeuds[noeud].nbArcs);
for(int i = 0; i < lesNoeuds[noeud].nbArcs; ++i) {
uint32_t numero;
this->lire(numero);
this->lire(lesNoeuds[noeud].liens[numero]);
}
// Lecture du nom du noeud
uint16_t nombreDeCaracteres;
this->lire(nombreDeCaracteres);
char* nom = new char[nombreDeCaracteres];
DATA.read(nom, nombreDeCaracteres);
lesNoeuds[noeud].nom = ((string)nom).substr(0, nombreDeCaracteres-1); // Pour enlever des espaces s'il y en a
delete[] nom;
}
}
}
void graphe::lire(uint16_t& noeud)
{
DATA.read(reinterpret_cast<char*>(&noeud), 2);
// Si l'architecture diffère du fichier, on swap les bits.
if(architecture != architectureMachine) {
// http://stackoverflow.com/a/2182184
noeud = (noeud >> 8) | (noeud << 8);
}
}
void graphe::lire(uint32_t& noeud)
{
DATA.read(reinterpret_cast<char*>(&noeud), 4);
// Si l'architecture diffère du fichier, on swap les bits.
if(architecture != architectureMachine) {
// http://stackoverflow.com/a/13001420
noeud = (noeud >> 24) | ((noeud << 8) & 0x00FF0000) | ((noeud >> 8) & 0x0000FF00) | (noeud << 24);
}
}
void graphe::lire(float& a)
{
DATA.read(reinterpret_cast<char*>(&a), 4);
// Si l'architecture diffère du fichier, on swap les bits.
if(architecture != architectureMachine) {
char *floatToConvert = ( char* ) & a;
// http://stackoverflow.com/a/2782742
swap(floatToConvert[0], floatToConvert[3]);
swap(floatToConvert[1], floatToConvert[2]);
}
}
const uint32_t graphe::size() const
{
return this->nbNOEUDS;
}
void graphe::afficher_noeud(const uint32_t noeud)
{
this->lire_noeud(noeud);
auto leNoeud = lesNoeuds[noeud];
cout << "+--------------------------------------------------------------------+" << endl;
cout << " Noeud #" << noeud << endl;
cout << " - Latitude: " << leNoeud.latitude << endl;
cout << " - Longitude: " << leNoeud.longitude << endl;
cout << " - Nom: " << leNoeud.nom << endl;
for(int i = 0; i < 4; ++i) {
this->lire_noeud(leNoeud.zone[i]);
cout << " -> Zone[" << i << "]: " << leNoeud.zone[i] << " - nom = " << lesNoeuds[leNoeud.zone[i]].nom << endl;
}
cout << " - Nombre d'arcs: " << leNoeud.nbArcs << endl;
for(map<uint32_t, float>::iterator it = leNoeud.liens.begin(); it != leNoeud.liens.end(); ++it) {
cout << " -> Arc vers le noeud " << it->first << " avec un poids de " << it->second << endl;
}
cout << "+--------------------------------------------------------------------+" << endl;
}
uint32_t graphe::localiser(float& latitude, float& longitude)
{
// Distance entre chaque noeud et le point donne par la latitude et la longitude.
pair<float, uint32_t> distance_point_noeud = make_pair(std::numeric_limits<float>::infinity(), -1);
// Essayer de trouver le noeud le plus proche en debutant par le noeud 0
uint32_t debut = 0;
this->trouver_noeud_le_plus_proche(debut, distance_point_noeud, latitude, longitude);
// Retourner le noeud le plus proche
return distance_point_noeud.second;
}
void graphe::trouver_noeud_le_plus_proche(uint32_t& numero_noeud, pair<float, uint32_t>& distance_point_noeud, float& latitude, float& longitude)
{
// Aller chercher les informations du noeud dans le graphe
this->lire_noeud(numero_noeud);
noeud* noeud = &lesNoeuds[numero_noeud];
// Calculer la distance entre le noeud et le point
float distance = this->distance(numero_noeud, latitude, longitude);
// On conserve uniquement l'information qui peut nous être utile
if(distance <= distance_point_noeud.first) {
distance_point_noeud = make_pair(distance, numero_noeud);
}
// Trouver la zone a explorer
int zone_du_noeud_a_explorer;
if(latitude > noeud->latitude) {
if(longitude > noeud->longitude) { // Zone 0
zone_du_noeud_a_explorer = 0;
} else if(longitude < noeud->longitude) { // Zone 1
zone_du_noeud_a_explorer = 1;
}
} else {
if(longitude > noeud->longitude) { // Zone 2
zone_du_noeud_a_explorer = 2;
} else if(longitude < noeud->longitude) { // Zone 3
zone_du_noeud_a_explorer = 3;
}
}
// Trouver quelles zones explorer
set<int> zones_a_explorer;
zones_a_explorer.insert(zone_du_noeud_a_explorer);
// Il ne sert a rien d'aller voir une zone où nous nous éloignons du point a trouver
if((latitude - noeud->latitude) < distance_point_noeud.first) {
zones_a_explorer.insert((zone_du_noeud_a_explorer > 1 ? (zone_du_noeud_a_explorer - 2) : (zone_du_noeud_a_explorer + 2)));
}
if((longitude - noeud->longitude) < distance_point_noeud.first) {
zones_a_explorer.insert((zone_du_noeud_a_explorer % 2 == 0 ? (zone_du_noeud_a_explorer + 1) : (zone_du_noeud_a_explorer - 1)));
}
// Lancer l'exploration dans ces zones
for(set<int>::iterator it = zones_a_explorer.begin(); it != zones_a_explorer.end(); ++it) {
if(noeud->zone[*it] > 0) {
this->trouver_noeud_le_plus_proche(noeud->zone[*it], distance_point_noeud, latitude, longitude);
}
}
}
string graphe::operator[](uint32_t& numero_noeud)
{
this->lire_noeud(numero_noeud);
return lesNoeuds[numero_noeud].nom;
}
float graphe::distance(uint32_t& numero_noeud, float& latitude, float& longitude)
{
this->lire_noeud(numero_noeud);
noeud& noeud = lesNoeuds[numero_noeud];
float x2 = pow((longitude - noeud.longitude), 2);
float y2 = pow((latitude - noeud.latitude), 2);
float c2 = pow(cos((noeud.latitude + latitude) / 2 * M_PI / 180), 2);
return sqrt(y2 + x2 * c2) * 111;
}
<commit_msg>Retrait de certains accents.<commit_after>/**
* IFT339 - TP3
* Recherche d’information bi-demensionnelle
*
* Membres de l'equipe :
* - Felix Hamel
* - Nabil Diab
*
* Universite de Sherbrooke, automne 2014
*/
#include "graphe.h"
uint8_t architectureMachine = 2;
#include <chrono>
#include <ctime>
#include <cmath>
#include <thread>
#include <set>
#include <vector>
graphe::graphe(const string& cheminVersFichier)
{
DATA.open(cheminVersFichier.c_str(), ios::in|ios::binary);
if(!DATA.is_open()) {
cout << "Erreur d'ouverture du fichier, celui-ci n'existe pas." << endl;
exit(1);
}
DATA >> nom >> nbNOEUDS >> architecture;
DATA.ignore(1);
DEBUT = DATA.tellg();
// Determiner l'architecture de la machine courante
short int word = 0x0001;
char *byte = (char *) &word;
architectureMachine = (byte[0] ? ___LITTLE_ENDIAN : ___BIG_ENDIAN);
}
graphe::~graphe()
{
// Fermer le fichier a la sortie du programme.
if (DATA.is_open()) {
DATA.close();
}
}
void graphe::lire_noeud(uint32_t noeud)
{
if(noeud < nbNOEUDS) {
// Si le noeud n'a jamais ete lu, alors il va l'etre !
if(lesNoeuds[noeud].partieVariable == 0) {
// Lecture des donn.es statiques du noeud
DATA.seekg(DEBUT + (28 * noeud), ios::beg);
this->lire(lesNoeuds[noeud].partieVariable);
this->lire(lesNoeuds[noeud].latitude);
this->lire(lesNoeuds[noeud].longitude);
for(int i = 0; i < 4; ++i) {
this->lire(lesNoeuds[noeud].zone[i]);
}
// Lecture des donnees variable du noeud
DATA.seekg(lesNoeuds[noeud].partieVariable);
this->lire(lesNoeuds[noeud].nbArcs);
for(int i = 0; i < lesNoeuds[noeud].nbArcs; ++i) {
uint32_t numero;
this->lire(numero);
this->lire(lesNoeuds[noeud].liens[numero]);
}
// Lecture du nom du noeud
uint16_t nombreDeCaracteres;
this->lire(nombreDeCaracteres);
char* nom = new char[nombreDeCaracteres];
DATA.read(nom, nombreDeCaracteres);
lesNoeuds[noeud].nom = ((string)nom).substr(0, nombreDeCaracteres-1); // Pour enlever des espaces s'il y en a
delete[] nom;
}
}
}
void graphe::lire(uint16_t& noeud)
{
DATA.read(reinterpret_cast<char*>(&noeud), 2);
// Si l'architecture differe du fichier, on swap les bits.
if(architecture != architectureMachine) {
// http://stackoverflow.com/a/2182184
noeud = (noeud >> 8) | (noeud << 8);
}
}
void graphe::lire(uint32_t& noeud)
{
DATA.read(reinterpret_cast<char*>(&noeud), 4);
// Si l'architecture differe du fichier, on swap les bits.
if(architecture != architectureMachine) {
// http://stackoverflow.com/a/13001420
noeud = (noeud >> 24) | ((noeud << 8) & 0x00FF0000) | ((noeud >> 8) & 0x0000FF00) | (noeud << 24);
}
}
void graphe::lire(float& a)
{
DATA.read(reinterpret_cast<char*>(&a), 4);
// Si l'architecture differe du fichier, on swap les bits.
if(architecture != architectureMachine) {
char *floatToConvert = ( char* ) & a;
// http://stackoverflow.com/a/2782742
swap(floatToConvert[0], floatToConvert[3]);
swap(floatToConvert[1], floatToConvert[2]);
}
}
const uint32_t graphe::size() const
{
return this->nbNOEUDS;
}
void graphe::afficher_noeud(const uint32_t noeud)
{
this->lire_noeud(noeud);
auto leNoeud = lesNoeuds[noeud];
cout << "+--------------------------------------------------------------------+" << endl;
cout << " Noeud #" << noeud << endl;
cout << " - Latitude: " << leNoeud.latitude << endl;
cout << " - Longitude: " << leNoeud.longitude << endl;
cout << " - Nom: " << leNoeud.nom << endl;
for(int i = 0; i < 4; ++i) {
this->lire_noeud(leNoeud.zone[i]);
cout << " -> Zone[" << i << "]: " << leNoeud.zone[i] << " - nom = " << lesNoeuds[leNoeud.zone[i]].nom << endl;
}
cout << " - Nombre d'arcs: " << leNoeud.nbArcs << endl;
for(map<uint32_t, float>::iterator it = leNoeud.liens.begin(); it != leNoeud.liens.end(); ++it) {
cout << " -> Arc vers le noeud " << it->first << " avec un poids de " << it->second << endl;
}
cout << "+--------------------------------------------------------------------+" << endl;
}
uint32_t graphe::localiser(float& latitude, float& longitude)
{
// Distance entre chaque noeud et le point donne par la latitude et la longitude.
pair<float, uint32_t> distance_point_noeud = make_pair(std::numeric_limits<float>::infinity(), -1);
// Essayer de trouver le noeud le plus proche en debutant par le noeud 0
uint32_t debut = 0;
this->trouver_noeud_le_plus_proche(debut, distance_point_noeud, latitude, longitude);
// Retourner le noeud le plus proche
return distance_point_noeud.second;
}
void graphe::trouver_noeud_le_plus_proche(uint32_t& numero_noeud, pair<float, uint32_t>& distance_point_noeud, float& latitude, float& longitude)
{
// Aller chercher les informations du noeud dans le graphe
this->lire_noeud(numero_noeud);
noeud* noeud = &lesNoeuds[numero_noeud];
// Calculer la distance entre le noeud et le point
float distance = this->distance(numero_noeud, latitude, longitude);
// On conserve uniquement l'information qui peut nous etre utile
if(distance <= distance_point_noeud.first) {
distance_point_noeud = make_pair(distance, numero_noeud);
}
// Trouver la zone a explorer
int zone_du_noeud_a_explorer;
if(latitude > noeud->latitude) {
if(longitude > noeud->longitude) { // Zone 0
zone_du_noeud_a_explorer = 0;
} else if(longitude < noeud->longitude) { // Zone 1
zone_du_noeud_a_explorer = 1;
}
} else {
if(longitude > noeud->longitude) { // Zone 2
zone_du_noeud_a_explorer = 2;
} else if(longitude < noeud->longitude) { // Zone 3
zone_du_noeud_a_explorer = 3;
}
}
// Trouver quelles zones explorer
set<int> zones_a_explorer;
zones_a_explorer.insert(zone_du_noeud_a_explorer);
// Il ne sert a rien d'aller voir une zone où nous nous eloignons du point a trouver
if((latitude - noeud->latitude) < distance_point_noeud.first) {
zones_a_explorer.insert((zone_du_noeud_a_explorer > 1 ? (zone_du_noeud_a_explorer - 2) : (zone_du_noeud_a_explorer + 2)));
}
if((longitude - noeud->longitude) < distance_point_noeud.first) {
zones_a_explorer.insert((zone_du_noeud_a_explorer % 2 == 0 ? (zone_du_noeud_a_explorer + 1) : (zone_du_noeud_a_explorer - 1)));
}
// Lancer l'exploration dans ces zones
for(set<int>::iterator it = zones_a_explorer.begin(); it != zones_a_explorer.end(); ++it) {
if(noeud->zone[*it] > 0) {
this->trouver_noeud_le_plus_proche(noeud->zone[*it], distance_point_noeud, latitude, longitude);
}
}
}
string graphe::operator[](uint32_t& numero_noeud)
{
this->lire_noeud(numero_noeud);
return lesNoeuds[numero_noeud].nom;
}
float graphe::distance(uint32_t& numero_noeud, float& latitude, float& longitude)
{
this->lire_noeud(numero_noeud);
noeud& noeud = lesNoeuds[numero_noeud];
float x2 = pow((longitude - noeud.longitude), 2);
float y2 = pow((latitude - noeud.latitude), 2);
float c2 = pow(cos((noeud.latitude + latitude) / 2 * M_PI / 180), 2);
return sqrt(y2 + x2 * c2) * 111;
}
<|endoftext|> |
<commit_before>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "content/browser/renderer_host/test_backing_store.h"
#include "content/browser/renderer_host/test_render_view_host.h"
#include "content/browser/site_instance_impl.h"
#include "content/browser/web_contents/navigation_controller_impl.h"
#include "content/browser/web_contents/test_web_contents.h"
#include "content/common/view_messages.h"
#include "content/public/browser/navigation_controller.h"
#include "content/public/common/content_client.h"
#include "ui/gfx/rect.h"
#include "webkit/dom_storage/dom_storage_types.h"
#include "webkit/forms/password_form.h"
#include "webkit/glue/webkit_glue.h"
#include "webkit/glue/webpreferences.h"
using content::NativeWebKeyboardEvent;
using webkit::forms::PasswordForm;
namespace content {
void InitNavigateParams(ViewHostMsg_FrameNavigate_Params* params,
int page_id,
const GURL& url,
PageTransition transition) {
params->page_id = page_id;
params->url = url;
params->referrer = Referrer();
params->transition = transition;
params->redirects = std::vector<GURL>();
params->should_update_history = false;
params->searchable_form_url = GURL();
params->searchable_form_encoding = std::string();
params->password_form = PasswordForm();
params->security_info = std::string();
params->gesture = NavigationGestureUser;
params->was_within_same_page = false;
params->is_post = false;
params->content_state = webkit_glue::CreateHistoryStateForURL(GURL(url));
}
TestRenderWidgetHostView::TestRenderWidgetHostView(RenderWidgetHost* rwh)
: rwh_(RenderWidgetHostImpl::From(rwh)),
is_showing_(false) {
}
TestRenderWidgetHostView::~TestRenderWidgetHostView() {
}
RenderWidgetHost* TestRenderWidgetHostView::GetRenderWidgetHost() const {
return NULL;
}
gfx::NativeView TestRenderWidgetHostView::GetNativeView() const {
return NULL;
}
gfx::NativeViewId TestRenderWidgetHostView::GetNativeViewId() const {
return 0;
}
gfx::NativeViewAccessible TestRenderWidgetHostView::GetNativeViewAccessible() {
return NULL;
}
bool TestRenderWidgetHostView::HasFocus() const {
return true;
}
bool TestRenderWidgetHostView::IsSurfaceAvailableForCopy() const {
return true;
}
void TestRenderWidgetHostView::Show() {
is_showing_ = true;
}
void TestRenderWidgetHostView::Hide() {
is_showing_ = false;
}
bool TestRenderWidgetHostView::IsShowing() {
return is_showing_;
}
void TestRenderWidgetHostView::RenderViewGone(base::TerminationStatus status,
int error_code) {
delete this;
}
gfx::Rect TestRenderWidgetHostView::GetViewBounds() const {
return gfx::Rect();
}
BackingStore* TestRenderWidgetHostView::AllocBackingStore(
const gfx::Size& size) {
return new TestBackingStore(rwh_, size);
}
void TestRenderWidgetHostView::CopyFromCompositingSurface(
const gfx::Size& size,
const base::Callback<void(bool)>& callback,
skia::PlatformCanvas* output) {
callback.Run(false);
}
void TestRenderWidgetHostView::OnAcceleratedCompositingStateChange() {
}
void TestRenderWidgetHostView::AcceleratedSurfaceBuffersSwapped(
const GpuHostMsg_AcceleratedSurfaceBuffersSwapped_Params& params,
int gpu_host_id) {
}
void TestRenderWidgetHostView::AcceleratedSurfacePostSubBuffer(
const GpuHostMsg_AcceleratedSurfacePostSubBuffer_Params& params,
int gpu_host_id) {
}
void TestRenderWidgetHostView::AcceleratedSurfaceSuspend() {
}
bool TestRenderWidgetHostView::HasAcceleratedSurface(
const gfx::Size& desired_size) {
return false;
}
#if defined(OS_MACOSX)
void TestRenderWidgetHostView::AboutToWaitForBackingStoreMsg() {
}
void TestRenderWidgetHostView::SetActive(bool active) {
// <viettrungluu@gmail.com>: Do I need to do anything here?
}
void TestRenderWidgetHostView::PluginFocusChanged(bool focused,
int plugin_id) {
}
void TestRenderWidgetHostView::StartPluginIme() {
}
bool TestRenderWidgetHostView::PostProcessEventForPluginIme(
const NativeWebKeyboardEvent& event) {
return false;
}
gfx::PluginWindowHandle
TestRenderWidgetHostView::AllocateFakePluginWindowHandle(
bool opaque,
bool root) {
return gfx::kNullPluginWindow;
}
void TestRenderWidgetHostView::DestroyFakePluginWindowHandle(
gfx::PluginWindowHandle window) {
}
void TestRenderWidgetHostView::AcceleratedSurfaceSetIOSurface(
gfx::PluginWindowHandle window,
int32 width,
int32 height,
uint64 surface_id) {
}
void TestRenderWidgetHostView::AcceleratedSurfaceSetTransportDIB(
gfx::PluginWindowHandle window,
int32 width,
int32 height,
TransportDIB::Handle transport_dib) {
}
#elif defined(OS_WIN) && !defined(USE_AURA)
void TestRenderWidgetHostView::WillWmDestroy() {
}
#endif
#if defined(OS_ANDROID)
void TestRenderWidgetHostView::StartContentIntent(const GURL&) {}
#endif
#if defined(OS_POSIX) || defined(USE_AURA)
gfx::Rect TestRenderWidgetHostView::GetRootWindowBounds() {
return gfx::Rect();
}
#endif
#if defined(TOOLKIT_GTK)
GdkEventButton* TestRenderWidgetHostView::GetLastMouseDown() {
return NULL;
}
gfx::NativeView TestRenderWidgetHostView::BuildInputMethodsGtkMenu() {
return NULL;
}
#endif // defined(TOOLKIT_GTK)
gfx::GLSurfaceHandle TestRenderWidgetHostView::GetCompositingSurface() {
return gfx::GLSurfaceHandle();
}
bool TestRenderWidgetHostView::LockMouse() {
return false;
}
void TestRenderWidgetHostView::UnlockMouse() {
}
TestRenderViewHost::TestRenderViewHost(
SiteInstance* instance,
RenderViewHostDelegate* delegate,
RenderWidgetHostDelegate* widget_delegate,
int routing_id,
bool swapped_out)
: RenderViewHostImpl(instance,
delegate,
widget_delegate,
routing_id,
swapped_out,
dom_storage::kInvalidSessionStorageNamespaceId),
render_view_created_(false),
delete_counter_(NULL),
simulate_fetch_via_proxy_(false),
contents_mime_type_("text/html") {
// For normal RenderViewHosts, this is freed when |Shutdown()| is
// called. For TestRenderViewHost, the view is explicitly
// deleted in the destructor below, because
// TestRenderWidgetHostView::Destroy() doesn't |delete this|.
SetView(new TestRenderWidgetHostView(this));
}
TestRenderViewHost::~TestRenderViewHost() {
if (delete_counter_)
++*delete_counter_;
// Since this isn't a traditional view, we have to delete it.
delete GetView();
}
bool TestRenderViewHost::CreateRenderView(
const string16& frame_name,
int opener_route_id,
int32 max_page_id,
const std::string& embedder_channel_name,
int embedder_container_id) {
DCHECK(!render_view_created_);
render_view_created_ = true;
return true;
}
bool TestRenderViewHost::IsRenderViewLive() const {
return render_view_created_;
}
void TestRenderViewHost::SendNavigate(int page_id, const GURL& url) {
SendNavigateWithTransition(page_id, url, PAGE_TRANSITION_LINK);
}
void TestRenderViewHost::SendNavigateWithTransition(
int page_id, const GURL& url, PageTransition transition) {
ViewHostMsg_FrameNavigate_Params params;
params.page_id = page_id;
params.url = url;
params.referrer = Referrer();
params.transition = transition;
params.redirects = std::vector<GURL>();
params.should_update_history = true;
params.searchable_form_url = GURL();
params.searchable_form_encoding = std::string();
params.password_form = PasswordForm();
params.security_info = std::string();
params.gesture = NavigationGestureUser;
params.contents_mime_type = contents_mime_type_;
params.is_post = false;
params.was_within_same_page = false;
params.http_status_code = 0;
params.socket_address.set_host("2001:db8::1");
params.socket_address.set_port(80);
params.was_fetched_via_proxy = simulate_fetch_via_proxy_;
params.content_state = webkit_glue::CreateHistoryStateForURL(GURL(url));
ViewHostMsg_FrameNavigate msg(1, params);
OnMsgNavigate(msg);
}
void TestRenderViewHost::SendShouldCloseACK(bool proceed) {
OnMsgShouldCloseACK(proceed, base::TimeTicks(), base::TimeTicks());
}
void TestRenderViewHost::SetContentsMimeType(const std::string& mime_type) {
contents_mime_type_ = mime_type;
}
void TestRenderViewHost::SimulateSwapOutACK() {
OnSwapOutACK();
}
void TestRenderViewHost::SimulateWasHidden() {
WasHidden();
}
void TestRenderViewHost::SimulateWasRestored() {
WasRestored();
}
void TestRenderViewHost::TestOnMsgStartDragging(
const WebDropData& drop_data) {
WebKit::WebDragOperationsMask drag_operation = WebKit::WebDragOperationEvery;
OnMsgStartDragging(drop_data, drag_operation, SkBitmap(), gfx::Point());
}
void TestRenderViewHost::set_simulate_fetch_via_proxy(bool proxy) {
simulate_fetch_via_proxy_ = proxy;
}
RenderViewHostImplTestHarness::RenderViewHostImplTestHarness() {
}
RenderViewHostImplTestHarness::~RenderViewHostImplTestHarness() {
}
TestRenderViewHost* RenderViewHostImplTestHarness::test_rvh() {
return static_cast<TestRenderViewHost*>(rvh());
}
TestRenderViewHost* RenderViewHostImplTestHarness::pending_test_rvh() {
return static_cast<TestRenderViewHost*>(pending_rvh());
}
TestRenderViewHost* RenderViewHostImplTestHarness::active_test_rvh() {
return static_cast<TestRenderViewHost*>(active_rvh());
}
TestWebContents* RenderViewHostImplTestHarness::contents() {
return static_cast<TestWebContents*>(web_contents());
}
} // namespace content
<commit_msg>When simulating a navigation via TestRenderViewHost, first start a provisional load before committing it<commit_after>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "content/browser/renderer_host/test_backing_store.h"
#include "content/browser/renderer_host/test_render_view_host.h"
#include "content/browser/site_instance_impl.h"
#include "content/browser/web_contents/navigation_controller_impl.h"
#include "content/browser/web_contents/test_web_contents.h"
#include "content/common/view_messages.h"
#include "content/public/browser/navigation_controller.h"
#include "content/public/common/content_client.h"
#include "ui/gfx/rect.h"
#include "webkit/dom_storage/dom_storage_types.h"
#include "webkit/forms/password_form.h"
#include "webkit/glue/webkit_glue.h"
#include "webkit/glue/webpreferences.h"
using content::NativeWebKeyboardEvent;
using webkit::forms::PasswordForm;
namespace content {
void InitNavigateParams(ViewHostMsg_FrameNavigate_Params* params,
int page_id,
const GURL& url,
PageTransition transition) {
params->page_id = page_id;
params->url = url;
params->referrer = Referrer();
params->transition = transition;
params->redirects = std::vector<GURL>();
params->should_update_history = false;
params->searchable_form_url = GURL();
params->searchable_form_encoding = std::string();
params->password_form = PasswordForm();
params->security_info = std::string();
params->gesture = NavigationGestureUser;
params->was_within_same_page = false;
params->is_post = false;
params->content_state = webkit_glue::CreateHistoryStateForURL(GURL(url));
}
TestRenderWidgetHostView::TestRenderWidgetHostView(RenderWidgetHost* rwh)
: rwh_(RenderWidgetHostImpl::From(rwh)),
is_showing_(false) {
}
TestRenderWidgetHostView::~TestRenderWidgetHostView() {
}
RenderWidgetHost* TestRenderWidgetHostView::GetRenderWidgetHost() const {
return NULL;
}
gfx::NativeView TestRenderWidgetHostView::GetNativeView() const {
return NULL;
}
gfx::NativeViewId TestRenderWidgetHostView::GetNativeViewId() const {
return 0;
}
gfx::NativeViewAccessible TestRenderWidgetHostView::GetNativeViewAccessible() {
return NULL;
}
bool TestRenderWidgetHostView::HasFocus() const {
return true;
}
bool TestRenderWidgetHostView::IsSurfaceAvailableForCopy() const {
return true;
}
void TestRenderWidgetHostView::Show() {
is_showing_ = true;
}
void TestRenderWidgetHostView::Hide() {
is_showing_ = false;
}
bool TestRenderWidgetHostView::IsShowing() {
return is_showing_;
}
void TestRenderWidgetHostView::RenderViewGone(base::TerminationStatus status,
int error_code) {
delete this;
}
gfx::Rect TestRenderWidgetHostView::GetViewBounds() const {
return gfx::Rect();
}
BackingStore* TestRenderWidgetHostView::AllocBackingStore(
const gfx::Size& size) {
return new TestBackingStore(rwh_, size);
}
void TestRenderWidgetHostView::CopyFromCompositingSurface(
const gfx::Size& size,
const base::Callback<void(bool)>& callback,
skia::PlatformCanvas* output) {
callback.Run(false);
}
void TestRenderWidgetHostView::OnAcceleratedCompositingStateChange() {
}
void TestRenderWidgetHostView::AcceleratedSurfaceBuffersSwapped(
const GpuHostMsg_AcceleratedSurfaceBuffersSwapped_Params& params,
int gpu_host_id) {
}
void TestRenderWidgetHostView::AcceleratedSurfacePostSubBuffer(
const GpuHostMsg_AcceleratedSurfacePostSubBuffer_Params& params,
int gpu_host_id) {
}
void TestRenderWidgetHostView::AcceleratedSurfaceSuspend() {
}
bool TestRenderWidgetHostView::HasAcceleratedSurface(
const gfx::Size& desired_size) {
return false;
}
#if defined(OS_MACOSX)
void TestRenderWidgetHostView::AboutToWaitForBackingStoreMsg() {
}
void TestRenderWidgetHostView::SetActive(bool active) {
// <viettrungluu@gmail.com>: Do I need to do anything here?
}
void TestRenderWidgetHostView::PluginFocusChanged(bool focused,
int plugin_id) {
}
void TestRenderWidgetHostView::StartPluginIme() {
}
bool TestRenderWidgetHostView::PostProcessEventForPluginIme(
const NativeWebKeyboardEvent& event) {
return false;
}
gfx::PluginWindowHandle
TestRenderWidgetHostView::AllocateFakePluginWindowHandle(
bool opaque,
bool root) {
return gfx::kNullPluginWindow;
}
void TestRenderWidgetHostView::DestroyFakePluginWindowHandle(
gfx::PluginWindowHandle window) {
}
void TestRenderWidgetHostView::AcceleratedSurfaceSetIOSurface(
gfx::PluginWindowHandle window,
int32 width,
int32 height,
uint64 surface_id) {
}
void TestRenderWidgetHostView::AcceleratedSurfaceSetTransportDIB(
gfx::PluginWindowHandle window,
int32 width,
int32 height,
TransportDIB::Handle transport_dib) {
}
#elif defined(OS_WIN) && !defined(USE_AURA)
void TestRenderWidgetHostView::WillWmDestroy() {
}
#endif
#if defined(OS_ANDROID)
void TestRenderWidgetHostView::StartContentIntent(const GURL&) {}
#endif
#if defined(OS_POSIX) || defined(USE_AURA)
gfx::Rect TestRenderWidgetHostView::GetRootWindowBounds() {
return gfx::Rect();
}
#endif
#if defined(TOOLKIT_GTK)
GdkEventButton* TestRenderWidgetHostView::GetLastMouseDown() {
return NULL;
}
gfx::NativeView TestRenderWidgetHostView::BuildInputMethodsGtkMenu() {
return NULL;
}
#endif // defined(TOOLKIT_GTK)
gfx::GLSurfaceHandle TestRenderWidgetHostView::GetCompositingSurface() {
return gfx::GLSurfaceHandle();
}
bool TestRenderWidgetHostView::LockMouse() {
return false;
}
void TestRenderWidgetHostView::UnlockMouse() {
}
TestRenderViewHost::TestRenderViewHost(
SiteInstance* instance,
RenderViewHostDelegate* delegate,
RenderWidgetHostDelegate* widget_delegate,
int routing_id,
bool swapped_out)
: RenderViewHostImpl(instance,
delegate,
widget_delegate,
routing_id,
swapped_out,
dom_storage::kInvalidSessionStorageNamespaceId),
render_view_created_(false),
delete_counter_(NULL),
simulate_fetch_via_proxy_(false),
contents_mime_type_("text/html") {
// For normal RenderViewHosts, this is freed when |Shutdown()| is
// called. For TestRenderViewHost, the view is explicitly
// deleted in the destructor below, because
// TestRenderWidgetHostView::Destroy() doesn't |delete this|.
SetView(new TestRenderWidgetHostView(this));
}
TestRenderViewHost::~TestRenderViewHost() {
if (delete_counter_)
++*delete_counter_;
// Since this isn't a traditional view, we have to delete it.
delete GetView();
}
bool TestRenderViewHost::CreateRenderView(
const string16& frame_name,
int opener_route_id,
int32 max_page_id,
const std::string& embedder_channel_name,
int embedder_container_id) {
DCHECK(!render_view_created_);
render_view_created_ = true;
return true;
}
bool TestRenderViewHost::IsRenderViewLive() const {
return render_view_created_;
}
void TestRenderViewHost::SendNavigate(int page_id, const GURL& url) {
SendNavigateWithTransition(page_id, url, PAGE_TRANSITION_LINK);
}
void TestRenderViewHost::SendNavigateWithTransition(
int page_id, const GURL& url, PageTransition transition) {
OnMsgDidStartProvisionalLoadForFrame(0, true, GURL(), url);
ViewHostMsg_FrameNavigate_Params params;
params.page_id = page_id;
params.frame_id = 0;
params.url = url;
params.referrer = Referrer();
params.transition = transition;
params.redirects = std::vector<GURL>();
params.should_update_history = true;
params.searchable_form_url = GURL();
params.searchable_form_encoding = std::string();
params.password_form = PasswordForm();
params.security_info = std::string();
params.gesture = NavigationGestureUser;
params.contents_mime_type = contents_mime_type_;
params.is_post = false;
params.was_within_same_page = false;
params.http_status_code = 0;
params.socket_address.set_host("2001:db8::1");
params.socket_address.set_port(80);
params.was_fetched_via_proxy = simulate_fetch_via_proxy_;
params.content_state = webkit_glue::CreateHistoryStateForURL(GURL(url));
ViewHostMsg_FrameNavigate msg(1, params);
OnMsgNavigate(msg);
}
void TestRenderViewHost::SendShouldCloseACK(bool proceed) {
OnMsgShouldCloseACK(proceed, base::TimeTicks(), base::TimeTicks());
}
void TestRenderViewHost::SetContentsMimeType(const std::string& mime_type) {
contents_mime_type_ = mime_type;
}
void TestRenderViewHost::SimulateSwapOutACK() {
OnSwapOutACK();
}
void TestRenderViewHost::SimulateWasHidden() {
WasHidden();
}
void TestRenderViewHost::SimulateWasRestored() {
WasRestored();
}
void TestRenderViewHost::TestOnMsgStartDragging(
const WebDropData& drop_data) {
WebKit::WebDragOperationsMask drag_operation = WebKit::WebDragOperationEvery;
OnMsgStartDragging(drop_data, drag_operation, SkBitmap(), gfx::Point());
}
void TestRenderViewHost::set_simulate_fetch_via_proxy(bool proxy) {
simulate_fetch_via_proxy_ = proxy;
}
RenderViewHostImplTestHarness::RenderViewHostImplTestHarness() {
}
RenderViewHostImplTestHarness::~RenderViewHostImplTestHarness() {
}
TestRenderViewHost* RenderViewHostImplTestHarness::test_rvh() {
return static_cast<TestRenderViewHost*>(rvh());
}
TestRenderViewHost* RenderViewHostImplTestHarness::pending_test_rvh() {
return static_cast<TestRenderViewHost*>(pending_rvh());
}
TestRenderViewHost* RenderViewHostImplTestHarness::active_test_rvh() {
return static_cast<TestRenderViewHost*>(active_rvh());
}
TestWebContents* RenderViewHostImplTestHarness::contents() {
return static_cast<TestWebContents*>(web_contents());
}
} // namespace content
<|endoftext|> |
<commit_before>/*
* Copyright 2012 Sebastian Gottfried <sebastiangottfried@web.de>
*
* 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, see <http://www.gnu.org/licenses/>.
*/
#include "linegraphbackgroundpainter.h"
#include <QAbstractTableModel>
#include <QPainter>
#include "linegraphcore.h"
#include "dimension.h"
#include <KDebug>
LineGraphBackgroundPainter::LineGraphBackgroundPainter(QDeclarativeItem* parent) :
QDeclarativeItem(parent),
m_lineGraphCore(0)
{
setFlag(QGraphicsItem::ItemHasNoContents, false);
}
LineGraphCore* LineGraphBackgroundPainter::lineGraphCore() const
{
return m_lineGraphCore;
}
void LineGraphBackgroundPainter::setGraphCoreItem(LineGraphCore* lineGraphCore)
{
if (lineGraphCore != m_lineGraphCore)
{
if (m_lineGraphCore)
{
m_lineGraphCore->disconnect(this);
}
m_lineGraphCore = lineGraphCore;
if (m_lineGraphCore)
{
connect(m_lineGraphCore, SIGNAL(updated()), SLOT(triggerUpdate()));
}
update();
emit lineGraphCoreChanged();
}
}
const QList<QPolygonF>& LineGraphBackgroundPainter::linePolygons() const
{
return m_linePolygons;
}
void LineGraphBackgroundPainter::paint(QPainter* painter, const QStyleOptionGraphicsItem*, QWidget*)
{
QList<Dimension*> dimensions = m_lineGraphCore->dimensionsList();
const qreal radius = m_lineGraphCore->pointRadius();
const qreal maxY = height();
for (int i = 0; i < dimensions.length(); i++)
{
QPolygonF line = m_linePolygons.at(i);
line << QPointF(line.last().x(), maxY - radius);
line << QPointF(line.first().x(), maxY - radius);
QColor bgColor = dimensions.at(i)->color();
bgColor.setAlphaF(0.7);
painter->setBrush(bgColor);
painter->setPen(Qt::NoPen);
painter->drawPolygon(line);
}
}
void LineGraphBackgroundPainter::triggerUpdate()
{
updateLinePolygons();
updateWidth();
update();
}
void LineGraphBackgroundPainter::updateWidth()
{
QAbstractTableModel* model = m_lineGraphCore->model();
if (!model)
{
setWidth(0);
return;
}
setWidth(model->rowCount() * m_lineGraphCore->pitch());
}
void LineGraphBackgroundPainter::updateLinePolygons()
{
m_linePolygons.clear();
QList<Dimension*> dimensions = m_lineGraphCore->dimensionsList();
QAbstractTableModel* model = m_lineGraphCore->model();
const qreal pitch = m_lineGraphCore->pitch();
const qreal radius = m_lineGraphCore->pointRadius();
foreach(Dimension* dimension, dimensions)
{
const int column = dimension->dataColumn();
const qreal maxValue = dimension->maximumValue();
const qreal maxY = height();
QPolygonF line;
for (int row = 0; row < model->rowCount(); row++)
{
const qreal value = model->data(model->index(row, column)).toReal();
line << QPointF(pointPos(pitch, radius, row, value, maxValue, maxY));
}
m_linePolygons << line;
}
}
QPointF LineGraphBackgroundPainter::pointPos(qreal pitch, qreal radius, int row, qreal value, qreal maxValue, qreal maxY)
{
const qreal x = (qreal(row) + 0.5) * pitch;
const qreal y = maxY - ((maxY - 2 * radius) * value / maxValue) - radius;
return QPointF(x, y);
}
<commit_msg>graph plugin: reduce the alpha of filled area under the graph lines<commit_after>/*
* Copyright 2012 Sebastian Gottfried <sebastiangottfried@web.de>
*
* 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, see <http://www.gnu.org/licenses/>.
*/
#include "linegraphbackgroundpainter.h"
#include <QAbstractTableModel>
#include <QPainter>
#include "linegraphcore.h"
#include "dimension.h"
#include <KDebug>
LineGraphBackgroundPainter::LineGraphBackgroundPainter(QDeclarativeItem* parent) :
QDeclarativeItem(parent),
m_lineGraphCore(0)
{
setFlag(QGraphicsItem::ItemHasNoContents, false);
}
LineGraphCore* LineGraphBackgroundPainter::lineGraphCore() const
{
return m_lineGraphCore;
}
void LineGraphBackgroundPainter::setGraphCoreItem(LineGraphCore* lineGraphCore)
{
if (lineGraphCore != m_lineGraphCore)
{
if (m_lineGraphCore)
{
m_lineGraphCore->disconnect(this);
}
m_lineGraphCore = lineGraphCore;
if (m_lineGraphCore)
{
connect(m_lineGraphCore, SIGNAL(updated()), SLOT(triggerUpdate()));
}
update();
emit lineGraphCoreChanged();
}
}
const QList<QPolygonF>& LineGraphBackgroundPainter::linePolygons() const
{
return m_linePolygons;
}
void LineGraphBackgroundPainter::paint(QPainter* painter, const QStyleOptionGraphicsItem*, QWidget*)
{
QList<Dimension*> dimensions = m_lineGraphCore->dimensionsList();
const qreal radius = m_lineGraphCore->pointRadius();
const qreal maxY = height();
for (int i = 0; i < dimensions.length(); i++)
{
QPolygonF line = m_linePolygons.at(i);
line << QPointF(line.last().x(), maxY - radius);
line << QPointF(line.first().x(), maxY - radius);
QColor bgColor = dimensions.at(i)->color();
bgColor.setAlphaF(0.4);
painter->setBrush(bgColor);
painter->setPen(Qt::NoPen);
painter->drawPolygon(line);
}
}
void LineGraphBackgroundPainter::triggerUpdate()
{
updateLinePolygons();
updateWidth();
update();
}
void LineGraphBackgroundPainter::updateWidth()
{
QAbstractTableModel* model = m_lineGraphCore->model();
if (!model)
{
setWidth(0);
return;
}
setWidth(model->rowCount() * m_lineGraphCore->pitch());
}
void LineGraphBackgroundPainter::updateLinePolygons()
{
m_linePolygons.clear();
QList<Dimension*> dimensions = m_lineGraphCore->dimensionsList();
QAbstractTableModel* model = m_lineGraphCore->model();
const qreal pitch = m_lineGraphCore->pitch();
const qreal radius = m_lineGraphCore->pointRadius();
foreach(Dimension* dimension, dimensions)
{
const int column = dimension->dataColumn();
const qreal maxValue = dimension->maximumValue();
const qreal maxY = height();
QPolygonF line;
for (int row = 0; row < model->rowCount(); row++)
{
const qreal value = model->data(model->index(row, column)).toReal();
line << QPointF(pointPos(pitch, radius, row, value, maxValue, maxY));
}
m_linePolygons << line;
}
}
QPointF LineGraphBackgroundPainter::pointPos(qreal pitch, qreal radius, int row, qreal value, qreal maxValue, qreal maxY)
{
const qreal x = (qreal(row) + 0.5) * pitch;
const qreal y = maxY - ((maxY - 2 * radius) * value / maxValue) - radius;
return QPointF(x, y);
}
<|endoftext|> |
<commit_before>//===-- Writer.cpp - Library for Printing VM assembly files ------*- C++ -*--=//
//
// This library implements the functionality defined in llvm/Assembly/Writer.h
//
// This library uses the Analysis library to figure out offsets for
// variables in the method tables...
//
// TODO: print out the type name instead of the full type if a particular type
// is in the symbol table...
//
//===----------------------------------------------------------------------===//
#include "llvm/Assembly/Writer.h"
#include "llvm/Analysis/SlotCalculator.h"
#include "llvm/Module.h"
#include "llvm/Method.h"
#include "llvm/BasicBlock.h"
#include "llvm/ConstPoolVals.h"
#include "llvm/iOther.h"
#include "llvm/iMemory.h"
void DebugValue(const Value *V) {
cerr << V << endl;
}
// WriteAsOperand - Write the name of the specified value out to the specified
// ostream. This can be useful when you just want to print int %reg126, not the
// whole instruction that generated it.
//
ostream &WriteAsOperand(ostream &Out, const Value *V, bool PrintType,
bool PrintName, SlotCalculator *Table) {
if (PrintType)
Out << " " << V->getType();
if (V->hasName() && PrintName) {
Out << " %" << V->getName();
} else {
if (const ConstPoolVal *CPV = V->castConstant()) {
Out << " " << CPV->getStrValue();
} else {
int Slot;
if (Table) {
Slot = Table->getValSlot(V);
} else {
if (const Type *Ty = V->castType()) {
return Out << " " << Ty;
} else if (const MethodArgument *MA = V->castMethodArgument()) {
Table = new SlotCalculator(MA->getParent(), true);
} else if (const Instruction *I = V->castInstruction()) {
Table = new SlotCalculator(I->getParent()->getParent(), true);
} else if (const BasicBlock *BB = V->castBasicBlock()) {
Table = new SlotCalculator(BB->getParent(), true);
} else if (const Method *Meth = V->castMethod()) {
Table = new SlotCalculator(Meth, true);
} else if (const Module *Mod = V->castModule()) {
Table = new SlotCalculator(Mod, true);
} else {
return Out << "BAD VALUE TYPE!";
}
Slot = Table->getValSlot(V);
delete Table;
}
if (Slot >= 0) Out << " %" << Slot;
else if (PrintName)
Out << "<badref>"; // Not embeded into a location?
}
}
return Out;
}
class AssemblyWriter : public ModuleAnalyzer {
ostream &Out;
SlotCalculator &Table;
public:
inline AssemblyWriter(ostream &o, SlotCalculator &Tab) : Out(o), Table(Tab) {
}
inline void write(const Module *M) { processModule(M); }
inline void write(const Method *M) { processMethod(M); }
inline void write(const BasicBlock *BB) { processBasicBlock(BB); }
inline void write(const Instruction *I) { processInstruction(I); }
inline void write(const ConstPoolVal *CPV) { processConstant(CPV); }
protected:
virtual bool visitMethod(const Method *M);
virtual bool processConstPool(const ConstantPool &CP, bool isMethod);
virtual bool processConstant(const ConstPoolVal *CPV);
virtual bool processMethod(const Method *M);
virtual bool processMethodArgument(const MethodArgument *MA);
virtual bool processBasicBlock(const BasicBlock *BB);
virtual bool processInstruction(const Instruction *I);
private :
void writeOperand(const Value *Op, bool PrintType, bool PrintName = true);
};
// visitMethod - This member is called after the above two steps, visting each
// method, because they are effectively values that go into the constant pool.
//
bool AssemblyWriter::visitMethod(const Method *M) {
return false;
}
bool AssemblyWriter::processConstPool(const ConstantPool &CP, bool isMethod) {
// Done printing arguments...
if (isMethod) {
if (CP.getParentV()->castMethodAsserting()->getType()->
isMethodType()->isVarArg())
Out << ", ..."; // Output varargs portion of signature!
Out << ")\n";
}
ModuleAnalyzer::processConstPool(CP, isMethod);
if (isMethod) {
if (!CP.getParentV()->castMethodAsserting()->isExternal())
Out << "begin";
} else {
Out << "implementation\n";
}
return false;
}
// processConstant - Print out a constant pool entry...
//
bool AssemblyWriter::processConstant(const ConstPoolVal *CPV) {
if (!CPV->hasName())
return false; // Don't print out unnamed constants, they will be inlined
// Print out name...
Out << "\t%" << CPV->getName() << " = ";
// Print out the constant type...
Out << CPV->getType();
// Write the value out now...
writeOperand(CPV, false, false);
if (!CPV->hasName() && CPV->getType() != Type::VoidTy) {
int Slot = Table.getValSlot(CPV); // Print out the def slot taken...
Out << "\t\t; <" << CPV->getType() << ">:";
if (Slot >= 0) Out << Slot;
else Out << "<badref>";
}
Out << endl;
return false;
}
// processMethod - Process all aspects of a method.
//
bool AssemblyWriter::processMethod(const Method *M) {
// Print out the return type and name...
Out << "\n" << (M->isExternal() ? "declare " : "")
<< M->getReturnType() << " \"" << M->getName() << "\"(";
Table.incorporateMethod(M);
ModuleAnalyzer::processMethod(M);
Table.purgeMethod();
if (!M->isExternal())
Out << "end\n";
return false;
}
// processMethodArgument - This member is called for every argument that
// is passed into the method. Simply print it out
//
bool AssemblyWriter::processMethodArgument(const MethodArgument *Arg) {
// Insert commas as we go... the first arg doesn't get a comma
if (Arg != Arg->getParent()->getArgumentList().front()) Out << ", ";
// Output type...
Out << Arg->getType();
// Output name, if available...
if (Arg->hasName())
Out << " %" << Arg->getName();
else if (Table.getValSlot(Arg) < 0)
Out << "<badref>";
return false;
}
// processBasicBlock - This member is called for each basic block in a methd.
//
bool AssemblyWriter::processBasicBlock(const BasicBlock *BB) {
if (BB->hasName()) { // Print out the label if it exists...
Out << "\n" << BB->getName() << ":";
} else {
int Slot = Table.getValSlot(BB);
Out << "\n; <label>:";
if (Slot >= 0)
Out << Slot; // Extra newline seperates out label's
else
Out << "<badref>";
}
Out << "\t\t\t\t\t;[#uses=" << BB->use_size() << "]\n"; // Output # uses
ModuleAnalyzer::processBasicBlock(BB);
return false;
}
// processInstruction - This member is called for each Instruction in a methd.
//
bool AssemblyWriter::processInstruction(const Instruction *I) {
Out << "\t";
// Print out name if it exists...
if (I && I->hasName())
Out << "%" << I->getName() << " = ";
// Print out the opcode...
Out << I->getOpcodeName();
// Print out the type of the operands...
const Value *Operand = I->getNumOperands() ? I->getOperand(0) : 0;
// Special case conditional branches to swizzle the condition out to the front
if (I->getOpcode() == Instruction::Br && I->getNumOperands() > 1) {
writeOperand(I->getOperand(2), true);
Out << ",";
writeOperand(Operand, true);
Out << ",";
writeOperand(I->getOperand(1), true);
} else if (I->getOpcode() == Instruction::Switch) {
// Special case switch statement to get formatting nice and correct...
writeOperand(Operand , true); Out << ",";
writeOperand(I->getOperand(1), true); Out << " [";
for (unsigned op = 2, Eop = I->getNumOperands(); op < Eop; op += 2) {
Out << "\n\t\t";
writeOperand(I->getOperand(op ), true); Out << ",";
writeOperand(I->getOperand(op+1), true);
}
Out << "\n\t]";
} else if (I->isPHINode()) {
Out << " " << Operand->getType();
Out << " ["; writeOperand(Operand, false); Out << ",";
writeOperand(I->getOperand(1), false); Out << " ]";
for (unsigned op = 2, Eop = I->getNumOperands(); op < Eop; op += 2) {
Out << ", [";
writeOperand(I->getOperand(op ), false); Out << ",";
writeOperand(I->getOperand(op+1), false); Out << " ]";
}
} else if (I->getOpcode() == Instruction::Ret && !Operand) {
Out << " void";
} else if (I->getOpcode() == Instruction::Call) {
writeOperand(Operand, true);
Out << "(";
if (I->getNumOperands() > 1) writeOperand(I->getOperand(1), true);
for (unsigned op = 2, Eop = I->getNumOperands(); op < Eop; ++op) {
Out << ",";
writeOperand(I->getOperand(op), true);
}
Out << " )";
} else if (I->getOpcode() == Instruction::Malloc ||
I->getOpcode() == Instruction::Alloca) {
Out << " " << ((const PointerType*)I->getType())->getValueType();
if (I->getNumOperands()) {
Out << ",";
writeOperand(I->getOperand(0), true);
}
} else if (I->getOpcode() == Instruction::Cast) {
writeOperand(Operand, true);
Out << " to " << I->getType();
} else if (Operand) { // Print the normal way...
// PrintAllTypes - Instructions who have operands of all the same type
// omit the type from all but the first operand. If the instruction has
// different type operands (for example br), then they are all printed.
bool PrintAllTypes = false;
const Type *TheType = Operand->getType();
for (unsigned i = 1, E = I->getNumOperands(); i != E; ++i) {
Operand = I->getOperand(i);
if (Operand->getType() != TheType) {
PrintAllTypes = true; // We have differing types! Print them all!
break;
}
}
if (!PrintAllTypes)
Out << " " << I->getOperand(0)->getType();
for (unsigned i = 0, E = I->getNumOperands(); i != E; ++i) {
if (i) Out << ",";
writeOperand(I->getOperand(i), PrintAllTypes);
}
}
// Print a little comment after the instruction indicating which slot it
// occupies.
//
if (I->getType() != Type::VoidTy) {
Out << "\t\t; <" << I->getType() << ">";
if (!I->hasName()) {
int Slot = Table.getValSlot(I); // Print out the def slot taken...
if (Slot >= 0) Out << ":" << Slot;
else Out << ":<badref>";
}
Out << "\t[#uses=" << I->use_size() << "]"; // Output # uses
}
Out << endl;
return false;
}
void AssemblyWriter::writeOperand(const Value *Operand, bool PrintType,
bool PrintName) {
WriteAsOperand(Out, Operand, PrintType, PrintName, &Table);
}
//===----------------------------------------------------------------------===//
// External Interface declarations
//===----------------------------------------------------------------------===//
void WriteToAssembly(const Module *M, ostream &o) {
if (M == 0) { o << "<null> module\n"; return; }
SlotCalculator SlotTable(M, true);
AssemblyWriter W(o, SlotTable);
W.write(M);
}
void WriteToAssembly(const Method *M, ostream &o) {
if (M == 0) { o << "<null> method\n"; return; }
SlotCalculator SlotTable(M->getParent(), true);
AssemblyWriter W(o, SlotTable);
W.write(M);
}
void WriteToAssembly(const BasicBlock *BB, ostream &o) {
if (BB == 0) { o << "<null> basic block\n"; return; }
SlotCalculator SlotTable(BB->getParent(), true);
AssemblyWriter W(o, SlotTable);
W.write(BB);
}
void WriteToAssembly(const ConstPoolVal *CPV, ostream &o) {
if (CPV == 0) { o << "<null> constant pool value\n"; return; }
SlotCalculator *SlotTable;
// A Constant pool value may have a parent that is either a method or a
// module. Untangle this now...
//
if (const Method *Meth = CPV->getParentV()->castMethod()) {
SlotTable = new SlotCalculator(Meth, true);
} else {
SlotTable =
new SlotCalculator(CPV->getParentV()->castModuleAsserting(), true);
}
AssemblyWriter W(o, *SlotTable);
W.write(CPV);
delete SlotTable;
}
void WriteToAssembly(const Instruction *I, ostream &o) {
if (I == 0) { o << "<null> instruction\n"; return; }
SlotCalculator SlotTable(I->getParent() ? I->getParent()->getParent() : 0,
true);
AssemblyWriter W(o, SlotTable);
W.write(I);
}
<commit_msg>* Fix bugs<commit_after>//===-- Writer.cpp - Library for Printing VM assembly files ------*- C++ -*--=//
//
// This library implements the functionality defined in llvm/Assembly/Writer.h
//
// This library uses the Analysis library to figure out offsets for
// variables in the method tables...
//
// TODO: print out the type name instead of the full type if a particular type
// is in the symbol table...
//
//===----------------------------------------------------------------------===//
#include "llvm/Assembly/Writer.h"
#include "llvm/Analysis/SlotCalculator.h"
#include "llvm/Module.h"
#include "llvm/Method.h"
#include "llvm/BasicBlock.h"
#include "llvm/ConstPoolVals.h"
#include "llvm/iOther.h"
#include "llvm/iMemory.h"
void DebugValue(const Value *V) {
cerr << V << endl;
}
// WriteAsOperand - Write the name of the specified value out to the specified
// ostream. This can be useful when you just want to print int %reg126, not the
// whole instruction that generated it.
//
ostream &WriteAsOperand(ostream &Out, const Value *V, bool PrintType,
bool PrintName, SlotCalculator *Table) {
if (PrintType)
Out << " " << V->getType();
if (V->hasName() && PrintName) {
Out << " %" << V->getName();
} else {
if (const ConstPoolVal *CPV = V->castConstant()) {
Out << " " << CPV->getStrValue();
} else {
int Slot;
if (Table) {
Slot = Table->getValSlot(V);
} else {
if (const Type *Ty = V->castType()) {
return Out << " " << Ty;
} else if (const MethodArgument *MA = V->castMethodArgument()) {
Table = new SlotCalculator(MA->getParent(), true);
} else if (const Instruction *I = V->castInstruction()) {
Table = new SlotCalculator(I->getParent()->getParent(), true);
} else if (const BasicBlock *BB = V->castBasicBlock()) {
Table = new SlotCalculator(BB->getParent(), true);
} else if (const Method *Meth = V->castMethod()) {
Table = new SlotCalculator(Meth, true);
} else if (const Module *Mod = V->castModule()) {
Table = new SlotCalculator(Mod, true);
} else {
return Out << "BAD VALUE TYPE!";
}
Slot = Table->getValSlot(V);
delete Table;
}
if (Slot >= 0) Out << " %" << Slot;
else if (PrintName)
Out << "<badref>"; // Not embeded into a location?
}
}
return Out;
}
class AssemblyWriter : public ModuleAnalyzer {
ostream &Out;
SlotCalculator &Table;
public:
inline AssemblyWriter(ostream &o, SlotCalculator &Tab) : Out(o), Table(Tab) {
}
inline void write(const Module *M) { processModule(M); }
inline void write(const Method *M) { processMethod(M); }
inline void write(const BasicBlock *BB) { processBasicBlock(BB); }
inline void write(const Instruction *I) { processInstruction(I); }
inline void write(const ConstPoolVal *CPV) { processConstant(CPV); }
protected:
virtual bool visitMethod(const Method *M);
virtual bool processConstPool(const ConstantPool &CP, bool isMethod);
virtual bool processConstant(const ConstPoolVal *CPV);
virtual bool processMethod(const Method *M);
virtual bool processMethodArgument(const MethodArgument *MA);
virtual bool processBasicBlock(const BasicBlock *BB);
virtual bool processInstruction(const Instruction *I);
private :
void writeOperand(const Value *Op, bool PrintType, bool PrintName = true);
};
// visitMethod - This member is called after the above two steps, visting each
// method, because they are effectively values that go into the constant pool.
//
bool AssemblyWriter::visitMethod(const Method *M) {
return false;
}
bool AssemblyWriter::processConstPool(const ConstantPool &CP, bool isMethod) {
// Done printing arguments...
if (isMethod) {
const MethodType *MT = CP.getParentV()->castMethodAsserting()->getType()->
isMethodType();
if (MT->isVarArg()) {
if (MT->getParamTypes().size())
Out << ", ";
Out << "..."; // Output varargs portion of signature!
}
Out << ")\n";
}
ModuleAnalyzer::processConstPool(CP, isMethod);
if (isMethod) {
if (!CP.getParentV()->castMethodAsserting()->isExternal())
Out << "begin";
} else {
Out << "implementation\n";
}
return false;
}
// processConstant - Print out a constant pool entry...
//
bool AssemblyWriter::processConstant(const ConstPoolVal *CPV) {
if (!CPV->hasName())
return false; // Don't print out unnamed constants, they will be inlined
// Print out name...
Out << "\t%" << CPV->getName() << " = ";
// Print out the constant type...
Out << CPV->getType();
// Write the value out now...
writeOperand(CPV, false, false);
if (!CPV->hasName() && CPV->getType() != Type::VoidTy) {
int Slot = Table.getValSlot(CPV); // Print out the def slot taken...
Out << "\t\t; <" << CPV->getType() << ">:";
if (Slot >= 0) Out << Slot;
else Out << "<badref>";
}
Out << endl;
return false;
}
// processMethod - Process all aspects of a method.
//
bool AssemblyWriter::processMethod(const Method *M) {
// Print out the return type and name...
Out << "\n" << (M->isExternal() ? "declare " : "")
<< M->getReturnType() << " \"" << M->getName() << "\"(";
Table.incorporateMethod(M);
ModuleAnalyzer::processMethod(M);
Table.purgeMethod();
if (!M->isExternal())
Out << "end\n";
return false;
}
// processMethodArgument - This member is called for every argument that
// is passed into the method. Simply print it out
//
bool AssemblyWriter::processMethodArgument(const MethodArgument *Arg) {
// Insert commas as we go... the first arg doesn't get a comma
if (Arg != Arg->getParent()->getArgumentList().front()) Out << ", ";
// Output type...
Out << Arg->getType();
// Output name, if available...
if (Arg->hasName())
Out << " %" << Arg->getName();
else if (Table.getValSlot(Arg) < 0)
Out << "<badref>";
return false;
}
// processBasicBlock - This member is called for each basic block in a methd.
//
bool AssemblyWriter::processBasicBlock(const BasicBlock *BB) {
if (BB->hasName()) { // Print out the label if it exists...
Out << "\n" << BB->getName() << ":";
} else {
int Slot = Table.getValSlot(BB);
Out << "\n; <label>:";
if (Slot >= 0)
Out << Slot; // Extra newline seperates out label's
else
Out << "<badref>";
}
Out << "\t\t\t\t\t;[#uses=" << BB->use_size() << "]\n"; // Output # uses
ModuleAnalyzer::processBasicBlock(BB);
return false;
}
// processInstruction - This member is called for each Instruction in a methd.
//
bool AssemblyWriter::processInstruction(const Instruction *I) {
Out << "\t";
// Print out name if it exists...
if (I && I->hasName())
Out << "%" << I->getName() << " = ";
// Print out the opcode...
Out << I->getOpcodeName();
// Print out the type of the operands...
const Value *Operand = I->getNumOperands() ? I->getOperand(0) : 0;
// Special case conditional branches to swizzle the condition out to the front
if (I->getOpcode() == Instruction::Br && I->getNumOperands() > 1) {
writeOperand(I->getOperand(2), true);
Out << ",";
writeOperand(Operand, true);
Out << ",";
writeOperand(I->getOperand(1), true);
} else if (I->getOpcode() == Instruction::Switch) {
// Special case switch statement to get formatting nice and correct...
writeOperand(Operand , true); Out << ",";
writeOperand(I->getOperand(1), true); Out << " [";
for (unsigned op = 2, Eop = I->getNumOperands(); op < Eop; op += 2) {
Out << "\n\t\t";
writeOperand(I->getOperand(op ), true); Out << ",";
writeOperand(I->getOperand(op+1), true);
}
Out << "\n\t]";
} else if (I->isPHINode()) {
Out << " " << Operand->getType();
Out << " ["; writeOperand(Operand, false); Out << ",";
writeOperand(I->getOperand(1), false); Out << " ]";
for (unsigned op = 2, Eop = I->getNumOperands(); op < Eop; op += 2) {
Out << ", [";
writeOperand(I->getOperand(op ), false); Out << ",";
writeOperand(I->getOperand(op+1), false); Out << " ]";
}
} else if (I->getOpcode() == Instruction::Ret && !Operand) {
Out << " void";
} else if (I->getOpcode() == Instruction::Call) {
writeOperand(Operand, true);
Out << "(";
if (I->getNumOperands() > 1) writeOperand(I->getOperand(1), true);
for (unsigned op = 2, Eop = I->getNumOperands(); op < Eop; ++op) {
Out << ",";
writeOperand(I->getOperand(op), true);
}
Out << " )";
} else if (I->getOpcode() == Instruction::Malloc ||
I->getOpcode() == Instruction::Alloca) {
Out << " " << ((const PointerType*)I->getType())->getValueType();
if (I->getNumOperands()) {
Out << ",";
writeOperand(I->getOperand(0), true);
}
} else if (I->getOpcode() == Instruction::Cast) {
writeOperand(Operand, true);
Out << " to " << I->getType();
} else if (Operand) { // Print the normal way...
// PrintAllTypes - Instructions who have operands of all the same type
// omit the type from all but the first operand. If the instruction has
// different type operands (for example br), then they are all printed.
bool PrintAllTypes = false;
const Type *TheType = Operand->getType();
for (unsigned i = 1, E = I->getNumOperands(); i != E; ++i) {
Operand = I->getOperand(i);
if (Operand->getType() != TheType) {
PrintAllTypes = true; // We have differing types! Print them all!
break;
}
}
if (!PrintAllTypes)
Out << " " << I->getOperand(0)->getType();
for (unsigned i = 0, E = I->getNumOperands(); i != E; ++i) {
if (i) Out << ",";
writeOperand(I->getOperand(i), PrintAllTypes);
}
}
// Print a little comment after the instruction indicating which slot it
// occupies.
//
if (I->getType() != Type::VoidTy) {
Out << "\t\t; <" << I->getType() << ">";
if (!I->hasName()) {
int Slot = Table.getValSlot(I); // Print out the def slot taken...
if (Slot >= 0) Out << ":" << Slot;
else Out << ":<badref>";
}
Out << "\t[#uses=" << I->use_size() << "]"; // Output # uses
}
Out << endl;
return false;
}
void AssemblyWriter::writeOperand(const Value *Operand, bool PrintType,
bool PrintName) {
WriteAsOperand(Out, Operand, PrintType, PrintName, &Table);
}
//===----------------------------------------------------------------------===//
// External Interface declarations
//===----------------------------------------------------------------------===//
void WriteToAssembly(const Module *M, ostream &o) {
if (M == 0) { o << "<null> module\n"; return; }
SlotCalculator SlotTable(M, true);
AssemblyWriter W(o, SlotTable);
W.write(M);
}
void WriteToAssembly(const Method *M, ostream &o) {
if (M == 0) { o << "<null> method\n"; return; }
SlotCalculator SlotTable(M->getParent(), true);
AssemblyWriter W(o, SlotTable);
W.write(M);
}
void WriteToAssembly(const BasicBlock *BB, ostream &o) {
if (BB == 0) { o << "<null> basic block\n"; return; }
SlotCalculator SlotTable(BB->getParent(), true);
AssemblyWriter W(o, SlotTable);
W.write(BB);
}
void WriteToAssembly(const ConstPoolVal *CPV, ostream &o) {
if (CPV == 0) { o << "<null> constant pool value\n"; return; }
WriteAsOperand(o, CPV, true, true, 0);
}
void WriteToAssembly(const Instruction *I, ostream &o) {
if (I == 0) { o << "<null> instruction\n"; return; }
SlotCalculator SlotTable(I->getParent() ? I->getParent()->getParent() : 0,
true);
AssemblyWriter W(o, SlotTable);
W.write(I);
}
<|endoftext|> |
<commit_before>#include "dxLog.h"
#include "dxLog_helper.h"
#include "mongoLog.h"
using namespace std;
namespace DXLog {
class MongoDbLog : public UnixDGRAMReader {
private:
dx::JSON schema;
deque<string> que;
int maxQueueSize;
string socketPath, messagePath, hostname;
bool active;
// ensure log mongodb indexes based on log schema
bool ensureIndex(string &errMsg) {
for (dx::JSON::object_iterator it = schema.object_begin(); it != schema.object_end(); ++it) {
string key = it->first;
dx::JSON index = it->second["mongodb"]["indexes"];
for (int i = 0; i < index.size(); i++) {
BSONObjBuilder b;
for(dx::JSON::object_iterator it2 = index[i].object_begin(); it2 != index[i].object_end(); ++it2)
b.append(it2->first, int(it2->second));
if (! MongoDriver::ensureIndex(b.obj(), key, errMsg)) return false;
}
}
return true;
}
// write own log message to rsyslog
void rsysLog(int level, const string &msg) {
string eMsg;
#pragma omp critical
SendMessage2Rsyslog(8, level, "DNAnexusLog", msg, msg.size() + 1, eMsg);
}
// send message to mongodb
bool sendMessage(dx::JSON &data, string &errMsg) {
if (! ValidateLogData(schema, data, errMsg)) return false;
if (! data.has("hostname")) data["hostname"] = hostname;
dx::JSON columns = schema[data["source"].get<string>()]["mongodb"]["columns"];
BSONObjBuilder b;
for(dx::JSON::object_iterator it = columns.object_begin(); it != columns.object_end(); ++it) {
string key = it->first, typ = it->second.get<string>();
if (! data.has(key)) continue;
if (typ.compare("string") == 0) {
b.append(key, data[key].get<string>());
} else if (typ.compare("int") == 0) {
b.append(key, int(data[key]));
} else if (typ.compare("int64") == 0) {
b.append(key, int64(data[key]));
} else if (typ.compare("boolean") == 0) {
b.append(key, bool(data[key]));
} else if (typ.compare("double") == 0) {
b.append(key, double(data[key]));
}
}
return MongoDriver::insert(b.obj(), data["source"].get<string>(), errMsg);
};
void processQueue() {
string errMsg;
while (true) {
if (que.size() > 0) {
bool succeed = false;
try {
dx::JSON data = dx::JSON::parse(que.front());
for (int i = 0; i < 10; i++) {
if ((succeed = sendMessage(data, errMsg))) break;
if (i == 0) rsysLog(3, errMsg + " Msg: " + que.front());
sleep(5);
}
} catch (std::exception &e) {
rsysLog(3, string(e.what()) + " Msg: " + que.front());
}
if (! succeed){
#pragma omp critical
StoreMsgLocal(messagePath, que.front());
}
#pragma omp critical
que.pop_front();
} else {
if (! active) return;
sleep(1);
}
}
};
bool processMsg() {
{
if (que.size() < maxQueueSize) {
que.push_back(string(buffer));
} else {
#pragma omp critical
StoreMsgLocal(messagePath, string(buffer));
rsysLog(3, "Msg Queue Full, drop message " + string(buffer));
}
}
return false;
};
public:
MongoDbLog(const dx::JSON &conf) : UnixDGRAMReader(1000 + int(conf["maxMsgSize"])) {
schema = readJSON(conf["schema"].get<string>());
ValidateLogSchema(schema);
socketPath = conf["socketPath"].get<string>();
maxQueueSize = (conf.has("maxQueueSize")) ? int(conf["maxQueueSize"]): 10000;
messagePath = (conf.has("messagePath")) ? conf["messagePath"].get<string>() : "/var/log/dnanexusLocal/DB";
if (conf.has("mongoServer")) DXLog::MongoDriver::setServer(conf["mongoServer"].get<string>());
if (conf.has("database")) DXLog::MongoDriver::setDB(conf["database"].get<string>());
hostname = getHostname();
};
void process() {
que.clear();
active = true;
string errMsg;
if (! ensureIndex(errMsg)) {
rsysLog(3, errMsg);
cerr << errMsg << endl;
// return;
}
getHostname();
#pragma omp parallel sections
{
string errMsg;
unlink(socketPath.c_str());
run(socketPath, errMsg);
rsysLog(3, errMsg);
cerr << errMsg << endl;
active = false;
#pragma omp section
processQueue();
}
};
};
};
int main(int argc, char **argv) {
if (argc < 2) {
cerr << "Usage: dxDbLog configFile\n";
exit(1);
}
try {
dx::JSON conf = DXLog::readJSON(argv[1]);
if (! conf.has("maxMsgSize")) conf["maxMsgSize"] = 2000;
if (! conf.has("schema")) DXLog::throwString("log schema is not specified");
if (! conf.has("socketPath")) DXLog::throwString("socketPath is not specified");
DXLog::MongoDbLog a(conf);
a.process();
} catch (const string &msg) {
cout << msg << endl;
exit(1);
} catch (std::exception &e) {
cout << string("JSONException: ") + e.what() << endl;
exit(1);
}
exit(0);
}
<commit_msg>add start message<commit_after>#include "dxLog.h"
#include "dxLog_helper.h"
#include "mongoLog.h"
using namespace std;
namespace DXLog {
class MongoDbLog : public UnixDGRAMReader {
private:
dx::JSON schema;
deque<string> que;
int maxQueueSize;
string socketPath, messagePath, hostname;
bool active;
// ensure log mongodb indexes based on log schema
bool ensureIndex(string &errMsg) {
for (dx::JSON::object_iterator it = schema.object_begin(); it != schema.object_end(); ++it) {
string key = it->first;
dx::JSON index = it->second["mongodb"]["indexes"];
for (int i = 0; i < index.size(); i++) {
BSONObjBuilder b;
for(dx::JSON::object_iterator it2 = index[i].object_begin(); it2 != index[i].object_end(); ++it2)
b.append(it2->first, int(it2->second));
if (! MongoDriver::ensureIndex(b.obj(), key, errMsg)) return false;
}
}
return true;
}
// write own log message to rsyslog
void rsysLog(int level, const string &msg) {
string eMsg;
#pragma omp critical
SendMessage2Rsyslog(8, level, "DNAnexusLog", msg, msg.size() + 1, eMsg);
}
// send message to mongodb
bool sendMessage(dx::JSON &data, string &errMsg) {
if (! ValidateLogData(schema, data, errMsg)) return false;
if (! data.has("hostname")) data["hostname"] = hostname;
dx::JSON columns = schema[data["source"].get<string>()]["mongodb"]["columns"];
BSONObjBuilder b;
for(dx::JSON::object_iterator it = columns.object_begin(); it != columns.object_end(); ++it) {
string key = it->first, typ = it->second.get<string>();
if (! data.has(key)) continue;
if (typ.compare("string") == 0) {
b.append(key, data[key].get<string>());
} else if (typ.compare("int") == 0) {
b.append(key, int(data[key]));
} else if (typ.compare("int64") == 0) {
b.append(key, int64(data[key]));
} else if (typ.compare("boolean") == 0) {
b.append(key, bool(data[key]));
} else if (typ.compare("double") == 0) {
b.append(key, double(data[key]));
}
}
return MongoDriver::insert(b.obj(), data["source"].get<string>(), errMsg);
};
void processQueue() {
string errMsg;
while (true) {
if (que.size() > 0) {
bool succeed = false;
try {
dx::JSON data = dx::JSON::parse(que.front());
for (int i = 0; i < 10; i++) {
if ((succeed = sendMessage(data, errMsg))) break;
if (i == 0) rsysLog(3, errMsg + " Msg: " + que.front());
sleep(5);
}
} catch (std::exception &e) {
rsysLog(3, string(e.what()) + " Msg: " + que.front());
}
if (! succeed){
#pragma omp critical
StoreMsgLocal(messagePath, que.front());
}
#pragma omp critical
que.pop_front();
} else {
if (! active) return;
sleep(1);
}
}
};
bool processMsg() {
{
if (que.size() < maxQueueSize) {
que.push_back(string(buffer));
} else {
#pragma omp critical
StoreMsgLocal(messagePath, string(buffer));
rsysLog(3, "Msg Queue Full, drop message " + string(buffer));
}
}
return false;
};
public:
MongoDbLog(const dx::JSON &conf) : UnixDGRAMReader(1000 + int(conf["maxMsgSize"])) {
schema = readJSON(conf["schema"].get<string>());
ValidateLogSchema(schema);
socketPath = conf["socketPath"].get<string>();
maxQueueSize = (conf.has("maxQueueSize")) ? int(conf["maxQueueSize"]): 10000;
messagePath = (conf.has("messagePath")) ? conf["messagePath"].get<string>() : "/var/log/dnanexusLocal/DB";
if (conf.has("mongoServer")) DXLog::MongoDriver::setServer(conf["mongoServer"].get<string>());
if (conf.has("database")) DXLog::MongoDriver::setDB(conf["database"].get<string>());
hostname = getHostname();
};
void process() {
que.clear();
active = true;
string errMsg;
if (! ensureIndex(errMsg)) {
rsysLog(3, errMsg);
cerr << errMsg << endl;
// return;
}
getHostname();
#pragma omp parallel sections
{
string errMsg;
unlink(socketPath.c_str());
run(socketPath, errMsg);
rsysLog(3, errMsg);
cerr << errMsg << endl;
active = false;
#pragma omp section
processQueue();
}
};
};
};
int main(int argc, char **argv) {
if (argc < 2) {
cerr << "Usage: dxDbLog configFile\n";
exit(1);
}
try {
dx::JSON conf = DXLog::readJSON(argv[1]);
if (! conf.has("maxMsgSize")) conf["maxMsgSize"] = 2000;
if (! conf.has("schema")) DXLog::throwString("log schema is not specified");
if (! conf.has("socketPath")) DXLog::throwString("socketPath is not specified");
DXLog::MongoDbLog a(conf);
cout << "listen to socket " + conf["socketPath"].get<string>() << endl;
a.process();
} catch (const string &msg) {
cout << msg << endl;
exit(1);
} catch (std::exception &e) {
cout << string("JSONException: ") + e.what() << endl;
exit(1);
}
exit(0);
}
<|endoftext|> |
<commit_before>#ifndef SILICIUM_REACTIVE_TRANSFORM_HPP
#define SILICIUM_REACTIVE_TRANSFORM_HPP
#include <silicium/observable/observer.hpp>
#include <silicium/config.hpp>
#include <silicium/detail/proper_value_function.hpp>
#include <type_traits>
#include <utility>
#include <cassert>
#include <functional>
#include <boost/config.hpp>
namespace Si
{
template <class Transform, class Original>
struct transformation
: private observer<typename Original::element_type>
{
typedef typename std::result_of<Transform (typename Original::element_type)>::type element_type;
typedef typename Original::element_type from_type;
transformation()
: receiver(nullptr)
{
}
explicit transformation(Transform transform, Original original)
: transform(std::move(transform))
, original(std::move(original))
, receiver(nullptr)
{
}
#if !SILICIUM_COMPILER_GENERATES_MOVES
transformation(transformation &&other)
: transform(std::move(other.transform))
, original(std::move(other.original))
, receiver(std::move(other.receiver))
{
}
transformation &operator = (transformation &&other)
{
//TODO: exception safety
transform = std::move(other.transform);
original = std::move(other.original);
receiver = std::move(other.receiver);
return *this;
}
#else
transformation(transformation &&other) = default;
transformation &operator = (transformation &&other) = default;
#endif
void async_get_one(observer<element_type> &receiver)
{
assert(!this->receiver);
this->receiver = &receiver;
original.async_get_one(*this);
}
private:
typedef typename detail::proper_value_function<
Transform,
element_type,
from_type
>::type proper_transform;
proper_transform transform; //TODO empty base optimization
Original original;
observer<element_type> *receiver;
virtual void got_element(from_type value) SILICIUM_OVERRIDE
{
assert(receiver);
auto *receiver_copy = receiver;
receiver = nullptr;
receiver_copy->got_element(transform(std::move(value)));
}
virtual void ended() SILICIUM_OVERRIDE
{
assert(receiver);
auto *receiver_copy = receiver;
receiver = nullptr;
receiver_copy->ended();
}
SILICIUM_DELETED_FUNCTION(transformation(transformation const &))
SILICIUM_DELETED_FUNCTION(transformation &operator = (transformation const &))
};
template <class Transform, class Original>
auto transform(Original &&original, Transform &&transform) -> transformation<
typename std::decay<Transform>::type,
typename std::decay<Original>::type
>
{
return transformation<
typename std::decay<Transform>::type,
typename std::decay<Original>::type
>(std::forward<Transform>(transform), std::forward<Original>(original));
}
}
#endif
<commit_msg>templatize the transformation parameter<commit_after>#ifndef SILICIUM_REACTIVE_TRANSFORM_HPP
#define SILICIUM_REACTIVE_TRANSFORM_HPP
#include <silicium/observable/observer.hpp>
#include <silicium/config.hpp>
#include <silicium/detail/proper_value_function.hpp>
#include <type_traits>
#include <utility>
#include <cassert>
#include <functional>
#include <boost/config.hpp>
namespace Si
{
template <class Transform, class Original>
struct transformation
: private observer<typename Original::element_type>
{
typedef typename std::result_of<Transform (typename Original::element_type)>::type element_type;
typedef typename Original::element_type from_type;
transformation()
: receiver(nullptr)
{
}
template <class Transform2>
explicit transformation(Transform2 &&transform, Original original)
: transform(std::forward<Transform2>(transform))
, original(std::move(original))
, receiver(nullptr)
{
}
#if !SILICIUM_COMPILER_GENERATES_MOVES
transformation(transformation &&other)
: transform(std::move(other.transform))
, original(std::move(other.original))
, receiver(std::move(other.receiver))
{
}
transformation &operator = (transformation &&other)
{
//TODO: exception safety
transform = std::move(other.transform);
original = std::move(other.original);
receiver = std::move(other.receiver);
return *this;
}
#else
transformation(transformation &&other) = default;
transformation &operator = (transformation &&other) = default;
#endif
void async_get_one(observer<element_type> &receiver)
{
assert(!this->receiver);
this->receiver = &receiver;
original.async_get_one(*this);
}
private:
typedef typename detail::proper_value_function<
Transform,
element_type,
from_type
>::type proper_transform;
proper_transform transform; //TODO empty base optimization
Original original;
observer<element_type> *receiver;
virtual void got_element(from_type value) SILICIUM_OVERRIDE
{
assert(receiver);
auto *receiver_copy = receiver;
receiver = nullptr;
receiver_copy->got_element(transform(std::move(value)));
}
virtual void ended() SILICIUM_OVERRIDE
{
assert(receiver);
auto *receiver_copy = receiver;
receiver = nullptr;
receiver_copy->ended();
}
SILICIUM_DELETED_FUNCTION(transformation(transformation const &))
SILICIUM_DELETED_FUNCTION(transformation &operator = (transformation const &))
};
template <class Transform, class Original>
auto transform(Original &&original, Transform &&transform) -> transformation<
typename std::decay<Transform>::type,
typename std::decay<Original>::type
>
{
return transformation<
typename std::decay<Transform>::type,
typename std::decay<Original>::type
>(std::forward<Transform>(transform), std::forward<Original>(original));
}
}
#endif
<|endoftext|> |
<commit_before>/*
Copyright (c) 2019, Michael Fisher <mfisher@kushview.net>
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
#pragma once
#include <lvtk/lvtk.hpp>
#include <lv2/dynmanifest/dynmanifest.h>
#include <sstream>
#include <cstdio>
namespace lvtk {
class DynManifest
{
public:
DynManifest() { }
virtual ~DynManifest() { }
virtual void subjects (StringArray& lines) =0;
virtual void get_data (const String& uri, StringArray& lines) =0;
static void write_lines (const StringArray& lines, FILE* fp) {
for (const auto& line : lines) {
fwrite (line.c_str(), sizeof(char), line.size(), fp);
}
}
};
DynManifest* create_dyn_manifest();
}
extern "C" {
LV2_SYMBOL_EXPORT
int lv2_dyn_manifest_open (LV2_Dyn_Manifest_Handle *handle, const LV2_Feature *const *features)
{
auto* manifest = lvtk::create_dyn_manifest();
*handle = static_cast<LV2_Dyn_Manifest_Handle> (manifest);
return 0;
}
LV2_SYMBOL_EXPORT
int lv2_dyn_manifest_get_subjects (LV2_Dyn_Manifest_Handle handle, FILE *fp)
{
auto* manifest = static_cast<lvtk::DynManifest*> (handle);
lvtk::StringArray lines;
manifest->subjects (lines);
lvtk::DynManifest::write_lines (lines, fp);
return 0;
}
LV2_SYMBOL_EXPORT
int lv2_dyn_manifest_get_data (LV2_Dyn_Manifest_Handle handle, FILE *fp, const char *uri)
{
auto* manifest = static_cast<lvtk::DynManifest*> (handle);
lvtk::StringArray lines;
manifest->get_data (uri, lines);
lvtk::DynManifest::write_lines (lines, fp);
return 0;
}
LV2_SYMBOL_EXPORT
void lv2_dyn_manifest_close (LV2_Dyn_Manifest_Handle handle)
{
delete static_cast<DynManifest*> (handle);
}
}
<commit_msg>Update dynmanifest<commit_after>/*
Copyright (c) 2019, Michael Fisher <mfisher@kushview.net>
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
#pragma once
#include <lvtk/lvtk.hpp>
#include <lv2/dynmanifest/dynmanifest.h>
#include <sstream>
#include <cstdio>
namespace lvtk {
class DynManifest
{
public:
DynManifest() { }
virtual ~DynManifest() { }
virtual void subjects (StringArray& lines) =0;
virtual void get_data (const String& uri, StringArray& lines) =0;
static void write_lines (const StringArray& lines, FILE* fp) {
for (const auto& l : lines) {
std::string line = l + "\n";
fwrite (line.c_str(), sizeof(char), line.size(), fp);
}
}
};
}
lvtk::DynManifest* lvtk_create_dyn_manifest();
extern "C" {
LV2_SYMBOL_EXPORT
int lv2_dyn_manifest_open (LV2_Dyn_Manifest_Handle *handle, const LV2_Feature *const *features)
{
auto* manifest = lvtk_create_dyn_manifest();
*handle = static_cast<LV2_Dyn_Manifest_Handle> (manifest);
return 0;
}
LV2_SYMBOL_EXPORT
int lv2_dyn_manifest_get_subjects (LV2_Dyn_Manifest_Handle handle, FILE *fp)
{
auto* manifest = static_cast<lvtk::DynManifest*> (handle);
lvtk::StringArray lines;
manifest->subjects (lines);
lvtk::DynManifest::write_lines (lines, fp);
return 0;
}
LV2_SYMBOL_EXPORT
int lv2_dyn_manifest_get_data (LV2_Dyn_Manifest_Handle handle, FILE *fp, const char *uri)
{
auto* manifest = static_cast<lvtk::DynManifest*> (handle);
lvtk::StringArray lines;
manifest->get_data (uri, lines);
lvtk::DynManifest::write_lines (lines, fp);
return 0;
}
LV2_SYMBOL_EXPORT
void lv2_dyn_manifest_close (LV2_Dyn_Manifest_Handle handle)
{
delete static_cast<lvtk::DynManifest*> (handle);
}
}
<|endoftext|> |
<commit_before>// definition of necessary units
static const double cm=1;
static const double cm3=cm*cm*cm;
static const double volt=1;
static const double C=1; // Coulomb
static const double e=1.6e-19*C; // electron charge
static const double epsilon0=8.854187817e-14*C/volt/cm; // vacuum permittivity
// https://link.springer.com/chapter/10.1007/10832182_519
static const double epsilon=15.8; // Ge dielectric constant
//______________________________________________________________________________
// (V'(r)r)'/r=a, https://www.wolframalpha.com/input/?i=(V%27(r)r)%27%2Fr%3Da
double V(double *coordinates, double *parameters)
{
double r = coordinates[0];// there is no phi and z dependence
double ri= parameters[0]; // inner radius
double ro= parameters[1]; // outer radius
double vi= parameters[2]; // inner voltage
double vo= parameters[3]; // outer voltage
double rho=parameters[4]; // space charge density [C/cm3]
double a =-rho/epsilon0/epsilon;
double c1= (vo-vi - a*(ro*ro-ri*ri)/4)/log(ro/ri);
double c2= vo*log(ri)-vi*log(ro) - a*(ro*ro*log(ri)-ri*ri*log(ro))/4;
c2/=log(ri)-log(ro);
return a*r*r/4 + c1*log(r) + c2;
}
//______________________________________________________________________________
// E=-V'
double E(double *coordinates, double *parameters)
{
double r = coordinates[0];
double ri= parameters[0];
double ro= parameters[1];
double vi= parameters[2];
double vo= parameters[3];
double rho=parameters[4];
double a =-rho/epsilon0/epsilon;
double c1= (vo-vi - a*(ro*ro-ri*ri)/4)/log(ro/ri);
return -a*r/2 - c1/r;
}
//______________________________________________________________________________
//
const int n=6; // number of curves
double rho[n]={-3.5e10*e/cm3, -1.5e10*e/cm3, 0,
1.5e10*e/cm3, 3.5e10*e/cm3, 6e10*e/cm3};
void drawV()
{
TLegend *l = new TLegend(0.75,0.55,0.98,0.98);
l->SetHeader("Impurity [cm^{-3}]");
TF1 *fV[n]={0};
double ri[n], ro[n], vi[n], vo[n]={0};
for (int i=0; i<n; i++) {
ri[i] = 0.25*cm;
ro[i] = 1.00*cm;
vi[i] = 2000*volt;
fV[i] = new TF1(Form("fV%d",i), V, ri[i], ro[i], 5);
fV[i]->SetParameters(ri[i],ro[i],vi[i],vo[i],rho[i]);
fV[i]->SetLineStyle(i+1);
fV[i]->SetLineColor(i+1);
if (i+1==5) fV[i]->SetLineColor(28); // yellow -> brown
if (i==0) fV[i]->Draw();
else fV[i]->Draw("same");
// net impurity concentration = - rho/e
l->AddEntry(fV[i],Form("%8.1e",-rho[i]/e*cm3),"l");
}
fV[0]->SetTitle("");
fV[0]->GetXaxis()->SetTitle("Radius [cm]");
fV[0]->GetYaxis()->SetTitle("Voltage [V]");
l->Draw();
gPad->Print("Vr.png");
}
//______________________________________________________________________________
//
void drawE()
{
TCanvas *c = new TCanvas;
TLegend *l = new TLegend(0.75,0.55,0.98,0.98);
l->SetHeader("Impurity [cm^{-3}]");
TF1 *fE[n]={0};
double ri[n], ro[n], vi[n], vo[n]={0};
for (int i=0; i<n; i++) {
ri[i] = 0.25*cm;
ro[i] = 1.00*cm;
vi[i] = 2000*volt;
fE[i] = new TF1(Form("fE%d",i), E, ri[i], ro[i], 5);
fE[i]->SetParameters(ri[i],ro[i],vi[i],vo[i],rho[i]);
fE[i]->SetLineStyle(i+1);
fE[i]->SetLineColor(i+1);
if (i+1==5) fE[i]->SetLineColor(28); // yellow -> brown
if (i==0) fE[i]->Draw();
else fE[i]->Draw("same");
// net impurity concentration = - rho/e
l->AddEntry(fE[i],Form("%8.1e",-rho[i]/e*cm3),"l");
}
fE[0]->SetTitle("");
fE[0]->GetXaxis()->SetTitle("Radius [cm]");
fE[0]->GetYaxis()->SetTitle("Electric field [V/cm]");
l->Draw();
c->Print("Er.png");
}
//______________________________________________________________________________
//
void coaxial()
{
gROOT->SetStyle("Plain"); // pick up a good default drawing style
// modify the default style
gStyle->SetLegendBorderSize(0);
gStyle->SetLegendFont(132);
gStyle->SetLabelFont(132,"XY");
gStyle->SetTitleFont(132,"XY");
gStyle->SetLabelSize(0.05,"XY");
gStyle->SetTitleSize(0.05,"XY");
gStyle->SetTitleOffset(1.2,"Y");
gStyle->SetPadRightMargin(0.01);
gStyle->SetPadLeftMargin(0.12);
gStyle->SetPadTopMargin(0.01);
gStyle->SetPadBottomMargin(0.11);
drawV();
drawE();
}
<commit_msg>changed output file names<commit_after>// definition of necessary units
static const double cm=1;
static const double cm3=cm*cm*cm;
static const double volt=1;
static const double C=1; // Coulomb
static const double e=1.6e-19*C; // electron charge
static const double epsilon0=8.854187817e-14*C/volt/cm; // vacuum permittivity
// https://link.springer.com/chapter/10.1007/10832182_519
static const double epsilon=15.8; // Ge dielectric constant
//______________________________________________________________________________
// (V'(r)r)'/r=a, https://www.wolframalpha.com/input/?i=(V%27(r)r)%27%2Fr%3Da
double V(double *coordinates, double *parameters)
{
double r = coordinates[0];// there is no phi and z dependence
double ri= parameters[0]; // inner radius
double ro= parameters[1]; // outer radius
double vi= parameters[2]; // inner voltage
double vo= parameters[3]; // outer voltage
double rho=parameters[4]; // space charge density [C/cm3]
double a =-rho/epsilon0/epsilon;
double c1= (vo-vi - a*(ro*ro-ri*ri)/4)/log(ro/ri);
double c2= vo*log(ri)-vi*log(ro) - a*(ro*ro*log(ri)-ri*ri*log(ro))/4;
c2/=log(ri)-log(ro);
return a*r*r/4 + c1*log(r) + c2;
}
//______________________________________________________________________________
// E=-V'
double E(double *coordinates, double *parameters)
{
double r = coordinates[0];
double ri= parameters[0];
double ro= parameters[1];
double vi= parameters[2];
double vo= parameters[3];
double rho=parameters[4];
double a =-rho/epsilon0/epsilon;
double c1= (vo-vi - a*(ro*ro-ri*ri)/4)/log(ro/ri);
return -a*r/2 - c1/r;
}
//______________________________________________________________________________
//
const int n=6; // number of curves
double rho[n]={-3.5e10*e/cm3, -1.5e10*e/cm3, 0,
1.5e10*e/cm3, 3.5e10*e/cm3, 6e10*e/cm3};
void drawV()
{
TLegend *l = new TLegend(0.75,0.55,0.98,0.98);
l->SetHeader("Impurity [cm^{-3}]");
TF1 *fV[n]={0};
double ri[n], ro[n], vi[n], vo[n]={0};
for (int i=0; i<n; i++) {
ri[i] = 0.25*cm;
ro[i] = 1.00*cm;
vi[i] = 2000*volt;
fV[i] = new TF1(Form("fV%d",i), V, ri[i], ro[i], 5);
fV[i]->SetParameters(ri[i],ro[i],vi[i],vo[i],rho[i]);
fV[i]->SetLineStyle(i+1);
fV[i]->SetLineColor(i+1);
if (i+1==5) fV[i]->SetLineColor(28); // yellow -> brown
if (i==0) fV[i]->Draw();
else fV[i]->Draw("same");
// net impurity concentration = - rho/e
l->AddEntry(fV[i],Form("%8.1e",-rho[i]/e*cm3),"l");
}
fV[0]->SetTitle("");
fV[0]->GetXaxis()->SetTitle("Radius [cm]");
fV[0]->GetYaxis()->SetTitle("Voltage [V]");
l->Draw();
gPad->Print("Vrho.png");
}
//______________________________________________________________________________
//
void drawE()
{
TCanvas *c = new TCanvas;
TLegend *l = new TLegend(0.75,0.55,0.98,0.98);
l->SetHeader("Impurity [cm^{-3}]");
TF1 *fE[n]={0};
double ri[n], ro[n], vi[n], vo[n]={0};
for (int i=0; i<n; i++) {
ri[i] = 0.25*cm;
ro[i] = 1.00*cm;
vi[i] = 2000*volt;
fE[i] = new TF1(Form("fE%d",i), E, ri[i], ro[i], 5);
fE[i]->SetParameters(ri[i],ro[i],vi[i],vo[i],rho[i]);
fE[i]->SetLineStyle(i+1);
fE[i]->SetLineColor(i+1);
if (i+1==5) fE[i]->SetLineColor(28); // yellow -> brown
if (i==0) fE[i]->Draw();
else fE[i]->Draw("same");
// net impurity concentration = - rho/e
l->AddEntry(fE[i],Form("%8.1e",-rho[i]/e*cm3),"l");
}
fE[0]->SetTitle("");
fE[0]->GetXaxis()->SetTitle("Radius [cm]");
fE[0]->GetYaxis()->SetTitle("Electric field [V/cm]");
l->Draw();
c->Print("Erho.png");
}
//______________________________________________________________________________
//
void coaxial()
{
gROOT->SetStyle("Plain"); // pick up a good default drawing style
// modify the default style
gStyle->SetLegendBorderSize(0);
gStyle->SetLegendFont(132);
gStyle->SetLabelFont(132,"XY");
gStyle->SetTitleFont(132,"XY");
gStyle->SetLabelSize(0.05,"XY");
gStyle->SetTitleSize(0.05,"XY");
gStyle->SetTitleOffset(1.2,"Y");
gStyle->SetPadRightMargin(0.01);
gStyle->SetPadLeftMargin(0.12);
gStyle->SetPadTopMargin(0.01);
gStyle->SetPadBottomMargin(0.11);
drawV();
drawE();
}
<|endoftext|> |
<commit_before>/******************************************************************************
* ____ _ _____ *
* / ___| / \ | ___| C++ *
* | | / _ \ | |_ Actor *
* | |___ / ___ \| _| Framework *
* \____/_/ \_|_| *
* *
* Copyright (C) 2011 - 2015 *
* Dominik Charousset <dominik.charousset (at) haw-hamburg.de> *
* *
* Distributed under the terms and conditions of the BSD 3-Clause License or *
* (at your option) under the terms and conditions of the Boost Software *
* License 1.0. See accompanying files LICENSE and LICENSE_ALTERNATIVE. *
* *
* If you did not receive a copy of the license files, see *
* http://opensource.org/licenses/BSD-3-Clause and *
* http://www.boost.org/LICENSE_1_0.txt. *
******************************************************************************/
#ifndef CAF_ATOM_HPP
#define CAF_ATOM_HPP
#include <string>
#include <functional>
#include <type_traits>
#include "caf/detail/atom_val.hpp"
namespace caf {
/// The value type of atoms.
enum class atom_value : uint64_t {
/// @cond PRIVATE
dirty_little_hack = 31337
/// @endcond
};
std::string to_string(const atom_value& x);
/// Creates an atom from given string literal.
template <size_t Size>
constexpr atom_value atom(char const (&str)[Size]) {
// last character is the NULL terminator
static_assert(Size <= 11, "only 10 characters are allowed");
return static_cast<atom_value>(detail::atom_val(str));
}
/// Lifts an `atom_value` to a compile-time constant.
template <atom_value V>
struct atom_constant {
constexpr atom_constant() {
// nop
}
/// Returns the wrapped value.
constexpr operator atom_value() const {
return V;
}
static constexpr uint64_t uint_value() {
return static_cast<uint64_t>(V);
}
/// Returns an instance *of this constant* (*not* an `atom_value`).
static const atom_constant value;
};
template <atom_value V>
std::string to_string(const atom_constant<V>&) {
return to_string(V);
}
template <atom_value V>
const atom_constant<V> atom_constant<V>::value = atom_constant<V>{};
/// Generic 'ADD' atom for request operations.
using add_atom = atom_constant<atom("ADD")>;
/// Generic 'GET' atom for request operations.
using get_atom = atom_constant<atom("GET")>;
/// Generic 'PUT' atom for request operations.
using put_atom = atom_constant<atom("PUT")>;
/// Generic 'UPDATE' atom, e.g., or signalizing updates in a key-value store.
using update_atom = atom_constant<atom("UPDATE")>;
/// Generic 'DELETE' atom for request operations.
using delete_atom = atom_constant<atom("DELETE")>;
/// Generic 'OK' atom for response messages.
using ok_atom = atom_constant<atom("OK")>;
/// Marker 'SYS' atom for prefixing messages to a forwarding chain
/// to address an otherwise transparent actor.
using sys_atom = atom_constant<atom("SYS")>;
/// Generic 'JOIN' atom, e.g., for signaling group subscriptions.
using join_atom = atom_constant<atom("JOIN")>;
/// Generic 'LEAVE' atom, e.g., for signaling group unsubscriptions.
using leave_atom = atom_constant<atom("LEAVE")>;
/// Generic 'FORWARD' atom, e.g., for signaling an actor that it
/// should drop the first element and forward the remainder to
/// a list of predefined receivers.
using forward_atom = atom_constant<atom("FORWARD")>;
/// Generic 'FLUSH' atom, e.g., used by `aout`.
using flush_atom = atom_constant<atom("FLUSH")>;
/// Generic 'REDIRECT' atom, e.g., used by `aout`.
using redirect_atom = atom_constant<atom("REDIRECT")>;
/// Generic 'LINK' atom for link requests over network.
using link_atom = atom_constant<atom("LINK")>;
/// Generic 'UNLINK' atom for removing networked links.
using unlink_atom = atom_constant<atom("UNLINK")>;
/// Generic 'PUBLISH' atom, e.g., for publishing actors at a given port.
using publish_atom = atom_constant<atom("PUBLISH")>;
/// Generic 'UNPUBLISH' atom, e.g., for removing an actor/port mapping.
using unpublish_atom = atom_constant<atom("UNPUBLISH")>;
/// Generic 'PUBLISH' atom, e.g., for publishing actors at a given port.
using subscribe_atom = atom_constant<atom("SUBSCRIBE")>;
/// Generic 'UNPUBLISH' atom, e.g., for removing an actor/port mapping.
using unsubscribe_atom = atom_constant<atom("UNSUBSCRIB")>;
/// Generic 'CONNECT' atom, e.g., for connecting to remote CAF instances.
using connect_atom = atom_constant<atom("CONNECT")>;
/// Generic 'OPEN' atom, e.g., for opening a port or file.
using open_atom = atom_constant<atom("OPEN")>;
/// Generic 'CLOSE' atom, e.g., for closing a port or file.
using close_atom = atom_constant<atom("CLOSE")>;
/// Generic 'SPAWN' atom, e.g., for spawning remote actors.
using spawn_atom = atom_constant<atom("SPAWN")>;
/// Atom to signalize an actor to migrate its state to another actor.
using migrate_atom = atom_constant<atom("MIGRATE")>;
} // namespace caf
namespace std {
template <>
struct hash<caf::atom_value> {
size_t operator()(caf::atom_value x) const {
hash<uint64_t> f;
return f(static_cast<uint64_t>(x));
}
};
} // namespace std
#endif // CAF_ATOM_HPP
<commit_msg>Use lowercase strings for atom constants<commit_after>/******************************************************************************
* ____ _ _____ *
* / ___| / \ | ___| C++ *
* | | / _ \ | |_ Actor *
* | |___ / ___ \| _| Framework *
* \____/_/ \_|_| *
* *
* Copyright (C) 2011 - 2015 *
* Dominik Charousset <dominik.charousset (at) haw-hamburg.de> *
* *
* Distributed under the terms and conditions of the BSD 3-Clause License or *
* (at your option) under the terms and conditions of the Boost Software *
* License 1.0. See accompanying files LICENSE and LICENSE_ALTERNATIVE. *
* *
* If you did not receive a copy of the license files, see *
* http://opensource.org/licenses/BSD-3-Clause and *
* http://www.boost.org/LICENSE_1_0.txt. *
******************************************************************************/
#ifndef CAF_ATOM_HPP
#define CAF_ATOM_HPP
#include <string>
#include <functional>
#include <type_traits>
#include "caf/detail/atom_val.hpp"
namespace caf {
/// The value type of atoms.
enum class atom_value : uint64_t {
/// @cond PRIVATE
dirty_little_hack = 31337
/// @endcond
};
std::string to_string(const atom_value& x);
/// Creates an atom from given string literal.
template <size_t Size>
constexpr atom_value atom(char const (&str)[Size]) {
// last character is the NULL terminator
static_assert(Size <= 11, "only 10 characters are allowed");
return static_cast<atom_value>(detail::atom_val(str));
}
/// Lifts an `atom_value` to a compile-time constant.
template <atom_value V>
struct atom_constant {
constexpr atom_constant() {
// nop
}
/// Returns the wrapped value.
constexpr operator atom_value() const {
return V;
}
static constexpr uint64_t uint_value() {
return static_cast<uint64_t>(V);
}
/// Returns an instance *of this constant* (*not* an `atom_value`).
static const atom_constant value;
};
template <atom_value V>
std::string to_string(const atom_constant<V>&) {
return to_string(V);
}
template <atom_value V>
const atom_constant<V> atom_constant<V>::value = atom_constant<V>{};
/// Used for request operations.
using add_atom = atom_constant<atom("add")>;
/// Used for request operations.
using get_atom = atom_constant<atom("get")>;
/// Used for request operations.
using put_atom = atom_constant<atom("put")>;
/// Used for signalizing updates, e.g., in a key-value store.
using update_atom = atom_constant<atom("update")>;
/// Used for request operations.
using delete_atom = atom_constant<atom("delete")>;
/// Used for response messages.
using ok_atom = atom_constant<atom("ok")>;
/// Used for triggering system-level message handling.
using sys_atom = atom_constant<atom("sys")>;
/// Used for signaling group subscriptions.
using join_atom = atom_constant<atom("join")>;
/// Used for signaling group unsubscriptions.
using leave_atom = atom_constant<atom("leave")>;
/// Used for signaling forwarding paths.
using forward_atom = atom_constant<atom("forward")>;
/// Used for buffer management.
using flush_atom = atom_constant<atom("flush")>;
/// Used for I/O redirection.
using redirect_atom = atom_constant<atom("redirect")>;
/// Used for link requests over network.
using link_atom = atom_constant<atom("link")>;
/// Used for removing networked links.
using unlink_atom = atom_constant<atom("unlink")>;
/// Used for publishing actors at a given port.
using publish_atom = atom_constant<atom("publish")>;
/// Used for removing an actor/port mapping.
using unpublish_atom = atom_constant<atom("unpublish")>;
/// Used for signalizing group membership.
using subscribe_atom = atom_constant<atom("subscribe")>;
/// Used for withdrawing group membership.
using unsubscribe_atom = atom_constant<atom("unsubscrib")>;
/// Used for establishing network connections.
using connect_atom = atom_constant<atom("connect")>;
/// Used for opening ports or files.
using open_atom = atom_constant<atom("open")>;
/// Used for closing ports or files.
using close_atom = atom_constant<atom("close")>;
/// Used for spawning remote actors.
using spawn_atom = atom_constant<atom("spawn")>;
/// Used for migrating actors to other nodes.
using migrate_atom = atom_constant<atom("migrate")>;
} // namespace caf
namespace std {
template <>
struct hash<caf::atom_value> {
size_t operator()(caf::atom_value x) const {
hash<uint64_t> f;
return f(static_cast<uint64_t>(x));
}
};
} // namespace std
#endif // CAF_ATOM_HPP
<|endoftext|> |
<commit_before>/*
This file is part of cpp-ethereum.
cpp-ethereum 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.
cpp-ethereum 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 cpp-ethereum. If not, see <http://www.gnu.org/licenses/>.
*/
/** @file BlockInfo.cpp
* @author Gav Wood <i@gavwood.com>
* @date 2014
*/
#include <libdevcore/Common.h>
#include <libdevcore/RLP.h>
#include <libdevcrypto/TrieDB.h>
#include <libethcore/Common.h>
#include "ProofOfWork.h"
#include "Exceptions.h"
#include "Params.h"
#include "BlockInfo.h"
using namespace std;
using namespace dev;
using namespace dev::eth;
BlockInfo::BlockInfo(): timestamp(Invalid256)
{
}
BlockInfo::BlockInfo(bytesConstRef _block, bool _checkNonce)
{
populate(_block, _checkNonce);
}
void BlockInfo::setEmpty()
{
parentHash = h256();
sha3Uncles = EmptyListSHA3;
coinbaseAddress = Address();
stateRoot = EmptyTrie;
transactionsRoot = EmptyTrie;
receiptsRoot = EmptyTrie;
logBloom = LogBloom();
difficulty = 0;
number = 0;
gasLimit = 0;
gasUsed = 0;
timestamp = 0;
extraData.clear();
seedHash = h256();
mixHash = h256();
nonce = Nonce();
hash = headerHash(WithNonce);
}
BlockInfo BlockInfo::fromHeader(bytesConstRef _block)
{
BlockInfo ret;
ret.populateFromHeader(RLP(_block));
return ret;
}
h256 BlockInfo::headerHash(IncludeNonce _n) const
{
RLPStream s;
streamRLP(s, _n);
return sha3(s.out());
}
void BlockInfo::streamRLP(RLPStream& _s, IncludeNonce _n) const
{
_s.appendList(_n == WithNonce ? 16 : 14)
<< parentHash << sha3Uncles << coinbaseAddress << stateRoot << transactionsRoot << receiptsRoot << logBloom
<< difficulty << number << gasLimit << gasUsed << timestamp << extraData << seedHash;
if (_n == WithNonce)
_s << mixHash << nonce;
}
h256 BlockInfo::headerHash(bytesConstRef _block)
{
return sha3(RLP(_block)[0].data());
}
void BlockInfo::populateFromHeader(RLP const& _header, bool _checkNonce)
{
hash = dev::sha3(_header.data());
int field = 0;
try
{
parentHash = _header[field = 0].toHash<h256>(RLP::VeryStrict);
sha3Uncles = _header[field = 1].toHash<h256>(RLP::VeryStrict);
coinbaseAddress = _header[field = 2].toHash<Address>(RLP::VeryStrict);
stateRoot = _header[field = 3].toHash<h256>(RLP::VeryStrict);
transactionsRoot = _header[field = 4].toHash<h256>(RLP::VeryStrict);
receiptsRoot = _header[field = 5].toHash<h256>(RLP::VeryStrict);
logBloom = _header[field = 6].toHash<LogBloom>(RLP::VeryStrict);
difficulty = _header[field = 7].toInt<u256>();
number = _header[field = 8].toInt<u256>();
gasLimit = _header[field = 9].toInt<u256>();
gasUsed = _header[field = 10].toInt<u256>();
timestamp = _header[field = 11].toInt<u256>();
extraData = _header[field = 12].toBytes();
seedHash = _header[field = 13].toHash<h256>(RLP::VeryStrict);
mixHash = _header[field = 14].toHash<h256>(RLP::VeryStrict);
nonce = _header[field = 15].toHash<Nonce>(RLP::VeryStrict);
}
catch (Exception const& _e)
{
_e << errinfo_name("invalid block header format") << BadFieldError(field, toHex(_header[field].data().toBytes()));
throw;
}
// check it hashes according to proof of work or that it's the genesis block.
if (_checkNonce && parentHash && !ProofOfWork::verify(*this))
BOOST_THROW_EXCEPTION(InvalidBlockNonce(headerHash(WithoutNonce), nonce, difficulty));
if (gasUsed > gasLimit)
BOOST_THROW_EXCEPTION(TooMuchGasUsed() << RequirementError(bigint(gasLimit), bigint(gasUsed)) );
if (number && extraData.size() > c_maximumExtraDataSize)
BOOST_THROW_EXCEPTION(ExtraDataTooBig());
}
void BlockInfo::populate(bytesConstRef _block, bool _checkNonce)
{
RLP root(_block);
RLP header = root[0];
if (!header.isList())
BOOST_THROW_EXCEPTION(InvalidBlockFormat(0, header.data()) << errinfo_comment("block header needs to be a list"));
populateFromHeader(header, _checkNonce);
if (!root[1].isList())
BOOST_THROW_EXCEPTION(InvalidBlockFormat(1, root[1].data()));
if (!root[2].isList())
BOOST_THROW_EXCEPTION(InvalidBlockFormat(2, root[2].data()));
}
void BlockInfo::verifyInternals(bytesConstRef _block) const
{
RLP root(_block);
u256 mgp = (u256)-1;
OverlayDB db;
GenericTrieDB<OverlayDB> t(&db);
t.init();
unsigned i = 0;
for (auto const& tr: root[1])
{
bytes k = rlp(i);
t.insert(&k, tr.data());
u256 gasprice = tr[1].toInt<u256>();
mgp = min(mgp, gasprice); // the minimum gas price is not used for anything //TODO delete?
++i;
}
if (transactionsRoot != t.root())
BOOST_THROW_EXCEPTION(InvalidTransactionsHash(t.root(), transactionsRoot));
if (sha3Uncles != sha3(root[2].data()))
BOOST_THROW_EXCEPTION(InvalidUnclesHash());
}
void BlockInfo::populateFromParent(BlockInfo const& _parent)
{
stateRoot = _parent.stateRoot;
parentHash = _parent.hash;
number = _parent.number + 1;
gasLimit = calculateGasLimit(_parent);
gasUsed = 0;
difficulty = calculateDifficulty(_parent);
seedHash = calculateSeedHash(_parent);
}
h256 BlockInfo::calculateSeedHash(BlockInfo const& _parent) const
{
return number % c_epochDuration == 0 ? sha3(_parent.seedHash.asBytes()) : _parent.seedHash;
}
u256 BlockInfo::calculateGasLimit(BlockInfo const& _parent) const
{
if (!parentHash)
return c_genesisGasLimit;
else
return max<u256>(c_minGasLimit, (_parent.gasLimit * (c_gasLimitBoundDivisor - 1) + (_parent.gasUsed * 6 / 5)) / c_gasLimitBoundDivisor);
}
u256 BlockInfo::calculateDifficulty(BlockInfo const& _parent) const
{
if (!parentHash)
return (u256)c_genesisDifficulty;
else
return max<u256>(c_minimumDifficulty, timestamp >= _parent.timestamp + c_durationLimit ? _parent.difficulty - (_parent.difficulty / c_difficultyBoundDivisor) : (_parent.difficulty + (_parent.difficulty / c_difficultyBoundDivisor)));
}
void BlockInfo::verifyParent(BlockInfo const& _parent) const
{
// Check difficulty is correct given the two timestamps.
if (difficulty != calculateDifficulty(_parent))
BOOST_THROW_EXCEPTION(InvalidDifficulty() << RequirementError((bigint)calculateDifficulty(_parent), (bigint)difficulty));
if (gasLimit < _parent.gasLimit * (c_gasLimitBoundDivisor - 1) / c_gasLimitBoundDivisor ||
gasLimit > _parent.gasLimit * (c_gasLimitBoundDivisor + 1) / c_gasLimitBoundDivisor)
BOOST_THROW_EXCEPTION(InvalidGasLimit(gasLimit, _parent.gasLimit * (c_gasLimitBoundDivisor - 1) / c_gasLimitBoundDivisor, _parent.gasLimit * (c_gasLimitBoundDivisor + 1) / c_gasLimitBoundDivisor));
if (gasLimit < _parent.gasLimit * (c_gasLimitBoundDivisor - 1) / c_gasLimitBoundDivisor ||
gasLimit > _parent.gasLimit * (c_gasLimitBoundDivisor + 1) / c_gasLimitBoundDivisor)
BOOST_THROW_EXCEPTION(InvalidGasLimit(gasLimit, _parent.gasLimit * (c_gasLimitBoundDivisor - 1) / c_gasLimitBoundDivisor, _parent.gasLimit * (c_gasLimitBoundDivisor + 1) / c_gasLimitBoundDivisor));
if (seedHash != calculateSeedHash(_parent))
BOOST_THROW_EXCEPTION(InvalidSeedHash());
// Check timestamp is after previous timestamp.
if (parentHash)
{
if (parentHash != _parent.hash)
BOOST_THROW_EXCEPTION(InvalidParentHash());
if (timestamp <= _parent.timestamp)
BOOST_THROW_EXCEPTION(InvalidTimestamp());
if (number != _parent.number + 1)
BOOST_THROW_EXCEPTION(InvalidNumber());
}
}
<commit_msg>check for minGasLimit and minDifficulty when constructing block<commit_after>/*
This file is part of cpp-ethereum.
cpp-ethereum 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.
cpp-ethereum 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 cpp-ethereum. If not, see <http://www.gnu.org/licenses/>.
*/
/** @file BlockInfo.cpp
* @author Gav Wood <i@gavwood.com>
* @date 2014
*/
#include <libdevcore/Common.h>
#include <libdevcore/RLP.h>
#include <libdevcrypto/TrieDB.h>
#include <libethcore/Common.h>
#include "ProofOfWork.h"
#include "Exceptions.h"
#include "Params.h"
#include "BlockInfo.h"
using namespace std;
using namespace dev;
using namespace dev::eth;
BlockInfo::BlockInfo(): timestamp(Invalid256)
{
}
BlockInfo::BlockInfo(bytesConstRef _block, bool _checkNonce)
{
populate(_block, _checkNonce);
}
void BlockInfo::setEmpty()
{
parentHash = h256();
sha3Uncles = EmptyListSHA3;
coinbaseAddress = Address();
stateRoot = EmptyTrie;
transactionsRoot = EmptyTrie;
receiptsRoot = EmptyTrie;
logBloom = LogBloom();
difficulty = 0;
number = 0;
gasLimit = 0;
gasUsed = 0;
timestamp = 0;
extraData.clear();
seedHash = h256();
mixHash = h256();
nonce = Nonce();
hash = headerHash(WithNonce);
}
BlockInfo BlockInfo::fromHeader(bytesConstRef _block)
{
BlockInfo ret;
ret.populateFromHeader(RLP(_block));
return ret;
}
h256 BlockInfo::headerHash(IncludeNonce _n) const
{
RLPStream s;
streamRLP(s, _n);
return sha3(s.out());
}
void BlockInfo::streamRLP(RLPStream& _s, IncludeNonce _n) const
{
_s.appendList(_n == WithNonce ? 16 : 14)
<< parentHash << sha3Uncles << coinbaseAddress << stateRoot << transactionsRoot << receiptsRoot << logBloom
<< difficulty << number << gasLimit << gasUsed << timestamp << extraData << seedHash;
if (_n == WithNonce)
_s << mixHash << nonce;
}
h256 BlockInfo::headerHash(bytesConstRef _block)
{
return sha3(RLP(_block)[0].data());
}
void BlockInfo::populateFromHeader(RLP const& _header, bool _checkNonce)
{
hash = dev::sha3(_header.data());
int field = 0;
try
{
parentHash = _header[field = 0].toHash<h256>(RLP::VeryStrict);
sha3Uncles = _header[field = 1].toHash<h256>(RLP::VeryStrict);
coinbaseAddress = _header[field = 2].toHash<Address>(RLP::VeryStrict);
stateRoot = _header[field = 3].toHash<h256>(RLP::VeryStrict);
transactionsRoot = _header[field = 4].toHash<h256>(RLP::VeryStrict);
receiptsRoot = _header[field = 5].toHash<h256>(RLP::VeryStrict);
logBloom = _header[field = 6].toHash<LogBloom>(RLP::VeryStrict);
difficulty = _header[field = 7].toInt<u256>();
number = _header[field = 8].toInt<u256>();
gasLimit = _header[field = 9].toInt<u256>();
gasUsed = _header[field = 10].toInt<u256>();
timestamp = _header[field = 11].toInt<u256>();
extraData = _header[field = 12].toBytes();
seedHash = _header[field = 13].toHash<h256>(RLP::VeryStrict);
mixHash = _header[field = 14].toHash<h256>(RLP::VeryStrict);
nonce = _header[field = 15].toHash<Nonce>(RLP::VeryStrict);
}
catch (Exception const& _e)
{
_e << errinfo_name("invalid block header format") << BadFieldError(field, toHex(_header[field].data().toBytes()));
throw;
}
// check it hashes according to proof of work or that it's the genesis block.
if (_checkNonce && parentHash && !ProofOfWork::verify(*this))
BOOST_THROW_EXCEPTION(InvalidBlockNonce(headerHash(WithoutNonce), nonce, difficulty));
if (gasUsed > gasLimit)
BOOST_THROW_EXCEPTION(TooMuchGasUsed() << RequirementError(bigint(gasLimit), bigint(gasUsed)) );
if (difficulty < c_minimumDifficulty)
BOOST_THROW_EXCEPTION(InvalidDifficulty() << RequirementError(bigint(c_minimumDifficulty), bigint(difficulty)) );
if (gasLimit < c_minGasLimit)
BOOST_THROW_EXCEPTION(InvalidGasLimit() << RequirementError(bigint(c_minGasLimit), bigint(gasLimit)) );
if (number && extraData.size() > c_maximumExtraDataSize)
BOOST_THROW_EXCEPTION(ExtraDataTooBig() << RequirementError(bigint(c_maximumExtraDataSize), bigint(extraData.size())));
}
void BlockInfo::populate(bytesConstRef _block, bool _checkNonce)
{
RLP root(_block);
RLP header = root[0];
if (!header.isList())
BOOST_THROW_EXCEPTION(InvalidBlockFormat(0, header.data()) << errinfo_comment("block header needs to be a list"));
populateFromHeader(header, _checkNonce);
if (!root[1].isList())
BOOST_THROW_EXCEPTION(InvalidBlockFormat(1, root[1].data()));
if (!root[2].isList())
BOOST_THROW_EXCEPTION(InvalidBlockFormat(2, root[2].data()));
}
void BlockInfo::verifyInternals(bytesConstRef _block) const
{
RLP root(_block);
u256 mgp = (u256)-1;
OverlayDB db;
GenericTrieDB<OverlayDB> t(&db);
t.init();
unsigned i = 0;
for (auto const& tr: root[1])
{
bytes k = rlp(i);
t.insert(&k, tr.data());
u256 gasprice = tr[1].toInt<u256>();
mgp = min(mgp, gasprice); // the minimum gas price is not used for anything //TODO delete?
++i;
}
if (transactionsRoot != t.root())
BOOST_THROW_EXCEPTION(InvalidTransactionsHash(t.root(), transactionsRoot));
if (sha3Uncles != sha3(root[2].data()))
BOOST_THROW_EXCEPTION(InvalidUnclesHash());
}
void BlockInfo::populateFromParent(BlockInfo const& _parent)
{
stateRoot = _parent.stateRoot;
parentHash = _parent.hash;
number = _parent.number + 1;
gasLimit = calculateGasLimit(_parent);
gasUsed = 0;
difficulty = calculateDifficulty(_parent);
seedHash = calculateSeedHash(_parent);
}
h256 BlockInfo::calculateSeedHash(BlockInfo const& _parent) const
{
return number % c_epochDuration == 0 ? sha3(_parent.seedHash.asBytes()) : _parent.seedHash;
}
u256 BlockInfo::calculateGasLimit(BlockInfo const& _parent) const
{
if (!parentHash)
return c_genesisGasLimit;
else
return max<u256>(c_minGasLimit, (_parent.gasLimit * (c_gasLimitBoundDivisor - 1) + (_parent.gasUsed * 6 / 5)) / c_gasLimitBoundDivisor);
}
u256 BlockInfo::calculateDifficulty(BlockInfo const& _parent) const
{
if (!parentHash)
return (u256)c_genesisDifficulty;
else
return max<u256>(c_minimumDifficulty, timestamp >= _parent.timestamp + c_durationLimit ? _parent.difficulty - (_parent.difficulty / c_difficultyBoundDivisor) : (_parent.difficulty + (_parent.difficulty / c_difficultyBoundDivisor)));
}
void BlockInfo::verifyParent(BlockInfo const& _parent) const
{
// Check difficulty is correct given the two timestamps.
if (difficulty != calculateDifficulty(_parent))
BOOST_THROW_EXCEPTION(InvalidDifficulty() << RequirementError((bigint)calculateDifficulty(_parent), (bigint)difficulty));
if (gasLimit < _parent.gasLimit * (c_gasLimitBoundDivisor - 1) / c_gasLimitBoundDivisor ||
gasLimit > _parent.gasLimit * (c_gasLimitBoundDivisor + 1) / c_gasLimitBoundDivisor)
BOOST_THROW_EXCEPTION(InvalidGasLimit(gasLimit, _parent.gasLimit * (c_gasLimitBoundDivisor - 1) / c_gasLimitBoundDivisor, _parent.gasLimit * (c_gasLimitBoundDivisor + 1) / c_gasLimitBoundDivisor));
if (seedHash != calculateSeedHash(_parent))
BOOST_THROW_EXCEPTION(InvalidSeedHash());
// Check timestamp is after previous timestamp.
if (parentHash)
{
if (parentHash != _parent.hash)
BOOST_THROW_EXCEPTION(InvalidParentHash());
if (timestamp <= _parent.timestamp)
BOOST_THROW_EXCEPTION(InvalidTimestamp());
if (number != _parent.number + 1)
BOOST_THROW_EXCEPTION(InvalidNumber());
}
}
<|endoftext|> |
<commit_before>// Copyright (c) 2015, Matthew Malensek.
// Distributed under the BSD 2-Clause License (see LICENSE.txt for details)
#include "Error.h"
#include <Windows.h>
#include "LanguageTranslator.h"
#include "Settings.h"
std::unordered_map<int, std::wstring> Error::errorMap = {
{ GENERR_NOTFOUND, L"File not found:\n{1}" },
{ GENERR_MISSING_XML, L"Could not locate XML tag: {1}" },
{ GENERR_UNKNOWN, L"An unknown error occurred: ID #{1}"},
{ SKINERR_INVALID_SKIN, L"Could not find specified skin:\n{1}" },
{ SKINERR_INVALID_SLIDERTYPE, L"Invalid slider type: {1}" },
{ SKINERR_MISSING_XML, L"Could not locate required skin XML tag: {1}" },
{ SKINERR_MISSING_XMLROOT, L"Could not locate root XML element" },
{ SKINERR_NO_RESOURCE, L"Skin resource '{1}' was not found in any of the "
"available skins." },
{ SKINERR_SKINDIR, L"Could not locate skin directory:\n{1}" },
{ SKINERR_XMLPARSE, L"Failed to parse skin XML file:\n{1}" },
{ SYSERR_REGISTERCLASS, L"Could not register window class." },
{ SYSERR_CREATEWINDOW, L"Could not create window." },
};
void Error::ErrorMessage(unsigned int error, std::wstring detail) {
std::wstring errType = ErrorType(error);
std::wstring errMsg = errorMap[error];
if (errMsg == L"") {
errMsg = errorMap[GENERR_UNKNOWN];
detail = std::to_wstring(error);
}
/* Check if a translator instance is available; if so, use it.
* Otherwise, we keep the original english message. */
Settings *settings = Settings::Instance();
LanguageTranslator *translator = nullptr;
if (settings) {
translator = settings->Translator();
}
if (translator) {
errMsg = translator->TranslateAndReplace(errMsg, detail);
errType = translator->Translate(errType);
}
MessageBox(NULL, errMsg.c_str(), errType.c_str(), MB_ICONERROR);
}
void Error::ErrorMessageDie(unsigned int error, std::wstring detail) {
ErrorMessage(error, detail);
exit(EXIT_FAILURE);
}
wchar_t *Error::ErrorType(unsigned int error) {
if (error & SKINERR) {
return L"3RVX Skin Error";
} else if (error & SYSERR) {
return L"3RVX System Error";
}
return L"3RVX Error";
}<commit_msg>Add error details to system error messages<commit_after>// Copyright (c) 2015, Matthew Malensek.
// Distributed under the BSD 2-Clause License (see LICENSE.txt for details)
#include "Error.h"
#include <Windows.h>
#include "LanguageTranslator.h"
#include "Settings.h"
std::unordered_map<int, std::wstring> Error::errorMap = {
{ GENERR_NOTFOUND, L"File not found:\n{1}" },
{ GENERR_MISSING_XML, L"Could not locate XML tag: {1}" },
{ GENERR_UNKNOWN, L"An unknown error occurred: ID #{1}"},
{ SKINERR_INVALID_SKIN, L"Could not find specified skin:\n{1}" },
{ SKINERR_INVALID_SLIDERTYPE, L"Invalid slider type: {1}" },
{ SKINERR_MISSING_XML, L"Could not locate required skin XML tag: {1}" },
{ SKINERR_MISSING_XMLROOT, L"Could not locate root XML element" },
{ SKINERR_NO_RESOURCE, L"Skin resource '{1}' was not found in any of the "
"available skins." },
{ SKINERR_SKINDIR, L"Could not locate skin directory:\n{1}" },
{ SKINERR_XMLPARSE, L"Failed to parse skin XML file:\n{1}" },
{ SYSERR_REGISTERCLASS, L"Could not register window class: {1}" },
{ SYSERR_CREATEWINDOW, L"Could not create window: {1}" },
};
void Error::ErrorMessage(unsigned int error, std::wstring detail) {
std::wstring errType = ErrorType(error);
std::wstring errMsg = errorMap[error];
if (errMsg == L"") {
errMsg = errorMap[GENERR_UNKNOWN];
detail = std::to_wstring(error);
}
/* Check if a translator instance is available; if so, use it.
* Otherwise, we keep the original english message. */
Settings *settings = Settings::Instance();
LanguageTranslator *translator = nullptr;
if (settings) {
translator = settings->Translator();
}
if (translator) {
errMsg = translator->TranslateAndReplace(errMsg, detail);
errType = translator->Translate(errType);
}
MessageBox(NULL, errMsg.c_str(), errType.c_str(), MB_ICONERROR);
}
void Error::ErrorMessageDie(unsigned int error, std::wstring detail) {
ErrorMessage(error, detail);
exit(EXIT_FAILURE);
}
wchar_t *Error::ErrorType(unsigned int error) {
if (error & SKINERR) {
return L"3RVX Skin Error";
} else if (error & SYSERR) {
return L"3RVX System Error";
}
return L"3RVX Error";
}<|endoftext|> |
<commit_before>
//@HEADER
// ************************************************************************
//
// HPCCG: Simple Conjugate Gradient Benchmark Code
// Copyright (2006) Sandia Corporation
//
// Under terms of Contract DE-AC04-94AL85000, there is a non-exclusive
// license for use of this work by or on behalf of the U.S. Government.
//
// BSD 3-Clause License
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * Neither the name of the copyright holder nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Questions? Contact Michael A. Heroux (maherou@sandia.gov)
//
// ************************************************************************
//@HEADER
// Main routine of a program that reads a sparse matrix, right side
// vector, solution vector and initial guess from a file in HPC
// format. This program then calls the HPCCG conjugate gradient
// solver to solve the problem, and then prints results.
// Calling sequence:
// test_HPCCG linear_system_file
// Routines called:
// read_HPC_row - Reads in linear system
// mytimer - Timing routine (compile with -DWALL to get wall clock
// times
// HPCCG - CG Solver
// compute_residual - Compares HPCCG solution to known solution.
#include <iostream>
using std::cout;
using std::cerr;
using std::endl;
#include <cstdio>
#include <cstdlib>
#include <cctype>
#include <cassert>
#include <string>
#include <cmath>
#ifdef USING_MPI
#include <mpi.h> // If this routine is compiled with -DUSING_MPI
// then include mpi.h
#include "make_local_matrix.hpp" // Also include this function
#endif
#ifdef USING_OMP
#include <omp.h>
#endif
#include "generate_matrix.hpp"
#include "mytimer.hpp"
#include "HPC_sparsemv.hpp"
#include "compute_residual.hpp"
//#include "read_HPC_row.hpp"
#include "HPCCG.hpp"
#include "HPC_Sparse_Matrix.hpp"
#include "dump_matlab_matrix.hpp"
#include "YAML_Element.hpp"
#include "YAML_Doc.hpp"
#include "Halide.h"
#undef DEBUG
#define MAX_ITER 150
int main_ref(int argc, char *argv[], double **r)
{
HPC_Sparse_Matrix *A;
double *x, *b, *xexact;
double norm, d;
int ierr = 0;
int i, j;
int ione = 1;
double times[7];
double t6 = 0.0;
int nx,ny,nz;
#ifdef USING_MPI
MPI_Init(&argc, &argv);
int size, rank; // Number of MPI processes, My process ID
MPI_Comm_size(MPI_COMM_WORLD, &size);
MPI_Comm_rank(MPI_COMM_WORLD, &rank);
// if (size < 100) cout << "Process "<<rank<<" of "<<size<<" is alive." <<endl;
#else
int size = 1; // Serial case (not using MPI)
int rank = 0;
#endif
if (argc==4)
{
nx = atoi(argv[1]);
ny = atoi(argv[2]);
nz = atoi(argv[3]);
generate_matrix(nx, ny, nz, &A, &x, &b, &xexact);
}
else
{
//read_HPC_row(argv[1], &A, &x, &b, &xexact);
std::cerr << "Reading a linear system is disabled\n";
exit(0);
}
bool dump_matrix = false;
if (dump_matrix && size<=4) dump_matlab_matrix(A, rank);
#ifdef USING_MPI
// Transform matrix indices from global to local values.
// Define number of columns for the local matrix.
t6 = mytimer(); make_local_matrix(A); t6 = mytimer() - t6;
times[6] = t6;
#endif
double t1 = mytimer(); // Initialize it (if needed)
int niters = 0;
double normr = 0.0;
int max_iter = MAX_ITER; //150 is the default.
double tolerance = 0.0; // Set tolerance to zero to make all runs do max_iter iterations
int nrow = A->local_nrow;
*r = (double *) malloc(sizeof(double)*nrow);
ierr = HPCCG_ref(A, b, x, max_iter, tolerance, niters, normr, times, *r);
if (ierr) cerr << "Error in call to CG: " << ierr << ".\n" << endl;
if (rank==0) // Only PE 0 needs to compute and report timing results
{
double fniters = 1; //niters;
double fnrow = A->total_nrow;
double fnnz = A->total_nnz;
double fnops_ddot = fniters*4*fnrow;
double fnops_waxpby = fniters*6*fnrow;
double fnops_sparsemv = fniters*2*fnnz;
double fnops = fnops_ddot+fnops_waxpby+fnops_sparsemv;
#ifdef USING_MPI
std::cout << "MPI (Number of ranks = " << size << ") - ";
#else
std::cout << "MPI (not enabled) - ";
#endif
#ifdef USING_OMP
int nthreads = 1;
#pragma omp parallel
nthreads = omp_get_num_threads();
std::cout << "OpenMP (Number of threads = " << nthreads << ")" << std::endl;
#else
std::cout << "OpenMP (not enabled)" << std::endl;
#endif
std::cout << "Dimensions : (nx, ny, nz) = (" << nx << ", " << ny << ", " << nz << ")" << std::endl;
std::cout << "Number of iterations: " << niters << ". ";
std::cout << "Final residual: " << normr << std::endl;
std::cout << "Time (per iteration): " << times[1] << ";" << std::endl;
std::cout << "Total number of Floating operations (FLOPS): " << fnops << std::endl;
std::cout << "MFLOPS: " << fnops/times[1]/1.0E6 << std::endl;
}
// Compute difference between known exact solution and computed solution
// All processors are needed here.
double residual = 0;
// if ((ierr = compute_residual(A->local_nrow, x, xexact, &residual)))
// cerr << "Error in call to compute_residual: " << ierr << ".\n" << endl;
// if (rank==0)
// cout << "Difference between computed and exact = "
// << residual << ".\n" << endl;
// Finish up
#ifdef USING_MPI
MPI_Finalize();
#endif
return nrow ;
}
int main_tiramisu(int argc, char *argv[], Halide::Buffer<double> &r_tiramisu)
{
HPC_Sparse_Matrix *A;
double *x, *b, *xexact;
double norm, d;
int ierr = 0;
int i, j;
int ione = 1;
double times[7];
double t6 = 0.0;
int nx,ny,nz;
#ifdef USING_MPI
MPI_Init(&argc, &argv);
int size, rank; // Number of MPI processes, My process ID
MPI_Comm_size(MPI_COMM_WORLD, &size);
MPI_Comm_rank(MPI_COMM_WORLD, &rank);
// if (size < 100) cout << "Process "<<rank<<" of "<<size<<" is alive." <<endl;
#else
int size = 1; // Serial case (not using MPI)
int rank = 0;
#endif
if (argc==4)
{
nx = atoi(argv[1]);
ny = atoi(argv[2]);
nz = atoi(argv[3]);
generate_matrix(nx, ny, nz, &A, &x, &b, &xexact);
}
else
{
//read_HPC_row(argv[1], &A, &x, &b, &xexact);
std::cerr << "Reading a linear system is disabled\n";
exit(0);
}
bool dump_matrix = false;
if (dump_matrix && size<=4) dump_matlab_matrix(A, rank);
#ifdef USING_MPI
// Transform matrix indices from global to local values.
// Define number of columns for the local matrix.
t6 = mytimer(); make_local_matrix(A); t6 = mytimer() - t6;
times[6] = t6;
#endif
double t1 = mytimer(); // Initialize it (if needed)
int niters = 0;
double normr = 0.0;
int max_iter = MAX_ITER; //150 is the default.
double tolerance = 0.0; // Set tolerance to zero to make all runs do max_iter iterations
int nrow = A->local_nrow;
//*r = (double *) malloc(sizeof(double)*nrow);
ierr = HPCCG_tiramisu(A, b, x, max_iter, tolerance, niters, normr, times, r_tiramisu);
if (ierr) cerr << "Error in call to CG: " << ierr << ".\n" << endl;
if (rank==0) // Only PE 0 needs to compute and report timing results
{
double fniters = 1; //niters;
double fnrow = A->total_nrow;
double fnnz = A->total_nnz;
double fnops_ddot = fniters*4*fnrow;
double fnops_waxpby = fniters*6*fnrow;
double fnops_sparsemv = fniters*2*fnnz;
double fnops = fnops_ddot+fnops_waxpby+fnops_sparsemv;
#ifdef USING_MPI
std::cout << "MPI (Number of ranks = " << size << ") - ";
#else
std::cout << "MPI (not enabled) - ";
#endif
#ifdef USING_OMP
int nthreads = 1;
#pragma omp parallel
nthreads = omp_get_num_threads();
std::cout << "OpenMP (Number of threads = " << nthreads << ")" << std::endl;
#else
std::cout << "OpenMP (not enabled)" << std::endl;
#endif
std::cout << "Dimensions : (nx, ny, nz) = (" << nx << ", " << ny << ", " << nz << ")" << std::endl;
std::cout << "Number of iterations: " << niters << ". ";
std::cout << "Final residual: " << normr << std::endl;
std::cout << "Time (per iteration): " << times[1] << ";" << std::endl;
std::cout << "Total number of Floating operations (FLOPS): " << fnops << std::endl;
std::cout << "MFLOPS: " << fnops/times[1]/1.0E6 << std::endl;
}
// Compute difference between known exact solution and computed solution
// All processors are needed here.
double residual = 0;
// if ((ierr = compute_residual(A->local_nrow, x, xexact, &residual)))
// cerr << "Error in call to compute_residual: " << ierr << ".\n" << endl;
// if (rank==0)
// cout << "Difference between computed and exact = "
// << residual << ".\n" << endl;
// Finish up
#ifdef USING_MPI
MPI_Finalize();
#endif
return nrow;
}
int flush_cache()
{
int cs = (1024 * 1024 * 1024);
double* flush = (double*) calloc (cs, sizeof(double));
double* flush2 = (double*) calloc (cs, sizeof(double));
double* flush3 = (double*) calloc (cs, sizeof(double));
double* flush4 = (double*) calloc (cs, sizeof(double));
int i;
double tmp = 0.0;
#pragma omp parallel for
for (i = 0; i < cs; i++)
{
tmp += flush[i];
tmp += flush2[i] + flush3[i] + flush4[i];
}
free (flush);
free (flush2);
free (flush3);
free (flush4);
return tmp;
}
int main(int argc, char *argv[])
{
assert(argc >= 3);
double * r_ref;
Halide::Buffer<double> r_tiramisu(atoi(argv[1])*atoi(argv[2])*atoi(argv[3]));
int res = flush_cache();
std::cout << "*************************** Tiramisu CG **************************************" << std::endl;
main_tiramisu(argc, argv, r_tiramisu);
std::cout << "*************************** Reference CG ***************************************" << std::endl;
res += flush_cache();
int nrow = main_ref(argc, argv, &r_ref);
std::cout << "******************************************************************" << std::endl;
// Compare r_ref and r_tiramisu
for (int i = 0; i < nrow; i++)
if (r_ref[i] - r_tiramisu(i) >= 0.001)
{
std::cerr << "r_ref[" << i << "] != r_tiramisu[" << i << "]" << std::endl;
exit(1);
}
std::cerr << "Correct computations." << std::endl;
free(r_ref);
return res ;
}
<commit_msg>Update HPCCG<commit_after>
//@HEADER
// ************************************************************************
//
// HPCCG: Simple Conjugate Gradient Benchmark Code
// Copyright (2006) Sandia Corporation
//
// Under terms of Contract DE-AC04-94AL85000, there is a non-exclusive
// license for use of this work by or on behalf of the U.S. Government.
//
// BSD 3-Clause License
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * Neither the name of the copyright holder nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Questions? Contact Michael A. Heroux (maherou@sandia.gov)
//
// ************************************************************************
//@HEADER
// Main routine of a program that reads a sparse matrix, right side
// vector, solution vector and initial guess from a file in HPC
// format. This program then calls the HPCCG conjugate gradient
// solver to solve the problem, and then prints results.
// Calling sequence:
// test_HPCCG linear_system_file
// Routines called:
// read_HPC_row - Reads in linear system
// mytimer - Timing routine (compile with -DWALL to get wall clock
// times
// HPCCG - CG Solver
// compute_residual - Compares HPCCG solution to known solution.
#include <iostream>
using std::cout;
using std::cerr;
using std::endl;
#include <cstdio>
#include <cstdlib>
#include <cctype>
#include <cassert>
#include <string>
#include <cmath>
#ifdef USING_MPI
#include <mpi.h> // If this routine is compiled with -DUSING_MPI
// then include mpi.h
#include "make_local_matrix.hpp" // Also include this function
#endif
#ifdef USING_OMP
#include <omp.h>
#endif
#include "generate_matrix.hpp"
#include "mytimer.hpp"
#include "HPC_sparsemv.hpp"
#include "compute_residual.hpp"
//#include "read_HPC_row.hpp"
#include "HPCCG.hpp"
#include "HPC_Sparse_Matrix.hpp"
#include "dump_matlab_matrix.hpp"
#include "YAML_Element.hpp"
#include "YAML_Doc.hpp"
#include "Halide.h"
#undef DEBUG
#define MAX_ITER 150
int main_ref(int argc, char *argv[], double **r, double &normr)
{
HPC_Sparse_Matrix *A;
double *x, *b, *xexact;
double norm, d;
int ierr = 0;
int i, j;
int ione = 1;
double times[7];
double t6 = 0.0;
int nx,ny,nz;
#ifdef USING_MPI
MPI_Init(&argc, &argv);
int size, rank; // Number of MPI processes, My process ID
MPI_Comm_size(MPI_COMM_WORLD, &size);
MPI_Comm_rank(MPI_COMM_WORLD, &rank);
// if (size < 100) cout << "Process "<<rank<<" of "<<size<<" is alive." <<endl;
#else
int size = 1; // Serial case (not using MPI)
int rank = 0;
#endif
if (argc==4)
{
nx = atoi(argv[1]);
ny = atoi(argv[2]);
nz = atoi(argv[3]);
generate_matrix(nx, ny, nz, &A, &x, &b, &xexact);
}
else
{
//read_HPC_row(argv[1], &A, &x, &b, &xexact);
std::cerr << "Reading a linear system is disabled\n";
exit(0);
}
bool dump_matrix = false;
if (dump_matrix && size<=4) dump_matlab_matrix(A, rank);
#ifdef USING_MPI
// Transform matrix indices from global to local values.
// Define number of columns for the local matrix.
t6 = mytimer(); make_local_matrix(A); t6 = mytimer() - t6;
times[6] = t6;
#endif
double t1 = mytimer(); // Initialize it (if needed)
int niters = 0;
int max_iter = MAX_ITER; //150 is the default.
double tolerance = 0.0; // Set tolerance to zero to make all runs do max_iter iterations
int nrow = A->local_nrow;
*r = (double *) malloc(sizeof(double)*nrow);
ierr = HPCCG_ref(A, b, x, max_iter, tolerance, niters, normr, times, *r);
if (ierr) cerr << "Error in call to CG: " << ierr << ".\n" << endl;
if (rank==0) // Only PE 0 needs to compute and report timing results
{
double fniters = 1; //niters;
double fnrow = A->total_nrow;
double fnnz = A->total_nnz;
double fnops_ddot = fniters*4*fnrow;
double fnops_waxpby = fniters*6*fnrow;
double fnops_sparsemv = fniters*2*fnnz;
double fnops = fnops_ddot+fnops_waxpby+fnops_sparsemv;
#ifdef USING_MPI
std::cout << "MPI (Number of ranks = " << size << ") - ";
#else
std::cout << "MPI (not enabled) - ";
#endif
#ifdef USING_OMP
int nthreads = 1;
#pragma omp parallel
nthreads = omp_get_num_threads();
std::cout << "OpenMP (Number of threads = " << nthreads << ")" << std::endl;
#else
std::cout << "OpenMP (not enabled)" << std::endl;
#endif
std::cout << "Dimensions : (nx, ny, nz) = (" << nx << ", " << ny << ", " << nz << ")" << std::endl;
std::cout << "Number of iterations: " << niters << ". ";
std::cout << "Final residual: " << normr << std::endl;
std::cout << "Time (per iteration): " << times[1] << ";" << std::endl;
std::cout << "Total number of Floating operations (FLOPS): " << fnops << std::endl;
std::cout << "MFLOPS: " << fnops/times[1]/1.0E6 << std::endl;
}
// Compute difference between known exact solution and computed solution
// All processors are needed here.
double residual = 0;
// if ((ierr = compute_residual(A->local_nrow, x, xexact, &residual)))
// cerr << "Error in call to compute_residual: " << ierr << ".\n" << endl;
// if (rank==0)
// cout << "Difference between computed and exact = "
// << residual << ".\n" << endl;
// Finish up
#ifdef USING_MPI
MPI_Finalize();
#endif
return nrow ;
}
int main_tiramisu(int argc, char *argv[], Halide::Buffer<double> &r_tiramisu, double &normr)
{
HPC_Sparse_Matrix *A;
double *x, *b, *xexact;
double norm, d;
int ierr = 0;
int i, j;
int ione = 1;
double times[7];
double t6 = 0.0;
int nx,ny,nz;
#ifdef USING_MPI
MPI_Init(&argc, &argv);
int size, rank; // Number of MPI processes, My process ID
MPI_Comm_size(MPI_COMM_WORLD, &size);
MPI_Comm_rank(MPI_COMM_WORLD, &rank);
// if (size < 100) cout << "Process "<<rank<<" of "<<size<<" is alive." <<endl;
#else
int size = 1; // Serial case (not using MPI)
int rank = 0;
#endif
if (argc==4)
{
nx = atoi(argv[1]);
ny = atoi(argv[2]);
nz = atoi(argv[3]);
generate_matrix(nx, ny, nz, &A, &x, &b, &xexact);
}
else
{
//read_HPC_row(argv[1], &A, &x, &b, &xexact);
std::cerr << "Reading a linear system is disabled\n";
exit(0);
}
bool dump_matrix = false;
if (dump_matrix && size<=4) dump_matlab_matrix(A, rank);
#ifdef USING_MPI
// Transform matrix indices from global to local values.
// Define number of columns for the local matrix.
t6 = mytimer(); make_local_matrix(A); t6 = mytimer() - t6;
times[6] = t6;
#endif
double t1 = mytimer(); // Initialize it (if needed)
int niters = 0;
int max_iter = MAX_ITER; //150 is the default.
double tolerance = 0.0; // Set tolerance to zero to make all runs do max_iter iterations
int nrow = A->local_nrow;
//*r = (double *) malloc(sizeof(double)*nrow);
ierr = HPCCG_tiramisu(A, b, x, max_iter, tolerance, niters, normr, times, r_tiramisu);
if (ierr) cerr << "Error in call to CG: " << ierr << ".\n" << endl;
if (rank==0) // Only PE 0 needs to compute and report timing results
{
double fniters = 1; //niters;
double fnrow = A->total_nrow;
double fnnz = A->total_nnz;
double fnops_ddot = fniters*4*fnrow;
double fnops_waxpby = fniters*6*fnrow;
double fnops_sparsemv = fniters*2*fnnz;
double fnops = fnops_ddot+fnops_waxpby+fnops_sparsemv;
#ifdef USING_MPI
std::cout << "MPI (Number of ranks = " << size << ") - ";
#else
std::cout << "MPI (not enabled) - ";
#endif
#ifdef USING_OMP
int nthreads = 1;
#pragma omp parallel
nthreads = omp_get_num_threads();
std::cout << "OpenMP (Number of threads = " << nthreads << ")" << std::endl;
#else
std::cout << "OpenMP (not enabled)" << std::endl;
#endif
std::cout << "Dimensions : (nx, ny, nz) = (" << nx << ", " << ny << ", " << nz << ")" << std::endl;
std::cout << "Number of iterations: " << niters << ". ";
std::cout << "Final residual: " << normr << std::endl;
std::cout << "Time (per iteration): " << times[1] << ";" << std::endl;
std::cout << "Total number of Floating operations (FLOPS): " << fnops << std::endl;
std::cout << "MFLOPS: " << fnops/times[1]/1.0E6 << std::endl;
}
// Compute difference between known exact solution and computed solution
// All processors are needed here.
double residual = 0;
// if ((ierr = compute_residual(A->local_nrow, x, xexact, &residual)))
// cerr << "Error in call to compute_residual: " << ierr << ".\n" << endl;
// if (rank==0)
// cout << "Difference between computed and exact = "
// << residual << ".\n" << endl;
// Finish up
#ifdef USING_MPI
MPI_Finalize();
#endif
return nrow;
}
int flush_cache()
{
int cs = (1024 * 1024 * 1024);
double* flush = (double*) calloc (cs, sizeof(double));
double* flush2 = (double*) calloc (cs, sizeof(double));
double* flush3 = (double*) calloc (cs, sizeof(double));
double* flush4 = (double*) calloc (cs, sizeof(double));
int i;
double tmp = 0.0;
#pragma omp parallel for
for (i = 0; i < cs; i++)
{
tmp += flush[i];
tmp += flush2[i] + flush3[i] + flush4[i];
}
free (flush);
free (flush2);
free (flush3);
free (flush4);
return tmp;
}
int main(int argc, char *argv[])
{
assert(argc >= 3);
double * r_ref;
Halide::Buffer<double> r_tiramisu(atoi(argv[1])*atoi(argv[2])*atoi(argv[3]));
double normr_tiramisu = 0.0;
double normr_ref = 0.0;
int res = flush_cache();
std::cout << "*************************** Tiramisu CG **************************************" << std::endl;
main_tiramisu(argc, argv, r_tiramisu, normr_tiramisu);
std::cout << "*************************** Reference CG ***************************************" << std::endl;
res += flush_cache();
int nrow = main_ref(argc, argv, &r_ref, normr_ref);
std::cout << "******************************************************************" << std::endl;
if (std::abs(normr_ref - normr_tiramisu) >= 0.000000000000000000001)
{
std::cerr << "Residuals of the two computations are not equal" << std::endl;
std::cerr << "normr_ref = " << normr_ref << " and normr_tiramisu = " << normr_tiramisu << std::endl;
std::cerr << "normr_ref - normr_tiramisu = " << normr_ref - normr_tiramisu << std::endl;
exit(1);
}
// Compare r_ref and r_tiramisu
for (int i = 0; i < nrow; i++)
if (std::abs(r_ref[i] - r_tiramisu(i)) >= 0.0001)
{
std::cerr << "r_ref[" << i << "] != r_tiramisu[" << i << "]" << std::endl;
exit(1);
}
std::cout << "Correct computations." << std::endl;
std::cout << "Residuals equal." << std::endl;
free(r_ref);
return res ;
}
<|endoftext|> |
<commit_before>/*--------------------------------------------------------------------------
File : ble_intrf.cpp
Author : Hoang Nguyen Hoan Feb. 6, 2017
Desc : Implementation allow the creation of generic serial interface of
a custom Bluetooth Smart service with multiple user defined
characteristics.
Copyright (c) 2017, I-SYST inc., all rights reserved
Permission to use, copy, modify, and distribute this software for any purpose
with or without fee is hereby granted, provided that the above copyright
notice and this permission notice appear in all copies, and none of the
names : I-SYST or its contributors may be used to endorse or
promote products derived from this software without specific prior written
permission.
For info or contributing contact : hnhoan at i-syst dot com
THIS SOFTWARE IS PROVIDED BY THE REGENTS 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 REGENTS 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.
----------------------------------------------------------------------------
Modified by Date Description
----------------------------------------------------------------------------*/
#include <string.h>
#include "cfifo.h"
#include "ble_intrf.h"
#include "ble_app.h"
#define NRFBLEINTRF_PACKET_SIZE NRF_BLE_MAX_MTU_SIZE
#define NRFBLEINTRF_CFIFO_SIZE CFIFO_TOTAL_MEMSIZE(2, NRFBLEINTRF_PACKET_SIZE + sizeof(BLEINTRF_PKT) - 1)
static uint8_t s_nRFBleRxFifoMem[NRFBLEINTRF_CFIFO_SIZE];
static uint8_t s_nRFBleTxFifoMem[NRFBLEINTRF_CFIFO_SIZE];
/**
* @brief - Disable
* Turn off the interface. If this is a physical interface, provide a
* way to turn off for energy saving. Make sure the turn off procedure can
* be turned back on without going through the full init sequence
*
* @param
* pDevIntrf : Pointer to an instance of the Device Interface
*
* @return None
*/
void BleIntrfDisable(DEVINTRF *pDevIntrf)
{
// TODO:
}
/**
* @brief - Enable
* Turn on the interface.
*
* @param
* pDevIntrf : Pointer to an instance of the Device Interface
*
* @return None
*/
void BleIntrfEnable(DEVINTRF *pDevIntrf)
{
// TODO:
}
/**
* @brief - GetRate
* Get data rate of the interface in Hertz. This is not a clock frequency
* but rather the transfer frequency (number of transfers per second). It has meaning base on the
* implementation as bits/sec or bytes/sec or whatever the case
*
* @param
* pDevIntrf : Pointer to an instance of the Device Interface
*
* @return Transfer rate per second
*/
int BleIntrfGetRate(DEVINTRF *pDevIntrf)
{
return 0; // BLE has no rate
}
/**
* @brief - SetRate
* Set data rate of the interface in Hertz. This is not a clock frequency
* but rather the transfer frequency (number of transfers per second). It has meaning base on the
* implementation as bits/sec or bytes/sec or whatever the case
*
* @param
* pDevIntrf : Pointer to an instance of the Device Interface
* Rate : Data rate to be set in Hertz (transfer per second)
*
* @return Actual transfer rate per second set. It is the real capable rate
* closes to rate being requested.
*/
int BleIntrfSetRate(DEVINTRF *pDevIntrf, int Rate)
{
return 0; // BLE has no rate
}
/**
* @brief - StartRx
* Prepare start condition to receive data with subsequence RxData.
* This can be in case such as start condition for I2C or Chip Select for
* SPI or precondition for DMA transfer or whatever requires it or not
* This function must check & set the busy state for re-entrancy
*
* @param
* pDevIntrf : Pointer to an instance of the Device Interface
* DevAddr : The device selection id scheme
*
* @return true - Success
* false - failed.
*/
bool BleIntrfStartRx(DEVINTRF *pDevIntrf, int DevAddr)
{
return true;
}
/**
* @brief - RxData : retrieve 1 packet of received data
* Receive data into pBuff passed in parameter. Assuming StartRx was
* called prior calling this function to get the actual data. BufferLen
* to receive data must be at least 1 packet in size. Otherwise remaining
* bytes are dropped.
*
* @param
* pDevIntrf : Pointer to an instance of the Device Interface
* pBuff : Pointer to memory area to receive data.
* BuffLen : Length of buffer memory in bytes. Must be at least 1 packet
* in size. Otherwise remaining bytes are dropped.
*
* @return Number of bytes read
*/
int BleIntrfRxData(DEVINTRF *pDevIntrf, uint8_t *pBuff, int BuffLen)
{
BLEINTRF *intrf = (BLEINTRF*)pDevIntrf->pDevData;
BLEINTRF_PKT *pkt;
int cnt = 0;
pkt = (BLEINTRF_PKT *)CFifoGet(intrf->hRxFifo);
if (pkt != NULL)
{
cnt = min(BuffLen, pkt->Len);
memcpy(pBuff, pkt->Data, cnt);
}
return cnt;
}
/**
* @brief - StopRx
* Completion of read data phase. Do require post processing
* after data has been received via RxData
* This function must clear the busy state for re-entrancy
*
* @param
* pDevIntrf : Pointer to an instance of the Device Interface
*
* @return None
*/
void BleIntrfStopRx(DEVINTRF *pSerDev)
{
// TODO:
}
/**
* @brief - StartTx
* Prepare start condition to transfer data with subsequence TxData.
* This can be in case such as start condition for I2C or Chip Select for
* SPI or precondition for DMA transfer or whatever requires it or not
* This function must check & set the busy state for re-entrancy
*
* @param
* pDevIntrf : Pointer to an instance of the Device Interface
* DevAddr : The device selection id scheme
*
* @return true - Success
* false - failed
*/
bool BleIntrfStartTx(DEVINTRF *pDevIntrf, int DevAddr)
{
return true;
}
bool BleIntrfNotify(BLEINTRF *pIntrf)
{
BLEINTRF_PKT *pkt;
uint32_t res = NRF_SUCCESS;
if (pIntrf->TransBuffLen > 0)
{
res = BleSrvcCharNotify(pIntrf->pBleSrv, pIntrf->TxCharIdx, pIntrf->TransBuff, pIntrf->TransBuffLen);
}
if (res == NRF_SUCCESS)
{
pIntrf->TransBuffLen = 0;
do {
pkt = (BLEINTRF_PKT *)CFifoGet(pIntrf->hTxFifo);
if (pkt != NULL)
{
uint32_t res = BleSrvcCharNotify(pIntrf->pBleSrv, pIntrf->TxCharIdx, pkt->Data, pkt->Len);
if (res != NRF_SUCCESS)
{
memcpy(pIntrf->TransBuff, pkt->Data, pkt->Len);
pIntrf->TransBuffLen = pkt->Len;
break;
}
}
} while (pkt != NULL);
}
}
/**
* @brief - TxData
* Transfer data from pData passed in parameter. Assuming StartTx was
* called prior calling this function to send the actual data
*
* @param
* pDevIntrf : Pointer to an instance of the Device Interface
* pData : Pointer to memory area of data to send.
* DataLen : Length of data memory in bytes
*
* @return Number of bytes sent
*/
int BleIntrfTxData(DEVINTRF *pDevIntrf, uint8_t *pData, int DataLen)
{
BLEINTRF *intrf = (BLEINTRF*)pDevIntrf->pDevData;
BLEINTRF_PKT *pkt;
int maxlen = intrf->hTxFifo->BlkSize - sizeof(pkt->Len);
int cnt = 0;
uint32_t res;
while (DataLen > 0)
{
pkt = (BLEINTRF_PKT *)CFifoPut(intrf->hTxFifo);
if (pkt == NULL)
break;
int l = min(DataLen, maxlen);
memcpy(pkt->Data, pData, l);
pkt->Len = l;
DataLen -= l;
pData += l;
cnt += l;
}
BleIntrfNotify(intrf);
return cnt;
}
/**
* @brief - StopTx
* Completion of sending data via TxData. Do require post processing
* after all data was transmitted via TxData.
* This function must clear the busy state for re-entrancy
*
* @param
* pDevIntrf : Pointer to an instance of the Device Interface
*
* @return None
*/
void BleIntrfStopTx(DEVINTRF *pDevIntrf)
{
}
/**
* @brief - Reset
* This function perform a reset of interface. Must provide empty
* function of not used.
*
* @param
* pDevIntrf : Pointer to an instance of the Device Interface
*
* @return None
*/
void BleIntrfReset(DEVINTRF *pDevIntrf)
{
}
/**
*
*
*/
void BleIntrfTxComplete(BLESRVC *pBleSvc, int CharIdx)
{
BleIntrfNotify((BLEINTRF*)pBleSvc->pContext);
}
void BleIntrfRxWrCB(BLESRVC *pBleSvc, uint8_t *pData, int Offset, int Len)
{
BLEINTRF *intrf = (BLEINTRF*)pBleSvc->pContext;
BLEINTRF_PKT *pkt;
int maxlen = intrf->hTxFifo->BlkSize - sizeof(pkt->Len);
while (Len > 0) {
pkt = (BLEINTRF_PKT *)CFifoPut(intrf->hRxFifo);
if (pkt == NULL)
break;
int l = min(intrf->PacketSize, Len);
memcpy(pkt->Data, pData, l);
pkt->Len = l;
Len -= l;
pData += l;
}
if (CFifoUsed(intrf->hRxFifo) > 0 && intrf->DevIntrf.EvtCB != NULL)
{
intrf->DevIntrf.EvtCB(&intrf->DevIntrf, DEVINTRF_EVT_RX_DATA, NULL, 0);
}
}
bool BleIntrfInit(BLEINTRF *pBleIntrf, const BLEINTRF_CFG *pCfg)
{
if (pBleIntrf == NULL || pCfg == NULL)
return false;
if (pCfg->PacketSize <= 0)
{
pBleIntrf->PacketSize = NRFBLEINTRF_PACKET_SIZE;
}
else
{
pBleIntrf->PacketSize = pCfg->PacketSize;
}
if (pCfg->pRxFifoMem == NULL || pCfg->pTxFifoMem == NULL)
{
pBleIntrf->hRxFifo = CFifoInit(s_nRFBleRxFifoMem, NRFBLEINTRF_CFIFO_SIZE, pBleIntrf->PacketSize, true);
pBleIntrf->hTxFifo = CFifoInit(s_nRFBleTxFifoMem, NRFBLEINTRF_CFIFO_SIZE, pBleIntrf->PacketSize, true);
}
else
{
pBleIntrf->hRxFifo = CFifoInit(pCfg->pRxFifoMem, pCfg->RxFifoMemSize, pBleIntrf->PacketSize, true);
pBleIntrf->hTxFifo = CFifoInit(pCfg->pTxFifoMem, pCfg->TxFifoMemSize, pBleIntrf->PacketSize, true);
}
pBleIntrf->DevIntrf.pDevData = (void*)pBleIntrf;
pBleIntrf->pBleSrv = pCfg->pBleSrv;
pBleIntrf->pBleSrv->pContext = pBleIntrf;
pBleIntrf->RxCharIdx = pCfg->RxCharIdx;
pBleIntrf->TxCharIdx = pCfg->TxCharIdx;
pBleIntrf->pBleSrv->pCharArray[pBleIntrf->RxCharIdx].WrCB = BleIntrfRxWrCB;
pBleIntrf->pBleSrv->pCharArray[pBleIntrf->TxCharIdx].TxCompleteCB = BleIntrfTxComplete;
pBleIntrf->DevIntrf.Enable = BleIntrfEnable;
pBleIntrf->DevIntrf.Disable = BleIntrfDisable;
pBleIntrf->DevIntrf.GetRate = BleIntrfGetRate;
pBleIntrf->DevIntrf.SetRate = BleIntrfSetRate;
pBleIntrf->DevIntrf.StartRx = BleIntrfStartRx;
pBleIntrf->DevIntrf.RxData = BleIntrfRxData;
pBleIntrf->DevIntrf.StopRx = BleIntrfStopRx;
pBleIntrf->DevIntrf.StartTx = BleIntrfStartTx;
pBleIntrf->DevIntrf.TxData = BleIntrfTxData;
pBleIntrf->DevIntrf.StopTx = BleIntrfStopTx;
pBleIntrf->DevIntrf.Busy = false;
pBleIntrf->DevIntrf.MaxRetry = 0;
pBleIntrf->DevIntrf.EvtCB = pCfg->EvtCB;
pBleIntrf->TransBuffLen = 0;
return true;
}
bool BleIntrf::Init(const BLEINTRF_CFG &Cfg)
{
return BleIntrfInit(&vBleIntrf, &Cfg);
}
bool BleIntrf::RequestToSend(int NbBytes)
{
bool retval = false;
// ****
// Some threaded application firmware may stop sending when queue full
// causing lockup
// Try to send to free up the queue before validating.
//
BleIntrfNotify(&vBleIntrf);
if (vBleIntrf.hTxFifo)
{
int avail = CFifoAvail(vBleIntrf.hTxFifo);
if ((avail * vBleIntrf.PacketSize) > NbBytes)
retval = true;
}
else
{
retval = true;
}
return retval;
}
<commit_msg>Softdevice still queue package even when returning non success. Only case it does not queue notif is no resource return code. This is still persist until now SDK14.2<commit_after>/*--------------------------------------------------------------------------
File : ble_intrf.cpp
Author : Hoang Nguyen Hoan Feb. 6, 2017
Desc : Implementation allow the creation of generic serial interface of
a custom Bluetooth Smart service with multiple user defined
characteristics.
Copyright (c) 2017, I-SYST inc., all rights reserved
Permission to use, copy, modify, and distribute this software for any purpose
with or without fee is hereby granted, provided that the above copyright
notice and this permission notice appear in all copies, and none of the
names : I-SYST or its contributors may be used to endorse or
promote products derived from this software without specific prior written
permission.
For info or contributing contact : hnhoan at i-syst dot com
THIS SOFTWARE IS PROVIDED BY THE REGENTS 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 REGENTS 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.
----------------------------------------------------------------------------
Modified by Date Description
----------------------------------------------------------------------------*/
#include <string.h>
#include "cfifo.h"
#include "ble_intrf.h"
#include "ble_app.h"
#define NRFBLEINTRF_PACKET_SIZE NRF_BLE_MAX_MTU_SIZE
#define NRFBLEINTRF_CFIFO_SIZE CFIFO_TOTAL_MEMSIZE(2, NRFBLEINTRF_PACKET_SIZE + sizeof(BLEINTRF_PKT) - 1)
static uint8_t s_nRFBleRxFifoMem[NRFBLEINTRF_CFIFO_SIZE];
static uint8_t s_nRFBleTxFifoMem[NRFBLEINTRF_CFIFO_SIZE];
/**
* @brief - Disable
* Turn off the interface. If this is a physical interface, provide a
* way to turn off for energy saving. Make sure the turn off procedure can
* be turned back on without going through the full init sequence
*
* @param
* pDevIntrf : Pointer to an instance of the Device Interface
*
* @return None
*/
void BleIntrfDisable(DEVINTRF *pDevIntrf)
{
// TODO:
}
/**
* @brief - Enable
* Turn on the interface.
*
* @param
* pDevIntrf : Pointer to an instance of the Device Interface
*
* @return None
*/
void BleIntrfEnable(DEVINTRF *pDevIntrf)
{
// TODO:
}
/**
* @brief - GetRate
* Get data rate of the interface in Hertz. This is not a clock frequency
* but rather the transfer frequency (number of transfers per second). It has meaning base on the
* implementation as bits/sec or bytes/sec or whatever the case
*
* @param
* pDevIntrf : Pointer to an instance of the Device Interface
*
* @return Transfer rate per second
*/
int BleIntrfGetRate(DEVINTRF *pDevIntrf)
{
return 0; // BLE has no rate
}
/**
* @brief - SetRate
* Set data rate of the interface in Hertz. This is not a clock frequency
* but rather the transfer frequency (number of transfers per second). It has meaning base on the
* implementation as bits/sec or bytes/sec or whatever the case
*
* @param
* pDevIntrf : Pointer to an instance of the Device Interface
* Rate : Data rate to be set in Hertz (transfer per second)
*
* @return Actual transfer rate per second set. It is the real capable rate
* closes to rate being requested.
*/
int BleIntrfSetRate(DEVINTRF *pDevIntrf, int Rate)
{
return 0; // BLE has no rate
}
/**
* @brief - StartRx
* Prepare start condition to receive data with subsequence RxData.
* This can be in case such as start condition for I2C or Chip Select for
* SPI or precondition for DMA transfer or whatever requires it or not
* This function must check & set the busy state for re-entrancy
*
* @param
* pDevIntrf : Pointer to an instance of the Device Interface
* DevAddr : The device selection id scheme
*
* @return true - Success
* false - failed.
*/
bool BleIntrfStartRx(DEVINTRF *pDevIntrf, int DevAddr)
{
return true;
}
/**
* @brief - RxData : retrieve 1 packet of received data
* Receive data into pBuff passed in parameter. Assuming StartRx was
* called prior calling this function to get the actual data. BufferLen
* to receive data must be at least 1 packet in size. Otherwise remaining
* bytes are dropped.
*
* @param
* pDevIntrf : Pointer to an instance of the Device Interface
* pBuff : Pointer to memory area to receive data.
* BuffLen : Length of buffer memory in bytes. Must be at least 1 packet
* in size. Otherwise remaining bytes are dropped.
*
* @return Number of bytes read
*/
int BleIntrfRxData(DEVINTRF *pDevIntrf, uint8_t *pBuff, int BuffLen)
{
BLEINTRF *intrf = (BLEINTRF*)pDevIntrf->pDevData;
BLEINTRF_PKT *pkt;
int cnt = 0;
pkt = (BLEINTRF_PKT *)CFifoGet(intrf->hRxFifo);
if (pkt != NULL)
{
cnt = min(BuffLen, pkt->Len);
memcpy(pBuff, pkt->Data, cnt);
}
return cnt;
}
/**
* @brief - StopRx
* Completion of read data phase. Do require post processing
* after data has been received via RxData
* This function must clear the busy state for re-entrancy
*
* @param
* pDevIntrf : Pointer to an instance of the Device Interface
*
* @return None
*/
void BleIntrfStopRx(DEVINTRF *pSerDev)
{
// TODO:
}
/**
* @brief - StartTx
* Prepare start condition to transfer data with subsequence TxData.
* This can be in case such as start condition for I2C or Chip Select for
* SPI or precondition for DMA transfer or whatever requires it or not
* This function must check & set the busy state for re-entrancy
*
* @param
* pDevIntrf : Pointer to an instance of the Device Interface
* DevAddr : The device selection id scheme
*
* @return true - Success
* false - failed
*/
bool BleIntrfStartTx(DEVINTRF *pDevIntrf, int DevAddr)
{
return true;
}
bool BleIntrfNotify(BLEINTRF *pIntrf)
{
BLEINTRF_PKT *pkt;
uint32_t res = NRF_SUCCESS;
if (pIntrf->TransBuffLen > 0)
{
res = BleSrvcCharNotify(pIntrf->pBleSrv, pIntrf->TxCharIdx, pIntrf->TransBuff, pIntrf->TransBuffLen);
}
if (res != NRF_ERROR_RESOURCES)
{
pIntrf->TransBuffLen = 0;
do {
pkt = (BLEINTRF_PKT *)CFifoGet(pIntrf->hTxFifo);
if (pkt != NULL)
{
uint32_t res = BleSrvcCharNotify(pIntrf->pBleSrv, pIntrf->TxCharIdx, pkt->Data, pkt->Len);
if (res == NRF_ERROR_RESOURCES)
{
memcpy(pIntrf->TransBuff, pkt->Data, pkt->Len);
pIntrf->TransBuffLen = pkt->Len;
break;
}
}
} while (pkt != NULL);
}
}
/**
* @brief - TxData
* Transfer data from pData passed in parameter. Assuming StartTx was
* called prior calling this function to send the actual data
*
* @param
* pDevIntrf : Pointer to an instance of the Device Interface
* pData : Pointer to memory area of data to send.
* DataLen : Length of data memory in bytes
*
* @return Number of bytes sent
*/
int BleIntrfTxData(DEVINTRF *pDevIntrf, uint8_t *pData, int DataLen)
{
BLEINTRF *intrf = (BLEINTRF*)pDevIntrf->pDevData;
BLEINTRF_PKT *pkt;
int maxlen = intrf->hTxFifo->BlkSize - sizeof(pkt->Len);
int cnt = 0;
uint32_t res;
while (DataLen > 0)
{
pkt = (BLEINTRF_PKT *)CFifoPut(intrf->hTxFifo);
if (pkt == NULL)
break;
int l = min(DataLen, maxlen);
memcpy(pkt->Data, pData, l);
pkt->Len = l;
DataLen -= l;
pData += l;
cnt += l;
}
BleIntrfNotify(intrf);
return cnt;
}
/**
* @brief - StopTx
* Completion of sending data via TxData. Do require post processing
* after all data was transmitted via TxData.
* This function must clear the busy state for re-entrancy
*
* @param
* pDevIntrf : Pointer to an instance of the Device Interface
*
* @return None
*/
void BleIntrfStopTx(DEVINTRF *pDevIntrf)
{
}
/**
* @brief - Reset
* This function perform a reset of interface. Must provide empty
* function of not used.
*
* @param
* pDevIntrf : Pointer to an instance of the Device Interface
*
* @return None
*/
void BleIntrfReset(DEVINTRF *pDevIntrf)
{
}
/**
*
*
*/
void BleIntrfTxComplete(BLESRVC *pBleSvc, int CharIdx)
{
BleIntrfNotify((BLEINTRF*)pBleSvc->pContext);
}
void BleIntrfRxWrCB(BLESRVC *pBleSvc, uint8_t *pData, int Offset, int Len)
{
BLEINTRF *intrf = (BLEINTRF*)pBleSvc->pContext;
BLEINTRF_PKT *pkt;
int maxlen = intrf->hTxFifo->BlkSize - sizeof(pkt->Len);
while (Len > 0) {
pkt = (BLEINTRF_PKT *)CFifoPut(intrf->hRxFifo);
if (pkt == NULL)
break;
int l = min(intrf->PacketSize, Len);
memcpy(pkt->Data, pData, l);
pkt->Len = l;
Len -= l;
pData += l;
}
if (CFifoUsed(intrf->hRxFifo) > 0 && intrf->DevIntrf.EvtCB != NULL)
{
intrf->DevIntrf.EvtCB(&intrf->DevIntrf, DEVINTRF_EVT_RX_DATA, NULL, 0);
}
}
bool BleIntrfInit(BLEINTRF *pBleIntrf, const BLEINTRF_CFG *pCfg)
{
if (pBleIntrf == NULL || pCfg == NULL)
return false;
if (pCfg->PacketSize <= 0)
{
pBleIntrf->PacketSize = NRFBLEINTRF_PACKET_SIZE;
}
else
{
pBleIntrf->PacketSize = pCfg->PacketSize;
}
if (pCfg->pRxFifoMem == NULL || pCfg->pTxFifoMem == NULL)
{
pBleIntrf->hRxFifo = CFifoInit(s_nRFBleRxFifoMem, NRFBLEINTRF_CFIFO_SIZE, pBleIntrf->PacketSize, true);
pBleIntrf->hTxFifo = CFifoInit(s_nRFBleTxFifoMem, NRFBLEINTRF_CFIFO_SIZE, pBleIntrf->PacketSize, true);
}
else
{
pBleIntrf->hRxFifo = CFifoInit(pCfg->pRxFifoMem, pCfg->RxFifoMemSize, pBleIntrf->PacketSize, true);
pBleIntrf->hTxFifo = CFifoInit(pCfg->pTxFifoMem, pCfg->TxFifoMemSize, pBleIntrf->PacketSize, true);
}
pBleIntrf->DevIntrf.pDevData = (void*)pBleIntrf;
pBleIntrf->pBleSrv = pCfg->pBleSrv;
pBleIntrf->pBleSrv->pContext = pBleIntrf;
pBleIntrf->RxCharIdx = pCfg->RxCharIdx;
pBleIntrf->TxCharIdx = pCfg->TxCharIdx;
pBleIntrf->pBleSrv->pCharArray[pBleIntrf->RxCharIdx].WrCB = BleIntrfRxWrCB;
pBleIntrf->pBleSrv->pCharArray[pBleIntrf->TxCharIdx].TxCompleteCB = BleIntrfTxComplete;
pBleIntrf->DevIntrf.Enable = BleIntrfEnable;
pBleIntrf->DevIntrf.Disable = BleIntrfDisable;
pBleIntrf->DevIntrf.GetRate = BleIntrfGetRate;
pBleIntrf->DevIntrf.SetRate = BleIntrfSetRate;
pBleIntrf->DevIntrf.StartRx = BleIntrfStartRx;
pBleIntrf->DevIntrf.RxData = BleIntrfRxData;
pBleIntrf->DevIntrf.StopRx = BleIntrfStopRx;
pBleIntrf->DevIntrf.StartTx = BleIntrfStartTx;
pBleIntrf->DevIntrf.TxData = BleIntrfTxData;
pBleIntrf->DevIntrf.StopTx = BleIntrfStopTx;
pBleIntrf->DevIntrf.Busy = false;
pBleIntrf->DevIntrf.MaxRetry = 0;
pBleIntrf->DevIntrf.EvtCB = pCfg->EvtCB;
pBleIntrf->TransBuffLen = 0;
return true;
}
bool BleIntrf::Init(const BLEINTRF_CFG &Cfg)
{
return BleIntrfInit(&vBleIntrf, &Cfg);
}
bool BleIntrf::RequestToSend(int NbBytes)
{
bool retval = false;
// ****
// Some threaded application firmware may stop sending when queue full
// causing lockup
// Try to send to free up the queue before validating.
//
BleIntrfNotify(&vBleIntrf);
if (vBleIntrf.hTxFifo)
{
int avail = CFifoAvail(vBleIntrf.hTxFifo);
if ((avail * vBleIntrf.PacketSize) > NbBytes)
retval = true;
}
else
{
retval = true;
}
return retval;
}
<|endoftext|> |
<commit_before>/*
* Open Chinese Convert
*
* Copyright 2010-2014 BYVoid <byvoid@byvoid.com>
*
* 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.
*/
#ifdef _MSC_VER
#define NOMINMAX
#include <Windows.h>
#undef NOMINMAX
#endif // _MSC_VER
#include "Config.hpp"
#include "Converter.hpp"
#include "opencc.h"
#include "UTF8Util.hpp"
using namespace opencc;
struct InternalData {
const ConverterPtr converter;
InternalData(const ConverterPtr& _converter) : converter(_converter) {}
};
SimpleConverter::SimpleConverter(const std::string& configFileName) {
try {
Config config;
internalData = new InternalData(config.NewFromFile(configFileName));
} catch (Exception& ex) {
throw std::runtime_error(ex.what());
}
}
SimpleConverter::~SimpleConverter() { delete (InternalData*)internalData; }
std::string SimpleConverter::Convert(const std::string& input) const {
try {
const InternalData* data = (InternalData*)internalData;
return data->converter->Convert(input);
} catch (Exception& ex) {
throw std::runtime_error(ex.what());
}
}
std::string SimpleConverter::Convert(const char* input) const {
return Convert(string(input));
}
std::string SimpleConverter::Convert(const char* input, size_t length) const {
if (length == static_cast<size_t>(-1)) {
return Convert(string(input));
} else {
return Convert(UTF8Util::FromSubstr(input, length));
}
}
size_t SimpleConverter::Convert(const char* input, char* output) const {
try {
const InternalData* data = (InternalData*)internalData;
return data->converter->Convert(input, output);
} catch (Exception& ex) {
throw std::runtime_error(ex.what());
}
}
size_t SimpleConverter::Convert(const char* input, size_t length,
char* output) const {
if (length == static_cast<size_t>(-1)) {
return Convert(input, output);
} else {
string trimmed = UTF8Util::FromSubstr(input, length);
return Convert(trimmed.c_str(), output);
}
}
static string cError;
opencc_t opencc_open_internal(const char* configFileName) {
try {
if (configFileName == nullptr) {
configFileName = OPENCC_DEFAULT_CONFIG_SIMP_TO_TRAD;
}
SimpleConverter* instance = new SimpleConverter(configFileName);
return instance;
} catch (std::runtime_error& ex) {
cError = ex.what();
return reinterpret_cast<opencc_t>(-1);
}
}
#ifdef _MSC_VER
opencc_t opencc_open_w(const wchar_t* configFileName) {
try {
if (configFileName == nullptr) {
return opencc_open_internal(nullptr);
}
std::string utf8fn = UTF8Util::U16ToU8(configFileName);
return opencc_open_internal(utf8fn.c_str());
} catch (std::runtime_error& ex) {
cError = ex.what();
return reinterpret_cast<opencc_t>(-1);
}
}
opencc_t opencc_open(const char* configFileName) {
if (configFileName == nullptr) {
return opencc_open_internal(nullptr);
}
std::wstring wFileName;
int convcnt = MultiByteToWideChar(CP_ACP, 0, configFileName, -1, NULL, 0);
if (convcnt > 0) {
wFileName.resize(convcnt);
MultiByteToWideChar(CP_ACP, 0, configFileName, -1, &wFileName[0], convcnt);
}
return opencc_open_w(wFileName.c_str());
}
#else
opencc_t opencc_open(const char* configFileName) {
return opencc_open_internal(configFileName);
}
#endif
int opencc_close(opencc_t opencc) {
try {
SimpleConverter* instance = reinterpret_cast<SimpleConverter*>(opencc);
delete instance;
return 0;
} catch (std::exception& ex) {
cError = ex.what();
return 1;
}
catch (Exception& ex) {
cError = ex.what();
return 1;
}
}
size_t opencc_convert_utf8_to_buffer(opencc_t opencc, const char* input,
size_t length, char* output) {
try {
SimpleConverter* instance = reinterpret_cast<SimpleConverter*>(opencc);
return instance->Convert(input, length, output);
} catch (std::runtime_error& ex) {
cError = ex.what();
return static_cast<size_t>(-1);
}
}
char* opencc_convert_utf8(opencc_t opencc, const char* input, size_t length) {
try {
SimpleConverter* instance = reinterpret_cast<SimpleConverter*>(opencc);
std::string converted = instance->Convert(input, length);
char* output = new char[converted.length() + 1];
strncpy(output, converted.c_str(), converted.length());
output[converted.length()] = '\0';
return output;
} catch (std::runtime_error& ex) {
cError = ex.what();
return nullptr;
}
}
void opencc_convert_utf8_free(char* str) { delete[] str; }
const char* opencc_error(void) { return cError.c_str(); }
<commit_msg>Remove unreachable code.<commit_after>/*
* Open Chinese Convert
*
* Copyright 2010-2014 BYVoid <byvoid@byvoid.com>
*
* 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.
*/
#ifdef _MSC_VER
#define NOMINMAX
#include <Windows.h>
#undef NOMINMAX
#endif // _MSC_VER
#include "Config.hpp"
#include "Converter.hpp"
#include "opencc.h"
#include "UTF8Util.hpp"
using namespace opencc;
struct InternalData {
const ConverterPtr converter;
InternalData(const ConverterPtr& _converter) : converter(_converter) {}
};
SimpleConverter::SimpleConverter(const std::string& configFileName) {
try {
Config config;
internalData = new InternalData(config.NewFromFile(configFileName));
} catch (Exception& ex) {
throw std::runtime_error(ex.what());
}
}
SimpleConverter::~SimpleConverter() { delete (InternalData*)internalData; }
std::string SimpleConverter::Convert(const std::string& input) const {
try {
const InternalData* data = (InternalData*)internalData;
return data->converter->Convert(input);
} catch (Exception& ex) {
throw std::runtime_error(ex.what());
}
}
std::string SimpleConverter::Convert(const char* input) const {
return Convert(string(input));
}
std::string SimpleConverter::Convert(const char* input, size_t length) const {
if (length == static_cast<size_t>(-1)) {
return Convert(string(input));
} else {
return Convert(UTF8Util::FromSubstr(input, length));
}
}
size_t SimpleConverter::Convert(const char* input, char* output) const {
try {
const InternalData* data = (InternalData*)internalData;
return data->converter->Convert(input, output);
} catch (Exception& ex) {
throw std::runtime_error(ex.what());
}
}
size_t SimpleConverter::Convert(const char* input, size_t length,
char* output) const {
if (length == static_cast<size_t>(-1)) {
return Convert(input, output);
} else {
string trimmed = UTF8Util::FromSubstr(input, length);
return Convert(trimmed.c_str(), output);
}
}
static string cError;
opencc_t opencc_open_internal(const char* configFileName) {
try {
if (configFileName == nullptr) {
configFileName = OPENCC_DEFAULT_CONFIG_SIMP_TO_TRAD;
}
SimpleConverter* instance = new SimpleConverter(configFileName);
return instance;
} catch (std::runtime_error& ex) {
cError = ex.what();
return reinterpret_cast<opencc_t>(-1);
}
}
#ifdef _MSC_VER
opencc_t opencc_open_w(const wchar_t* configFileName) {
try {
if (configFileName == nullptr) {
return opencc_open_internal(nullptr);
}
std::string utf8fn = UTF8Util::U16ToU8(configFileName);
return opencc_open_internal(utf8fn.c_str());
} catch (std::runtime_error& ex) {
cError = ex.what();
return reinterpret_cast<opencc_t>(-1);
}
}
opencc_t opencc_open(const char* configFileName) {
if (configFileName == nullptr) {
return opencc_open_internal(nullptr);
}
std::wstring wFileName;
int convcnt = MultiByteToWideChar(CP_ACP, 0, configFileName, -1, NULL, 0);
if (convcnt > 0) {
wFileName.resize(convcnt);
MultiByteToWideChar(CP_ACP, 0, configFileName, -1, &wFileName[0], convcnt);
}
return opencc_open_w(wFileName.c_str());
}
#else
opencc_t opencc_open(const char* configFileName) {
return opencc_open_internal(configFileName);
}
#endif
int opencc_close(opencc_t opencc) {
SimpleConverter* instance = reinterpret_cast<SimpleConverter*>(opencc);
delete instance;
return 0;
}
size_t opencc_convert_utf8_to_buffer(opencc_t opencc, const char* input,
size_t length, char* output) {
try {
SimpleConverter* instance = reinterpret_cast<SimpleConverter*>(opencc);
return instance->Convert(input, length, output);
} catch (std::runtime_error& ex) {
cError = ex.what();
return static_cast<size_t>(-1);
}
}
char* opencc_convert_utf8(opencc_t opencc, const char* input, size_t length) {
try {
SimpleConverter* instance = reinterpret_cast<SimpleConverter*>(opencc);
std::string converted = instance->Convert(input, length);
char* output = new char[converted.length() + 1];
strncpy(output, converted.c_str(), converted.length());
output[converted.length()] = '\0';
return output;
} catch (std::runtime_error& ex) {
cError = ex.what();
return nullptr;
}
}
void opencc_convert_utf8_free(char* str) { delete[] str; }
const char* opencc_error(void) { return cError.c_str(); }
<|endoftext|> |
<commit_before>#include <grouper.hpp>
#include <vector>
#include <array>
#include <string>
#include <utility>
#include "helpers.hpp"
#include "catch.hpp"
using iter::grouper;
using Vec = std::vector<int>;
using ResVec = std::vector<Vec>;
TEST_CASE("grouper: basic test", "[grouper]") {
Vec ns = {1,2,3,4,5,6};
ResVec results;
for (auto&& g : grouper(ns, 2)) {
results.emplace_back(std::begin(g), std::end(g));
}
ResVec rc = { {1, 2}, {3, 4}, {5, 6} };
REQUIRE( results == rc );
}
TEST_CASE("grouper: len(iterable) % groupsize != 0", "[grouper]") {
Vec ns = {1,2,3,4,5,6,7};
ResVec results;
for (auto&& g : grouper(ns, 3)) {
results.emplace_back(std::begin(g), std::end(g));
}
ResVec rc = { {1, 2, 3}, {4, 5, 6}, {7} };
REQUIRE( results == rc );
}
TEST_CASE("grouper: iterators can be compared", "[grouper]") {
Vec ns = {1,2,3,4,5,6,7};
auto g = grouper(ns, 3);
auto it = std::begin(g);
REQUIRE( it == std::begin(g) );
REQUIRE_FALSE( it != std::begin(g) );
++it;
REQUIRE( it != std::begin(g) );
REQUIRE_FALSE( it == std::begin(g) );
}
TEST_CASE("grouper: size 0 is empty", "[grouper]") {
Vec ns{1, 2, 3};
auto g = grouper(ns, 0);
REQUIRE( std::begin(g) == std::end(g) );
}
<commit_msg>tests grouper with empty iterable<commit_after>#include <grouper.hpp>
#include <vector>
#include <array>
#include <string>
#include <utility>
#include "helpers.hpp"
#include "catch.hpp"
using iter::grouper;
using Vec = std::vector<int>;
using ResVec = std::vector<Vec>;
TEST_CASE("grouper: basic test", "[grouper]") {
Vec ns = {1,2,3,4,5,6};
ResVec results;
for (auto&& g : grouper(ns, 2)) {
results.emplace_back(std::begin(g), std::end(g));
}
ResVec rc = { {1, 2}, {3, 4}, {5, 6} };
REQUIRE( results == rc );
}
TEST_CASE("grouper: len(iterable) % groupsize != 0", "[grouper]") {
Vec ns = {1,2,3,4,5,6,7};
ResVec results;
for (auto&& g : grouper(ns, 3)) {
results.emplace_back(std::begin(g), std::end(g));
}
ResVec rc = { {1, 2, 3}, {4, 5, 6}, {7} };
REQUIRE( results == rc );
}
TEST_CASE("grouper: iterators can be compared", "[grouper]") {
Vec ns = {1,2,3,4,5,6,7};
auto g = grouper(ns, 3);
auto it = std::begin(g);
REQUIRE( it == std::begin(g) );
REQUIRE_FALSE( it != std::begin(g) );
++it;
REQUIRE( it != std::begin(g) );
REQUIRE_FALSE( it == std::begin(g) );
}
TEST_CASE("grouper: size 0 is empty", "[grouper]") {
Vec ns{1, 2, 3};
auto g = grouper(ns, 0);
REQUIRE( std::begin(g) == std::end(g) );
}
TEST_CASE("grouper: empty iterable gives empty grouper", "[grouper]") {
Vec ns{};
auto g = grouper(ns, 1);
REQUIRE( std::begin(g) == std::end(g) );
}
<|endoftext|> |
<commit_before>#include "cinder/Cinder.h"
#include "cinder/app/AppNative.h"
#include "cinder/gl/gl.h"
#include "cinder/Clipboard.h"
#include "cinder/gl/Texture.h"
#include "cinder/Utilities.h"
#include "Resources.h"
using namespace ci;
using namespace ci::app;
using namespace std;
class ClipboardBasicApp : public AppNative {
public:
void keyDown( KeyEvent event );
void draw();
};
void ClipboardBasicApp::keyDown( KeyEvent event )
{
if( event.getChar() == 'c' && event.isAccelDown() ) {
Clipboard::setImage( loadImage( loadResource( RES_CINDER_LOGO ) ) );
// to copy the contents of the window, you might do something like
// Clipboard::setImage( copyWindowSurface() );
}
}
void ClipboardBasicApp::draw()
{
gl::clear( Color( 0.5f, 0.5f, 0.5f ) );
gl::setMatricesWindow( getWindowSize() );
if( Clipboard::hasImage() )
gl::draw( gl::Texture( Clipboard::getImage() ) );
else if( Clipboard::hasString() )
gl::drawString( Clipboard::getString(), Vec2f( 0, getWindowCenter().y ) );
else
gl::drawString( "Clipboard contents unknown", Vec2f( 0, getWindowCenter().y ) );
}
CINDER_APP_NATIVE( ClipboardBasicApp, RendererGl )
<commit_msg>Restored alpha blending on ClipboardSample<commit_after>#include "cinder/Cinder.h"
#include "cinder/app/AppNative.h"
#include "cinder/gl/gl.h"
#include "cinder/Clipboard.h"
#include "cinder/gl/Texture.h"
#include "cinder/Utilities.h"
#include "Resources.h"
using namespace ci;
using namespace ci::app;
using namespace std;
class ClipboardBasicApp : public AppNative {
public:
void keyDown( KeyEvent event );
void draw();
};
void ClipboardBasicApp::keyDown( KeyEvent event )
{
if( event.getChar() == 'c' && event.isAccelDown() ) {
Clipboard::setImage( loadImage( loadResource( RES_CINDER_LOGO ) ) );
// to copy the contents of the window, you might do something like
// Clipboard::setImage( copyWindowSurface() );
}
}
void ClipboardBasicApp::draw()
{
gl::clear( Color( 0.5f, 0.5f, 0.5f ) );
gl::setMatricesWindow( getWindowSize() );
gl::enableAlphaBlending();
if( Clipboard::hasImage() )
gl::draw( gl::Texture( Clipboard::getImage() ) );
else if( Clipboard::hasString() )
gl::drawString( Clipboard::getString(), Vec2f( 0, getWindowCenter().y ) );
else
gl::drawString( "Clipboard contents unknown", Vec2f( 0, getWindowCenter().y ) );
}
CINDER_APP_NATIVE( ClipboardBasicApp, RendererGl )
<|endoftext|> |
<commit_before>/*
* Telefónica Digital - Product Development and Innovation
*
* THIS CODE AND INFORMATION ARE PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND,
* EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR PURPOSE.
*
* Copyright (c) Telefónica Investigación y Desarrollo S.A.U.
* All rights reserved.
*/
#include "samson/stream/BlockListContainer.h" // Own interface
#include <list>
#include "samson/stream/Block.h" // Block
#include "samson/stream/BlockList.h" // BlockList
namespace samson {
namespace stream {
BlockListContainer::BlockListContainer(std::string container_name, size_t task_id) {
container_name_ = container_name;
task_id_ = task_id;
}
BlockListContainer::~BlockListContainer() {
blockLists_.clearMap(); // Remove all BlockList instances
}
BlockList *BlockListContainer::FindBlockList(std::string name) const {
// au::TokenTaker tt(&token_);
return blockLists_.findInMap(name);
}
BlockList *BlockListContainer::GetBlockList(std::string name) {
// au::TokenTaker tt(&token_);
BlockList *blockList = blockLists_.findInMap(name);
if (!blockList) {
blockList = new BlockList(au::str("<%s:%s>", container_name_.c_str(), name.c_str()), task_id_);
blockLists_.insertInMap(name, blockList);
}
return blockList;
}
void BlockListContainer::ClearBlockListcontainer() {
// au::TokenTaker tt(&token_);
blockLists_.clearMap(); // Remove all BlockList instances
}
size_t BlockListContainer::GetNumBlocks() const {
size_t total = 0;
au::map<std::string, BlockList>::const_iterator it;
for (it = blockLists_.begin(); it != blockLists_.end(); ++it) {
total += (it->second->getNumBlocks());
}
return total;
}
bool BlockListContainer::is_content_in_memory() const {
au::map<std::string, BlockList>::const_iterator it;
for (it = blockLists_.begin(); it != blockLists_.end(); ++it) {
BlockList *block_list = it->second;
if (!block_list->IsContentInMemory()) {
return false;
}
}
return true;
}
void BlockListContainer::lock_content_in_memory() {
au::map<std::string, BlockList>::iterator it;
for (it = blockLists_.begin(); it != blockLists_.end(); ++it) {
BlockList *block_list = it->second;
block_list->lock_content_in_memory();
}
}
std::string BlockListContainer::str_blocks() const {
std::ostringstream output;
au::map<std::string, BlockList>::const_iterator it;
for (it = blockLists_.begin(); it != blockLists_.end(); ++it) {
BlockList *block_list = it->second;
output << "<<" << it->first << " " << block_list->str_blocks() << ">> ";
}
return output.str();
}
std::string BlockListContainer::str_block_ids() const {
std::ostringstream output;
int num_inputs = 0;
for (int i = 0; i < 10; ++i) {
if (blockLists_.findInMap(au::str("input_%d", i))) {
num_inputs = i + 1;
}
}
int num_outputs = 0;
for (int i = 0; i < 10; ++i) {
if (blockLists_.findInMap(au::str("output_%d", i))) {
num_outputs = i + 1;
}
}
for (int i = 0; i < num_inputs; ++i) {
BlockList *block_list = blockLists_.findInMap(au::str("input_%d", i));
if (!block_list) {
output << "-";
} else {
output << block_list->str_blocks();
}
}
for (int i = 0; i < num_outputs; i++) {
BlockList *block_list = blockLists_.findInMap(au::str("output_%d", i));
if (!block_list) {
output << "-";
} else {
output << block_list->str_blocks();
}
}
return output.str();
}
std::string BlockListContainer::str_inputs() const {
int num_inputs = 0;
for (int i = 0; i < 10; ++i) {
if (blockLists_.findInMap(au::str("input_%d", i))) {
num_inputs = i + 1;
}
}
std::ostringstream output;
for (int i = 0; i < num_inputs; ++i) {
BlockList *block_list = blockLists_.findInMap(au::str("input_%d", i));
if (!block_list) {
output << "-";
}
BlockInfo block_info = block_list->getBlockInfo();
output << "[" << block_info.strShortInfo() << "]";
}
return output.str();
}
std::string BlockListContainer::str_outputs() const {
int num_outputs = 0;
for (int i = 0; i < 10; ++i) {
if (blockLists_.findInMap(au::str("output_%d", i))) {
num_outputs = i + 1;
}
}
std::ostringstream output;
for (int i = 0; i < num_outputs; i++) {
BlockList *block_list = blockLists_.findInMap(au::str("output_%d", i));
if (!block_list) {
output << "-";
}
BlockInfo block_info = block_list->getBlockInfo();
output << "[" << block_info.strShortInfo() << "]";
}
return output.str();
}
FullKVInfo BlockListContainer::GetInputsInfo() const {
int num_inputs = 0;
for (int i = 0; i < 10; ++i) {
if (blockLists_.findInMap(au::str("input_%d", i))) {
num_inputs = i + 1;
}
}
FullKVInfo info;
for (int i = 0; i < num_inputs; ++i) {
BlockList *block_list = blockLists_.findInMap(au::str("input_%d", i));
if (block_list) {
BlockInfo block_info = block_list->getBlockInfo();
info.append(block_info.info);
}
}
return info;
}
FullKVInfo BlockListContainer::GetOutputsInfo() const {
int num_outputs = 0;
for (int i = 0; i < 10; ++i) {
if (blockLists_.findInMap(au::str("output_%d", i))) {
num_outputs = i + 1;
}
}
FullKVInfo info;
for (int i = 0; i < num_outputs; ++i) {
BlockList *block_list = blockLists_.findInMap(au::str("output_%d", i));
if (block_list) {
BlockInfo block_info = block_list->getBlockInfo();
info.append(block_info.info);
}
}
return info;
}
}
}
<commit_msg>Fix bug in BlockListContainer<commit_after>/*
* Telefónica Digital - Product Development and Innovation
*
* THIS CODE AND INFORMATION ARE PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND,
* EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR PURPOSE.
*
* Copyright (c) Telefónica Investigación y Desarrollo S.A.U.
* All rights reserved.
*/
#include "samson/stream/BlockListContainer.h" // Own interface
#include <list>
#include "samson/stream/Block.h" // Block
#include "samson/stream/BlockList.h" // BlockList
namespace samson {
namespace stream {
BlockListContainer::BlockListContainer(std::string container_name, size_t task_id) {
container_name_ = container_name;
task_id_ = task_id;
}
BlockListContainer::~BlockListContainer() {
blockLists_.clearMap(); // Remove all BlockList instances
}
BlockList *BlockListContainer::FindBlockList(std::string name) const {
// au::TokenTaker tt(&token_);
return blockLists_.findInMap(name);
}
BlockList *BlockListContainer::GetBlockList(std::string name) {
// au::TokenTaker tt(&token_);
BlockList *blockList = blockLists_.findInMap(name);
if (!blockList) {
blockList = new BlockList(au::str("<%s:%s>", container_name_.c_str(), name.c_str()), task_id_);
blockLists_.insertInMap(name, blockList);
}
return blockList;
}
void BlockListContainer::ClearBlockListcontainer() {
// au::TokenTaker tt(&token_);
blockLists_.clearMap(); // Remove all BlockList instances
}
size_t BlockListContainer::GetNumBlocks() const {
size_t total = 0;
au::map<std::string, BlockList>::const_iterator it;
for (it = blockLists_.begin(); it != blockLists_.end(); ++it) {
total += (it->second->getNumBlocks());
}
return total;
}
bool BlockListContainer::is_content_in_memory() const {
au::map<std::string, BlockList>::const_iterator it;
for (it = blockLists_.begin(); it != blockLists_.end(); ++it) {
BlockList *block_list = it->second;
if (!block_list->IsContentInMemory()) {
return false;
}
}
return true;
}
void BlockListContainer::lock_content_in_memory() {
au::map<std::string, BlockList>::iterator it;
for (it = blockLists_.begin(); it != blockLists_.end(); ++it) {
BlockList *block_list = it->second;
block_list->lock_content_in_memory();
}
}
std::string BlockListContainer::str_blocks() const {
std::ostringstream output;
au::map<std::string, BlockList>::const_iterator it;
for (it = blockLists_.begin(); it != blockLists_.end(); ++it) {
BlockList *block_list = it->second;
output << "<<" << it->first << " " << block_list->str_blocks() << ">> ";
}
return output.str();
}
std::string BlockListContainer::str_block_ids() const {
std::ostringstream output;
int num_inputs = 0;
for (int i = 0; i < 10; ++i) {
if (blockLists_.findInMap(au::str("input_%d", i))) {
num_inputs = i + 1;
}
}
int num_outputs = 0;
for (int i = 0; i < 10; ++i) {
if (blockLists_.findInMap(au::str("output_%d", i))) {
num_outputs = i + 1;
}
}
for (int i = 0; i < num_inputs; ++i) {
BlockList *block_list = blockLists_.findInMap(au::str("input_%d", i));
if (!block_list) {
output << "-";
} else {
output << block_list->str_blocks();
}
}
for (int i = 0; i < num_outputs; i++) {
BlockList *block_list = blockLists_.findInMap(au::str("output_%d", i));
if (!block_list) {
output << "-";
} else {
output << block_list->str_blocks();
}
}
return output.str();
}
std::string BlockListContainer::str_inputs() const {
int num_inputs = 0;
for (int i = 0; i < 10; ++i) {
if (blockLists_.findInMap(au::str("input_%d", i))) {
num_inputs = i + 1;
}
}
std::ostringstream output;
for (int i = 0; i < num_inputs; ++i) {
BlockList *block_list = blockLists_.findInMap(au::str("input_%d", i));
if (!block_list) {
output << "-";
} else {
BlockInfo block_info = block_list->getBlockInfo();
output << "[" << block_info.strShortInfo() << "]";
}
}
return output.str();
}
std::string BlockListContainer::str_outputs() const {
int num_outputs = 0;
for (int i = 0; i < 10; ++i) {
if (blockLists_.findInMap(au::str("output_%d", i))) {
num_outputs = i + 1;
}
}
std::ostringstream output;
for (int i = 0; i < num_outputs; i++) {
BlockList *block_list = blockLists_.findInMap(au::str("output_%d", i));
if (!block_list) {
output << "-";
} else {
BlockInfo block_info = block_list->getBlockInfo();
output << "[" << block_info.strShortInfo() << "]";
}
}
return output.str();
}
FullKVInfo BlockListContainer::GetInputsInfo() const {
int num_inputs = 0;
for (int i = 0; i < 10; ++i) {
if (blockLists_.findInMap(au::str("input_%d", i))) {
num_inputs = i + 1;
}
}
FullKVInfo info;
for (int i = 0; i < num_inputs; ++i) {
BlockList *block_list = blockLists_.findInMap(au::str("input_%d", i));
if (block_list) {
BlockInfo block_info = block_list->getBlockInfo();
info.append(block_info.info);
}
}
return info;
}
FullKVInfo BlockListContainer::GetOutputsInfo() const {
int num_outputs = 0;
for (int i = 0; i < 10; ++i) {
if (blockLists_.findInMap(au::str("output_%d", i))) {
num_outputs = i + 1;
}
}
FullKVInfo info;
for (int i = 0; i < num_outputs; ++i) {
BlockList *block_list = blockLists_.findInMap(au::str("output_%d", i));
if (block_list) {
BlockInfo block_info = block_list->getBlockInfo();
info.append(block_info.info);
}
}
return info;
}
}
}
<|endoftext|> |
<commit_before>// SciTE - Scintilla based Text Editor
/** @file StyleDefinition.cxx
** Implementation of style aggregate.
**/
// Copyright 2013 by Neil Hodgson <neilh@scintilla.org>
// The License.txt file describes the conditions under which this software may be distributed.
#include <stdlib.h>
#include <string.h>
#include <string>
#include <vector>
#include <algorithm>
#include "Scintilla.h"
#include "GUI.h"
#include "SString.h"
#include "StringHelpers.h"
#include "StyleDefinition.h"
StyleDefinition::StyleDefinition(const char *definition) :
sizeFractional(10.0), size(10), fore("#000000"), back("#FFFFFF"),
weight(SC_WEIGHT_NORMAL), italics(false), eolfilled(false), underlined(false),
caseForce(SC_CASE_MIXED),
visible(true), changeable(true),
specified(sdNone) {
ParseStyleDefinition(definition);
}
bool StyleDefinition::ParseStyleDefinition(const char *definition) {
if (definition == NULL || *definition == '\0') {
return false;
}
char *val = StringDup(definition);
char *opt = val;
while (opt) {
// Find attribute separator
char *cpComma = strchr(opt, ',');
if (cpComma) {
// If found, we terminate the current attribute (opt) string
*cpComma = '\0';
}
// Find attribute name/value separator
char *colon = strchr(opt, ':');
if (colon) {
// If found, we terminate the current attribute name and point on the value
*colon++ = '\0';
}
if (0 == strcmp(opt, "italics")) {
specified = static_cast<flags>(specified | sdItalics);
italics = true;
}
if (0 == strcmp(opt, "notitalics")) {
specified = static_cast<flags>(specified | sdItalics);
italics = false;
}
if (0 == strcmp(opt, "bold")) {
specified = static_cast<flags>(specified | sdWeight);
weight = SC_WEIGHT_BOLD;
}
if (0 == strcmp(opt, "notbold")) {
specified = static_cast<flags>(specified | sdWeight);
weight = SC_WEIGHT_NORMAL;
}
if ((0 == strcmp(opt, "weight")) && colon) {
specified = static_cast<flags>(specified | sdWeight);
weight = atoi(colon);
}
if (0 == strcmp(opt, "font")) {
specified = static_cast<flags>(specified | sdFont);
font = colon;
std::replace(font.begin(), font.end(), '|', ',');
}
if (0 == strcmp(opt, "fore")) {
specified = static_cast<flags>(specified | sdFore);
fore = colon;
}
if (0 == strcmp(opt, "back")) {
specified = static_cast<flags>(specified | sdBack);
back = colon;
}
if ((0 == strcmp(opt, "size")) && colon) {
specified = static_cast<flags>(specified | sdSize);
sizeFractional = static_cast<float>(atof(colon));
size = static_cast<int>(sizeFractional);
}
if (0 == strcmp(opt, "eolfilled")) {
specified = static_cast<flags>(specified | sdEOLFilled);
eolfilled = true;
}
if (0 == strcmp(opt, "noteolfilled")) {
specified = static_cast<flags>(specified | sdEOLFilled);
eolfilled = false;
}
if (0 == strcmp(opt, "underlined")) {
specified = static_cast<flags>(specified | sdUnderlined);
underlined = true;
}
if (0 == strcmp(opt, "notunderlined")) {
specified = static_cast<flags>(specified | sdUnderlined);
underlined = false;
}
if (0 == strcmp(opt, "case")) {
specified = static_cast<flags>(specified | sdCaseForce);
caseForce = SC_CASE_MIXED;
if (colon) {
if (*colon == 'u')
caseForce = SC_CASE_UPPER;
else if (*colon == 'l')
caseForce = SC_CASE_LOWER;
}
}
if (0 == strcmp(opt, "visible")) {
specified = static_cast<flags>(specified | sdVisible);
visible = true;
}
if (0 == strcmp(opt, "notvisible")) {
specified = static_cast<flags>(specified | sdVisible);
visible = false;
}
if (0 == strcmp(opt, "changeable")) {
specified = static_cast<flags>(specified | sdChangeable);
changeable = true;
}
if (0 == strcmp(opt, "notchangeable")) {
specified = static_cast<flags>(specified | sdChangeable);
changeable = false;
}
if (cpComma)
opt = cpComma + 1;
else
opt = 0;
}
delete []val;
return true;
}
long StyleDefinition::ForeAsLong() const {
return ColourFromString(fore);
}
long StyleDefinition::BackAsLong() const {
return ColourFromString(back);
}
int StyleDefinition::FractionalSize() const {
return static_cast<int>(sizeFractional * SC_FONT_SIZE_MULTIPLIER);
}
bool StyleDefinition::IsBold() const {
return weight > SC_WEIGHT_NORMAL;
}
int IntFromHexDigit(int ch) {
if ((ch >= '0') && (ch <= '9')) {
return ch - '0';
} else if (ch >= 'A' && ch <= 'F') {
return ch - 'A' + 10;
} else if (ch >= 'a' && ch <= 'f') {
return ch - 'a' + 10;
} else {
return 0;
}
}
int IntFromHexByte(const char *hexByte) {
return IntFromHexDigit(hexByte[0]) * 16 + IntFromHexDigit(hexByte[1]);
}
Colour ColourFromString(const std::string &s) {
if (s.length()) {
int r = IntFromHexByte(s.c_str() + 1);
int g = IntFromHexByte(s.c_str() + 3);
int b = IntFromHexByte(s.c_str() + 5);
return ColourRGB(r, g, b);
} else {
return 0;
}
}
IndicatorDefinition::IndicatorDefinition(const char *definition) :
style(INDIC_PLAIN), colour(0), fillAlpha(30), outlineAlpha(50), under(false) {
ParseIndicatorDefinition(definition);
}
bool IndicatorDefinition::ParseIndicatorDefinition(const char *definition) {
if (definition == NULL || *definition == '\0') {
return false;
}
struct {
const char *name;
int value;
} indicStyleNames[] = {
{ "plain", INDIC_PLAIN },
{ "squiggle", INDIC_SQUIGGLE },
{ "tt", INDIC_TT },
{ "diagonal", INDIC_DIAGONAL },
{ "strike", INDIC_STRIKE },
{ "hidden", INDIC_HIDDEN },
{ "box", INDIC_BOX },
{ "roundbox", INDIC_ROUNDBOX },
{ "straightbox", INDIC_STRAIGHTBOX },
{ "dash", INDIC_DASH },
{ "dots", INDIC_DOTS },
{ "squigglelow", INDIC_SQUIGGLELOW },
{ "dotbox", INDIC_DOTBOX },
{ "squigglepixmap", INDIC_SQUIGGLEPIXMAP },
{ "compositionthick", INDIC_COMPOSITIONTHICK },
};
std::string val(definition);
LowerCaseAZ(val);
char *opt = &val[0];
while (opt) {
// Find attribute separator
char *cpComma = strchr(opt, ',');
if (cpComma) {
// If found, we terminate the current attribute (opt) string
*cpComma = '\0';
}
// Find attribute name/value separator
char *colon = strchr(opt, ':');
if (colon) {
// If found, we terminate the current attribute name and point on the value
*colon++ = '\0';
}
if (colon && (0 == strcmp(opt, "style"))) {
bool found = false;
for (size_t i=0;i<ELEMENTS(indicStyleNames);i++) {
if ((indicStyleNames[i].name) && (0 == strcmp(colon, indicStyleNames[i].name))) {
style = indicStyleNames[i].value;
found = true;
}
}
if (!found)
style = atoi(colon);
}
if (colon && ((0 == strcmp(opt, "colour")) || (0 == strcmp(opt, "color")))) {
colour = ColourFromString(std::string(colon));
}
if (colon && (0 == strcmp(opt, "fillalpha"))) {
fillAlpha = atoi(colon);
}
if (colon && (0 == strcmp(opt, "outlinealpha"))) {
outlineAlpha = atoi(colon);
}
if (0 == strcmp(opt, "under")) {
under = true;
}
if (0 == strcmp(opt, "notunder")) {
under = false;
}
if (cpComma)
opt = cpComma + 1;
else
opt = 0;
}
return true;
}
<commit_msg>Avoid potential NULL dereferences.<commit_after>// SciTE - Scintilla based Text Editor
/** @file StyleDefinition.cxx
** Implementation of style aggregate.
**/
// Copyright 2013 by Neil Hodgson <neilh@scintilla.org>
// The License.txt file describes the conditions under which this software may be distributed.
#include <stdlib.h>
#include <string.h>
#include <string>
#include <vector>
#include <algorithm>
#include "Scintilla.h"
#include "GUI.h"
#include "SString.h"
#include "StringHelpers.h"
#include "StyleDefinition.h"
StyleDefinition::StyleDefinition(const char *definition) :
sizeFractional(10.0), size(10), fore("#000000"), back("#FFFFFF"),
weight(SC_WEIGHT_NORMAL), italics(false), eolfilled(false), underlined(false),
caseForce(SC_CASE_MIXED),
visible(true), changeable(true),
specified(sdNone) {
ParseStyleDefinition(definition);
}
bool StyleDefinition::ParseStyleDefinition(const char *definition) {
if (definition == NULL || *definition == '\0') {
return false;
}
char *val = StringDup(definition);
char *opt = val;
while (opt) {
// Find attribute separator
char *cpComma = strchr(opt, ',');
if (cpComma) {
// If found, we terminate the current attribute (opt) string
*cpComma = '\0';
}
// Find attribute name/value separator
char *colon = strchr(opt, ':');
if (colon) {
// If found, we terminate the current attribute name and point on the value
*colon++ = '\0';
}
if (0 == strcmp(opt, "italics")) {
specified = static_cast<flags>(specified | sdItalics);
italics = true;
}
if (0 == strcmp(opt, "notitalics")) {
specified = static_cast<flags>(specified | sdItalics);
italics = false;
}
if (0 == strcmp(opt, "bold")) {
specified = static_cast<flags>(specified | sdWeight);
weight = SC_WEIGHT_BOLD;
}
if (0 == strcmp(opt, "notbold")) {
specified = static_cast<flags>(specified | sdWeight);
weight = SC_WEIGHT_NORMAL;
}
if ((0 == strcmp(opt, "weight")) && colon) {
specified = static_cast<flags>(specified | sdWeight);
weight = atoi(colon);
}
if ((0 == strcmp(opt, "font")) && colon) {
specified = static_cast<flags>(specified | sdFont);
font = colon;
std::replace(font.begin(), font.end(), '|', ',');
}
if ((0 == strcmp(opt, "fore")) && colon) {
specified = static_cast<flags>(specified | sdFore);
fore = colon;
}
if ((0 == strcmp(opt, "back")) && colon) {
specified = static_cast<flags>(specified | sdBack);
back = colon;
}
if ((0 == strcmp(opt, "size")) && colon) {
specified = static_cast<flags>(specified | sdSize);
sizeFractional = static_cast<float>(atof(colon));
size = static_cast<int>(sizeFractional);
}
if (0 == strcmp(opt, "eolfilled")) {
specified = static_cast<flags>(specified | sdEOLFilled);
eolfilled = true;
}
if (0 == strcmp(opt, "noteolfilled")) {
specified = static_cast<flags>(specified | sdEOLFilled);
eolfilled = false;
}
if (0 == strcmp(opt, "underlined")) {
specified = static_cast<flags>(specified | sdUnderlined);
underlined = true;
}
if (0 == strcmp(opt, "notunderlined")) {
specified = static_cast<flags>(specified | sdUnderlined);
underlined = false;
}
if (0 == strcmp(opt, "case")) {
specified = static_cast<flags>(specified | sdCaseForce);
caseForce = SC_CASE_MIXED;
if (colon) {
if (*colon == 'u')
caseForce = SC_CASE_UPPER;
else if (*colon == 'l')
caseForce = SC_CASE_LOWER;
}
}
if (0 == strcmp(opt, "visible")) {
specified = static_cast<flags>(specified | sdVisible);
visible = true;
}
if (0 == strcmp(opt, "notvisible")) {
specified = static_cast<flags>(specified | sdVisible);
visible = false;
}
if (0 == strcmp(opt, "changeable")) {
specified = static_cast<flags>(specified | sdChangeable);
changeable = true;
}
if (0 == strcmp(opt, "notchangeable")) {
specified = static_cast<flags>(specified | sdChangeable);
changeable = false;
}
if (cpComma)
opt = cpComma + 1;
else
opt = 0;
}
delete []val;
return true;
}
long StyleDefinition::ForeAsLong() const {
return ColourFromString(fore);
}
long StyleDefinition::BackAsLong() const {
return ColourFromString(back);
}
int StyleDefinition::FractionalSize() const {
return static_cast<int>(sizeFractional * SC_FONT_SIZE_MULTIPLIER);
}
bool StyleDefinition::IsBold() const {
return weight > SC_WEIGHT_NORMAL;
}
int IntFromHexDigit(int ch) {
if ((ch >= '0') && (ch <= '9')) {
return ch - '0';
} else if (ch >= 'A' && ch <= 'F') {
return ch - 'A' + 10;
} else if (ch >= 'a' && ch <= 'f') {
return ch - 'a' + 10;
} else {
return 0;
}
}
int IntFromHexByte(const char *hexByte) {
return IntFromHexDigit(hexByte[0]) * 16 + IntFromHexDigit(hexByte[1]);
}
Colour ColourFromString(const std::string &s) {
if (s.length()) {
int r = IntFromHexByte(s.c_str() + 1);
int g = IntFromHexByte(s.c_str() + 3);
int b = IntFromHexByte(s.c_str() + 5);
return ColourRGB(r, g, b);
} else {
return 0;
}
}
IndicatorDefinition::IndicatorDefinition(const char *definition) :
style(INDIC_PLAIN), colour(0), fillAlpha(30), outlineAlpha(50), under(false) {
ParseIndicatorDefinition(definition);
}
bool IndicatorDefinition::ParseIndicatorDefinition(const char *definition) {
if (definition == NULL || *definition == '\0') {
return false;
}
struct {
const char *name;
int value;
} indicStyleNames[] = {
{ "plain", INDIC_PLAIN },
{ "squiggle", INDIC_SQUIGGLE },
{ "tt", INDIC_TT },
{ "diagonal", INDIC_DIAGONAL },
{ "strike", INDIC_STRIKE },
{ "hidden", INDIC_HIDDEN },
{ "box", INDIC_BOX },
{ "roundbox", INDIC_ROUNDBOX },
{ "straightbox", INDIC_STRAIGHTBOX },
{ "dash", INDIC_DASH },
{ "dots", INDIC_DOTS },
{ "squigglelow", INDIC_SQUIGGLELOW },
{ "dotbox", INDIC_DOTBOX },
{ "squigglepixmap", INDIC_SQUIGGLEPIXMAP },
{ "compositionthick", INDIC_COMPOSITIONTHICK },
};
std::string val(definition);
LowerCaseAZ(val);
char *opt = &val[0];
while (opt) {
// Find attribute separator
char *cpComma = strchr(opt, ',');
if (cpComma) {
// If found, we terminate the current attribute (opt) string
*cpComma = '\0';
}
// Find attribute name/value separator
char *colon = strchr(opt, ':');
if (colon) {
// If found, we terminate the current attribute name and point on the value
*colon++ = '\0';
}
if (colon && (0 == strcmp(opt, "style"))) {
bool found = false;
for (size_t i=0;i<ELEMENTS(indicStyleNames);i++) {
if ((indicStyleNames[i].name) && (0 == strcmp(colon, indicStyleNames[i].name))) {
style = indicStyleNames[i].value;
found = true;
}
}
if (!found)
style = atoi(colon);
}
if (colon && ((0 == strcmp(opt, "colour")) || (0 == strcmp(opt, "color")))) {
colour = ColourFromString(std::string(colon));
}
if (colon && (0 == strcmp(opt, "fillalpha"))) {
fillAlpha = atoi(colon);
}
if (colon && (0 == strcmp(opt, "outlinealpha"))) {
outlineAlpha = atoi(colon);
}
if (0 == strcmp(opt, "under")) {
under = true;
}
if (0 == strcmp(opt, "notunder")) {
under = false;
}
if (cpComma)
opt = cpComma + 1;
else
opt = 0;
}
return true;
}
<|endoftext|> |
<commit_before>/*
CrystalSpace 3D renderer view
Copyright (C) 1998 by Jorrit Tyberghein
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; if not, write to the Free
Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
#include "sysdef.h"
#include "csgeom/polyclip.h"
#include "csengine/csview.h"
#include "csengine/world.h"
#include "csengine/pol2d.h"
#include "csengine/camera.h"
#include "igraph3d.h"
#include "qint.h"
csView::csView (csWorld *iWorld, iGraphics3D* ig3d)
{
bview = NULL;
world = iWorld;
(G3D = ig3d)->IncRef ();
CHK (view = new csPolygon2D ());
CHK (camera = new csCamera ());
clipper = NULL;
}
csView::~csView ()
{
G3D->DecRef ();
CHK (delete bview);
CHK (delete camera);
CHK (delete view);
CHK (delete clipper);
}
void csView::ClearView ()
{
if (view) view->MakeEmpty ();
}
void csView::SetRectangle (int x, int y, int w, int h)
{
orig_width = G3D->GetWidth ();
orig_height = G3D->GetHeight();
// Do not allow the rectangle to go out of the screen
if (x < 0) { w += x; x = 0; }
if (y < 0) { h += y; y = 0; }
if (x + w > orig_width) { w = orig_width - x; }
if (y + h > orig_height) { h = orig_height - y; }
CHK (delete view); view = NULL;
CHK (delete bview);
CHK (bview = new csBox2 (x, y, x + w - 1, y + h - 1));
CHK (delete clipper); clipper = NULL;
}
void csView::AddViewVertex (int x, int y)
{
if (!view)
CHKB (view = new csPolygon2D ());
view->AddVertex (x, y);
CHK (delete clipper); clipper = NULL;
}
void csView::Draw ()
{
if ((orig_width != G3D->GetWidth ()) || (orig_height != G3D->GetHeight()))
{
float xscale = ((float)G3D->GetWidth ()) / ((float)orig_width);
float yscale = ((float)G3D->GetHeight ()) / ((float)orig_height);
orig_width = G3D->GetWidth ();
orig_height = G3D->GetHeight ();
int xmin, ymin, xmax, ymax;
if (!bview)
{
xmin = 0;
ymin = 0;
xmax = orig_width - 1;
ymax = orig_height - 1;
}
else
{
xmin = QRound (xscale * bview->MinX());
xmax = QRound (xscale * (bview->MaxX() + 1));
ymin = QRound (yscale * bview->MinY());
ymax = QRound (yscale * (bview->MaxY() + 1));
CHK (delete bview);
}
CHK (bview = new csBox2 (xmin, ymin, xmax - 1, ymax - 1));
CHK (delete clipper);
clipper = NULL;
}
if (!clipper)
if (view)
CHKB (clipper = new csPolygonClipper (view))
else
CHKB (clipper = new csBoxClipper (*bview));
G3D->SetPerspectiveCenter ((int)camera->shift_x, (int)camera->shift_y);
world->Draw (camera, clipper);
}
void csView::SetSector (csSector *sector)
{
camera->SetSector (sector);
}
void csView::SetPerspectiveCenter (float x, float y)
{
camera->SetPerspectiveCenter (x, y);
}
<commit_msg>moved recalculation of clipper from Draw to a seperate Method<commit_after>/*
CrystalSpace 3D renderer view
Copyright (C) 1998 by Jorrit Tyberghein
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; if not, write to the Free
Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
#include "sysdef.h"
#include "csgeom/polyclip.h"
#include "csengine/csview.h"
#include "csengine/world.h"
#include "csengine/pol2d.h"
#include "csengine/camera.h"
#include "igraph3d.h"
#include "qint.h"
csView::csView (csWorld *iWorld, iGraphics3D* ig3d)
{
bview = NULL;
world = iWorld;
(G3D = ig3d)->IncRef ();
CHK (view = new csPolygon2D ());
CHK (camera = new csCamera ());
clipper = NULL;
}
csView::~csView ()
{
G3D->DecRef ();
CHK (delete bview);
CHK (delete camera);
CHK (delete view);
CHK (delete clipper);
}
void csView::ClearView ()
{
if (view) view->MakeEmpty ();
}
void csView::SetRectangle (int x, int y, int w, int h)
{
orig_width = G3D->GetWidth ();
orig_height = G3D->GetHeight();
// Do not allow the rectangle to go out of the screen
if (x < 0) { w += x; x = 0; }
if (y < 0) { h += y; y = 0; }
if (x + w > orig_width) { w = orig_width - x; }
if (y + h > orig_height) { h = orig_height - y; }
CHK (delete view); view = NULL;
CHK (delete bview);
CHK (bview = new csBox2 (x, y, x + w - 1, y + h - 1));
CHK (delete clipper); clipper = NULL;
}
void csView::AddViewVertex (int x, int y)
{
if (!view)
CHKB (view = new csPolygon2D ());
view->AddVertex (x, y);
CHK (delete clipper); clipper = NULL;
}
void csView::Draw ()
{
UpdateClipper();
G3D->SetPerspectiveCenter ((int)camera->shift_x, (int)camera->shift_y);
world->Draw (camera, clipper);
}
void csView::UpdateClipper ()
{
if ((orig_width != G3D->GetWidth ()) || (orig_height != G3D->GetHeight()))
{
float xscale = ((float)G3D->GetWidth ()) / ((float)orig_width);
float yscale = ((float)G3D->GetHeight ()) / ((float)orig_height);
orig_width = G3D->GetWidth ();
orig_height = G3D->GetHeight ();
int xmin, ymin, xmax, ymax;
if (!bview)
{
xmin = 0;
ymin = 0;
xmax = orig_width - 1;
ymax = orig_height - 1;
}
else
{
xmin = QRound (xscale * bview->MinX());
xmax = QRound (xscale * (bview->MaxX() + 1));
ymin = QRound (yscale * bview->MinY());
ymax = QRound (yscale * (bview->MaxY() + 1));
CHK (delete bview);
}
CHK (bview = new csBox2 (xmin, ymin, xmax - 1, ymax - 1));
CHK (delete clipper);
clipper = NULL;
}
if (!clipper)
if (view)
CHKB (clipper = new csPolygonClipper (view))
else
CHKB (clipper = new csBoxClipper (*bview));
}
void csView::SetSector (csSector *sector)
{
camera->SetSector (sector);
}
void csView::SetPerspectiveCenter (float x, float y)
{
camera->SetPerspectiveCenter (x, y);
}
<|endoftext|> |
<commit_before>/*
* ARServer.cpp
*
* Created on: Dec 6, 2011
* Author: ddaeschler
*/
#include "ARServer.h"
#include "PacketBufferPool.h"
#include <boost/bind.hpp>
#include <stdexcept>
#include <vector>
#include <iostream>
using boost::asio::ip::udp;
using namespace std;
namespace audioreflector
{
ARServer::ARServer(ushort subscriptionPort, int sampleRate, IEncoderPtr encoder)
: _subscriptionPort(subscriptionPort), _sampleRate(sampleRate),
_ioService(),
_socket(_ioService, udp::endpoint(udp::v4(), subscriptionPort)),
_encoderStage(new EncoderStage(encoder, boost::bind(&ARServer::onEncodeComplete, this, _1))),
_subscriberMgr(new SubscriberManager(_ioService, _socket))
{
PacketBufferPool::getInstance();
}
ARServer::~ARServer()
{
}
void ARServer::start()
{
//we then need to fire up asio to throw udp at the subscriber
this->initAsio();
//the encoder stage
_encoderStage->start();
//and finally, fire up portaudio to feed the encoder
this->initPortaudio();
}
void ARServer::initAsio()
{
_networkThread.reset(new boost::thread(boost::bind(&ARServer::asioThreadRun, this)));
}
void ARServer::asioThreadRun()
{
this->beginReceive();
_ioService.run();
}
void ARServer::beginReceive()
{
//we dont worry about allocating from the pool here, because
//these messages will be few and far between
packet_buffer_ptr buffer(new packet_buffer());
_socket.async_receive_from(
boost::asio::buffer(buffer->contents, packet_buffer::BUF_SZ), _remoteEndpoint,
boost::bind(&ARServer::handleReceive, this,
boost::asio::placeholders::error,
boost::asio::placeholders::bytes_transferred,
buffer));
}
void ARServer::handleReceive(const boost::system::error_code& error,
std::size_t bytes_transferred,
packet_buffer_ptr buffer)
{
udp::endpoint epCopy = _remoteEndpoint;
this->beginReceive();
if (! error) {
if (CSS_SUBSCRIBED == (ClientSubscriptionStatus) buffer->contents[0]) {
this->subscribeClient(epCopy);
} else if (CSS_UNSUBSCRIBED == (ClientSubscriptionStatus) buffer->contents[0]) {
this->unsubscribeClient(epCopy);
} else if (CSS_UPDATESUBSC == (ClientSubscriptionStatus) buffer->contents[0]) {
this->updateClientSubscription(epCopy);
}
}
}
void ARServer::updateClientSubscription(boost::asio::ip::udp::endpoint ep)
{
_subscriberMgr->updateSubscription(ep);
}
void ARServer::subscribeClient(boost::asio::ip::udp::endpoint ep)
{
cout << "New client connection: " << ep << endl;
_subscriberMgr->newSubscriber(ep);
}
void ARServer::unsubscribeClient(boost::asio::ip::udp::endpoint ep)
{
cout << "End client connection: " << ep << endl;
_subscriberMgr->unsubscribe(ep);
}
int ARServer::PaCallback(const void *inputBuffer, void *outputBuffer,
unsigned long framesPerBuffer,
const PaStreamCallbackTimeInfo* timeInfo,
PaStreamCallbackFlags statusFlags,
void *userData)
{
ARServer* server = static_cast<ARServer*>(userData);
return server->paCallbackMethod(inputBuffer, outputBuffer, framesPerBuffer, timeInfo, statusFlags);
}
int ARServer::paCallbackMethod(const void *inputBuffer, void *outputBuffer,
unsigned long framesPerBuffer,
const PaStreamCallbackTimeInfo* timeInfo,
PaStreamCallbackFlags statusFlags)
{
//broadcast to all clients
//packetize the given data using our selected MTU
size_t numBytes = framesPerBuffer * BIT_DEPTH_IN_BYTES;
//calculate the number of buffers we need
int reqdBuffers = numBytes / MTU;
if (numBytes % MTU > 0) {
reqdBuffers++;
}
char* inBufferAsCharBuffer = (char*)inputBuffer;
for (int i = 0; i < reqdBuffers; ++i) {
size_t copiedSoFar = i * MTU;
size_t amtToCopy;
if (MTU < numBytes - copiedSoFar) {
amtToCopy = MTU;
} else {
amtToCopy = numBytes - copiedSoFar;
}
packet_buffer_ptr buffer(PacketBufferPool::getInstance().alloc());
memcpy(buffer->contents, inBufferAsCharBuffer + copiedSoFar, amtToCopy);
_encoderStage->enqueue(buffer, framesPerBuffer, _sampleRate);
}
return paContinue;
}
void ARServer::initPortaudio()
{
PaError err;
/* Open an audio I/O stream. */
err = Pa_OpenDefaultStream( &_inputStream,
1, /* 1 input channel*/
0, /* no output */
paInt16, /* 16 bit audio */
_sampleRate,
paFramesPerBufferUnspecified, /* frames per buffer, i.e. the number
of sample frames that PortAudio will
request from the callback. Many apps
may want to use
paFramesPerBufferUnspecified, which
tells PortAudio to pick the best,
possibly changing, buffer size.*/
&ARServer::PaCallback, /* this is your callback function */
static_cast<void*>(this) ); /*This is a pointer that will be passed to
your callback*/
if( err != paNoError ) throw std::runtime_error("Could not initialize audio input");
this->beginRecording();
}
void ARServer::beginRecording()
{
if (Pa_StartStream(_inputStream) != paNoError) {
throw std::runtime_error("Could not start audio input");
}
}
void ARServer::onEncodeComplete(EncodedSamplesPtr samples)
{
_subscriberMgr->enqueueOrSend(samples);
}
}
<commit_msg>Include the actual sample rate given back by portaudio after opening the stream. In the future this will be sent to the client before the stream begins so that it doesnt have to be typed<commit_after>/*
* ARServer.cpp
*
* Created on: Dec 6, 2011
* Author: ddaeschler
*/
#include "ARServer.h"
#include "PacketBufferPool.h"
#include <boost/bind.hpp>
#include <stdexcept>
#include <vector>
#include <iostream>
using boost::asio::ip::udp;
using namespace std;
namespace audioreflector
{
ARServer::ARServer(ushort subscriptionPort, int sampleRate, IEncoderPtr encoder)
: _subscriptionPort(subscriptionPort), _sampleRate(sampleRate),
_ioService(),
_socket(_ioService, udp::endpoint(udp::v4(), subscriptionPort)),
_encoderStage(new EncoderStage(encoder, boost::bind(&ARServer::onEncodeComplete, this, _1))),
_subscriberMgr(new SubscriberManager(_ioService, _socket))
{
PacketBufferPool::getInstance();
}
ARServer::~ARServer()
{
}
void ARServer::start()
{
//we then need to fire up asio to throw udp at the subscriber
this->initAsio();
//the encoder stage
_encoderStage->start();
//and finally, fire up portaudio to feed the encoder
this->initPortaudio();
}
void ARServer::initAsio()
{
_networkThread.reset(new boost::thread(boost::bind(&ARServer::asioThreadRun, this)));
}
void ARServer::asioThreadRun()
{
this->beginReceive();
_ioService.run();
}
void ARServer::beginReceive()
{
//we dont worry about allocating from the pool here, because
//these messages will be few and far between
packet_buffer_ptr buffer(new packet_buffer());
_socket.async_receive_from(
boost::asio::buffer(buffer->contents, packet_buffer::BUF_SZ), _remoteEndpoint,
boost::bind(&ARServer::handleReceive, this,
boost::asio::placeholders::error,
boost::asio::placeholders::bytes_transferred,
buffer));
}
void ARServer::handleReceive(const boost::system::error_code& error,
std::size_t bytes_transferred,
packet_buffer_ptr buffer)
{
udp::endpoint epCopy = _remoteEndpoint;
this->beginReceive();
if (! error) {
if (CSS_SUBSCRIBED == (ClientSubscriptionStatus) buffer->contents[0]) {
this->subscribeClient(epCopy);
} else if (CSS_UNSUBSCRIBED == (ClientSubscriptionStatus) buffer->contents[0]) {
this->unsubscribeClient(epCopy);
} else if (CSS_UPDATESUBSC == (ClientSubscriptionStatus) buffer->contents[0]) {
this->updateClientSubscription(epCopy);
}
}
}
void ARServer::updateClientSubscription(boost::asio::ip::udp::endpoint ep)
{
_subscriberMgr->updateSubscription(ep);
}
void ARServer::subscribeClient(boost::asio::ip::udp::endpoint ep)
{
cout << "New client connection: " << ep << endl;
_subscriberMgr->newSubscriber(ep);
}
void ARServer::unsubscribeClient(boost::asio::ip::udp::endpoint ep)
{
cout << "End client connection: " << ep << endl;
_subscriberMgr->unsubscribe(ep);
}
int ARServer::PaCallback(const void *inputBuffer, void *outputBuffer,
unsigned long framesPerBuffer,
const PaStreamCallbackTimeInfo* timeInfo,
PaStreamCallbackFlags statusFlags,
void *userData)
{
ARServer* server = static_cast<ARServer*>(userData);
return server->paCallbackMethod(inputBuffer, outputBuffer, framesPerBuffer, timeInfo, statusFlags);
}
int ARServer::paCallbackMethod(const void *inputBuffer, void *outputBuffer,
unsigned long framesPerBuffer,
const PaStreamCallbackTimeInfo* timeInfo,
PaStreamCallbackFlags statusFlags)
{
//broadcast to all clients
//packetize the given data using our selected MTU
size_t numBytes = framesPerBuffer * BIT_DEPTH_IN_BYTES;
//calculate the number of buffers we need
int reqdBuffers = numBytes / MTU;
if (numBytes % MTU > 0) {
reqdBuffers++;
}
char* inBufferAsCharBuffer = (char*)inputBuffer;
for (int i = 0; i < reqdBuffers; ++i) {
size_t copiedSoFar = i * MTU;
size_t amtToCopy;
if (MTU < numBytes - copiedSoFar) {
amtToCopy = MTU;
} else {
amtToCopy = numBytes - copiedSoFar;
}
packet_buffer_ptr buffer(PacketBufferPool::getInstance().alloc());
memcpy(buffer->contents, inBufferAsCharBuffer + copiedSoFar, amtToCopy);
_encoderStage->enqueue(buffer, framesPerBuffer, _sampleRate);
}
return paContinue;
}
void ARServer::initPortaudio()
{
PaError err;
/* Open an audio I/O stream. */
err = Pa_OpenDefaultStream( &_inputStream,
1, /* 1 input channel*/
0, /* no output */
paInt16, /* 16 bit audio */
_sampleRate,
paFramesPerBufferUnspecified, /* frames per buffer, i.e. the number
of sample frames that PortAudio will
request from the callback. Many apps
may want to use
paFramesPerBufferUnspecified, which
tells PortAudio to pick the best,
possibly changing, buffer size.*/
&ARServer::PaCallback, /* this is your callback function */
static_cast<void*>(this) ); /*This is a pointer that will be passed to
your callback*/
if( err != paNoError ) throw std::runtime_error("Could not initialize audio input");
const PaStreamInfo* streamInfo = Pa_GetStreamInfo( _inputStream );
cout << "Measured Sample Rate: " << streamInfo->sampleRate << endl;
this->beginRecording();
}
void ARServer::beginRecording()
{
if (Pa_StartStream(_inputStream) != paNoError) {
throw std::runtime_error("Could not start audio input");
}
}
void ARServer::onEncodeComplete(EncodedSamplesPtr samples)
{
_subscriberMgr->enqueueOrSend(samples);
}
}
<|endoftext|> |
<commit_before><commit_msg>use Xin_s directory<commit_after><|endoftext|> |
<commit_before>/*The MIT License (MIT)
Copyright (c) 2015 k-brac
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
#include <string>
#include <vector>
#include <iostream>
#ifdef WIN32
#pragma warning( push )
#pragma warning( disable : 4251 )
#endif
#if __MACH__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wpadded"
#pragma clang diagnostic ignored "-Wweak-vtables"
#pragma clang diagnostic ignored "-Wextra-semi"
#pragma clang diagnostic ignored "-Wdocumentation"
#pragma clang diagnostic ignored "-Wreserved-id-macro"
#pragma clang diagnostic ignored "-Wdocumentation-unknown-command"
#define CPPUNIT_STD_NEED_ALLOCATOR 0
#endif
#include "cppunit/extensions/TestFactoryRegistry.h"
#include "cppunit/CompilerOutputter.h"
#include "cppunit/XmlOutputter.h"
#include "cppunit/TestResult.h"
#include "cppunit/TestResultCollector.h"
#include "cppunit/TestRunner.h"
#include "cppunit/BriefTestProgressListener.h"
#include "cppunit/plugin/PlugInManager.h"
#include <chrono>
class TimedBriefTestProgressListener : public CppUnit::BriefTestProgressListener {
private:
std::chrono::time_point<std::chrono::steady_clock> mTimer;
public:
void startTest(CppUnit::Test *test)
{
CppUnit::BriefTestProgressListener::startTest(test);
mTimer = std::chrono::high_resolution_clock::now();
}
void endTest(CppUnit::Test *test)
{
const std::chrono::duration<float, std::milli> elapsed = std::chrono::steady_clock::now() - mTimer;
CppUnit::stdCOut() << " (" << std::to_string(elapsed.count()) << " ms elapsed)";
#if defined(WIN32)
CppUnit::stdCOut().flush();
#endif
CppUnit::BriefTestProgressListener::endTest(test);
}
};
#if __MACH__
#pragma clang diagnostic pop
#endif
#ifdef WIN32
#pragma warning( pop )
#endif
struct CommandLineParser {
std::string xmlOutputFile;
std::string plugName;
std::vector<std::string> testPaths;
void parseArgs(int argc, char* argv[]) {
for (int i = 1; i < argc; i++) {
std::string arg = argv[i];
if (arg.size() >= 2 && arg.front() == '-') {
auto it = arg.find("=");
if (it != std::string::npos) {
auto key = arg.substr(0, it);
auto val = arg.substr(it + 1, arg.size());
if (val.empty()) {
continue;
}
if (key == "-x" || key == "--xml") {
xmlOutputFile = val;
}
else if (key == "-t" || key == "--test") {
testPaths.emplace_back(val);
}
else {
std::cerr << "Unknow arguments " << key << " with value : " << val << std::endl;
}
}
}
else {
plugName = arg;
}
}
}
};
bool runPlugin(const CommandLineParser &arguments) {
CppUnit::PlugInManager pluginManager;
pluginManager.load(arguments.plugName);
// Create the event manager and test controller
CppUnit::TestResult controller;
// Add a listener that collects test result
CppUnit::TestResultCollector result;
controller.addListener(&result);
// Add a listener
TimedBriefTestProgressListener progress;
controller.addListener(&progress);
pluginManager.addListener(&controller);
// Add the top suite to the test runner
CppUnit::TestRunner runner;
runner.addTest(CppUnit::TestFactoryRegistry::getRegistry().makeTest());
try
{
if (arguments.testPaths.empty()) {
std::cout << "Running " << std::endl;
runner.run(controller);
}
else {
for (const auto & p : arguments.testPaths) {
std::cout << "Running " << p << std::endl;
runner.run(controller, p);
}
}
std::cerr << std::endl;
// Print test in a compiler compatible format.
CppUnit::CompilerOutputter outputter(&result, std::cerr);
outputter.write();
if (!arguments.xmlOutputFile.empty()) {
std::ofstream file(arguments.xmlOutputFile);
CppUnit::XmlOutputter xOutputter(&result, file);
xOutputter.write();
}
}
catch (std::invalid_argument &e) // Test path not resolved
{
std::cerr << std::endl
<< "ERROR: " << e.what()
<< std::endl;
return false;
}
return result.wasSuccessful();
}
int main(int argc, char* argv[])
{
if (argc < 2) {
std::cout << "usage : " << argv[0] << " {-x | -xml=file} {-t | --test=Namespace::ClassName::TestName} test_plugin_path" << std::endl << std::endl;
return 1;
}
bool result = false;
try {
CommandLineParser command;
command.parseArgs(argc, argv);
result = runPlugin(command);
}
catch (std::exception &e) {
std::cerr << std::endl
<< "ERROR: " << e.what()
<< std::endl;
}
return result ? 0 : 1;
}
<commit_msg>fix build with gcc<commit_after>/*The MIT License (MIT)
Copyright (c) 2015 k-brac
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
#include <string>
#include <vector>
#include <iostream>
#ifdef WIN32
#pragma warning( push )
#pragma warning( disable : 4251 )
#endif
#if __MACH__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wpadded"
#pragma clang diagnostic ignored "-Wweak-vtables"
#pragma clang diagnostic ignored "-Wextra-semi"
#pragma clang diagnostic ignored "-Wdocumentation"
#pragma clang diagnostic ignored "-Wreserved-id-macro"
#pragma clang diagnostic ignored "-Wdocumentation-unknown-command"
#define CPPUNIT_STD_NEED_ALLOCATOR 0
#endif
#include "cppunit/extensions/TestFactoryRegistry.h"
#include "cppunit/CompilerOutputter.h"
#include "cppunit/XmlOutputter.h"
#include "cppunit/TestResult.h"
#include "cppunit/TestResultCollector.h"
#include "cppunit/TestRunner.h"
#include "cppunit/BriefTestProgressListener.h"
#include "cppunit/plugin/PlugInManager.h"
#include <chrono>
class TimedBriefTestProgressListener : public CppUnit::BriefTestProgressListener {
private:
std::chrono::time_point<std::chrono::steady_clock> mTimer;
public:
void startTest(CppUnit::Test *test)
{
CppUnit::BriefTestProgressListener::startTest(test);
mTimer = std::chrono::steady_clock::now();
}
void endTest(CppUnit::Test *test)
{
const std::chrono::duration<float, std::milli> elapsed = std::chrono::steady_clock::now() - mTimer;
CppUnit::stdCOut() << " (" << std::to_string(elapsed.count()) << " ms elapsed)";
#if defined(WIN32)
CppUnit::stdCOut().flush();
#endif
CppUnit::BriefTestProgressListener::endTest(test);
}
};
#if __MACH__
#pragma clang diagnostic pop
#endif
#ifdef WIN32
#pragma warning( pop )
#endif
struct CommandLineParser {
std::string xmlOutputFile;
std::string plugName;
std::vector<std::string> testPaths;
void parseArgs(int argc, char* argv[]) {
for (int i = 1; i < argc; i++) {
std::string arg = argv[i];
if (arg.size() >= 2 && arg.front() == '-') {
auto it = arg.find("=");
if (it != std::string::npos) {
auto key = arg.substr(0, it);
auto val = arg.substr(it + 1, arg.size());
if (val.empty()) {
continue;
}
if (key == "-x" || key == "--xml") {
xmlOutputFile = val;
}
else if (key == "-t" || key == "--test") {
testPaths.emplace_back(val);
}
else {
std::cerr << "Unknow arguments " << key << " with value : " << val << std::endl;
}
}
}
else {
plugName = arg;
}
}
}
};
bool runPlugin(const CommandLineParser &arguments) {
CppUnit::PlugInManager pluginManager;
pluginManager.load(arguments.plugName);
// Create the event manager and test controller
CppUnit::TestResult controller;
// Add a listener that collects test result
CppUnit::TestResultCollector result;
controller.addListener(&result);
// Add a listener
TimedBriefTestProgressListener progress;
controller.addListener(&progress);
pluginManager.addListener(&controller);
// Add the top suite to the test runner
CppUnit::TestRunner runner;
runner.addTest(CppUnit::TestFactoryRegistry::getRegistry().makeTest());
try
{
if (arguments.testPaths.empty()) {
std::cout << "Running " << std::endl;
runner.run(controller);
}
else {
for (const auto & p : arguments.testPaths) {
std::cout << "Running " << p << std::endl;
runner.run(controller, p);
}
}
std::cerr << std::endl;
// Print test in a compiler compatible format.
CppUnit::CompilerOutputter outputter(&result, std::cerr);
outputter.write();
if (!arguments.xmlOutputFile.empty()) {
std::ofstream file(arguments.xmlOutputFile);
CppUnit::XmlOutputter xOutputter(&result, file);
xOutputter.write();
}
}
catch (std::invalid_argument &e) // Test path not resolved
{
std::cerr << std::endl
<< "ERROR: " << e.what()
<< std::endl;
return false;
}
return result.wasSuccessful();
}
int main(int argc, char* argv[])
{
if (argc < 2) {
std::cout << "usage : " << argv[0] << " {-x | -xml=file} {-t | --test=Namespace::ClassName::TestName} test_plugin_path" << std::endl << std::endl;
return 1;
}
bool result = false;
try {
CommandLineParser command;
command.parseArgs(argc, argv);
result = runPlugin(command);
}
catch (std::exception &e) {
std::cerr << std::endl
<< "ERROR: " << e.what()
<< std::endl;
}
return result ? 0 : 1;
}
<|endoftext|> |
<commit_before>/*****************************************************************************/
/*!
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*****************************************************************************
*
* \file Debugger.cpp
*
* \brief Implementation of the Debugger.
*
* \version
* - S Panyam 05/12/2008
* Initial version.
*/
//*****************************************************************************
#include <iostream>
#include <string>
#include <sstream>
#include <errno.h>
#include <assert.h>
#include <netdb.h>
#include <stdlib.h>
#include <signal.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <sys/types.h>
#include "lpfwddefs.h"
#include "Debugger.h"
#include "DebugContext.h"
#include "LuaBindings.h"
LUNARPROBE_NS_BEGIN
//*****************************************************************************
/*!
* \brief Creates a new instance of the lua debugger.
*
* \param The port on which the server will be started.
*
* \version
* - S Panyam 27/10/2008
* Initial version.
*/
//*****************************************************************************
Debugger::Debugger() : pLuaBindings(NULL)
{
}
//*****************************************************************************
/*!
* \brief Destroys the debugger.
*
* \version
* - S Panyam 27/10/2008
* Initial version.
*/
//*****************************************************************************
Debugger::~Debugger()
{
// remove any debug contexts that wasnt removed (via StopDebugging)
for (DebugContextMap::iterator iter = debugContexts.begin();iter != debugContexts.end(); ++iter)
{
DebugContext *ctx = iter->second;
if (ctx != NULL)
delete ctx;
}
if (pLuaBindings != NULL)
delete pLuaBindings;
}
//*****************************************************************************
/*!
* \brief Gets the debug contexts
*
* \version
* - S Panyam 23/10/2008
* Initial version.
*/
//*****************************************************************************
const Debugger::DebugContextMap &GetContexts() const
{
return debugContexts;
}
//*****************************************************************************
/*!
* \brief Starts debugging of a lua stack.
*
* \version
* - S Panyam 23/10/2008
* Initial version.
*/
//*****************************************************************************
bool Debugger::StartDebugging(LuaStack pStack, const char *name)
{
DebugContext *pContext = GetDebugContext(pStack);
if (pContext != NULL)
{
return false;
}
pContext = AddDebugContext(pStack, name);
return true;
}
//*****************************************************************************
/*!
* \brief Stops debugging of a lua stack.
*
* \version
* - S Panyam 23/10/2008
* Initial version.
*/
//*****************************************************************************
bool Debugger::StopDebugging(LuaStack pStack)
{
DebugContextMap::iterator iter = debugContexts.find(pStack);
if (iter != debugContexts.end())
{
DebugContext *pContext = iter->second;
debugContexts.erase(iter);
GetLuaBindings()->ContextRemoved(pContext);
delete pContext;
}
return true;
}
//*****************************************************************************
/*!
* \brief Gets the debug context associated with a lua_State object.
*
* \version
* - S Panyam 23/10/2008
* Initial version.
*/
//*****************************************************************************
DebugContext *Debugger::GetDebugContext(LuaStack pStack)
{
DebugContextMap::iterator iter = debugContexts.find(pStack);
if (iter == debugContexts.end())
return NULL;
return iter->second;
}
//*****************************************************************************
/*!
* \brief Adds a new lua stack to the list of stacks being debugged.
*
* \param LuaStack The new lua stack to be debugged.
*
* \return The DebugContext object that maintains the debugger state
* for this stack.
*
* \version
* - S Panyam 23/10/2008
* Initial version.
*/
//*****************************************************************************
DebugContext *Debugger::AddDebugContext(LuaStack pStack, const char *name)
{
DebugContext *pContext = new DebugContext(pStack, name);
debugContexts[pStack] = pContext;
GetLuaBindings()->ContextAdded(pContext);
return pContext;
}
//*****************************************************************************
/*!
* \brief Called by the liblua (actually via LunarProbe::HookFunction)
* when a breakpoint is hit.
*
* \version
* - S Panyam 27/10/2008
* Initial version.
*/
//*****************************************************************************
void Debugger::HandleDebugHook(LuaStack pStack, LuaDebug pDebug)
{
DebugContext *pContext = GetDebugContext(pStack);
if (pContext == NULL)
{
assert(" =================== DebugContext cannot be NULL. " && pContext != NULL);
return ;
}
// get the stack info about the curr function
lua_getinfo(pStack, "nSluf", pDebug);
lua_pop(pStack, 1); // pop the name of the function off the stack
// ignore non-lua functions
if (pDebug->what == NULL || strcasecmp(pDebug->what, "lua") != 0)
{
// we are in a non-lua file so return straight away!
// TODO: Should we alert someone or do SOMETHING here?
return ;
}
switch (pDebug->event)
{
case LUA_HOOKCALL:
{
if (pDebug->name != NULL)
{
GetLuaBindings()->HandleBreakpoint(pContext, pDebug);
}
} break ;
case LUA_HOOKLINE:
{
if (pDebug->source[0] == '@')
{
GetLuaBindings()->HandleBreakpoint(pContext, pDebug);
}
} break ;
case LUA_HOOKRET:
{
GetLuaBindings()->HandleBreakpoint(pContext, pDebug);
} break ;
case LUA_HOOKCOUNT:
{
/*
std::cerr << "========================================================" << std::endl << std::endl
<< "LUA_HOOKCOUNT not yet handled..........." << std::endl << std::endl
<< "========================================================" << std::endl << std::endl;
*/
} break ;
case LUA_HOOKTAILRET:
{
// can come here with a "step", "next" or "return"
// leave it out for now
std::cerr << "========================================================" << std::endl << std::endl
<< "LUA_HOOKTAILRET not yet handled ..........." << std::endl << std::endl
<< "========================================================" << std::endl << std::endl;
} break ;
}
}
//*****************************************************************************
/*!
* \brief Gets the instance of the lua side of debugger.
*
* \return The lua bindings for the debugger.
*
* \version
* - S Panyam 12/11/2008
* Initial version.
*/
//*****************************************************************************
LuaBindings *Debugger::GetLuaBindings()
{
if (pLuaBindings == NULL)
{
pLuaBindings = new LuaBindings(this);
}
return pLuaBindings;
}
LUNARPROBE_NS_END
<commit_msg>FIxed error<commit_after>/*****************************************************************************/
/*!
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*****************************************************************************
*
* \file Debugger.cpp
*
* \brief Implementation of the Debugger.
*
* \version
* - S Panyam 05/12/2008
* Initial version.
*/
//*****************************************************************************
#include <iostream>
#include <string>
#include <sstream>
#include <errno.h>
#include <assert.h>
#include <netdb.h>
#include <stdlib.h>
#include <signal.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <sys/types.h>
#include "lpfwddefs.h"
#include "Debugger.h"
#include "DebugContext.h"
#include "LuaBindings.h"
LUNARPROBE_NS_BEGIN
//*****************************************************************************
/*!
* \brief Creates a new instance of the lua debugger.
*
* \param The port on which the server will be started.
*
* \version
* - S Panyam 27/10/2008
* Initial version.
*/
//*****************************************************************************
Debugger::Debugger() : pLuaBindings(NULL)
{
}
//*****************************************************************************
/*!
* \brief Destroys the debugger.
*
* \version
* - S Panyam 27/10/2008
* Initial version.
*/
//*****************************************************************************
Debugger::~Debugger()
{
// remove any debug contexts that wasnt removed (via StopDebugging)
for (DebugContextMap::iterator iter = debugContexts.begin();iter != debugContexts.end(); ++iter)
{
DebugContext *ctx = iter->second;
if (ctx != NULL)
delete ctx;
}
if (pLuaBindings != NULL)
delete pLuaBindings;
}
//*****************************************************************************
/*!
* \brief Gets the debug contexts
*
* \version
* - S Panyam 23/10/2008
* Initial version.
*/
//*****************************************************************************
const DebugContextMap &Debugger::GetContexts() const
{
return debugContexts;
}
//*****************************************************************************
/*!
* \brief Starts debugging of a lua stack.
*
* \version
* - S Panyam 23/10/2008
* Initial version.
*/
//*****************************************************************************
bool Debugger::StartDebugging(LuaStack pStack, const char *name)
{
DebugContext *pContext = GetDebugContext(pStack);
if (pContext != NULL)
{
return false;
}
pContext = AddDebugContext(pStack, name);
return true;
}
//*****************************************************************************
/*!
* \brief Stops debugging of a lua stack.
*
* \version
* - S Panyam 23/10/2008
* Initial version.
*/
//*****************************************************************************
bool Debugger::StopDebugging(LuaStack pStack)
{
DebugContextMap::iterator iter = debugContexts.find(pStack);
if (iter != debugContexts.end())
{
DebugContext *pContext = iter->second;
debugContexts.erase(iter);
GetLuaBindings()->ContextRemoved(pContext);
delete pContext;
}
return true;
}
//*****************************************************************************
/*!
* \brief Gets the debug context associated with a lua_State object.
*
* \version
* - S Panyam 23/10/2008
* Initial version.
*/
//*****************************************************************************
DebugContext *Debugger::GetDebugContext(LuaStack pStack)
{
DebugContextMap::iterator iter = debugContexts.find(pStack);
if (iter == debugContexts.end())
return NULL;
return iter->second;
}
//*****************************************************************************
/*!
* \brief Adds a new lua stack to the list of stacks being debugged.
*
* \param LuaStack The new lua stack to be debugged.
*
* \return The DebugContext object that maintains the debugger state
* for this stack.
*
* \version
* - S Panyam 23/10/2008
* Initial version.
*/
//*****************************************************************************
DebugContext *Debugger::AddDebugContext(LuaStack pStack, const char *name)
{
DebugContext *pContext = new DebugContext(pStack, name);
debugContexts[pStack] = pContext;
GetLuaBindings()->ContextAdded(pContext);
return pContext;
}
//*****************************************************************************
/*!
* \brief Called by the liblua (actually via LunarProbe::HookFunction)
* when a breakpoint is hit.
*
* \version
* - S Panyam 27/10/2008
* Initial version.
*/
//*****************************************************************************
void Debugger::HandleDebugHook(LuaStack pStack, LuaDebug pDebug)
{
DebugContext *pContext = GetDebugContext(pStack);
if (pContext == NULL)
{
assert(" =================== DebugContext cannot be NULL. " && pContext != NULL);
return ;
}
// get the stack info about the curr function
lua_getinfo(pStack, "nSluf", pDebug);
lua_pop(pStack, 1); // pop the name of the function off the stack
// ignore non-lua functions
if (pDebug->what == NULL || strcasecmp(pDebug->what, "lua") != 0)
{
// we are in a non-lua file so return straight away!
// TODO: Should we alert someone or do SOMETHING here?
return ;
}
switch (pDebug->event)
{
case LUA_HOOKCALL:
{
if (pDebug->name != NULL)
{
GetLuaBindings()->HandleBreakpoint(pContext, pDebug);
}
} break ;
case LUA_HOOKLINE:
{
if (pDebug->source[0] == '@')
{
GetLuaBindings()->HandleBreakpoint(pContext, pDebug);
}
} break ;
case LUA_HOOKRET:
{
GetLuaBindings()->HandleBreakpoint(pContext, pDebug);
} break ;
case LUA_HOOKCOUNT:
{
/*
std::cerr << "========================================================" << std::endl << std::endl
<< "LUA_HOOKCOUNT not yet handled..........." << std::endl << std::endl
<< "========================================================" << std::endl << std::endl;
*/
} break ;
case LUA_HOOKTAILRET:
{
// can come here with a "step", "next" or "return"
// leave it out for now
std::cerr << "========================================================" << std::endl << std::endl
<< "LUA_HOOKTAILRET not yet handled ..........." << std::endl << std::endl
<< "========================================================" << std::endl << std::endl;
} break ;
}
}
//*****************************************************************************
/*!
* \brief Gets the instance of the lua side of debugger.
*
* \return The lua bindings for the debugger.
*
* \version
* - S Panyam 12/11/2008
* Initial version.
*/
//*****************************************************************************
LuaBindings *Debugger::GetLuaBindings()
{
if (pLuaBindings == NULL)
{
pLuaBindings = new LuaBindings(this);
}
return pLuaBindings;
}
LUNARPROBE_NS_END
<|endoftext|> |
<commit_before>#include "pch.h"
#include "DspChunk.h"
namespace SaneAudioRenderer
{
static_assert((int32_t{-1} >> 31) == -1 && (int64_t{-1} >> 63) == -1, "Code relies on right signed shift UB");
static_assert((int64_t)(float)((uint32_t)INT32_MAX + 1) == ((uint32_t)INT32_MAX + 1), "Rounding error");
static_assert((int32_t)(float)(INT32_MAX - 127) == (INT32_MAX - 127), "Rounding error");
static_assert((int32_t)(double)INT32_MAX == INT32_MAX, "Rounding error");
namespace
{
inline int32_t UnpackPcm24(const int24_t& input)
{
int32_t x = *(reinterpret_cast<const uint16_t*>(&input));
int32_t h = *(reinterpret_cast<const uint8_t*>(&input) + 2);
x |= (h << 16);
x <<= 8;
return x;
}
inline void PackPcm24(const int32_t& input, int24_t& output)
{
*(reinterpret_cast<uint16_t*>(&output)) = (uint16_t)(input >> 8);
*(reinterpret_cast<uint8_t*>(&output) + 2) = (uint8_t)(input >> 24);
}
template <DspFormat InputFormat, DspFormat OutputFormat>
inline void ConvertSample(const typename DspFormatTraits<InputFormat>::SampleType& input,
typename DspFormatTraits<OutputFormat>::SampleType& output);
template <>
inline void ConvertSample<DspFormat::Pcm8, DspFormat::Pcm8>(const int8_t& input, int8_t& output)
{
output = input;
}
template <>
inline void ConvertSample<DspFormat::Pcm8, DspFormat::Pcm16>(const int8_t& input, int16_t& output)
{
output = (int16_t)input << 8;
}
template <>
inline void ConvertSample<DspFormat::Pcm8, DspFormat::Pcm24>(const int8_t& input, int24_t& output)
{
PackPcm24((int32_t)input << 24, output);
}
template <>
inline void ConvertSample<DspFormat::Pcm8, DspFormat::Pcm32>(const int8_t& input, int32_t& output)
{
output = (int32_t)input << 24;
}
template <>
inline void ConvertSample<DspFormat::Pcm8, DspFormat::Float>(const int8_t& input, float& output)
{
output = (float)input / ((int32_t)INT8_MAX + 1);
}
template <>
inline void ConvertSample<DspFormat::Pcm8, DspFormat::Double>(const int8_t& input, double& output)
{
output = (double)input / ((int32_t)INT8_MAX + 1);
}
template <>
inline void ConvertSample<DspFormat::Pcm16, DspFormat::Pcm16>(const int16_t& input, int16_t& output)
{
output = input;
}
template <>
inline void ConvertSample<DspFormat::Pcm16, DspFormat::Pcm24>(const int16_t& input, int24_t& output)
{
PackPcm24((int32_t)input << 16, output);
}
template <>
inline void ConvertSample<DspFormat::Pcm16, DspFormat::Pcm32>(const int16_t& input, int32_t& output)
{
output = (int32_t)input << 16;
}
template <>
inline void ConvertSample<DspFormat::Pcm16, DspFormat::Float>(const int16_t& input, float& output)
{
output = (float)input / ((int32_t)INT16_MAX + 1);
}
template <>
inline void ConvertSample<DspFormat::Pcm16, DspFormat::Double>(const int16_t& input, double& output)
{
output = (double)input / ((int32_t)INT16_MAX + 1);
}
template <>
inline void ConvertSample<DspFormat::Pcm24, DspFormat::Pcm16>(const int24_t &input, int16_t& output)
{
output = *(int16_t*)(input.d + 1);
}
template <>
inline void ConvertSample<DspFormat::Pcm24, DspFormat::Pcm24>(const int24_t& input, int24_t& output)
{
output = input;
}
template <>
inline void ConvertSample<DspFormat::Pcm24, DspFormat::Pcm32>(const int24_t& input, int32_t& output)
{
output = UnpackPcm24(input);
}
template <>
inline void ConvertSample<DspFormat::Pcm24, DspFormat::Float>(const int24_t& input, float& output)
{
output = (float)UnpackPcm24(input) / ((uint32_t)INT32_MAX + 1);
}
template <>
inline void ConvertSample<DspFormat::Pcm24, DspFormat::Double>(const int24_t& input, double& output)
{
output = (double)UnpackPcm24(input) / ((uint32_t)INT32_MAX + 1);
}
template <>
inline void ConvertSample<DspFormat::Pcm32, DspFormat::Pcm16>(const int32_t& input, int16_t& output)
{
output = (int16_t)(input >> 16);
}
template <>
inline void ConvertSample<DspFormat::Pcm32, DspFormat::Pcm24>(const int32_t& input, int24_t& output)
{
PackPcm24(input, output);
}
template <>
inline void ConvertSample<DspFormat::Pcm32, DspFormat::Pcm32>(const int32_t& input, int32_t& output)
{
output = input;
}
template <>
inline void ConvertSample<DspFormat::Pcm32, DspFormat::Float>(const int32_t& input, float& output)
{
output = (float)input / ((uint32_t)INT32_MAX + 1);
}
template <>
inline void ConvertSample<DspFormat::Pcm32, DspFormat::Double>(const int32_t& input, double& output)
{
output = (double)input / ((uint32_t)INT32_MAX + 1);
}
template <>
inline void ConvertSample<DspFormat::Float, DspFormat::Pcm16>(const float& input, int16_t& output)
{
output = (int16_t)(input * INT16_MAX);
}
template <>
inline void ConvertSample<DspFormat::Float, DspFormat::Pcm24>(const float& input, int24_t& output)
{
PackPcm24((int32_t)(input * (INT32_MAX - 127)), output);
}
template <>
inline void ConvertSample<DspFormat::Float, DspFormat::Pcm32>(const float& input, int32_t& output)
{
//assert(fabs(input) <= 1.0f);
output = (int32_t)(input * (INT32_MAX - 127));
}
template <>
inline void ConvertSample<DspFormat::Float, DspFormat::Float>(const float& input, float& output)
{
output = input;
}
template <>
inline void ConvertSample<DspFormat::Float, DspFormat::Double>(const float& input, double& output)
{
output = input;
}
template <>
inline void ConvertSample<DspFormat::Double, DspFormat::Pcm16>(const double& input, int16_t& output)
{
output = (int16_t)(input * INT16_MAX);
}
template <>
inline void ConvertSample<DspFormat::Double, DspFormat::Pcm24>(const double& input, int24_t& output)
{
PackPcm24((int32_t)(input * INT32_MAX), output);
}
template <>
inline void ConvertSample<DspFormat::Double, DspFormat::Pcm32>(const double& input, int32_t& output)
{
output = (int32_t)(input * INT32_MAX);
}
template <>
inline void ConvertSample<DspFormat::Double, DspFormat::Float>(const double& input, float& output)
{
output = (float)input;
}
template <>
inline void ConvertSample<DspFormat::Double, DspFormat::Double>(const double& input, double& output)
{
output = input;
}
template <DspFormat InputFormat, DspFormat OutputFormat>
void ConvertSamples(const char* input, typename DspFormatTraits<OutputFormat>::SampleType* output, size_t samples)
{
const DspFormatTraits<InputFormat>::SampleType* inputData;
inputData = (decltype(inputData))input;
for (size_t i = 0; i < samples; i++)
ConvertSample<InputFormat, OutputFormat>(inputData[i], output[i]);
}
template <DspFormat OutputFormat>
void ConvertChunk(DspChunk& chunk)
{
const DspFormat inputFormat = chunk.GetFormat();
assert(!chunk.IsEmpty() && OutputFormat != inputFormat);
DspChunk output(OutputFormat, chunk.GetChannelCount(), chunk.GetFrameCount(), chunk.GetRate());
auto outputData = (DspFormatTraits<OutputFormat>::SampleType*)output.GetData();
switch (inputFormat)
{
case DspFormat::Pcm8:
ConvertSamples<DspFormat::Pcm8, OutputFormat>(chunk.GetConstData(), outputData, chunk.GetSampleCount());
break;
case DspFormat::Pcm16:
ConvertSamples<DspFormat::Pcm16, OutputFormat>(chunk.GetConstData(), outputData, chunk.GetSampleCount());
break;
case DspFormat::Pcm24:
ConvertSamples<DspFormat::Pcm24, OutputFormat>(chunk.GetConstData(), outputData, chunk.GetSampleCount());
break;
case DspFormat::Pcm32:
ConvertSamples<DspFormat::Pcm32, OutputFormat>(chunk.GetConstData(), outputData, chunk.GetSampleCount());
break;
case DspFormat::Float:
ConvertSamples<DspFormat::Float, OutputFormat>(chunk.GetConstData(), outputData, chunk.GetSampleCount());
break;
case DspFormat::Double:
ConvertSamples<DspFormat::Double, OutputFormat>(chunk.GetConstData(), outputData, chunk.GetSampleCount());
break;
}
chunk = std::move(output);
}
}
void DspChunk::ToFormat(DspFormat format, DspChunk& chunk)
{
assert(format != DspFormat::Pcm8);
if (chunk.IsEmpty() || format == chunk.GetFormat())
return;
assert(chunk.GetFormat() != DspFormat::Unknown);
switch (format)
{
case DspFormat::Pcm16:
ConvertChunk<DspFormat::Pcm16>(chunk);
break;
case DspFormat::Pcm24:
ConvertChunk<DspFormat::Pcm24>(chunk);
break;
case DspFormat::Pcm32:
ConvertChunk<DspFormat::Pcm32>(chunk);
break;
case DspFormat::Float:
ConvertChunk<DspFormat::Float>(chunk);
break;
case DspFormat::Double:
ConvertChunk<DspFormat::Double>(chunk);
break;
}
}
DspChunk::DspChunk()
: m_format(DspFormat::Unknown)
, m_formatSize(1)
, m_channels(1)
, m_rate(1)
, m_dataSize(0)
, m_constData(nullptr)
, m_delayedCopy(false)
{
}
DspChunk::DspChunk(DspFormat format, uint32_t channels, size_t frames, uint32_t rate)
: m_format(format)
, m_formatSize(DspFormatSize(m_format))
, m_channels(channels)
, m_rate(rate)
, m_dataSize(m_formatSize * channels * frames)
, m_constData(nullptr)
, m_delayedCopy(false)
{
assert(m_format != DspFormat::Unknown);
Allocate();
}
DspChunk::DspChunk(IMediaSample* pSample, const AM_SAMPLE2_PROPERTIES& sampleProps, const WAVEFORMATEX& sampleFormat)
: m_mediaSample(pSample)
, m_format(DspFormatFromWaveFormat(sampleFormat))
, m_formatSize(m_format != DspFormat::Unknown ? DspFormatSize(m_format) : sampleFormat.wBitsPerSample / 8)
, m_channels(sampleFormat.nChannels)
, m_rate(sampleFormat.nSamplesPerSec)
, m_dataSize(sampleProps.lActual)
, m_constData((char*)sampleProps.pbBuffer)
, m_delayedCopy(true)
{
assert(m_formatSize == sampleFormat.wBitsPerSample / 8);
assert(m_mediaSample);
assert(m_constData);
assert(m_dataSize % GetFrameSize() == 0);
m_dataSize = m_dataSize - m_dataSize % GetFrameSize();
}
DspChunk::DspChunk(DspChunk&& other)
: m_mediaSample(other.m_mediaSample)
, m_format(other.m_format)
, m_formatSize(other.m_formatSize)
, m_channels(other.m_channels)
, m_rate(other.m_rate)
, m_dataSize(other.m_dataSize)
, m_constData(other.m_constData)
, m_delayedCopy(other.m_delayedCopy)
{
other.m_mediaSample = nullptr;
other.m_dataSize = 0;
std::swap(m_data, other.m_data);
}
DspChunk& DspChunk::operator=(DspChunk&& other)
{
if (this != &other)
{
m_mediaSample = other.m_mediaSample; other.m_mediaSample = nullptr;
m_format = other.m_format;
m_formatSize = other.m_formatSize;
m_channels = other.m_channels;
m_rate = other.m_rate;
m_dataSize = other.m_dataSize; other.m_dataSize = 0;
m_constData = other.m_constData;
m_delayedCopy = other.m_delayedCopy;
m_data = nullptr; std::swap(m_data, other.m_data);
}
return *this;
}
char* DspChunk::GetData()
{
InvokeDelayedCopy();
return m_data.get();
}
void DspChunk::Shrink(size_t toFrames)
{
if (toFrames < GetFrameCount())
{
InvokeDelayedCopy();
m_dataSize = GetFormatSize() * GetChannelCount() * toFrames;
}
}
void DspChunk::Allocate()
{
if (m_dataSize > 0)
{
m_data.reset((char*)_aligned_malloc(m_dataSize, 16));
if (!m_data.get())
throw std::bad_alloc();
}
}
void DspChunk::InvokeDelayedCopy()
{
if (m_delayedCopy)
{
Allocate();
assert(m_constData);
memcpy(m_data.get(), m_constData, m_dataSize);
m_delayedCopy = false;
}
}
}
<commit_msg>And more code refactoring<commit_after>#include "pch.h"
#include "DspChunk.h"
namespace SaneAudioRenderer
{
static_assert((int32_t{-1} >> 31) == -1 && (int64_t{-1} >> 63) == -1, "Code relies on right signed shift UB");
static_assert((int64_t)(float)((uint32_t)INT32_MAX + 1) == ((uint32_t)INT32_MAX + 1), "Rounding error");
static_assert((int32_t)(float)(INT32_MAX - 127) == (INT32_MAX - 127), "Rounding error");
static_assert((int32_t)(double)INT32_MAX == INT32_MAX, "Rounding error");
namespace
{
inline int32_t UnpackPcm24(const int24_t& input)
{
int32_t x = *(reinterpret_cast<const uint16_t*>(&input));
int32_t h = *(reinterpret_cast<const uint8_t*>(&input) + 2);
x |= (h << 16);
x <<= 8;
return x;
}
inline void PackPcm24(const int32_t& input, int24_t& output)
{
*(reinterpret_cast<uint16_t*>(&output)) = (uint16_t)(input >> 8);
*(reinterpret_cast<uint8_t*>(&output) + 2) = (uint8_t)(input >> 24);
}
template <DspFormat InputFormat, DspFormat OutputFormat>
inline void ConvertSample(const typename DspFormatTraits<InputFormat>::SampleType& input,
typename DspFormatTraits<OutputFormat>::SampleType& output);
template <>
inline void ConvertSample<DspFormat::Pcm8, DspFormat::Pcm8>(const int8_t& input, int8_t& output)
{
output = input;
}
template <>
inline void ConvertSample<DspFormat::Pcm8, DspFormat::Pcm16>(const int8_t& input, int16_t& output)
{
output = (int16_t)input << 8;
}
template <>
inline void ConvertSample<DspFormat::Pcm8, DspFormat::Pcm24>(const int8_t& input, int24_t& output)
{
PackPcm24((int32_t)input << 24, output);
}
template <>
inline void ConvertSample<DspFormat::Pcm8, DspFormat::Pcm32>(const int8_t& input, int32_t& output)
{
output = (int32_t)input << 24;
}
template <>
inline void ConvertSample<DspFormat::Pcm8, DspFormat::Float>(const int8_t& input, float& output)
{
output = (float)input / ((int32_t)INT8_MAX + 1);
}
template <>
inline void ConvertSample<DspFormat::Pcm8, DspFormat::Double>(const int8_t& input, double& output)
{
output = (double)input / ((int32_t)INT8_MAX + 1);
}
template <>
inline void ConvertSample<DspFormat::Pcm16, DspFormat::Pcm16>(const int16_t& input, int16_t& output)
{
output = input;
}
template <>
inline void ConvertSample<DspFormat::Pcm16, DspFormat::Pcm24>(const int16_t& input, int24_t& output)
{
PackPcm24((int32_t)input << 16, output);
}
template <>
inline void ConvertSample<DspFormat::Pcm16, DspFormat::Pcm32>(const int16_t& input, int32_t& output)
{
output = (int32_t)input << 16;
}
template <>
inline void ConvertSample<DspFormat::Pcm16, DspFormat::Float>(const int16_t& input, float& output)
{
output = (float)input / ((int32_t)INT16_MAX + 1);
}
template <>
inline void ConvertSample<DspFormat::Pcm16, DspFormat::Double>(const int16_t& input, double& output)
{
output = (double)input / ((int32_t)INT16_MAX + 1);
}
template <>
inline void ConvertSample<DspFormat::Pcm24, DspFormat::Pcm16>(const int24_t &input, int16_t& output)
{
output = *(int16_t*)(input.d + 1);
}
template <>
inline void ConvertSample<DspFormat::Pcm24, DspFormat::Pcm24>(const int24_t& input, int24_t& output)
{
output = input;
}
template <>
inline void ConvertSample<DspFormat::Pcm24, DspFormat::Pcm32>(const int24_t& input, int32_t& output)
{
output = UnpackPcm24(input);
}
template <>
inline void ConvertSample<DspFormat::Pcm24, DspFormat::Float>(const int24_t& input, float& output)
{
output = (float)UnpackPcm24(input) / ((uint32_t)INT32_MAX + 1);
}
template <>
inline void ConvertSample<DspFormat::Pcm24, DspFormat::Double>(const int24_t& input, double& output)
{
output = (double)UnpackPcm24(input) / ((uint32_t)INT32_MAX + 1);
}
template <>
inline void ConvertSample<DspFormat::Pcm32, DspFormat::Pcm16>(const int32_t& input, int16_t& output)
{
output = (int16_t)(input >> 16);
}
template <>
inline void ConvertSample<DspFormat::Pcm32, DspFormat::Pcm24>(const int32_t& input, int24_t& output)
{
PackPcm24(input, output);
}
template <>
inline void ConvertSample<DspFormat::Pcm32, DspFormat::Pcm32>(const int32_t& input, int32_t& output)
{
output = input;
}
template <>
inline void ConvertSample<DspFormat::Pcm32, DspFormat::Float>(const int32_t& input, float& output)
{
output = (float)input / ((uint32_t)INT32_MAX + 1);
}
template <>
inline void ConvertSample<DspFormat::Pcm32, DspFormat::Double>(const int32_t& input, double& output)
{
output = (double)input / ((uint32_t)INT32_MAX + 1);
}
template <>
inline void ConvertSample<DspFormat::Float, DspFormat::Pcm16>(const float& input, int16_t& output)
{
output = (int16_t)(input * INT16_MAX);
}
template <>
inline void ConvertSample<DspFormat::Float, DspFormat::Pcm24>(const float& input, int24_t& output)
{
PackPcm24((int32_t)(input * (INT32_MAX - 127)), output);
}
template <>
inline void ConvertSample<DspFormat::Float, DspFormat::Pcm32>(const float& input, int32_t& output)
{
//assert(fabs(input) <= 1.0f);
output = (int32_t)(input * (INT32_MAX - 127));
}
template <>
inline void ConvertSample<DspFormat::Float, DspFormat::Float>(const float& input, float& output)
{
output = input;
}
template <>
inline void ConvertSample<DspFormat::Float, DspFormat::Double>(const float& input, double& output)
{
output = input;
}
template <>
inline void ConvertSample<DspFormat::Double, DspFormat::Pcm16>(const double& input, int16_t& output)
{
output = (int16_t)(input * INT16_MAX);
}
template <>
inline void ConvertSample<DspFormat::Double, DspFormat::Pcm24>(const double& input, int24_t& output)
{
PackPcm24((int32_t)(input * INT32_MAX), output);
}
template <>
inline void ConvertSample<DspFormat::Double, DspFormat::Pcm32>(const double& input, int32_t& output)
{
output = (int32_t)(input * INT32_MAX);
}
template <>
inline void ConvertSample<DspFormat::Double, DspFormat::Float>(const double& input, float& output)
{
output = (float)input;
}
template <>
inline void ConvertSample<DspFormat::Double, DspFormat::Double>(const double& input, double& output)
{
output = input;
}
template <DspFormat InputFormat, DspFormat OutputFormat>
void ConvertSamples(const char* input, typename DspFormatTraits<OutputFormat>::SampleType* output, size_t samples)
{
auto inputData = reinterpret_cast<const DspFormatTraits<InputFormat>::SampleType*>(input);
for (size_t i = 0; i < samples; i++)
ConvertSample<InputFormat, OutputFormat>(inputData[i], output[i]);
}
template <DspFormat OutputFormat>
void ConvertChunk(DspChunk& chunk)
{
const DspFormat inputFormat = chunk.GetFormat();
assert(!chunk.IsEmpty() && OutputFormat != inputFormat);
DspChunk outputChunk(OutputFormat, chunk.GetChannelCount(), chunk.GetFrameCount(), chunk.GetRate());
auto outputData = reinterpret_cast<DspFormatTraits<OutputFormat>::SampleType*>(outputChunk.GetData());
switch (inputFormat)
{
case DspFormat::Pcm8:
ConvertSamples<DspFormat::Pcm8, OutputFormat>(chunk.GetConstData(), outputData, chunk.GetSampleCount());
break;
case DspFormat::Pcm16:
ConvertSamples<DspFormat::Pcm16, OutputFormat>(chunk.GetConstData(), outputData, chunk.GetSampleCount());
break;
case DspFormat::Pcm24:
ConvertSamples<DspFormat::Pcm24, OutputFormat>(chunk.GetConstData(), outputData, chunk.GetSampleCount());
break;
case DspFormat::Pcm32:
ConvertSamples<DspFormat::Pcm32, OutputFormat>(chunk.GetConstData(), outputData, chunk.GetSampleCount());
break;
case DspFormat::Float:
ConvertSamples<DspFormat::Float, OutputFormat>(chunk.GetConstData(), outputData, chunk.GetSampleCount());
break;
case DspFormat::Double:
ConvertSamples<DspFormat::Double, OutputFormat>(chunk.GetConstData(), outputData, chunk.GetSampleCount());
break;
}
chunk = std::move(outputChunk);
}
}
void DspChunk::ToFormat(DspFormat format, DspChunk& chunk)
{
assert(format != DspFormat::Pcm8);
if (chunk.IsEmpty() || format == chunk.GetFormat())
return;
assert(chunk.GetFormat() != DspFormat::Unknown);
switch (format)
{
case DspFormat::Pcm16:
ConvertChunk<DspFormat::Pcm16>(chunk);
break;
case DspFormat::Pcm24:
ConvertChunk<DspFormat::Pcm24>(chunk);
break;
case DspFormat::Pcm32:
ConvertChunk<DspFormat::Pcm32>(chunk);
break;
case DspFormat::Float:
ConvertChunk<DspFormat::Float>(chunk);
break;
case DspFormat::Double:
ConvertChunk<DspFormat::Double>(chunk);
break;
}
}
DspChunk::DspChunk()
: m_format(DspFormat::Unknown)
, m_formatSize(1)
, m_channels(1)
, m_rate(1)
, m_dataSize(0)
, m_constData(nullptr)
, m_delayedCopy(false)
{
}
DspChunk::DspChunk(DspFormat format, uint32_t channels, size_t frames, uint32_t rate)
: m_format(format)
, m_formatSize(DspFormatSize(m_format))
, m_channels(channels)
, m_rate(rate)
, m_dataSize(m_formatSize * channels * frames)
, m_constData(nullptr)
, m_delayedCopy(false)
{
assert(m_format != DspFormat::Unknown);
Allocate();
}
DspChunk::DspChunk(IMediaSample* pSample, const AM_SAMPLE2_PROPERTIES& sampleProps, const WAVEFORMATEX& sampleFormat)
: m_mediaSample(pSample)
, m_format(DspFormatFromWaveFormat(sampleFormat))
, m_formatSize(m_format != DspFormat::Unknown ? DspFormatSize(m_format) : sampleFormat.wBitsPerSample / 8)
, m_channels(sampleFormat.nChannels)
, m_rate(sampleFormat.nSamplesPerSec)
, m_dataSize(sampleProps.lActual)
, m_constData((char*)sampleProps.pbBuffer)
, m_delayedCopy(true)
{
assert(m_formatSize == sampleFormat.wBitsPerSample / 8);
assert(m_mediaSample);
assert(m_constData);
assert(m_dataSize % GetFrameSize() == 0);
m_dataSize = m_dataSize - m_dataSize % GetFrameSize();
}
DspChunk::DspChunk(DspChunk&& other)
: m_mediaSample(other.m_mediaSample)
, m_format(other.m_format)
, m_formatSize(other.m_formatSize)
, m_channels(other.m_channels)
, m_rate(other.m_rate)
, m_dataSize(other.m_dataSize)
, m_constData(other.m_constData)
, m_delayedCopy(other.m_delayedCopy)
{
other.m_mediaSample = nullptr;
other.m_dataSize = 0;
std::swap(m_data, other.m_data);
}
DspChunk& DspChunk::operator=(DspChunk&& other)
{
if (this != &other)
{
m_mediaSample = other.m_mediaSample; other.m_mediaSample = nullptr;
m_format = other.m_format;
m_formatSize = other.m_formatSize;
m_channels = other.m_channels;
m_rate = other.m_rate;
m_dataSize = other.m_dataSize; other.m_dataSize = 0;
m_constData = other.m_constData;
m_delayedCopy = other.m_delayedCopy;
m_data = nullptr; std::swap(m_data, other.m_data);
}
return *this;
}
char* DspChunk::GetData()
{
InvokeDelayedCopy();
return m_data.get();
}
void DspChunk::Shrink(size_t toFrames)
{
if (toFrames < GetFrameCount())
{
InvokeDelayedCopy();
m_dataSize = GetFormatSize() * GetChannelCount() * toFrames;
}
}
void DspChunk::Allocate()
{
if (m_dataSize > 0)
{
m_data.reset((char*)_aligned_malloc(m_dataSize, 16));
if (!m_data.get())
throw std::bad_alloc();
}
}
void DspChunk::InvokeDelayedCopy()
{
if (m_delayedCopy)
{
Allocate();
assert(m_constData);
memcpy(m_data.get(), m_constData, m_dataSize);
m_delayedCopy = false;
}
}
}
<|endoftext|> |
<commit_before>#include "HRSC/HRSC.h"
#include "MOC/Metadata.h"
#include "HRSC/ExtoriExtrinsics.h"
#include <fstream>
#include <vw/Core/Exception.h>
#include <vw/Math/EulerAngles.h>
using namespace vw::camera;
HRSCImageMetadata::HRSCImageMetadata(std::string const& filename) {
m_filename = filename;
m_line_times.clear();
m_extori_ephem_times.clear();
}
/// Returns a newly allocated camera model object of the appropriate
/// type. It is the responsibility of the user to later deallocate
/// this camera model object or to manage it using some sort of smart
/// pointer.
vw::camera::CameraModel* HRSCImageMetadata::camera_model() {
// The HRSC frame of reference is defined as follows:
//
// +Z out of the front of the camera (nadir)
// +Y perpindicular to the imaging lines in the direction of flight
// +X parallel to the scanlines, but increasing X is decreasing u...
vw::Vector3 pointing_vec(0,0,1);
vw::Vector3 u_vec(-1,0,0);
if (m_extori_ephem_times.size() > 0) {
std::cout << "NOTE: Generating HRSC camera model based on EXTORI metadata...\n";
std::cout << "rows(): " << rows() << "\n";
std::cout << "t0: " << m_first_line_ephem_time << "\n";
std::cout << "LT: " << m_line_times[0] << "\n";
std::cout << "LT: " << m_line_times[m_line_times.size()-1] << "\n";
std::cout << "LT s: " << m_line_times.size() << "\n";
std::cout << "LT: " << m_extori_ephem_times[m_extori_ephem_times.size()-1] << "\n";
std::cout << "QUAT0: " << m_extori_quat[0] << "\n\n";
// If there is extori information, it takes precedence because it is
// more accurate.
return new LinescanModel<ExtoriPositionInterpolation,
ExtoriPoseInterpolation>(rows(),
cols(),
int(m_start_sample/m_crosstrack_summing),
m_focal_length,
m_along_scan_pixel_size*m_downtrack_summing,
m_across_scan_pixel_size*m_crosstrack_summing,
m_line_times,
pointing_vec, u_vec,
ExtoriPositionInterpolation(m_extori_ephem_times, m_extori_ephem),
ExtoriPoseInterpolation(m_extori_ephem_times, m_extori_quat));
} else {
// Use the values that were obtained from the *.sup file to program
// the camera model parameters.
return new LinescanModel<Curve3DPositionInterpolation,
SLERPPoseInterpolation>(rows(),
cols(),
int(m_start_sample/m_crosstrack_summing),
m_focal_length,
m_along_scan_pixel_size*m_downtrack_summing,
m_across_scan_pixel_size*m_crosstrack_summing,
m_line_times,
pointing_vec, u_vec,
Curve3DPositionInterpolation(m_ephem, m_t0_ephem, m_dt_ephem),
SLERPPoseInterpolation(m_quat, m_t0_quat, m_dt_quat));
}
}
/// Read the line times from an HRSC metadata file
void HRSCImageMetadata::read_line_times(std::string const& filename) {
std::ifstream infile(filename.c_str());
double scanline, sclk_time, integration_time;
if ( infile.is_open() ) {
m_line_times.clear();
while (infile >> scanline >> sclk_time >> integration_time ) {
m_line_times.push_back(sclk_time);
}
} else {
throw vw::IOErr() << "hrsc_line_integration_times: could not open file \"" << filename << "\"\n";
}
std::cout << filename << ": " << m_line_times.size() << " records.\n";
m_first_line_ephem_time = m_line_times[0];
for (int i = 0; i < m_line_times.size(); ++i) {
m_line_times[i] -= m_first_line_ephem_time;
}
infile.close();
}
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
// HRSC SUP FILE MANIPULATION
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
//
// Read a HRSC *.sup data file provided by Ross Beyer
// This file is used to initialize a linescan camera model.
void HRSCImageMetadata::read_ephemeris_supplement(std::string const& filename) {
SupplementaryEphemerisParser parser(filename);
try {
// First, gather the basic intrinsic camera prameters
//
// Note that these values may be overridden by the values in the
// description.tab file (though they should be identical values).
//
m_crosstrack_summing = parser.read_double("PIXEL_SUMMING");
m_downtrack_summing = parser.read_double("PIXEL_SUMMING");
double scan_duration = parser.read_double("SCAN_DURATION");
double downloaded_lines = parser.read_double("DOWNLOADED_LINES");
m_height_pixels = downloaded_lines/m_downtrack_summing;
m_focal_length = parser.read_double("FOCAL_LENGTH") / 1000.0;
m_across_scan_pixel_size = parser.read_double("ACROSS_SCAN_PIXEL_SIZE") / 1.0e6;
m_along_scan_pixel_size = parser.read_double("ALONG_SCAN_PIXEL_SIZE") / 1.0e6;
double downloaded_samples = parser.read_double("DOWNLOADED_SAMPLES");
m_width_pixels = downloaded_samples/m_crosstrack_summing;
// This is really the only piece of information we need from the ephemeris file.
// (This does noet appear in the description.tab file)
m_start_sample = parser.read_double("START_SAMPLE");
/* Read the full ephemeris information into a Nx3 matrix*/
double n_ephem = parser.read_double("N_EPHEM");
m_t0_ephem = parser.read_double("T0_EPHEM");
m_dt_ephem = parser.read_double("DT_EPHEM");
m_ephem = parser.read_vector3s("EPHEM", (int)n_ephem, 3);
m_ephem_rate = parser.read_vector3s("EPHEM_RATE", (int)n_ephem, 3);
/* Next, read in the time serios of data regarding orientation */
double n_quat = parser.read_double("NUM_QUAT");
m_t0_quat = parser.read_double("T0_QUAT");
m_dt_quat = parser.read_double("DT_QUAT");
m_quat = parser.read_quaternions("QUATERNIONS", (int)n_quat, 4);
} catch (EphemerisErr &e) {
throw vw::IOErr() << "An error occured while parsing the ephemeris file.\n";
}
}
// This is test code for comprehending the extori angles. It should be deleted. -mbroxton
// // This additional rotation takes us from the extori "spacecraft"
// // frame to the more familiar spice HRSC instrument frame.
// vw::Matrix<double,3,3> hack;
// hack(0,0) = 0; hack(0,1) = 1.0; hack(0,2) = 0;
// hack(1,0) = 1; hack(1,1) = 0.0; hack(1,2) = 0;
// hack(2,0) = 0; hack(2,1) = 0; hack(2,2) = -1;
// // Here we incorporate the rotation for individual HRSC scanlines.
// vw::Matrix<double,3,3> scanline_phi, scanline_omega;
// if (scanline == "S1") {
// scanline_phi = rotation_z_axis(0.0205*M_PI/180.0);
// scanline_omega = rotation_x_axis(18.9414*M_PI/180.0);
// } else if (scanline == "S2") {
// scanline_phi = rotation_z_axis(0.0270*M_PI/180.0);
// scanline_omega = rotation_x_axis(-18.9351*M_PI/180.0);
// } else {
// throw vw::ArgumentErr() << "euler_to_quaternion(): unsupported scanline name.";
// }
// vw::Matrix<double,3,3> scanline_rotation = transpose(scanline_omega);
// vw::Matrix<double,3,3> instrumenthead_rotation = transpose(rotation_x_axis(-0.3340*M_PI/180.0) * rotation_y_axis(0.0101*M_PI/180.0));
/// Read the line times from an HRSC metadata file
void HRSCImageMetadata::read_extori_file(std::string const& filename, std::string const& scanline) {
if (m_line_times.size() == 0)
throw vw::LogicErr() << "read_extori_file(): cannot read extori file until the line times file has been read. please read that file first.\n";
std::ifstream infile(filename.c_str());
double sclk_time;
vw::Vector3 position;
double phi, omega, kappa;
m_extori_ephem_times.clear();
m_extori_ephem.clear();
m_extori_quat.clear();
if ( infile.is_open() ) {
// read through the lines in the header
char dummy[256];
for (int i =0; i < 7; ++i) {
infile.getline(dummy, 256);
}
// Build up the fixed rotation from "extori frame" to the frame for this HRSC scanline.
vw::math::Quaternion<double> extori_to_mex_spacecraft = vw::math::euler_to_quaternion(M_PI, M_PI/2, 0, "XZX");
vw::math::Quaternion<double> hrsc_head_to_hrsc_scanline;
if (scanline == "S1") {
hrsc_head_to_hrsc_scanline = vw::math::euler_to_quaternion(0.0205*M_PI/180.0, 18.9414*M_PI/180.0, 0, "ZXZ");
} else if (scanline == "S2") {
hrsc_head_to_hrsc_scanline = vw::math::euler_to_quaternion(0.0270*M_PI/180.0, -18.9351*M_PI/180.0, 0, "ZXZ");
} else if (scanline == "P1") {
hrsc_head_to_hrsc_scanline = vw::math::euler_to_quaternion(0.0457*M_PI/180.0, 12.7544*M_PI/180.0, 0, "ZXZ");
} else if (scanline == "P2") {
hrsc_head_to_hrsc_scanline = vw::math::euler_to_quaternion(0.0343*M_PI/180.0, -12.7481*M_PI/180.0, 0, "ZXZ");
}
vw::math::Quaternion<double> rotation_correction = hrsc_head_to_hrsc_scanline*extori_to_mex_spacecraft;
// Read the actual data
//
// The extori file contains euler angles phi, omega, kappa, which
// correspond to rotations to be applied about the y, x, and
// z-axes respectively.
//
// NOTE!!: However, these angles are in units of gon. There are
// 400 gon in a circle, so we convert that here.
while (infile >> sclk_time >> position(0) >> position(1) >> position(2) >> phi >> omega >> kappa ) {
m_extori_ephem_times.push_back(sclk_time);
m_extori_ephem.push_back(position);
m_extori_quat.push_back(rotation_correction*vw::math::euler_to_quaternion(-phi*360/400*M_PI/180.0, -omega*360/400*M_PI/180.0, -kappa*360/400*M_PI/180.0, "YXZ"));
}
} else {
throw vw::IOErr() << "read_extori_file(): could not open file \"" << filename << "\"\n";
}
// Some basic error checking
if (m_extori_ephem.size() == 0) {
throw vw::IOErr() << "read_extori_file(): there was a problem reading \"" << filename << "\"\n";
} else {
std::cout << filename << ": " << m_extori_ephem.size() << " records.\n";
}
// Subtract off the time for the first scanline.
for (int i = 0; i < m_extori_ephem_times.size(); ++i) {
m_extori_ephem_times[i] -= m_first_line_ephem_time;
// std::cout << m_extori_ephem_times[i] << ": " << m_extori_ephem[i] << " " << m_extori_quat[i] << " \n";
}
infile.close();
}
<commit_msg>Made some changes to debugging output and variable names.<commit_after>#include "HRSC/HRSC.h"
#include "MOC/Metadata.h"
#include "HRSC/ExtoriExtrinsics.h"
#include <fstream>
#include <vw/Core/Exception.h>
#include <vw/Math/EulerAngles.h>
using namespace vw::camera;
HRSCImageMetadata::HRSCImageMetadata(std::string const& filename) {
m_filename = filename;
m_line_times.clear();
m_extori_ephem_times.clear();
}
/// Returns a newly allocated camera model object of the appropriate
/// type. It is the responsibility of the user to later deallocate
/// this camera model object or to manage it using some sort of smart
/// pointer.
vw::camera::CameraModel* HRSCImageMetadata::camera_model() {
// The HRSC frame of reference is defined as follows:
//
// +Z out of the front of the camera (nadir)
// +Y perpindicular to the imaging lines in the direction of flight
// +X parallel to the scanlines, but increasing X is decreasing u...
vw::Vector3 pointing_vec(0,0,1);
vw::Vector3 u_vec(-1,0,0);
if (m_extori_ephem_times.size() > 0) {
std::cout << "NOTE: Generating HRSC camera model based on EXTORI metadata...\n";
std::cout << "rows(): " << rows() << "\n";
std::cout << "t0: " << m_first_line_ephem_time << "\n";
std::cout << "LT: " << m_line_times[0] << "\n";
std::cout << "LT: " << m_line_times[m_line_times.size()-1] << "\n";
std::cout << "LT s: " << m_line_times.size() << "\n";
std::cout << "LT: " << m_extori_ephem_times[m_extori_ephem_times.size()-1] << "\n";
std::cout << "QUAT0: " << m_extori_quat[0] << "\n\n";
// If there is extori information, it takes precedence because it is
// more accurate.
return new LinescanModel<ExtoriPositionInterpolation,
ExtoriPoseInterpolation>(rows(),
cols(),
int(m_start_sample/m_crosstrack_summing),
m_focal_length,
m_along_scan_pixel_size*m_downtrack_summing,
m_across_scan_pixel_size*m_crosstrack_summing,
m_line_times,
pointing_vec, u_vec,
ExtoriPositionInterpolation(m_extori_ephem_times, m_extori_ephem),
ExtoriPoseInterpolation(m_extori_ephem_times, m_extori_quat));
} else {
// Use the values that were obtained from the *.sup file to program
// the camera model parameters.
return new LinescanModel<Curve3DPositionInterpolation,
SLERPPoseInterpolation>(rows(),
cols(),
int(m_start_sample/m_crosstrack_summing),
m_focal_length,
m_along_scan_pixel_size*m_downtrack_summing,
m_across_scan_pixel_size*m_crosstrack_summing,
m_line_times,
pointing_vec, u_vec,
Curve3DPositionInterpolation(m_ephem, m_t0_ephem, m_dt_ephem),
SLERPPoseInterpolation(m_quat, m_t0_quat, m_dt_quat));
}
}
/// Read the line times from an HRSC metadata file
void HRSCImageMetadata::read_line_times(std::string const& filename) {
std::ifstream infile(filename.c_str());
double scanline, ephemeris_time, integration_time;
if ( infile.is_open() ) {
m_line_times.clear();
while (infile >> scanline >> ephemeris_time >> integration_time ) {
m_line_times.push_back(ephemeris_time);
}
} else {
throw vw::IOErr() << "hrsc_line_integration_times: could not open file \"" << filename << "\"\n";
}
std::cout << filename << ": " << m_line_times.size() << " records.\n";
m_first_line_ephem_time = m_line_times[0];
for (int i = 0; i < m_line_times.size(); ++i) {
m_line_times[i] -= m_first_line_ephem_time;
}
infile.close();
}
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
// HRSC SUP FILE MANIPULATION
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
//
// Read a HRSC *.sup data file provided by Ross Beyer
// This file is used to initialize a linescan camera model.
void HRSCImageMetadata::read_ephemeris_supplement(std::string const& filename) {
SupplementaryEphemerisParser parser(filename);
try {
// First, gather the basic intrinsic camera prameters
//
// Note that these values may be overridden by the values in the
// description.tab file (though they should be identical values).
//
m_crosstrack_summing = parser.read_double("PIXEL_SUMMING");
m_downtrack_summing = parser.read_double("PIXEL_SUMMING");
double scan_duration = parser.read_double("SCAN_DURATION");
double downloaded_lines = parser.read_double("DOWNLOADED_LINES");
m_height_pixels = downloaded_lines/m_downtrack_summing;
m_focal_length = parser.read_double("FOCAL_LENGTH") / 1000.0;
m_across_scan_pixel_size = parser.read_double("ACROSS_SCAN_PIXEL_SIZE") / 1.0e6;
m_along_scan_pixel_size = parser.read_double("ALONG_SCAN_PIXEL_SIZE") / 1.0e6;
double downloaded_samples = parser.read_double("DOWNLOADED_SAMPLES");
m_width_pixels = downloaded_samples/m_crosstrack_summing;
// This is really the only piece of information we need from the ephemeris file.
// (This does noet appear in the description.tab file)
m_start_sample = parser.read_double("START_SAMPLE");
/* Read the full ephemeris information into a Nx3 matrix*/
double n_ephem = parser.read_double("N_EPHEM");
m_t0_ephem = parser.read_double("T0_EPHEM");
m_dt_ephem = parser.read_double("DT_EPHEM");
m_ephem = parser.read_vector3s("EPHEM", (int)n_ephem, 3);
m_ephem_rate = parser.read_vector3s("EPHEM_RATE", (int)n_ephem, 3);
/* Next, read in the time serios of data regarding orientation */
double n_quat = parser.read_double("NUM_QUAT");
m_t0_quat = parser.read_double("T0_QUAT");
m_dt_quat = parser.read_double("DT_QUAT");
m_quat = parser.read_quaternions("QUATERNIONS", (int)n_quat, 4);
} catch (EphemerisErr &e) {
throw vw::IOErr() << "An error occured while parsing the ephemeris file.\n";
}
}
// This is test code for comprehending the extori angles. It should be deleted. -mbroxton
// // This additional rotation takes us from the extori "spacecraft"
// // frame to the more familiar spice HRSC instrument frame.
// vw::Matrix<double,3,3> hack;
// hack(0,0) = 0; hack(0,1) = 1.0; hack(0,2) = 0;
// hack(1,0) = 1; hack(1,1) = 0.0; hack(1,2) = 0;
// hack(2,0) = 0; hack(2,1) = 0; hack(2,2) = -1;
// // Here we incorporate the rotation for individual HRSC scanlines.
// vw::Matrix<double,3,3> scanline_phi, scanline_omega;
// if (scanline == "S1") {
// scanline_phi = rotation_z_axis(0.0205*M_PI/180.0);
// scanline_omega = rotation_x_axis(18.9414*M_PI/180.0);
// } else if (scanline == "S2") {
// scanline_phi = rotation_z_axis(0.0270*M_PI/180.0);
// scanline_omega = rotation_x_axis(-18.9351*M_PI/180.0);
// } else {
// throw vw::ArgumentErr() << "euler_to_quaternion(): unsupported scanline name.";
// }
// vw::Matrix<double,3,3> scanline_rotation = transpose(scanline_omega);
// vw::Matrix<double,3,3> instrumenthead_rotation = transpose(rotation_x_axis(-0.3340*M_PI/180.0) * rotation_y_axis(0.0101*M_PI/180.0));
/// Read the line times from an HRSC metadata file
void HRSCImageMetadata::read_extori_file(std::string const& filename, std::string const& scanline) {
if (m_line_times.size() == 0)
throw vw::LogicErr() << "read_extori_file(): cannot read extori file until the line times file has been read. please read that file first.\n";
std::ifstream infile(filename.c_str());
double sclk_time;
vw::Vector3 position;
double phi, omega, kappa;
m_extori_ephem_times.clear();
m_extori_ephem.clear();
m_extori_quat.clear();
if ( infile.is_open() ) {
// read through the lines in the header
char dummy[256];
for (int i =0; i < 7; ++i) {
infile.getline(dummy, 256);
}
// Build up the fixed rotation from "extori frame" to the frame for this HRSC scanline.
vw::math::Quaternion<double> extori_to_mex_spacecraft = vw::math::euler_to_quaternion(M_PI, M_PI/2, 0, "XZX");
vw::math::Quaternion<double> hrsc_head_to_hrsc_scanline;
if (scanline == "S1") {
hrsc_head_to_hrsc_scanline = vw::math::euler_to_quaternion(0.0205*M_PI/180.0, 18.9414*M_PI/180.0, 0, "ZXZ");
} else if (scanline == "S2") {
hrsc_head_to_hrsc_scanline = vw::math::euler_to_quaternion(0.0270*M_PI/180.0, -18.9351*M_PI/180.0, 0, "ZXZ");
} else if (scanline == "P1") {
hrsc_head_to_hrsc_scanline = vw::math::euler_to_quaternion(0.0457*M_PI/180.0, 12.7544*M_PI/180.0, 0, "ZXZ");
} else if (scanline == "P2") {
hrsc_head_to_hrsc_scanline = vw::math::euler_to_quaternion(0.0343*M_PI/180.0, -12.7481*M_PI/180.0, 0, "ZXZ");
} else {
throw vw::IOErr() << "read_extori_file(): unrecognized scanline ID. You must specify the scanline id's after the extori filenames on the command line.";
}
vw::math::Quaternion<double> rotation_correction = hrsc_head_to_hrsc_scanline*extori_to_mex_spacecraft;
// Read the actual data
//
// The extori file contains euler angles phi, omega, kappa, which
// correspond to rotations to be applied about the y, x, and
// z-axes respectively.
//
// NOTE!!: However, these angles are in units of gon. There are
// 400 gon in a circle, so we convert that here.
while (infile >> sclk_time >> position(0) >> position(1) >> position(2) >> phi >> omega >> kappa ) {
m_extori_ephem_times.push_back(sclk_time);
m_extori_ephem.push_back(position);
m_extori_quat.push_back(rotation_correction*vw::math::euler_to_quaternion(-phi*360/400*M_PI/180.0, -omega*360/400*M_PI/180.0, -kappa*360/400*M_PI/180.0, "YXZ"));
}
} else {
throw vw::IOErr() << "read_extori_file(): could not open file \"" << filename << "\"\n";
}
// Some basic error checking
if (m_extori_ephem.size() == 0) {
throw vw::IOErr() << "read_extori_file(): there was a problem reading \"" << filename << "\"\n";
} else {
std::cout << filename << ": " << m_extori_ephem.size() << " records.\n";
}
// Subtract off the time for the first scanline.
for (int i = 0; i < m_extori_ephem_times.size(); ++i) {
m_extori_ephem_times[i] -= m_first_line_ephem_time;
// std::cout << m_extori_ephem_times[i] << ": " << m_extori_ephem[i] << " " << m_extori_quat[i] << " \n";
}
infile.close();
}
<|endoftext|> |
<commit_before>/* --------------------------------------------------------------------------
libmusicbrainz4 - Client library to access MusicBrainz
Copyright (C) 2011 Andrew Hawkins
This file is part of libmusicbrainz4.
This library is free software; you can redistribute it and/or
modify it under the terms of v2 of the GNU Lesser General Public
License as published by the Free Software Foundation.
libmusicbrainz4 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 General Public License
along with this library. If not, see <http://www.gnu.org/licenses/>.
$Id$
----------------------------------------------------------------------------*/
#include "config.h"
#include "coverart/defines.h"
#include "coverart/HTTPFetch.h"
#include <stdlib.h>
#include <string.h>
#include "ne_session.h"
#include "ne_auth.h"
#include "ne_string.h"
#include "ne_request.h"
#include "ne_uri.h"
class CoverArtArchive::CHTTPFetchPrivate
{
public:
CHTTPFetchPrivate()
: m_Result(0),
m_Status(0),
m_ProxyPort(0)
{
}
std::string m_UserAgent;
std::vector<unsigned char> m_Data;
int m_Result;
int m_Status;
std::string m_ErrorMessage;
std::string m_UserName;
std::string m_Password;
std::string m_ProxyHost;
int m_ProxyPort;
std::string m_ProxyUserName;
std::string m_ProxyPassword;
};
CoverArtArchive::CHTTPFetch::CHTTPFetch(const std::string& UserAgent)
: m_d(new CHTTPFetchPrivate)
{
m_d->m_UserAgent=UserAgent;
for (std::string::size_type Pos=0;Pos<m_d->m_UserAgent.length();Pos++)
if (m_d->m_UserAgent[Pos]=='-')
m_d->m_UserAgent[Pos]='/';
// Parse http_proxy environmnent variable
const char *http_proxy = getenv("http_proxy");
if (http_proxy)
{
ne_uri uri;
if (!ne_uri_parse(http_proxy, &uri))
{
if (uri.host)
m_d->m_ProxyHost = uri.host;
if (uri.port)
m_d->m_ProxyPort = uri.port;
if (uri.userinfo)
{
char *pos = strchr(uri.userinfo, ':');
if (pos)
{
*pos = '\0';
m_d->m_ProxyUserName = uri.userinfo;
m_d->m_ProxyPassword = pos + 1;
}
else
{
m_d->m_ProxyUserName = uri.userinfo;
}
}
}
ne_uri_free(&uri);
}
}
CoverArtArchive::CHTTPFetch::~CHTTPFetch()
{
delete m_d;
}
void CoverArtArchive::CHTTPFetch::SetUserName(const std::string& UserName)
{
m_d->m_UserName=UserName;
}
void CoverArtArchive::CHTTPFetch::SetPassword(const std::string& Password)
{
m_d->m_Password=Password;
}
void CoverArtArchive::CHTTPFetch::SetProxyHost(const std::string& ProxyHost)
{
m_d->m_ProxyHost=ProxyHost;
}
void CoverArtArchive::CHTTPFetch::SetProxyPort(int ProxyPort)
{
m_d->m_ProxyPort=ProxyPort;
}
void CoverArtArchive::CHTTPFetch::SetProxyUserName(const std::string& ProxyUserName)
{
m_d->m_ProxyUserName=ProxyUserName;
}
void CoverArtArchive::CHTTPFetch::SetProxyPassword(const std::string& ProxyPassword)
{
m_d->m_ProxyPassword=ProxyPassword;
}
int CoverArtArchive::CHTTPFetch::Fetch(const std::string& URL, bool FollowRedirects)
{
int Ret=0;
bool Finished=false;
std::string RequestURL=URL;
while (!Finished)
{
try
{
Ret=DoRequest(RequestURL);
Finished=true;
}
catch(CRedirect r)
{
if (FollowRedirects)
{
RequestURL=r.Location();
Finished=false;
}
else
throw r;
}
catch(...)
{
throw;
}
}
return Ret;
}
int CoverArtArchive::CHTTPFetch::DoRequest(const std::string& URL)
{
int Ret=0;
ne_uri uri;
ne_uri_parse(URL.c_str(),&uri);
int Port=uri.port;
if (0==Port)
Port=ne_uri_defaultport(uri.scheme);
m_d->m_Data.clear();
ne_sock_init();
ne_session *sess=ne_session_create(uri.scheme, uri.host, Port);
if (sess)
{
ne_set_useragent(sess, m_d->m_UserAgent.c_str());
ne_set_server_auth(sess, httpAuth, this);
// Use proxy server
if (!m_d->m_ProxyHost.empty())
{
ne_session_proxy(sess, m_d->m_ProxyHost.c_str(), m_d->m_ProxyPort);
ne_set_proxy_auth(sess, proxyAuth, this);
}
ne_request *req = ne_request_create(sess, "GET", uri.path);
ne_add_response_body_reader(req, ne_accept_2xx, httpResponseReader, &m_d->m_Data);
m_d->m_Result = ne_request_dispatch(req);
m_d->m_Status = ne_get_status(req)->code;
const char *Location = ne_get_response_header(req,"Location");
std::string strLocation;
if (0!=Location)
strLocation=Location;
Ret=m_d->m_Data.size();
ne_request_destroy(req);
m_d->m_ErrorMessage = ne_get_error(sess);
ne_session_destroy(sess);
switch (m_d->m_Result)
{
case NE_OK:
break;
case NE_CONNECT:
case NE_LOOKUP:
throw CConnectionError(m_d->m_ErrorMessage);
break;
case NE_TIMEOUT:
throw CTimeoutError(m_d->m_ErrorMessage);
break;
case NE_AUTH:
case NE_PROXYAUTH:
throw CAuthenticationError(m_d->m_ErrorMessage);
break;
default:
throw CFetchError(m_d->m_ErrorMessage);
break;
}
switch (m_d->m_Status)
{
case 200:
break;
case 300:
case 301:
case 302:
case 303:
case 304:
case 305:
case 306:
case 307:
throw CRedirect(strLocation);
break;
case 400:
throw CRequestError(m_d->m_ErrorMessage);
break;
case 401:
throw CAuthenticationError(m_d->m_ErrorMessage);
break;
case 404:
throw CResourceNotFoundError(m_d->m_ErrorMessage);
break;
default:
throw CFetchError(m_d->m_ErrorMessage);
break;
}
}
ne_sock_exit();
return Ret;
}
int CoverArtArchive::CHTTPFetch::httpAuth(void *userdata, const char *realm, int attempts,
char *username, char *password)
{
realm=realm;
CoverArtArchive::CHTTPFetch *Fetch = (CoverArtArchive::CHTTPFetch *)userdata;
strncpy(username, Fetch->m_d->m_UserName.c_str(), NE_ABUFSIZ);
strncpy(password, Fetch->m_d->m_Password.c_str(), NE_ABUFSIZ);
return attempts;
}
int CoverArtArchive::CHTTPFetch::proxyAuth(void *userdata, const char *realm, int attempts,
char *username, char *password)
{
realm=realm;
CoverArtArchive::CHTTPFetch *Fetch = (CoverArtArchive::CHTTPFetch *)userdata;
strncpy(username, Fetch->m_d->m_ProxyUserName.c_str(), NE_ABUFSIZ);
strncpy(password, Fetch->m_d->m_ProxyPassword.c_str(), NE_ABUFSIZ);
return attempts;
}
int CoverArtArchive::CHTTPFetch::httpResponseReader(void *userdata, const char *buf, size_t len)
{
std::vector<unsigned char> *buffer = reinterpret_cast<std::vector<unsigned char> *>(userdata);
buffer->insert(buffer->end(),buf,buf+len);
return 0;
}
std::vector<unsigned char> CoverArtArchive::CHTTPFetch::Data() const
{
return m_d->m_Data;
}
int CoverArtArchive::CHTTPFetch::Result() const
{
return m_d->m_Result;
}
int CoverArtArchive::CHTTPFetch::Status() const
{
return m_d->m_Status;
}
std::string CoverArtArchive::CHTTPFetch::ErrorMessage() const
{
return m_d->m_ErrorMessage;
}
<commit_msg>No need to specifically throw the redirect exception<commit_after>/* --------------------------------------------------------------------------
libmusicbrainz4 - Client library to access MusicBrainz
Copyright (C) 2011 Andrew Hawkins
This file is part of libmusicbrainz4.
This library is free software; you can redistribute it and/or
modify it under the terms of v2 of the GNU Lesser General Public
License as published by the Free Software Foundation.
libmusicbrainz4 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 General Public License
along with this library. If not, see <http://www.gnu.org/licenses/>.
$Id$
----------------------------------------------------------------------------*/
#include "config.h"
#include "coverart/defines.h"
#include "coverart/HTTPFetch.h"
#include <stdlib.h>
#include <string.h>
#include "ne_session.h"
#include "ne_auth.h"
#include "ne_string.h"
#include "ne_request.h"
#include "ne_uri.h"
class CoverArtArchive::CHTTPFetchPrivate
{
public:
CHTTPFetchPrivate()
: m_Result(0),
m_Status(0),
m_ProxyPort(0)
{
}
std::string m_UserAgent;
std::vector<unsigned char> m_Data;
int m_Result;
int m_Status;
std::string m_ErrorMessage;
std::string m_UserName;
std::string m_Password;
std::string m_ProxyHost;
int m_ProxyPort;
std::string m_ProxyUserName;
std::string m_ProxyPassword;
};
CoverArtArchive::CHTTPFetch::CHTTPFetch(const std::string& UserAgent)
: m_d(new CHTTPFetchPrivate)
{
m_d->m_UserAgent=UserAgent;
for (std::string::size_type Pos=0;Pos<m_d->m_UserAgent.length();Pos++)
if (m_d->m_UserAgent[Pos]=='-')
m_d->m_UserAgent[Pos]='/';
// Parse http_proxy environmnent variable
const char *http_proxy = getenv("http_proxy");
if (http_proxy)
{
ne_uri uri;
if (!ne_uri_parse(http_proxy, &uri))
{
if (uri.host)
m_d->m_ProxyHost = uri.host;
if (uri.port)
m_d->m_ProxyPort = uri.port;
if (uri.userinfo)
{
char *pos = strchr(uri.userinfo, ':');
if (pos)
{
*pos = '\0';
m_d->m_ProxyUserName = uri.userinfo;
m_d->m_ProxyPassword = pos + 1;
}
else
{
m_d->m_ProxyUserName = uri.userinfo;
}
}
}
ne_uri_free(&uri);
}
}
CoverArtArchive::CHTTPFetch::~CHTTPFetch()
{
delete m_d;
}
void CoverArtArchive::CHTTPFetch::SetUserName(const std::string& UserName)
{
m_d->m_UserName=UserName;
}
void CoverArtArchive::CHTTPFetch::SetPassword(const std::string& Password)
{
m_d->m_Password=Password;
}
void CoverArtArchive::CHTTPFetch::SetProxyHost(const std::string& ProxyHost)
{
m_d->m_ProxyHost=ProxyHost;
}
void CoverArtArchive::CHTTPFetch::SetProxyPort(int ProxyPort)
{
m_d->m_ProxyPort=ProxyPort;
}
void CoverArtArchive::CHTTPFetch::SetProxyUserName(const std::string& ProxyUserName)
{
m_d->m_ProxyUserName=ProxyUserName;
}
void CoverArtArchive::CHTTPFetch::SetProxyPassword(const std::string& ProxyPassword)
{
m_d->m_ProxyPassword=ProxyPassword;
}
int CoverArtArchive::CHTTPFetch::Fetch(const std::string& URL, bool FollowRedirects)
{
int Ret=0;
bool Finished=false;
std::string RequestURL=URL;
while (!Finished)
{
try
{
Ret=DoRequest(RequestURL);
Finished=true;
}
catch(CRedirect r)
{
if (FollowRedirects)
{
RequestURL=r.Location();
Finished=false;
}
else
{
throw;
}
}
catch(...)
{
throw;
}
}
return Ret;
}
int CoverArtArchive::CHTTPFetch::DoRequest(const std::string& URL)
{
int Ret=0;
ne_uri uri;
ne_uri_parse(URL.c_str(),&uri);
int Port=uri.port;
if (0==Port)
Port=ne_uri_defaultport(uri.scheme);
m_d->m_Data.clear();
ne_sock_init();
ne_session *sess=ne_session_create(uri.scheme, uri.host, Port);
if (sess)
{
ne_set_useragent(sess, m_d->m_UserAgent.c_str());
ne_set_server_auth(sess, httpAuth, this);
// Use proxy server
if (!m_d->m_ProxyHost.empty())
{
ne_session_proxy(sess, m_d->m_ProxyHost.c_str(), m_d->m_ProxyPort);
ne_set_proxy_auth(sess, proxyAuth, this);
}
ne_request *req = ne_request_create(sess, "GET", uri.path);
ne_add_response_body_reader(req, ne_accept_2xx, httpResponseReader, &m_d->m_Data);
m_d->m_Result = ne_request_dispatch(req);
m_d->m_Status = ne_get_status(req)->code;
const char *Location = ne_get_response_header(req,"Location");
std::string strLocation;
if (0!=Location)
strLocation=Location;
Ret=m_d->m_Data.size();
ne_request_destroy(req);
m_d->m_ErrorMessage = ne_get_error(sess);
ne_session_destroy(sess);
switch (m_d->m_Result)
{
case NE_OK:
break;
case NE_CONNECT:
case NE_LOOKUP:
throw CConnectionError(m_d->m_ErrorMessage);
break;
case NE_TIMEOUT:
throw CTimeoutError(m_d->m_ErrorMessage);
break;
case NE_AUTH:
case NE_PROXYAUTH:
throw CAuthenticationError(m_d->m_ErrorMessage);
break;
default:
throw CFetchError(m_d->m_ErrorMessage);
break;
}
switch (m_d->m_Status)
{
case 200:
break;
case 300:
case 301:
case 302:
case 303:
case 304:
case 305:
case 306:
case 307:
throw CRedirect(strLocation);
break;
case 400:
throw CRequestError(m_d->m_ErrorMessage);
break;
case 401:
throw CAuthenticationError(m_d->m_ErrorMessage);
break;
case 404:
throw CResourceNotFoundError(m_d->m_ErrorMessage);
break;
default:
throw CFetchError(m_d->m_ErrorMessage);
break;
}
}
ne_sock_exit();
return Ret;
}
int CoverArtArchive::CHTTPFetch::httpAuth(void *userdata, const char *realm, int attempts,
char *username, char *password)
{
realm=realm;
CoverArtArchive::CHTTPFetch *Fetch = (CoverArtArchive::CHTTPFetch *)userdata;
strncpy(username, Fetch->m_d->m_UserName.c_str(), NE_ABUFSIZ);
strncpy(password, Fetch->m_d->m_Password.c_str(), NE_ABUFSIZ);
return attempts;
}
int CoverArtArchive::CHTTPFetch::proxyAuth(void *userdata, const char *realm, int attempts,
char *username, char *password)
{
realm=realm;
CoverArtArchive::CHTTPFetch *Fetch = (CoverArtArchive::CHTTPFetch *)userdata;
strncpy(username, Fetch->m_d->m_ProxyUserName.c_str(), NE_ABUFSIZ);
strncpy(password, Fetch->m_d->m_ProxyPassword.c_str(), NE_ABUFSIZ);
return attempts;
}
int CoverArtArchive::CHTTPFetch::httpResponseReader(void *userdata, const char *buf, size_t len)
{
std::vector<unsigned char> *buffer = reinterpret_cast<std::vector<unsigned char> *>(userdata);
buffer->insert(buffer->end(),buf,buf+len);
return 0;
}
std::vector<unsigned char> CoverArtArchive::CHTTPFetch::Data() const
{
return m_d->m_Data;
}
int CoverArtArchive::CHTTPFetch::Result() const
{
return m_d->m_Result;
}
int CoverArtArchive::CHTTPFetch::Status() const
{
return m_d->m_Status;
}
std::string CoverArtArchive::CHTTPFetch::ErrorMessage() const
{
return m_d->m_ErrorMessage;
}
<|endoftext|> |
<commit_before>#include "JsPlayer.h"
#include <string.h>
#include <node_buffer.h>
#include <nah/NodeHelpers.h>
///////////////////////////////////////////////////////////////////////////////
struct JsPlayer::AsyncData
{
virtual void process( JsPlayer* ) = 0;
};
///////////////////////////////////////////////////////////////////////////////
struct JsPlayer::AppSinkEventData : public JsPlayer::AsyncData
{
AppSinkEventData( GstAppSink* appSink, JsPlayer::AppSinkEvent event ) :
appSink( appSink), event( event ) {}
void process( JsPlayer* );
GstAppSink* appSink;
const JsPlayer::AppSinkEvent event;
};
void JsPlayer::AppSinkEventData::process( JsPlayer* player )
{
switch( event ) {
case JsPlayer::AppSinkEvent::NewPreroll:
player->onNewPreroll( appSink );
break;
case JsPlayer::AppSinkEvent::NewSample:
player->onNewSample( appSink );
break;
case JsPlayer::AppSinkEvent::Eos:
player->onEos( appSink );
break;
}
}
///////////////////////////////////////////////////////////////////////////////
v8::Persistent<v8::Function> JsPlayer::_jsConstructor;
std::set<JsPlayer*> JsPlayer::_instances;
void JsPlayer::initJsApi( const v8::Handle<v8::Object>& exports )
{
node::AtExit( [] ( void* ) { JsPlayer::closeAll(); } );
gst_init( 0, 0 );
using namespace v8;
Isolate* isolate = Isolate::GetCurrent();
HandleScope scope( isolate );
Local<FunctionTemplate> constructorTemplate = FunctionTemplate::New( isolate, jsCreate );
constructorTemplate->SetClassName( String::NewFromUtf8( isolate, "Player", v8::String::kInternalizedString ) );
Local<ObjectTemplate> instanceTemplate = constructorTemplate->InstanceTemplate();
instanceTemplate->SetInternalFieldCount( 1 );
instanceTemplate->Set( String::NewFromUtf8( isolate, "AppSinkSetup", v8::String::kInternalizedString ),
Integer::New( isolate, Setup ),
static_cast<v8::PropertyAttribute>( ReadOnly | DontDelete ) );
instanceTemplate->Set( String::NewFromUtf8( isolate, "AppSinkNewPreroll", v8::String::kInternalizedString ),
Integer::New( isolate, NewPreroll ),
static_cast<v8::PropertyAttribute>( ReadOnly | DontDelete ) );
instanceTemplate->Set( String::NewFromUtf8( isolate, "AppSinkNewSample", v8::String::kInternalizedString ),
Integer::New( isolate, NewSample ),
static_cast<v8::PropertyAttribute>( ReadOnly | DontDelete ) );
instanceTemplate->Set( String::NewFromUtf8( isolate, "AppSinkEos", v8::String::kInternalizedString ),
Integer::New( isolate, Eos ),
static_cast<v8::PropertyAttribute>( ReadOnly | DontDelete ) );
instanceTemplate->Set( String::NewFromUtf8( isolate, "GST_STATE_VOID_PENDING", v8::String::kInternalizedString ),
Integer::New( isolate, GST_STATE_VOID_PENDING ),
static_cast<v8::PropertyAttribute>( ReadOnly | DontDelete ) );
instanceTemplate->Set( String::NewFromUtf8( isolate, "GST_STATE_NULL", v8::String::kInternalizedString ),
Integer::New( isolate, GST_STATE_NULL ),
static_cast<v8::PropertyAttribute>( ReadOnly | DontDelete ) );
instanceTemplate->Set( String::NewFromUtf8( isolate, "GST_STATE_READY", v8::String::kInternalizedString ),
Integer::New( isolate, GST_STATE_READY ),
static_cast<v8::PropertyAttribute>( ReadOnly | DontDelete ) );
instanceTemplate->Set( String::NewFromUtf8( isolate, "GST_STATE_PAUSED", v8::String::kInternalizedString ),
Integer::New( isolate, GST_STATE_PAUSED ),
static_cast<v8::PropertyAttribute>( ReadOnly | DontDelete ) );
instanceTemplate->Set( String::NewFromUtf8( isolate, "GST_STATE_PLAYING", v8::String::kInternalizedString ),
Integer::New( isolate, GST_STATE_PLAYING ),
static_cast<v8::PropertyAttribute>( ReadOnly | DontDelete ) );
SET_METHOD( instanceTemplate, "parseLaunch", &JsPlayer::parseLaunch );
SET_METHOD( instanceTemplate, "addAppSinkCallback", &JsPlayer::addAppSinkCallback );
SET_METHOD( instanceTemplate, "setState", &JsPlayer::setState );
Local<Function> constructor = constructorTemplate->GetFunction();
_jsConstructor.Reset( isolate, constructor );
exports->Set( String::NewFromUtf8( isolate, "createPlayer", v8::String::kInternalizedString ), constructor );
exports->Set( String::NewFromUtf8( isolate, "Player", v8::String::kInternalizedString ), constructor );
}
void JsPlayer::jsCreate( const v8::FunctionCallbackInfo<v8::Value>& args )
{
using namespace v8;
Isolate* isolate = Isolate::GetCurrent();
HandleScope scope( isolate );
Local<Object> thisObject = args.Holder();
if( args.IsConstructCall() ) {
JsPlayer* jsPlayer = new JsPlayer( thisObject );
args.GetReturnValue().Set( jsPlayer->handle() );
} else {
Local<Value> argv[] = { args[0] };
Local<Function> constructor =
Local<Function>::New( isolate, _jsConstructor );
args.GetReturnValue().Set( constructor->NewInstance( sizeof( argv ) / sizeof( argv[0] ), argv ) );
}
}
void JsPlayer::closeAll()
{
for( JsPlayer* p : _instances ) {
p->close();
}
gst_deinit();
}
JsPlayer::JsPlayer( v8::Local<v8::Object>& thisObject ) :
_pipeline( nullptr ), _firstSample( true )
{
Wrap( thisObject );
_instances.insert( this );
uv_loop_t* loop = uv_default_loop();
uv_async_init( loop, &_async,
[] ( uv_async_t* handle ) {
if( handle->data )
reinterpret_cast<JsPlayer*>( handle->data )->handleAsync();
}
);
_async.data = this;
}
JsPlayer::~JsPlayer()
{
close();
_instances.erase( this );
}
void JsPlayer::close()
{
_async.data = nullptr;
uv_close( reinterpret_cast<uv_handle_t*>( &_async ), 0 );
}
void JsPlayer::handleAsync()
{
while( !_asyncData.empty() ) {
std::deque<std::unique_ptr<AsyncData> > tmpData;
_asyncDataGuard.lock();
_asyncData.swap( tmpData );
_asyncDataGuard.unlock();
for( const auto& i: tmpData ) {
i->process( this );
}
}
}
GstFlowReturn JsPlayer::onNewPrerollProxy( GstAppSink *appSink, gpointer userData )
{
JsPlayer* player = static_cast<JsPlayer*>( userData );
player->_asyncDataGuard.lock();
player->_asyncData.emplace_back( new AppSinkEventData( appSink, NewPreroll ) );
player->_asyncDataGuard.unlock();
uv_async_send( &player->_async );
return GST_FLOW_OK;
}
GstFlowReturn JsPlayer::onNewSampleProxy( GstAppSink *appSink, gpointer userData )
{
JsPlayer* player = static_cast<JsPlayer*>( userData );
player->_appSinks[appSink].waitingSample.clear();
player->_asyncDataGuard.lock();
player->_asyncData.emplace_back( new AppSinkEventData( appSink, NewSample ) );
player->_asyncDataGuard.unlock();
uv_async_send( &player->_async );
return GST_FLOW_OK;
}
void JsPlayer::onEosProxy( GstAppSink* appSink, gpointer userData )
{
JsPlayer* player = static_cast<JsPlayer*>( userData );
player->_asyncDataGuard.lock();
player->_asyncData.emplace_back( new AppSinkEventData( appSink, Eos ) );
player->_asyncDataGuard.unlock();
uv_async_send( &player->_async );
}
void JsPlayer::callCallback( GstAppSink* appSink, JsPlayer::AppSinkEvent event,
std::initializer_list<v8::Local<v8::Value> > list )
{
auto it = _appSinks.find( appSink );
if( _appSinks.end() == it )
return;
if( it->second.callback.IsEmpty() )
return;
using namespace v8;
Isolate* isolate = Isolate::GetCurrent();
HandleScope scope( isolate );
Local<Function> callbackFunc =
Local<Function>::New( isolate, _appSinks[appSink].callback );
std::vector<v8::Local<v8::Value> > argList;
argList.push_back( Integer::New( isolate, event ) );
argList.insert( argList.end(), list );
callbackFunc->Call( handle(), static_cast<int>( argList.size() ), argList.data() );
}
void JsPlayer::onSetup( GstAppSink* appSink, const GstVideoInfo& videoInfo )
{
if( !appSink )
return;
using namespace v8;
Isolate* isolate = Isolate::GetCurrent();
HandleScope scope( isolate );
_firstSample = false;
callCallback( appSink, Setup,
{ String::NewFromUtf8( isolate, videoInfo.finfo->name, v8::String::kNormalString ),
Integer::New( isolate, videoInfo.width ),
Integer::New( isolate, videoInfo.height ),
Integer::New( isolate, videoInfo.finfo->format ) } );
}
void JsPlayer::onNewPreroll( GstAppSink* appSink )
{
GstSample* sample = gst_app_sink_pull_preroll( appSink );
onSample( appSink, sample, true );
gst_sample_unref( sample );
}
void JsPlayer::onNewSample( GstAppSink* appSink )
{
if( _appSinks[appSink].waitingSample.test_and_set() )
return;
GstSample* sample = gst_app_sink_pull_sample( appSink );
_appSinks[appSink].waitingSample.test_and_set();
onSample( appSink, sample, false );
gst_sample_unref( sample );
}
void JsPlayer::onSample( GstAppSink* appSink, GstSample* sample, bool preroll )
{
if( !sample )
return;
GstVideoInfo videoInfo;
GstCaps* caps = gst_sample_get_caps( sample );
if( !caps || !gst_video_info_from_caps( &videoInfo, caps ) )
return;
if( _firstSample )
onSetup( appSink, videoInfo );
GstBuffer* buffer = gst_sample_get_buffer( sample );
if( !buffer )
return;
GstMapInfo mapInfo;
if( gst_buffer_map( buffer, &mapInfo, GST_MAP_READ ) ) {
using namespace v8;
Isolate* isolate = Isolate::GetCurrent();
HandleScope scope( isolate );
v8::MaybeLocal<v8::Object> maybeFrame =
node::Buffer::New( isolate, reinterpret_cast<char*>( mapInfo.data ), mapInfo.size,
[] ( char* data, void* hint ) {}, nullptr );
Local<v8::Object> frame;
if( maybeFrame.ToLocal( &frame ) ) {
frame->ForceSet( String::NewFromUtf8( isolate, "pixelFormatName", v8::String::kInternalizedString ),
String::NewFromUtf8( isolate, videoInfo.finfo->name, v8::String::kNormalString ),
static_cast<v8::PropertyAttribute>( ReadOnly | DontDelete ) );
frame->ForceSet( String::NewFromUtf8( isolate, "pixelFormat", v8::String::kInternalizedString ),
Integer::New( isolate, videoInfo.finfo->format ),
static_cast<v8::PropertyAttribute>( ReadOnly | DontDelete ) );
frame->ForceSet( String::NewFromUtf8( isolate, "width", v8::String::kInternalizedString ),
Integer::New( isolate, videoInfo.width ),
static_cast<v8::PropertyAttribute>( ReadOnly | DontDelete ) );
frame->ForceSet( String::NewFromUtf8( isolate, "height", v8::String::kInternalizedString ),
Integer::New( isolate, videoInfo.height ),
static_cast<v8::PropertyAttribute>( ReadOnly | DontDelete ) );
Local<Array> planes = Array::New( isolate, videoInfo.finfo->n_planes );
for( guint p = 0; p < videoInfo.finfo->n_planes; ++p ) {
planes->Set( p, Integer::New( isolate, videoInfo.offset[p] ) );
}
frame->ForceSet( String::NewFromUtf8( isolate, "planes", v8::String::kInternalizedString ),
planes,
static_cast<v8::PropertyAttribute>( ReadOnly | DontDelete ) );
callCallback( appSink, ( preroll ? NewPreroll : NewSample ), { frame } );
}
gst_buffer_unmap( buffer, &mapInfo );
}
}
void JsPlayer::onEos( GstAppSink* appSink )
{
callCallback( appSink, Eos );
}
bool JsPlayer::parseLaunch( const std::string& pipelineDescription )
{
if( _pipeline ) {
_appSinks.clear();
gst_object_unref( _pipeline );
_pipeline = nullptr;
_firstSample = true;
}
GError* error = nullptr;
_pipeline = gst_parse_launch( pipelineDescription.c_str(), &error );
return ( nullptr != _pipeline );
}
bool JsPlayer::addAppSinkCallback( const std::string& appSinkName, v8::Local<v8::Value> value )
{
if( !_pipeline || appSinkName.empty() )
return false;
GstElement* sink = gst_bin_get_by_name( GST_BIN( _pipeline ), appSinkName.c_str() );
if( !sink )
return false;
GstAppSink* appSink = GST_APP_SINK_CAST( sink );
if( !appSink )
return appSink;
using namespace v8;
Local<Function> callbackFunc = Local<Function>::Cast( value );
if( callbackFunc.IsEmpty() )
return false;
auto it = _appSinks.find( appSink );
if( _appSinks.end() == it ) {
gst_app_sink_set_drop( appSink, true );
gst_app_sink_set_max_buffers( appSink, 1 );
GstAppSinkCallbacks callbacks = { onEosProxy, onNewPrerollProxy, onNewSampleProxy };
gst_app_sink_set_callbacks( appSink, &callbacks, this, nullptr );
it = _appSinks.emplace( appSink, AppSinkData() ).first;
}
AppSinkData& sinkData = it->second;
sinkData.callback.Reset( Isolate::GetCurrent(), callbackFunc );
sinkData.waitingSample.test_and_set();
}
void JsPlayer::setState( unsigned state )
{
if( _pipeline )
gst_element_set_state( _pipeline, static_cast<GstState>( state ) );
}
<commit_msg>fixed compatibility with nw.js<commit_after>#include "JsPlayer.h"
#include <string.h>
#include <node_buffer.h>
#include <nah/NodeHelpers.h>
#if NODE_MAJOR_VERSION > 3 || \
( NODE_MAJOR_VERSION == 3 && NODE_MINOR_VERSION > 0 ) || \
( NODE_MAJOR_VERSION == 3 && NODE_MINOR_VERSION == 0 && NODE_BUILD_NUMBER >= 0 )
#define USE_MAYBE_LOCAL 1
#endif
///////////////////////////////////////////////////////////////////////////////
struct JsPlayer::AsyncData
{
virtual void process( JsPlayer* ) = 0;
};
///////////////////////////////////////////////////////////////////////////////
struct JsPlayer::AppSinkEventData : public JsPlayer::AsyncData
{
AppSinkEventData( GstAppSink* appSink, JsPlayer::AppSinkEvent event ) :
appSink( appSink), event( event ) {}
void process( JsPlayer* );
GstAppSink* appSink;
const JsPlayer::AppSinkEvent event;
};
void JsPlayer::AppSinkEventData::process( JsPlayer* player )
{
switch( event ) {
case JsPlayer::AppSinkEvent::NewPreroll:
player->onNewPreroll( appSink );
break;
case JsPlayer::AppSinkEvent::NewSample:
player->onNewSample( appSink );
break;
case JsPlayer::AppSinkEvent::Eos:
player->onEos( appSink );
break;
}
}
///////////////////////////////////////////////////////////////////////////////
v8::Persistent<v8::Function> JsPlayer::_jsConstructor;
std::set<JsPlayer*> JsPlayer::_instances;
void JsPlayer::initJsApi( const v8::Handle<v8::Object>& exports )
{
node::AtExit( [] ( void* ) { JsPlayer::closeAll(); } );
gst_init( 0, 0 );
using namespace v8;
Isolate* isolate = Isolate::GetCurrent();
HandleScope scope( isolate );
Local<FunctionTemplate> constructorTemplate = FunctionTemplate::New( isolate, jsCreate );
constructorTemplate->SetClassName( String::NewFromUtf8( isolate, "Player", v8::String::kInternalizedString ) );
Local<ObjectTemplate> instanceTemplate = constructorTemplate->InstanceTemplate();
instanceTemplate->SetInternalFieldCount( 1 );
instanceTemplate->Set( String::NewFromUtf8( isolate, "AppSinkSetup", v8::String::kInternalizedString ),
Integer::New( isolate, Setup ),
static_cast<v8::PropertyAttribute>( ReadOnly | DontDelete ) );
instanceTemplate->Set( String::NewFromUtf8( isolate, "AppSinkNewPreroll", v8::String::kInternalizedString ),
Integer::New( isolate, NewPreroll ),
static_cast<v8::PropertyAttribute>( ReadOnly | DontDelete ) );
instanceTemplate->Set( String::NewFromUtf8( isolate, "AppSinkNewSample", v8::String::kInternalizedString ),
Integer::New( isolate, NewSample ),
static_cast<v8::PropertyAttribute>( ReadOnly | DontDelete ) );
instanceTemplate->Set( String::NewFromUtf8( isolate, "AppSinkEos", v8::String::kInternalizedString ),
Integer::New( isolate, Eos ),
static_cast<v8::PropertyAttribute>( ReadOnly | DontDelete ) );
instanceTemplate->Set( String::NewFromUtf8( isolate, "GST_STATE_VOID_PENDING", v8::String::kInternalizedString ),
Integer::New( isolate, GST_STATE_VOID_PENDING ),
static_cast<v8::PropertyAttribute>( ReadOnly | DontDelete ) );
instanceTemplate->Set( String::NewFromUtf8( isolate, "GST_STATE_NULL", v8::String::kInternalizedString ),
Integer::New( isolate, GST_STATE_NULL ),
static_cast<v8::PropertyAttribute>( ReadOnly | DontDelete ) );
instanceTemplate->Set( String::NewFromUtf8( isolate, "GST_STATE_READY", v8::String::kInternalizedString ),
Integer::New( isolate, GST_STATE_READY ),
static_cast<v8::PropertyAttribute>( ReadOnly | DontDelete ) );
instanceTemplate->Set( String::NewFromUtf8( isolate, "GST_STATE_PAUSED", v8::String::kInternalizedString ),
Integer::New( isolate, GST_STATE_PAUSED ),
static_cast<v8::PropertyAttribute>( ReadOnly | DontDelete ) );
instanceTemplate->Set( String::NewFromUtf8( isolate, "GST_STATE_PLAYING", v8::String::kInternalizedString ),
Integer::New( isolate, GST_STATE_PLAYING ),
static_cast<v8::PropertyAttribute>( ReadOnly | DontDelete ) );
SET_METHOD( instanceTemplate, "parseLaunch", &JsPlayer::parseLaunch );
SET_METHOD( instanceTemplate, "addAppSinkCallback", &JsPlayer::addAppSinkCallback );
SET_METHOD( instanceTemplate, "setState", &JsPlayer::setState );
Local<Function> constructor = constructorTemplate->GetFunction();
_jsConstructor.Reset( isolate, constructor );
exports->Set( String::NewFromUtf8( isolate, "createPlayer", v8::String::kInternalizedString ), constructor );
exports->Set( String::NewFromUtf8( isolate, "Player", v8::String::kInternalizedString ), constructor );
}
void JsPlayer::jsCreate( const v8::FunctionCallbackInfo<v8::Value>& args )
{
using namespace v8;
Isolate* isolate = Isolate::GetCurrent();
HandleScope scope( isolate );
Local<Object> thisObject = args.Holder();
if( args.IsConstructCall() ) {
JsPlayer* jsPlayer = new JsPlayer( thisObject );
args.GetReturnValue().Set( jsPlayer->handle() );
} else {
Local<Value> argv[] = { args[0] };
Local<Function> constructor =
Local<Function>::New( isolate, _jsConstructor );
args.GetReturnValue().Set( constructor->NewInstance( sizeof( argv ) / sizeof( argv[0] ), argv ) );
}
}
void JsPlayer::closeAll()
{
for( JsPlayer* p : _instances ) {
p->close();
}
gst_deinit();
}
JsPlayer::JsPlayer( v8::Local<v8::Object>& thisObject ) :
_pipeline( nullptr ), _firstSample( true )
{
Wrap( thisObject );
_instances.insert( this );
uv_loop_t* loop = uv_default_loop();
uv_async_init( loop, &_async,
[] ( uv_async_t* handle ) {
if( handle->data )
reinterpret_cast<JsPlayer*>( handle->data )->handleAsync();
}
);
_async.data = this;
}
JsPlayer::~JsPlayer()
{
close();
_instances.erase( this );
}
void JsPlayer::close()
{
_async.data = nullptr;
uv_close( reinterpret_cast<uv_handle_t*>( &_async ), 0 );
}
void JsPlayer::handleAsync()
{
while( !_asyncData.empty() ) {
std::deque<std::unique_ptr<AsyncData> > tmpData;
_asyncDataGuard.lock();
_asyncData.swap( tmpData );
_asyncDataGuard.unlock();
for( const auto& i: tmpData ) {
i->process( this );
}
}
}
GstFlowReturn JsPlayer::onNewPrerollProxy( GstAppSink *appSink, gpointer userData )
{
JsPlayer* player = static_cast<JsPlayer*>( userData );
player->_asyncDataGuard.lock();
player->_asyncData.emplace_back( new AppSinkEventData( appSink, NewPreroll ) );
player->_asyncDataGuard.unlock();
uv_async_send( &player->_async );
return GST_FLOW_OK;
}
GstFlowReturn JsPlayer::onNewSampleProxy( GstAppSink *appSink, gpointer userData )
{
JsPlayer* player = static_cast<JsPlayer*>( userData );
player->_appSinks[appSink].waitingSample.clear();
player->_asyncDataGuard.lock();
player->_asyncData.emplace_back( new AppSinkEventData( appSink, NewSample ) );
player->_asyncDataGuard.unlock();
uv_async_send( &player->_async );
return GST_FLOW_OK;
}
void JsPlayer::onEosProxy( GstAppSink* appSink, gpointer userData )
{
JsPlayer* player = static_cast<JsPlayer*>( userData );
player->_asyncDataGuard.lock();
player->_asyncData.emplace_back( new AppSinkEventData( appSink, Eos ) );
player->_asyncDataGuard.unlock();
uv_async_send( &player->_async );
}
void JsPlayer::callCallback( GstAppSink* appSink, JsPlayer::AppSinkEvent event,
std::initializer_list<v8::Local<v8::Value> > list )
{
auto it = _appSinks.find( appSink );
if( _appSinks.end() == it )
return;
if( it->second.callback.IsEmpty() )
return;
using namespace v8;
Isolate* isolate = Isolate::GetCurrent();
HandleScope scope( isolate );
Local<Function> callbackFunc =
Local<Function>::New( isolate, _appSinks[appSink].callback );
std::vector<v8::Local<v8::Value> > argList;
argList.push_back( Integer::New( isolate, event ) );
argList.insert( argList.end(), list );
callbackFunc->Call( handle(), static_cast<int>( argList.size() ), argList.data() );
}
void JsPlayer::onSetup( GstAppSink* appSink, const GstVideoInfo& videoInfo )
{
if( !appSink )
return;
using namespace v8;
Isolate* isolate = Isolate::GetCurrent();
HandleScope scope( isolate );
_firstSample = false;
callCallback( appSink, Setup,
{ String::NewFromUtf8( isolate, videoInfo.finfo->name, v8::String::kNormalString ),
Integer::New( isolate, videoInfo.width ),
Integer::New( isolate, videoInfo.height ),
Integer::New( isolate, videoInfo.finfo->format ) } );
}
void JsPlayer::onNewPreroll( GstAppSink* appSink )
{
GstSample* sample = gst_app_sink_pull_preroll( appSink );
onSample( appSink, sample, true );
gst_sample_unref( sample );
}
void JsPlayer::onNewSample( GstAppSink* appSink )
{
if( _appSinks[appSink].waitingSample.test_and_set() )
return;
GstSample* sample = gst_app_sink_pull_sample( appSink );
_appSinks[appSink].waitingSample.test_and_set();
onSample( appSink, sample, false );
gst_sample_unref( sample );
}
void JsPlayer::onSample( GstAppSink* appSink, GstSample* sample, bool preroll )
{
if( !sample )
return;
GstVideoInfo videoInfo;
GstCaps* caps = gst_sample_get_caps( sample );
if( !caps || !gst_video_info_from_caps( &videoInfo, caps ) )
return;
if( _firstSample )
onSetup( appSink, videoInfo );
GstBuffer* buffer = gst_sample_get_buffer( sample );
if( !buffer )
return;
GstMapInfo mapInfo;
if( gst_buffer_map( buffer, &mapInfo, GST_MAP_READ ) ) {
using namespace v8;
Isolate* isolate = Isolate::GetCurrent();
HandleScope scope( isolate );
#if USE_MAYBE_LOCAL
v8::MaybeLocal<v8::Object> maybeFrame =
#else
v8::Local<v8::Object> frame =
#endif
node::Buffer::New( isolate, reinterpret_cast<char*>( mapInfo.data ), mapInfo.size,
[] ( char* data, void* hint ) {}, nullptr );
#if USE_MAYBE_LOCAL
Local<v8::Object> frame;
if( maybeFrame.ToLocal( &frame ) )
#endif
{
frame->ForceSet( String::NewFromUtf8( isolate, "pixelFormatName", v8::String::kInternalizedString ),
String::NewFromUtf8( isolate, videoInfo.finfo->name, v8::String::kNormalString ),
static_cast<v8::PropertyAttribute>( ReadOnly | DontDelete ) );
frame->ForceSet( String::NewFromUtf8( isolate, "pixelFormat", v8::String::kInternalizedString ),
Integer::New( isolate, videoInfo.finfo->format ),
static_cast<v8::PropertyAttribute>( ReadOnly | DontDelete ) );
frame->ForceSet( String::NewFromUtf8( isolate, "width", v8::String::kInternalizedString ),
Integer::New( isolate, videoInfo.width ),
static_cast<v8::PropertyAttribute>( ReadOnly | DontDelete ) );
frame->ForceSet( String::NewFromUtf8( isolate, "height", v8::String::kInternalizedString ),
Integer::New( isolate, videoInfo.height ),
static_cast<v8::PropertyAttribute>( ReadOnly | DontDelete ) );
Local<Array> planes = Array::New( isolate, videoInfo.finfo->n_planes );
for( guint p = 0; p < videoInfo.finfo->n_planes; ++p ) {
planes->Set( p, Integer::New( isolate, videoInfo.offset[p] ) );
}
frame->ForceSet( String::NewFromUtf8( isolate, "planes", v8::String::kInternalizedString ),
planes,
static_cast<v8::PropertyAttribute>( ReadOnly | DontDelete ) );
callCallback( appSink, ( preroll ? NewPreroll : NewSample ), { frame } );
}
gst_buffer_unmap( buffer, &mapInfo );
}
}
void JsPlayer::onEos( GstAppSink* appSink )
{
callCallback( appSink, Eos );
}
bool JsPlayer::parseLaunch( const std::string& pipelineDescription )
{
if( _pipeline ) {
_appSinks.clear();
gst_object_unref( _pipeline );
_pipeline = nullptr;
_firstSample = true;
}
GError* error = nullptr;
_pipeline = gst_parse_launch( pipelineDescription.c_str(), &error );
return ( nullptr != _pipeline );
}
bool JsPlayer::addAppSinkCallback( const std::string& appSinkName, v8::Local<v8::Value> value )
{
if( !_pipeline || appSinkName.empty() )
return false;
GstElement* sink = gst_bin_get_by_name( GST_BIN( _pipeline ), appSinkName.c_str() );
if( !sink )
return false;
GstAppSink* appSink = GST_APP_SINK_CAST( sink );
if( !appSink )
return appSink;
using namespace v8;
Local<Function> callbackFunc = Local<Function>::Cast( value );
if( callbackFunc.IsEmpty() )
return false;
auto it = _appSinks.find( appSink );
if( _appSinks.end() == it ) {
gst_app_sink_set_drop( appSink, true );
gst_app_sink_set_max_buffers( appSink, 1 );
GstAppSinkCallbacks callbacks = { onEosProxy, onNewPrerollProxy, onNewSampleProxy };
gst_app_sink_set_callbacks( appSink, &callbacks, this, nullptr );
it = _appSinks.emplace( appSink, AppSinkData() ).first;
}
AppSinkData& sinkData = it->second;
sinkData.callback.Reset( Isolate::GetCurrent(), callbackFunc );
sinkData.waitingSample.test_and_set();
}
void JsPlayer::setState( unsigned state )
{
if( _pipeline )
gst_element_set_state( _pipeline, static_cast<GstState>( state ) );
}
<|endoftext|> |
<commit_before>/*----------------------------------------------------------------------------*/
/* Copyright (c) FIRST 2015. All Rights Reserved. */
/* Open Source Software - may be modified and shared by FRC teams. The code */
/* must be accompanied by the FIRST BSD license file in the root directory of */
/* the project. */
/*----------------------------------------------------------------------------*/
#include "Notifier.h"
#include <queue>
#include <vector>
using namespace nt;
ATOMIC_STATIC_INIT(Notifier)
bool Notifier::s_destroyed = false;
class Notifier::Thread : public SafeThread {
public:
Thread(std::function<void()> on_start, std::function<void()> on_exit)
: m_on_start(on_start), m_on_exit(on_exit) {}
void Main();
struct EntryListener {
EntryListener(StringRef prefix_, EntryListenerCallback callback_,
unsigned int flags_)
: prefix(prefix_), callback(callback_), flags(flags_) {}
std::string prefix;
EntryListenerCallback callback;
unsigned int flags;
};
std::vector<EntryListener> m_entry_listeners;
std::vector<ConnectionListenerCallback> m_conn_listeners;
struct EntryNotification {
EntryNotification(StringRef name_, std::shared_ptr<Value> value_,
unsigned int flags_, EntryListenerCallback only_)
: name(name_),
value(value_),
flags(flags_),
only(only_) {}
std::string name;
std::shared_ptr<Value> value;
unsigned int flags;
EntryListenerCallback only;
};
std::queue<EntryNotification> m_entry_notifications;
struct ConnectionNotification {
ConnectionNotification(bool connected_, const ConnectionInfo& conn_info_,
ConnectionListenerCallback only_)
: connected(connected_), conn_info(conn_info_), only(only_) {}
bool connected;
ConnectionInfo conn_info;
ConnectionListenerCallback only;
};
std::queue<ConnectionNotification> m_conn_notifications;
std::function<void()> m_on_start;
std::function<void()> m_on_exit;
};
Notifier::Notifier() {
m_local_notifiers = false;
s_destroyed = false;
}
Notifier::~Notifier() { s_destroyed = true; }
void Notifier::Start() { m_owner.Start(new Thread(m_on_start, m_on_exit)); }
void Notifier::Stop() { m_owner.Stop(); }
void Notifier::Thread::Main() {
if (m_on_start) m_on_start();
std::unique_lock<std::mutex> lock(m_mutex);
while (m_active) {
while (m_entry_notifications.empty() && m_conn_notifications.empty()) {
m_cond.wait(lock);
if (!m_active) goto done;
}
// Entry notifications
while (!m_entry_notifications.empty()) {
if (!m_active) goto done;
auto item = std::move(m_entry_notifications.front());
m_entry_notifications.pop();
if (!item.value) continue;
StringRef name(item.name);
if (item.only) {
// Don't hold mutex during callback execution!
lock.unlock();
item.only(0, name, item.value, item.flags);
lock.lock();
continue;
}
// Use index because iterator might get invalidated.
for (std::size_t i=0; i<m_entry_listeners.size(); ++i) {
if (!m_entry_listeners[i].callback) continue; // removed
// Flags must be within requested flag set for this listener.
// Because assign messages can result in both a value and flags update,
// we handle that case specially.
unsigned int listen_flags = m_entry_listeners[i].flags;
unsigned int flags = item.flags;
unsigned int assign_both = NT_NOTIFY_UPDATE | NT_NOTIFY_FLAGS;
if ((flags & assign_both) == assign_both) {
if ((listen_flags & assign_both) == 0) continue;
listen_flags &= ~assign_both;
flags &= ~assign_both;
}
if ((flags & ~listen_flags) != 0) continue;
// must match prefix
if (!name.startswith(m_entry_listeners[i].prefix)) continue;
// make a copy of the callback so we can safely release the mutex
auto callback = m_entry_listeners[i].callback;
// Don't hold mutex during callback execution!
lock.unlock();
callback(i+1, name, item.value, item.flags);
lock.lock();
}
}
// Connection notifications
while (!m_conn_notifications.empty()) {
if (!m_active) goto done;
auto item = std::move(m_conn_notifications.front());
m_conn_notifications.pop();
if (item.only) {
// Don't hold mutex during callback execution!
lock.unlock();
item.only(0, item.connected, item.conn_info);
lock.lock();
continue;
}
// Use index because iterator might get invalidated.
for (std::size_t i=0; i<m_conn_listeners.size(); ++i) {
if (!m_conn_listeners[i]) continue; // removed
auto callback = m_conn_listeners[i];
// Don't hold mutex during callback execution!
lock.unlock();
callback(i+1, item.connected, item.conn_info);
lock.lock();
}
}
}
done:
if (m_on_exit) m_on_exit();
}
unsigned int Notifier::AddEntryListener(StringRef prefix,
EntryListenerCallback callback,
unsigned int flags) {
auto thr = m_owner.GetThread();
if (!thr) {
Start();
thr = m_owner.GetThread();
}
unsigned int uid = thr->m_entry_listeners.size();
thr->m_entry_listeners.emplace_back(prefix, callback, flags);
if ((flags & NT_NOTIFY_LOCAL) != 0) m_local_notifiers = true;
return uid + 1;
}
void Notifier::RemoveEntryListener(unsigned int entry_listener_uid) {
auto thr = m_owner.GetThread();
if (!thr) return;
--entry_listener_uid;
if (entry_listener_uid < thr->m_entry_listeners.size())
thr->m_entry_listeners[entry_listener_uid].callback = nullptr;
}
void Notifier::NotifyEntry(StringRef name, std::shared_ptr<Value> value,
unsigned int flags, EntryListenerCallback only) {
// optimization: don't generate needless local queue entries if we have
// no local listeners (as this is a common case on the server side)
if ((flags & NT_NOTIFY_LOCAL) != 0 && !m_local_notifiers) return;
auto thr = m_owner.GetThread();
if (!thr) return;
thr->m_entry_notifications.emplace(name, value, flags, only);
thr->m_cond.notify_one();
}
unsigned int Notifier::AddConnectionListener(
ConnectionListenerCallback callback) {
auto thr = m_owner.GetThread();
if (!thr) {
Start();
thr = m_owner.GetThread();
}
unsigned int uid = thr->m_entry_listeners.size();
thr->m_conn_listeners.emplace_back(callback);
return uid + 1;
}
void Notifier::RemoveConnectionListener(unsigned int conn_listener_uid) {
auto thr = m_owner.GetThread();
if (!thr) return;
--conn_listener_uid;
if (conn_listener_uid < thr->m_conn_listeners.size())
thr->m_conn_listeners[conn_listener_uid] = nullptr;
}
void Notifier::NotifyConnection(bool connected,
const ConnectionInfo& conn_info,
ConnectionListenerCallback only) {
auto thr = m_owner.GetThread();
if (!thr) return;
thr->m_conn_notifications.emplace(connected, conn_info, only);
thr->m_cond.notify_one();
}
<commit_msg>Unbreak build on VS2012.<commit_after>/*----------------------------------------------------------------------------*/
/* Copyright (c) FIRST 2015. All Rights Reserved. */
/* Open Source Software - may be modified and shared by FRC teams. The code */
/* must be accompanied by the FIRST BSD license file in the root directory of */
/* the project. */
/*----------------------------------------------------------------------------*/
#include "Notifier.h"
#include <queue>
#include <vector>
using namespace nt;
ATOMIC_STATIC_INIT(Notifier)
bool Notifier::s_destroyed = false;
class Notifier::Thread : public SafeThread {
public:
Thread(std::function<void()> on_start, std::function<void()> on_exit)
: m_on_start(on_start), m_on_exit(on_exit) {}
void Main();
struct EntryListener {
EntryListener(StringRef prefix_, EntryListenerCallback callback_,
unsigned int flags_)
: prefix(prefix_), callback(callback_), flags(flags_) {}
std::string prefix;
EntryListenerCallback callback;
unsigned int flags;
};
std::vector<EntryListener> m_entry_listeners;
std::vector<ConnectionListenerCallback> m_conn_listeners;
struct EntryNotification {
EntryNotification(StringRef name_, std::shared_ptr<Value> value_,
unsigned int flags_, EntryListenerCallback only_)
: name(name_),
value(value_),
flags(flags_),
only(only_) {}
std::string name;
std::shared_ptr<Value> value;
unsigned int flags;
EntryListenerCallback only;
};
std::queue<EntryNotification> m_entry_notifications;
struct ConnectionNotification {
ConnectionNotification(bool connected_, const ConnectionInfo& conn_info_,
ConnectionListenerCallback only_)
: connected(connected_), conn_info(conn_info_), only(only_) {}
bool connected;
ConnectionInfo conn_info;
ConnectionListenerCallback only;
};
std::queue<ConnectionNotification> m_conn_notifications;
std::function<void()> m_on_start;
std::function<void()> m_on_exit;
};
Notifier::Notifier() {
m_local_notifiers = false;
s_destroyed = false;
}
Notifier::~Notifier() { s_destroyed = true; }
void Notifier::Start() {
auto thr = m_owner.GetThread();
if (!thr) m_owner.Start(new Thread(m_on_start, m_on_exit));
}
void Notifier::Stop() { m_owner.Stop(); }
void Notifier::Thread::Main() {
if (m_on_start) m_on_start();
std::unique_lock<std::mutex> lock(m_mutex);
while (m_active) {
while (m_entry_notifications.empty() && m_conn_notifications.empty()) {
m_cond.wait(lock);
if (!m_active) goto done;
}
// Entry notifications
while (!m_entry_notifications.empty()) {
if (!m_active) goto done;
auto item = std::move(m_entry_notifications.front());
m_entry_notifications.pop();
if (!item.value) continue;
StringRef name(item.name);
if (item.only) {
// Don't hold mutex during callback execution!
lock.unlock();
item.only(0, name, item.value, item.flags);
lock.lock();
continue;
}
// Use index because iterator might get invalidated.
for (std::size_t i=0; i<m_entry_listeners.size(); ++i) {
if (!m_entry_listeners[i].callback) continue; // removed
// Flags must be within requested flag set for this listener.
// Because assign messages can result in both a value and flags update,
// we handle that case specially.
unsigned int listen_flags = m_entry_listeners[i].flags;
unsigned int flags = item.flags;
unsigned int assign_both = NT_NOTIFY_UPDATE | NT_NOTIFY_FLAGS;
if ((flags & assign_both) == assign_both) {
if ((listen_flags & assign_both) == 0) continue;
listen_flags &= ~assign_both;
flags &= ~assign_both;
}
if ((flags & ~listen_flags) != 0) continue;
// must match prefix
if (!name.startswith(m_entry_listeners[i].prefix)) continue;
// make a copy of the callback so we can safely release the mutex
auto callback = m_entry_listeners[i].callback;
// Don't hold mutex during callback execution!
lock.unlock();
callback(i+1, name, item.value, item.flags);
lock.lock();
}
}
// Connection notifications
while (!m_conn_notifications.empty()) {
if (!m_active) goto done;
auto item = std::move(m_conn_notifications.front());
m_conn_notifications.pop();
if (item.only) {
// Don't hold mutex during callback execution!
lock.unlock();
item.only(0, item.connected, item.conn_info);
lock.lock();
continue;
}
// Use index because iterator might get invalidated.
for (std::size_t i=0; i<m_conn_listeners.size(); ++i) {
if (!m_conn_listeners[i]) continue; // removed
auto callback = m_conn_listeners[i];
// Don't hold mutex during callback execution!
lock.unlock();
callback(i+1, item.connected, item.conn_info);
lock.lock();
}
}
}
done:
if (m_on_exit) m_on_exit();
}
unsigned int Notifier::AddEntryListener(StringRef prefix,
EntryListenerCallback callback,
unsigned int flags) {
Start();
auto thr = m_owner.GetThread();
unsigned int uid = thr->m_entry_listeners.size();
thr->m_entry_listeners.emplace_back(prefix, callback, flags);
if ((flags & NT_NOTIFY_LOCAL) != 0) m_local_notifiers = true;
return uid + 1;
}
void Notifier::RemoveEntryListener(unsigned int entry_listener_uid) {
auto thr = m_owner.GetThread();
if (!thr) return;
--entry_listener_uid;
if (entry_listener_uid < thr->m_entry_listeners.size())
thr->m_entry_listeners[entry_listener_uid].callback = nullptr;
}
void Notifier::NotifyEntry(StringRef name, std::shared_ptr<Value> value,
unsigned int flags, EntryListenerCallback only) {
// optimization: don't generate needless local queue entries if we have
// no local listeners (as this is a common case on the server side)
if ((flags & NT_NOTIFY_LOCAL) != 0 && !m_local_notifiers) return;
auto thr = m_owner.GetThread();
if (!thr) return;
thr->m_entry_notifications.emplace(name, value, flags, only);
thr->m_cond.notify_one();
}
unsigned int Notifier::AddConnectionListener(
ConnectionListenerCallback callback) {
Start();
auto thr = m_owner.GetThread();
unsigned int uid = thr->m_entry_listeners.size();
thr->m_conn_listeners.emplace_back(callback);
return uid + 1;
}
void Notifier::RemoveConnectionListener(unsigned int conn_listener_uid) {
auto thr = m_owner.GetThread();
if (!thr) return;
--conn_listener_uid;
if (conn_listener_uid < thr->m_conn_listeners.size())
thr->m_conn_listeners[conn_listener_uid] = nullptr;
}
void Notifier::NotifyConnection(bool connected,
const ConnectionInfo& conn_info,
ConnectionListenerCallback only) {
auto thr = m_owner.GetThread();
if (!thr) return;
thr->m_conn_notifications.emplace(connected, conn_info, only);
thr->m_cond.notify_one();
}
<|endoftext|> |
<commit_before>/*
* Reporter.cpp
*
* Created on: Apr 28, 2014
* Author: khanhn
*/
#include "Reporter.h"
Reporter::Reporter() {
}
Reporter::~Reporter() {
}
// Is it working?
// Looks like it's not working?
<commit_msg>It should be working by this commit<commit_after>/*
* Reporter.cpp
*
* Created on: Apr 28, 2014
* Author: khanhn
*/
#include "Reporter.h"
Reporter::Reporter() {
}
Reporter::~Reporter() {
}
<|endoftext|> |
<commit_before>//************************************************************/
//
// Spectrum
//
// @Author: J. Gibson, C. Embree, T. Carli - CERN ATLAS
// @Date: 19.09.2014
// @Email: gibsjose@mail.gvsu.edu
//
//************************************************************/
#include <iostream>
#include "SPXROOT.h"
#include "SPXSteeringFile.h"
#include "SPXAnalysis.h"
#include "SPXException.h"
//Determines whether or not to draw the actual ROOT application canvases
#define DRAW_APPLICATION true
int main(int argc, char *argv[]) {
if((argc - 1) < 1) {
std::cout << "@usage: Spectrum <steering_file>" << std::endl;
exit(0);
}
std::string file;
std::cout << "==================================" << std::endl;
std::cout << " Spectrum " << std::endl;
std::cout << "==================================" << std::endl <<std::endl;
#if DRAW_APPLICATION
TApplication *spectrum = new TApplication("Spectrum",0,0);
spectrum->SetReturnFromRun(true);
#endif
file = std::string(argv[1]);
SPXSteeringFile steeringFile = SPXSteeringFile(file);
//=========================================================
// Configuration
//=========================================================
try {
steeringFile.ParseAll(true);
} catch(const SPXException &e) {
std::cerr << e.what() << std::endl;
std::cerr << "FATAL: Could not parse the steering file: " << file << std::endl;
exit(-1);
}
//=========================================================
// Analysis
//=========================================================
try {
SPXAnalysis analysis = SPXAnalysis(&steeringFile);
analysis.Run();
} catch(const SPXException &e) {
std::cerr << e.what() << std::endl;
std::cerr << "FATAL: Unable to perform successful analysis" << std::endl;
exit(-1);
}
#if DRAW_APPLICATION
spectrum->Run(kTRUE);
#endif
return 0;
}
<commit_msg>Fixed tabing<commit_after>//************************************************************/
//
// Spectrum
//
// @Author: J. Gibson, C. Embree, T. Carli - CERN ATLAS
// @Date: 19.09.2014
// @Email: gibsjose@mail.gvsu.edu
//
//************************************************************/
#include <iostream>
#include "SPXROOT.h"
#include "SPXSteeringFile.h"
#include "SPXAnalysis.h"
#include "SPXException.h"
//Determines whether or not to draw the actual ROOT application canvases
#define DRAW_APPLICATION true
int main(int argc, char *argv[]) {
if((argc - 1) < 1) {
std::cout << "@usage: Spectrum <steering_file>" << std::endl;
exit(0);
}
std::string file;
std::cout << "==================================" << std::endl;
std::cout << " Spectrum " << std::endl;
std::cout << "==================================" << std::endl <<std::endl;
#if DRAW_APPLICATION
TApplication *spectrum = new TApplication("Spectrum",0,0);
spectrum->SetReturnFromRun(true);
#endif
file = std::string(argv[1]);
SPXSteeringFile steeringFile = SPXSteeringFile(file);
//=========================================================
// Configuration
//=========================================================
try {
steeringFile.ParseAll(true);
} catch(const SPXException &e) {
std::cerr << e.what() << std::endl;
std::cerr << "FATAL: Could not parse the steering file: " << file << std::endl;
exit(-1);
}
//=========================================================
// Analysis
//=========================================================
try {
SPXAnalysis analysis = SPXAnalysis(&steeringFile);
analysis.Run();
} catch(const SPXException &e) {
std::cerr << e.what() << std::endl;
std::cerr << "FATAL: Unable to perform successful analysis" << std::endl;
exit(-1);
}
#if DRAW_APPLICATION
spectrum->Run(kTRUE);
#endif
return 0;
}
<|endoftext|> |
<commit_before>// Vaca - Visual Application Components Abstraction
// Copyright (c) 2008, 2009, Jie Zhang, David Capello
// 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 "Vaca/SplitBar.h"
#include "Vaca/Color.h"
#include "Vaca/Brush.h"
#include "Vaca/Cursor.h"
#include "Vaca/MouseEvent.h"
#include "Vaca/System.h"
using namespace Vaca;
#define SPLITBAR_DEFAULT_SIZE 5
#define SPLITBAR_DEFAULT_POS 50
SplitBar::SplitBar(Orientation orientation, Widget* parent, Style style)
: Widget(SplitBarClass::getClassName(), parent, style)
, m_orientation(orientation)
, m_first(NULL)
, m_second(NULL)
, m_barSize(SPLITBAR_DEFAULT_SIZE)
, m_barPos(SPLITBAR_DEFAULT_POS)
, m_fullDrag(false)
, m_trackerIsVisible(false)
, m_gripperVisible(true)
{
}
SplitBar::~SplitBar()
{
}
void SplitBar::layout()
{
Widget::layout();
Rect rcL, rcR;
getRects(rcL, rcR);
if (m_first) m_first->setBounds(rcL);
if (m_second) m_second->setBounds(rcR);
}
void SplitBar::setFirstWidget(Widget* widget)
{
m_first = widget;
updateChildrenVisibility();
layout();
}
void SplitBar::setSecondWidget(Widget* widget)
{
m_second = widget;
updateChildrenVisibility();
layout();
}
Widget* SplitBar::getFirstWidget() const
{
return m_first;
}
Widget* SplitBar::getSecondWidget() const
{
return m_second;
}
int SplitBar::getBarSize() const
{
return m_barSize;
}
void SplitBar::setBarSize(int size)
{
if (m_barSize != size) {
m_barSize = size;
layout();
}
}
double SplitBar::getBarPosition() const
{
return m_barPos;
}
void SplitBar::setBarPosition(double pos)
{
m_barPos = pos;
layout();
}
Orientation SplitBar::getOrientation() const
{
return m_orientation;
}
void SplitBar::setOrientation(Orientation orientation)
{
m_orientation = orientation;
layout();
}
void SplitBar::setFullDrag(bool state)
{
m_fullDrag = state;
}
bool SplitBar::isFullDrag() const
{
return m_fullDrag;
}
void SplitBar::setGripperVisible(bool state)
{
if (m_gripperVisible != state) {
m_gripperVisible = state;
invalidate(true);
}
}
bool SplitBar::isGripperVisible() const
{
return m_gripperVisible;
}
void SplitBar::onResize(const Size& sz)
{
invalidate(true);
layout();
}
void SplitBar::onPaint(Graphics& g)
{
if (m_gripperVisible) {
Rect rcBar(getBarRect());
for (int c=0; c<8; ++c) {
Rect rc(0, 0, 3, 3);
if (m_orientation == Orientation::Vertical) {
rc.x = rcBar.x+rcBar.w/2-rc.w/2;
rc.y = rcBar.y+rcBar.h/2-8*(rc.h+1)/2+c*(rc.h+1);
}
else {
rc.x = rcBar.x+rcBar.w/2-8*(rc.w+1)/2+c*(rc.w+1);
rc.y = rcBar.y+rcBar.h/2-rc.h/2;
}
g.draw3dRect(rc,
System::getColor(COLOR_3DSHADOW),
System::getColor(COLOR_3DHIGHLIGHT));
}
}
else {
Widget::onPaint(g);
}
}
void SplitBar::onMouseDown(MouseEvent& ev)
{
Widget::MouseDown(ev);
// capture the mouse only if the user clicks in the bar
if (getBarRect().contains(ev.getPoint())) {
m_oldPoint = ev.getPoint();
m_oldBarPos = m_barPos;
captureMouse();
if (!isFullDrag()) {
ScreenGraphics g;
drawTracker(g);
}
}
}
void SplitBar::onMouseUp(MouseEvent& ev)
{
Widget::MouseUp(ev);
releaseMouse();
if (!isFullDrag()) {
ScreenGraphics g;
cleanTracker(g);
layout();
}
}
void SplitBar::onMouseMove(MouseEvent& ev)
{
Widget::MouseMove(ev);
if (hasCapture()) {
Rect rcClient(getClientBounds());
ScreenGraphics g;
if (!isFullDrag())
cleanTracker(g);
bool byPixels = (getStyle() & Styles::ByPixels) == Styles::ByPixels;
// Bar-position by pixels
if (byPixels) {
if (m_orientation == Orientation::Vertical) {
m_barPos = m_oldBarPos + (ev.getPoint().x - m_oldPoint.x);
m_barPos = clamp_value(m_barPos, 0.0, (double)rcClient.w-m_barSize);
}
else {
m_barPos = m_oldBarPos + (ev.getPoint().y - m_oldPoint.y);
m_barPos = clamp_value(m_barPos, 0.0, (double)rcClient.h-m_barSize);
}
}
// Bar-position by percentage
else {
if (m_orientation == Orientation::Vertical) {
m_barPos = m_oldBarPos + 100.0 * (ev.getPoint().x - m_oldPoint.x) / getBounds().w;
}
else {
m_barPos = m_oldBarPos + 100.0 * (ev.getPoint().y - m_oldPoint.y) / getBounds().h;
}
m_barPos = clamp_value(m_barPos, 0.0, 100.0);
}
if (!isFullDrag())
drawTracker(g);
else
layout();
}
}
void SplitBar::onSetCursor(WidgetHitTest hitTest)
{
bool isVertical = (m_orientation == Orientation::Vertical);
SysCursor modCursor = isVertical ? SysCursor::SizeE : SysCursor::SizeN;
SysCursor sysCursor = SysCursor::Arrow;
if (hasCapture()) {
sysCursor = modCursor;
}
else {
Point pt = System::getCursorPos() - getAbsoluteBounds().getOrigin();
if (getBarRect().contains(pt))
sysCursor = modCursor;
}
setCursor(Cursor(sysCursor));
}
void SplitBar::onAddChild(Widget* child)
{
Widget::onAddChild(child);
if (m_first == NULL)
setFirstWidget(child);
else if (m_second == NULL)
setSecondWidget(child);
}
void SplitBar::updateChildrenVisibility()
{
// hide children that aren't first or second
Container children = getChildren();
for (Container::iterator
it = children.begin(); it != children.end(); ++it) {
Widget* child = *it;
child->setVisible(child == m_first ||
child == m_second);
}
}
Rect SplitBar::getBarRect() const
{
Rect rcBar(getClientBounds());
bool byPixels = (getStyle() & Styles::ByPixels) == Styles::ByPixels;
if (m_orientation == Orientation::Vertical) {
if (byPixels)
rcBar.x = clamp_value(m_barPos, 0.0, (double)rcBar.w-m_barSize);
else
rcBar.x = clamp_value(rcBar.w * m_barPos / 100, 0.0, (double)rcBar.w-m_barSize);
rcBar.w = m_barSize;
}
else {
if (byPixels)
rcBar.y = clamp_value(m_barPos, 0.0, (double)rcBar.h-m_barSize);
else
rcBar.y = clamp_value(rcBar.h * m_barPos / 100.0, 0.0, (double)rcBar.h-m_barSize);
rcBar.h = m_barSize;
}
return rcBar;
}
void SplitBar::getRects(Rect& rcFirst, Rect& rcSecond) const
{
Rect rcClient, rcBar(getBarRect());
rcClient = getClientBounds();
rcFirst = rcSecond = rcClient;
if (m_orientation == Orientation::Vertical) {
rcFirst.w = rcBar.x;
rcSecond.x = rcBar.x+rcBar.w;
rcSecond.w -= rcSecond.x - rcClient.x;
}
else {
rcFirst.h = rcBar.y;
rcSecond.y = rcBar.y+rcBar.h;
rcSecond.h -= rcSecond.y - rcClient.y;
}
}
void SplitBar::drawTracker(Graphics& g)
{
if (!m_trackerIsVisible) {
g.fillXorFrame(getBarRect().offset(getAbsoluteBounds().getOrigin()));
m_trackerIsVisible = true;
}
}
void SplitBar::cleanTracker(Graphics& g)
{
if (m_trackerIsVisible) {
g.fillXorFrame(getBarRect().offset(getAbsoluteBounds().getOrigin()));
m_trackerIsVisible = false;
}
}
<commit_msg>Fixed a bug where Widget::layout method was not called. It is because SplitBar is a special widget that acts like Layout but it is not a layout manager. Maybe the method of Layout class to move widgets (beginMovement, moveWidget, endMovement) should be in another class.<commit_after>// Vaca - Visual Application Components Abstraction
// Copyright (c) 2008, 2009, Jie Zhang, David Capello
// 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 "Vaca/SplitBar.h"
#include "Vaca/Color.h"
#include "Vaca/Brush.h"
#include "Vaca/Cursor.h"
#include "Vaca/MouseEvent.h"
#include "Vaca/System.h"
using namespace Vaca;
#define SPLITBAR_DEFAULT_SIZE 5
#define SPLITBAR_DEFAULT_POS 50
SplitBar::SplitBar(Orientation orientation, Widget* parent, Style style)
: Widget(SplitBarClass::getClassName(), parent, style)
, m_orientation(orientation)
, m_first(NULL)
, m_second(NULL)
, m_barSize(SPLITBAR_DEFAULT_SIZE)
, m_barPos(SPLITBAR_DEFAULT_POS)
, m_fullDrag(false)
, m_trackerIsVisible(false)
, m_gripperVisible(true)
{
}
SplitBar::~SplitBar()
{
}
void SplitBar::layout()
{
Widget::layout();
Rect rcL, rcR;
getRects(rcL, rcR);
if (m_first) {
m_first->setBounds(rcL);
m_first->layout();
}
if (m_second) {
m_second->setBounds(rcR);
m_second->layout();
}
}
void SplitBar::setFirstWidget(Widget* widget)
{
m_first = widget;
updateChildrenVisibility();
layout();
}
void SplitBar::setSecondWidget(Widget* widget)
{
m_second = widget;
updateChildrenVisibility();
layout();
}
Widget* SplitBar::getFirstWidget() const
{
return m_first;
}
Widget* SplitBar::getSecondWidget() const
{
return m_second;
}
int SplitBar::getBarSize() const
{
return m_barSize;
}
void SplitBar::setBarSize(int size)
{
if (m_barSize != size) {
m_barSize = size;
layout();
}
}
double SplitBar::getBarPosition() const
{
return m_barPos;
}
void SplitBar::setBarPosition(double pos)
{
m_barPos = pos;
layout();
}
Orientation SplitBar::getOrientation() const
{
return m_orientation;
}
void SplitBar::setOrientation(Orientation orientation)
{
m_orientation = orientation;
layout();
}
void SplitBar::setFullDrag(bool state)
{
m_fullDrag = state;
}
bool SplitBar::isFullDrag() const
{
return m_fullDrag;
}
void SplitBar::setGripperVisible(bool state)
{
if (m_gripperVisible != state) {
m_gripperVisible = state;
invalidate(true);
}
}
bool SplitBar::isGripperVisible() const
{
return m_gripperVisible;
}
void SplitBar::onResize(const Size& sz)
{
invalidate(true);
layout();
}
void SplitBar::onPaint(Graphics& g)
{
if (m_gripperVisible) {
Rect rcBar(getBarRect());
for (int c=0; c<8; ++c) {
Rect rc(0, 0, 3, 3);
if (m_orientation == Orientation::Vertical) {
rc.x = rcBar.x+rcBar.w/2-rc.w/2;
rc.y = rcBar.y+rcBar.h/2-8*(rc.h+1)/2+c*(rc.h+1);
}
else {
rc.x = rcBar.x+rcBar.w/2-8*(rc.w+1)/2+c*(rc.w+1);
rc.y = rcBar.y+rcBar.h/2-rc.h/2;
}
g.draw3dRect(rc,
System::getColor(COLOR_3DSHADOW),
System::getColor(COLOR_3DHIGHLIGHT));
}
}
else {
Widget::onPaint(g);
}
}
void SplitBar::onMouseDown(MouseEvent& ev)
{
Widget::MouseDown(ev);
// capture the mouse only if the user clicks in the bar
if (getBarRect().contains(ev.getPoint())) {
m_oldPoint = ev.getPoint();
m_oldBarPos = m_barPos;
captureMouse();
if (!isFullDrag()) {
ScreenGraphics g;
drawTracker(g);
}
}
}
void SplitBar::onMouseUp(MouseEvent& ev)
{
Widget::MouseUp(ev);
releaseMouse();
if (!isFullDrag()) {
ScreenGraphics g;
cleanTracker(g);
layout();
}
}
void SplitBar::onMouseMove(MouseEvent& ev)
{
Widget::MouseMove(ev);
if (hasCapture()) {
Rect rcClient(getClientBounds());
ScreenGraphics g;
if (!isFullDrag())
cleanTracker(g);
bool byPixels = (getStyle() & Styles::ByPixels) == Styles::ByPixels;
// Bar-position by pixels
if (byPixels) {
if (m_orientation == Orientation::Vertical) {
m_barPos = m_oldBarPos + (ev.getPoint().x - m_oldPoint.x);
m_barPos = clamp_value(m_barPos, 0.0, (double)rcClient.w-m_barSize);
}
else {
m_barPos = m_oldBarPos + (ev.getPoint().y - m_oldPoint.y);
m_barPos = clamp_value(m_barPos, 0.0, (double)rcClient.h-m_barSize);
}
}
// Bar-position by percentage
else {
if (m_orientation == Orientation::Vertical) {
m_barPos = m_oldBarPos + 100.0 * (ev.getPoint().x - m_oldPoint.x) / getBounds().w;
}
else {
m_barPos = m_oldBarPos + 100.0 * (ev.getPoint().y - m_oldPoint.y) / getBounds().h;
}
m_barPos = clamp_value(m_barPos, 0.0, 100.0);
}
if (!isFullDrag())
drawTracker(g);
else
layout();
}
}
void SplitBar::onSetCursor(WidgetHitTest hitTest)
{
bool isVertical = (m_orientation == Orientation::Vertical);
SysCursor modCursor = isVertical ? SysCursor::SizeE : SysCursor::SizeN;
SysCursor sysCursor = SysCursor::Arrow;
if (hasCapture()) {
sysCursor = modCursor;
}
else {
Point pt = System::getCursorPos() - getAbsoluteBounds().getOrigin();
if (getBarRect().contains(pt))
sysCursor = modCursor;
}
setCursor(Cursor(sysCursor));
}
void SplitBar::onAddChild(Widget* child)
{
Widget::onAddChild(child);
if (m_first == NULL)
setFirstWidget(child);
else if (m_second == NULL)
setSecondWidget(child);
}
void SplitBar::updateChildrenVisibility()
{
// hide children that aren't first or second
Container children = getChildren();
for (Container::iterator
it = children.begin(); it != children.end(); ++it) {
Widget* child = *it;
child->setVisible(child == m_first ||
child == m_second);
}
}
Rect SplitBar::getBarRect() const
{
Rect rcBar(getClientBounds());
bool byPixels = (getStyle() & Styles::ByPixels) == Styles::ByPixels;
if (m_orientation == Orientation::Vertical) {
if (byPixels)
rcBar.x = clamp_value(m_barPos, 0.0, (double)rcBar.w-m_barSize);
else
rcBar.x = clamp_value(rcBar.w * m_barPos / 100, 0.0, (double)rcBar.w-m_barSize);
rcBar.w = m_barSize;
}
else {
if (byPixels)
rcBar.y = clamp_value(m_barPos, 0.0, (double)rcBar.h-m_barSize);
else
rcBar.y = clamp_value(rcBar.h * m_barPos / 100.0, 0.0, (double)rcBar.h-m_barSize);
rcBar.h = m_barSize;
}
return rcBar;
}
void SplitBar::getRects(Rect& rcFirst, Rect& rcSecond) const
{
Rect rcClient, rcBar(getBarRect());
rcClient = getClientBounds();
rcFirst = rcSecond = rcClient;
if (m_orientation == Orientation::Vertical) {
rcFirst.w = rcBar.x;
rcSecond.x = rcBar.x+rcBar.w;
rcSecond.w -= rcSecond.x - rcClient.x;
}
else {
rcFirst.h = rcBar.y;
rcSecond.y = rcBar.y+rcBar.h;
rcSecond.h -= rcSecond.y - rcClient.y;
}
}
void SplitBar::drawTracker(Graphics& g)
{
if (!m_trackerIsVisible) {
g.fillXorFrame(getBarRect().offset(getAbsoluteBounds().getOrigin()));
m_trackerIsVisible = true;
}
}
void SplitBar::cleanTracker(Graphics& g)
{
if (m_trackerIsVisible) {
g.fillXorFrame(getBarRect().offset(getAbsoluteBounds().getOrigin()));
m_trackerIsVisible = false;
}
}
<|endoftext|> |
<commit_before>// adbwatch.cpp : Defines the entry point for the console application.
//
#include <WinSDKVer.h>
#include <SDKDDKVer.h>
#include <stdio.h>
#include <tchar.h>
#include <Windows.h>
#include <Wtsapi32.h>
#include <atlstr.h>
#include <atlcoll.h>
#include <Shlwapi.h>
int startup_delay = 60;
bool must_exit = false;
bool IsAdbHung();
void KillAdb();
void SetAdbAffinity();
CAtlArray<CString> launch_processes;
BOOL CtrlHandler(DWORD fdwCtrlType) {
printf("Exiting...\n");
must_exit = true;
return TRUE;
}
void LoadSettings() {
wchar_t launch_section[32767];
wchar_t ini_file[MAX_PATH];
GetModuleFileName(NULL, ini_file, MAX_PATH);
lstrcpy(PathFindExtension(ini_file), L".ini");
if (GetPrivateProfileSection(L"Launch", launch_section,
sizeof(launch_section) / sizeof(launch_section[0]), ini_file)) {
wchar_t * next_token = NULL;
wchar_t * line = wcstok_s(launch_section, L"\r\n", &next_token);
while (line) {
CString trimmed(line);
trimmed.Trim();
if (trimmed.GetLength())
launch_processes.Add(line);
line = wcstok_s(NULL, L"\r\n", &next_token);
}
}
startup_delay = GetPrivateProfileInt(L"General", L"Startup Delay",
startup_delay, ini_file);
}
void LaunchAndWait(LPWSTR command_line, LPWSTR label) {
PROCESS_INFORMATION pi;
STARTUPINFO si;
memset(&si, 0, sizeof(si));
memset(&pi, 0, sizeof(pi));
si.cb = sizeof(si);
if (label && lstrlen(label))
si.lpTitle = label;
if (CreateProcess(NULL, command_line, NULL, NULL, FALSE, CREATE_NEW_CONSOLE,
NULL, NULL, &si, &pi)) {
if (pi.hThread)
CloseHandle(pi.hThread);
if (pi.hProcess) {
WaitForSingleObject(pi.hProcess, INFINITE);
CloseHandle(pi.hProcess);
}
}
}
DWORD WINAPI LaunchProcess(LPVOID param) {
int index = (int)param;
wchar_t label[100];
memset(label, 0, sizeof(label));
CString cmd;
if (index >= 0 && index < (int)launch_processes.GetCount()) {
cmd = launch_processes.GetAt(index);
int separator = cmd.Find(L"=");
if (separator > -1) {
lstrcpy(label, (LPCWSTR)cmd.Left(separator).Trim());
cmd = cmd.Mid(separator + 1).Trim();
}
}
if (cmd.GetLength()) {
wchar_t command_line[10000];
lstrcpy(command_line, (LPCWSTR)cmd);
while (!must_exit) {
LaunchAndWait(command_line, label);
if (!must_exit) {
SYSTEMTIME t;
GetLocalTime(&t);
wprintf(L"%d/%d/%d %d:%02d:%02d - %s exited, restarting...\n",
t.wMonth, t.wDay, t.wYear, t.wHour, t.wMinute, t.wSecond, label);
}
}
}
return 0;
}
int _tmain(int argc, _TCHAR* argv[]) {
SetConsoleCtrlHandler((PHANDLER_ROUTINE)CtrlHandler, TRUE);
LoadSettings();
if (startup_delay) {
printf("Waiting for statup delay...\n");
for (int seconds = 0; seconds < startup_delay && !must_exit; seconds++)
Sleep(1000);
}
int thread_count = launch_processes.GetCount();
if (thread_count) {
printf("Spawning %d processes...\n", thread_count);
for (int i = 0; i < thread_count; i++) {
HANDLE thread = CreateThread(NULL, 0, LaunchProcess, (LPVOID)i, 0, NULL);
CloseHandle(thread);
}
}
printf("Monitoring adb for hangs...\n");
SetAdbAffinity();
while (!must_exit) {
for (int seconds = 0; seconds < 60 && !must_exit; seconds++)
Sleep(1000);
if (IsAdbHung()) {
KillAdb();
IsAdbHung();
SetAdbAffinity();
}
}
return 0;
}
bool IsAdbHung() {
bool is_hung = false;
SECURITY_ATTRIBUTES sa;
// Set the bInheritHandle flag so pipe handles are inherited.
sa.nLength = sizeof(SECURITY_ATTRIBUTES);
sa.bInheritHandle = TRUE;
sa.lpSecurityDescriptor = NULL;
HANDLE stdout_read = NULL;
HANDLE stdout_write = NULL;
HANDLE stderr_read = NULL;
HANDLE stderr_write = NULL;
CStringA std_out, std_err;
// Create a pipe for the child process's STDERR.
if (CreatePipe(&stderr_read, &stderr_write, &sa, 0) &&
CreatePipe(&stdout_read, &stdout_write, &sa, 0)) {
SetHandleInformation(stderr_read, HANDLE_FLAG_INHERIT, 0);
SetHandleInformation(stdout_read, HANDLE_FLAG_INHERIT, 0);
// launch the adb command and wait for it to exit
PROCESS_INFORMATION pi;
STARTUPINFO si;
ZeroMemory(&pi, sizeof(pi));
ZeroMemory(&si, sizeof(si));
si.cb = sizeof(si);
si.hStdError = stderr_write;
si.hStdOutput = stdout_write;
si.dwFlags = STARTF_USESTDHANDLES;
TCHAR command[MAX_PATH];
lstrcpy(command, _T("adb devices"));
if (CreateProcess(NULL, command, NULL, NULL, TRUE,
CREATE_NO_WINDOW, NULL, NULL, &si, &pi)) {
if (pi.hProcess)
WaitForSingleObject(pi.hProcess, 60000);
// read all of the stderr and stdout data
char buff[4097];
DWORD bytes = 0;
while (PeekNamedPipe(stdout_read, buff, sizeof(buff), &bytes, NULL, NULL) &&
bytes &&
ReadFile(stdout_read, buff, sizeof(buff) - 1, &bytes, NULL) &&
bytes) {
buff[bytes] = 0;
std_out += buff;
}
while (PeekNamedPipe(stderr_read, buff, sizeof(buff), &bytes, NULL, NULL) &&
bytes &&
ReadFile(stderr_read, buff, sizeof(buff) - 1, &bytes, NULL) &&
bytes) {
buff[bytes] = 0;
std_err += buff;
}
CloseHandle(pi.hProcess);
CloseHandle(pi.hThread);
}
}
// Close the pipe handles
if (stdout_read)
CloseHandle(stdout_read);
if (stdout_write)
CloseHandle(stdout_write);
if (stderr_read)
CloseHandle(stderr_read);
if (stderr_write)
CloseHandle(stderr_write);
if (std_err.GetLength())
is_hung = true;
return is_hung;
}
void KillAdb() {
SYSTEMTIME t;
GetLocalTime(&t);
printf("%d/%d/%d %d:%02d:%02d - hang detected\n",
t.wMonth, t.wDay, t.wYear, t.wHour, t.wMinute, t.wSecond);
WTS_PROCESS_INFO * proc = NULL;
DWORD count = 0;
if (WTSEnumerateProcesses(WTS_CURRENT_SERVER_HANDLE, 0, 1, &proc ,&count)) {
for (DWORD i = 0; i < count; i++) {
TCHAR * process = PathFindFileName(proc[i].pProcessName);
if (!lstrcmpi(process, _T("adb.exe"))) {
HANDLE process_handle = OpenProcess(PROCESS_TERMINATE, FALSE,
proc[i].ProcessId);
if (process_handle) {
TerminateProcess(process_handle, 0);
CloseHandle(process_handle);
}
}
}
if (proc)
WTSFreeMemory(proc);
}
}
void SetAdbAffinity() {
WTS_PROCESS_INFO * proc = NULL;
DWORD count = 0;
if (WTSEnumerateProcesses(WTS_CURRENT_SERVER_HANDLE, 0, 1, &proc ,&count)) {
for (DWORD i = 0; i < count; i++) {
TCHAR * process = PathFindFileName(proc[i].pProcessName);
if (!lstrcmpi(process, _T("adb.exe"))) {
HANDLE process_handle = OpenProcess(PROCESS_SET_INFORMATION, FALSE,
proc[i].ProcessId);
if (process_handle) {
SetProcessAffinityMask(process_handle, 1);
CloseHandle(process_handle);
}
}
}
if (proc)
WTSFreeMemory(proc);
}
}<commit_msg>Fixed the launch support to handle multiple processes (ini parsing was incorrect)<commit_after>// adbwatch.cpp : Defines the entry point for the console application.
//
#include <WinSDKVer.h>
#include <SDKDDKVer.h>
#include <stdio.h>
#include <tchar.h>
#include <Windows.h>
#include <Wtsapi32.h>
#include <atlstr.h>
#include <atlcoll.h>
#include <Shlwapi.h>
int startup_delay = 60;
bool must_exit = false;
bool IsAdbHung();
void KillAdb();
void SetAdbAffinity();
CAtlArray<CString> launch_processes;
BOOL CtrlHandler(DWORD fdwCtrlType) {
printf("Exiting...\n");
must_exit = true;
return TRUE;
}
void LoadSettings() {
wchar_t launch_section[32767];
wchar_t ini_file[MAX_PATH];
GetModuleFileName(NULL, ini_file, MAX_PATH);
lstrcpy(PathFindExtension(ini_file), L".ini");
if (GetPrivateProfileSection(L"Launch", launch_section,
sizeof(launch_section) / sizeof(launch_section[0]), ini_file)) {
wchar_t * line = launch_section;
while (line && lstrlen(line)) {
CString trimmed(line);
trimmed.Trim();
if (trimmed.GetLength())
launch_processes.Add(line);
line += lstrlen(line) + 1;
}
}
startup_delay = GetPrivateProfileInt(L"General", L"Startup Delay",
startup_delay, ini_file);
}
void LaunchAndWait(LPWSTR command_line, LPWSTR label) {
PROCESS_INFORMATION pi;
STARTUPINFO si;
memset(&si, 0, sizeof(si));
memset(&pi, 0, sizeof(pi));
si.cb = sizeof(si);
if (label && lstrlen(label))
si.lpTitle = label;
if (CreateProcess(NULL, command_line, NULL, NULL, FALSE, CREATE_NEW_CONSOLE,
NULL, NULL, &si, &pi)) {
if (pi.hThread)
CloseHandle(pi.hThread);
if (pi.hProcess) {
WaitForSingleObject(pi.hProcess, INFINITE);
CloseHandle(pi.hProcess);
}
}
}
DWORD WINAPI LaunchProcess(LPVOID param) {
int index = (int)param;
wchar_t label[100];
memset(label, 0, sizeof(label));
CString cmd;
if (index >= 0 && index < (int)launch_processes.GetCount()) {
cmd = launch_processes.GetAt(index);
int separator = cmd.Find(L"=");
if (separator > -1) {
lstrcpy(label, (LPCWSTR)cmd.Left(separator).Trim());
cmd = cmd.Mid(separator + 1).Trim();
}
}
if (cmd.GetLength()) {
wchar_t command_line[10000];
lstrcpy(command_line, (LPCWSTR)cmd);
while (!must_exit) {
LaunchAndWait(command_line, label);
if (!must_exit) {
SYSTEMTIME t;
GetLocalTime(&t);
wprintf(L"%d/%d/%d %d:%02d:%02d - %s exited, restarting...\n",
t.wMonth, t.wDay, t.wYear, t.wHour, t.wMinute, t.wSecond, label);
}
}
}
return 0;
}
int _tmain(int argc, _TCHAR* argv[]) {
SetConsoleCtrlHandler((PHANDLER_ROUTINE)CtrlHandler, TRUE);
LoadSettings();
if (startup_delay) {
printf("Waiting for statup delay...\n");
for (int seconds = 0; seconds < startup_delay && !must_exit; seconds++)
Sleep(1000);
}
int thread_count = launch_processes.GetCount();
if (thread_count) {
printf("Spawning %d processes...\n", thread_count);
for (int i = 0; i < thread_count; i++) {
HANDLE thread = CreateThread(NULL, 0, LaunchProcess, (LPVOID)i, 0, NULL);
CloseHandle(thread);
}
}
printf("Monitoring adb for hangs...\n");
SetAdbAffinity();
while (!must_exit) {
for (int seconds = 0; seconds < 60 && !must_exit; seconds++)
Sleep(1000);
if (IsAdbHung()) {
KillAdb();
IsAdbHung();
SetAdbAffinity();
}
}
return 0;
}
bool IsAdbHung() {
bool is_hung = false;
SECURITY_ATTRIBUTES sa;
// Set the bInheritHandle flag so pipe handles are inherited.
sa.nLength = sizeof(SECURITY_ATTRIBUTES);
sa.bInheritHandle = TRUE;
sa.lpSecurityDescriptor = NULL;
HANDLE stdout_read = NULL;
HANDLE stdout_write = NULL;
HANDLE stderr_read = NULL;
HANDLE stderr_write = NULL;
CStringA std_out, std_err;
// Create a pipe for the child process's STDERR.
if (CreatePipe(&stderr_read, &stderr_write, &sa, 0) &&
CreatePipe(&stdout_read, &stdout_write, &sa, 0)) {
SetHandleInformation(stderr_read, HANDLE_FLAG_INHERIT, 0);
SetHandleInformation(stdout_read, HANDLE_FLAG_INHERIT, 0);
// launch the adb command and wait for it to exit
PROCESS_INFORMATION pi;
STARTUPINFO si;
ZeroMemory(&pi, sizeof(pi));
ZeroMemory(&si, sizeof(si));
si.cb = sizeof(si);
si.hStdError = stderr_write;
si.hStdOutput = stdout_write;
si.dwFlags = STARTF_USESTDHANDLES;
TCHAR command[MAX_PATH];
lstrcpy(command, _T("adb devices"));
if (CreateProcess(NULL, command, NULL, NULL, TRUE,
CREATE_NO_WINDOW, NULL, NULL, &si, &pi)) {
if (pi.hProcess)
WaitForSingleObject(pi.hProcess, 60000);
// read all of the stderr and stdout data
char buff[4097];
DWORD bytes = 0;
while (PeekNamedPipe(stdout_read, buff, sizeof(buff), &bytes, NULL, NULL) &&
bytes &&
ReadFile(stdout_read, buff, sizeof(buff) - 1, &bytes, NULL) &&
bytes) {
buff[bytes] = 0;
std_out += buff;
}
while (PeekNamedPipe(stderr_read, buff, sizeof(buff), &bytes, NULL, NULL) &&
bytes &&
ReadFile(stderr_read, buff, sizeof(buff) - 1, &bytes, NULL) &&
bytes) {
buff[bytes] = 0;
std_err += buff;
}
CloseHandle(pi.hProcess);
CloseHandle(pi.hThread);
}
}
// Close the pipe handles
if (stdout_read)
CloseHandle(stdout_read);
if (stdout_write)
CloseHandle(stdout_write);
if (stderr_read)
CloseHandle(stderr_read);
if (stderr_write)
CloseHandle(stderr_write);
if (std_err.GetLength())
is_hung = true;
return is_hung;
}
void KillAdb() {
SYSTEMTIME t;
GetLocalTime(&t);
printf("%d/%d/%d %d:%02d:%02d - hang detected\n",
t.wMonth, t.wDay, t.wYear, t.wHour, t.wMinute, t.wSecond);
WTS_PROCESS_INFO * proc = NULL;
DWORD count = 0;
if (WTSEnumerateProcesses(WTS_CURRENT_SERVER_HANDLE, 0, 1, &proc ,&count)) {
for (DWORD i = 0; i < count; i++) {
TCHAR * process = PathFindFileName(proc[i].pProcessName);
if (!lstrcmpi(process, _T("adb.exe"))) {
HANDLE process_handle = OpenProcess(PROCESS_TERMINATE, FALSE,
proc[i].ProcessId);
if (process_handle) {
TerminateProcess(process_handle, 0);
CloseHandle(process_handle);
}
}
}
if (proc)
WTSFreeMemory(proc);
}
}
void SetAdbAffinity() {
WTS_PROCESS_INFO * proc = NULL;
DWORD count = 0;
if (WTSEnumerateProcesses(WTS_CURRENT_SERVER_HANDLE, 0, 1, &proc ,&count)) {
for (DWORD i = 0; i < count; i++) {
TCHAR * process = PathFindFileName(proc[i].pProcessName);
if (!lstrcmpi(process, _T("adb.exe"))) {
HANDLE process_handle = OpenProcess(PROCESS_SET_INFORMATION, FALSE,
proc[i].ProcessId);
if (process_handle) {
SetProcessAffinityMask(process_handle, 1);
CloseHandle(process_handle);
}
}
}
if (proc)
WTSFreeMemory(proc);
}
}<|endoftext|> |
<commit_before>#include "iApp.h"
#include "bbcConfig.h"
#include "Poco/DateTimeParser.h"
string iApp::app_name = "iApp";
string iApp::app_version = "1.0.0";
// Archive (compress) logs that are 1MB
#define IAPP_DEF_LOG_SIZE_ARCH_KB_MAX 1024
using namespace bbc::utils;
iApp::iApp(string _app_name, string _app_version, bool _log_to_file, bool _archive_logs) {
if(!Config::instance()->load_success){
ofLogError("Config XML failed to load") << Config::data_file_path;
}else{
ofLogNotice("Config XML loaded!") << Config::data_file_path;
}
auto_hide_cursor = true;
cursor_visible = true;
keep_cursor_hidden = false; // a lock
header_logged = false;
cursor_duration_ms = 3000;
if(_app_name != "") app_name = _app_name;
if(_app_version != "") app_version = _app_version;
log_to_file = _log_to_file;
archive_logs = _archive_logs;
if(CONFIG_GET("log", "to_file", false)) {
if(!log_to_file) { // not already setup
log_to_file = true;
logSetup(CONFIG_GET("log", "append", true));
logHeader(); // relog header so it gets to file
}
}else{
logSetup();
logHeader();
}
ofSetLogLevel((ofLogLevel)CONFIG_GET("log", "level", (int)OF_LOG_NOTICE));
if(Config::instance()->attributeExists("config:window", "fps")) {
int fps = CONFIG_GET("window", "fps", 60);
ofSetFrameRate(fps);
ofLogNotice("iApp set") << "fps=" << fps;
}
bool vs = CONFIG_GET("window", "vertical_sync", true);
ofSetVerticalSync(vs);
ofLogNotice("iApp set") << "vertical_sync=" << vs;
// NOTE: to get full fps, dont specify fps and set vertical_sync="0"
if(CONFIG_GET("window", "fullscreen", true)){
ofToggleFullscreen();
}
cursor_timer = ofGetElapsedTimeMillis() + cursor_duration_ms;
if(CONFIG_GET("mouse", "hide", false)) { // override auto hide cursor
auto_hide_cursor = false;
hideCursor(true);
}
auto_shutdown = CONFIG_GET("shutdown", "enabled", false);
if(auto_shutdown) { // override auto hide cursor
string time_str = CONFIG_GET("shutdown", "time", "20:20");
ofLogNotice("auto_shutdown setting up with time") << time_str;
Poco::LocalDateTime now;
int time_zone_dif = now.tzd();
Poco::DateTime t = Poco::DateTimeParser::parse("%H:%M:%S", time_str, time_zone_dif);
Poco::LocalDateTime next(now.year(), now.month(), now.day(), t.hour(), t.minute(), t.second());
if(next < now) {
ofLogNotice("Shutdown time already elapsed for today making it for tomorrow");
// Add a day
Poco::Timespan dif(0, 24, 0, 0, 0);
shutdown_time = next + dif;
}else{
shutdown_time = next;
}
}
}
void iApp::setup() {
ofBaseApp::setup();
ofLogNotice("iApp:setup");
// NOT SURE THIS WILL WORK?
}
void iApp::draw(ofEventArgs & args) {
ofBaseApp::draw(args);
}
void iApp::update(ofEventArgs& args) {
ofBaseApp::update(args);
if(auto_hide_cursor) cursorCheck();
if(keep_cursor_hidden) hideCursor();
if(auto_shutdown) {
Poco::LocalDateTime now;
if(now > shutdown_time) {
ofLogWarning("iApp: AUTO SHUTDOWN was scheduled for now. Terminating app.");
ofExit();
}
}
}
void iApp::cursorCheck() {
// cout << "check cursor " << ofGetElapsedTimeMillis() << endl;
if(cursor_visible) {
if(ofGetElapsedTimeMillis() >= cursor_timer) { // its been still long enough to auto hide it
hideCursor();
// cout << " hideCursor " << ofGetElapsedTimeMillis() << endl;
cursor_visible = false;
}
}
}
void iApp::hideCursor(bool permanent) {
// Cursor show and hide not working on mac in 0.8.0 : using workaroud from http://forum.openframeworks.cc/t/ofhidecursor-not-working-on-osx-10-8-v0-8-0/13379/3
// Is working in 0.8.1 so do a OF compile check here
#ifdef __APPLE__
CGDisplayHideCursor(NULL);
#else
ofHideCursor();
#endif
if(permanent) keep_cursor_hidden = true;
}
void iApp::showCursor() {
#ifdef __APPLE__
CGDisplayShowCursor(NULL);
#else
ofShowCursor();
#endif
if(keep_cursor_hidden) keep_cursor_hidden = false;
}
void iApp::cursorUpdate() {
// cout << "cursorUpdate " << ofGetElapsedTimeMillis() << endl;
if(!cursor_visible) {
cursor_visible = true;
showCursor();
}
cursor_timer = ofGetElapsedTimeMillis() + cursor_duration_ms; // reset timer hid it after 3 seconds of no movement
}
//------------------------------------------------------------------------------------------------------
void iApp::keyPressed(ofKeyEventArgs & key) {
ofBaseApp::keyPressed(key);
}
void iApp::keyReleased(ofKeyEventArgs & key) {
ofBaseApp::keyReleased(key);
}
//------------------------------------------------------------------------------------------------------
void iApp::mouseMoved( ofMouseEventArgs & mouse ) {
ofBaseApp::mouseMoved(mouse);
if(auto_hide_cursor) cursorUpdate();
}
void iApp::mouseDragged( ofMouseEventArgs & mouse ) {
ofBaseApp::mouseDragged(mouse);
if(auto_hide_cursor) cursorUpdate();
}
void iApp::mousePressed( ofMouseEventArgs & mouse ) {
ofBaseApp::mousePressed(mouse);
if(auto_hide_cursor) cursorUpdate();
}
void iApp::mouseReleased( ofMouseEventArgs & mouse ) {
ofBaseApp::mouseReleased(mouse);
}
//------------------------------------------------------------------------------------------------------
void iApp::windowResized(ofResizeEventArgs & resize) {
ofBaseApp::windowResized(resize);
}
void iApp::dragEvent(ofDragInfo dragInfo) {
ofBaseApp::dragEvent(dragInfo);
}
void iApp::gotMessage(ofMessage msg){
ofBaseApp::gotMessage(msg);
}
void iApp::exit(ofEventArgs & args) {
ofBaseApp::exit(args);
logFooter();
ofLogToConsole(); // reset logging to file
}
//------------------------------------------------------------------------------------------------------
void iApp::drawCalibration(int alpha) {
/*
Draw a screen calibration graphic, useful for projection calibration,
*/
ofPushStyle();
float sw = 2.0f;
ofSetLineWidth(sw);
float w = ofGetWidth();
float h = ofGetHeight();
float cx = w / 2.0;
float cy = h / 2.0;
float hsw = sw / 2.0;
ofSetCircleResolution(36);
ofSetColor(255, alpha);
ofNoFill();
// border
ofRectMode(OF_RECTMODE_CORNER);
ofRect(hsw, hsw, w-sw, h-sw);
// diagonal lines
ofLine(hsw, hsw, w+hsw, h-hsw);
ofLine(-hsw, h-hsw, w-hsw, hsw);
// centre lines
ofLine(cx, 0, cx, h);
ofLine(0, cy, w, cy);
// horizontal 1/4 lines
ofLine(0, h/4, w, h/4);
ofLine(0, h-h/4, w, h-h/4);
// Draw centre rect & circle
ofRectMode(OF_RECTMODE_CENTER);
float dim = min(w, h) * .66f;
ofEllipse(cx, cy, dim, dim);
ofSetLineWidth(1.0f);
// Draw circles at the sides
int n = 8;
float mini_rad = h / n;
float y;
for(int i = 0; i<n-1; i++) {
y = (mini_rad)+(i*mini_rad);
int c = i % 4;
switch(c) {
case 0: ofSetColor(255, alpha); break;
case 1: ofSetColor(255,0,0, alpha); break;
case 2: ofSetColor(0,255,0, alpha); break;
case 3: ofSetColor(0,0,255, alpha); break;
}
ofEllipse(0, y, mini_rad, mini_rad); // LHS
ofEllipse(w, y, mini_rad, mini_rad); // RHS
}
// Draw more comprehensive grid
// do this at the ratio of the screen?
// TODO: make the ratio dynamic too reading getWidth and getHeight
float wc = 16.0f;
float hc = 9.0f;
float grid_x = w / wc;
float grid_y = h / hc;
ofSetColor(255, alpha);
// vertical lines
for(int col = 1; col < wc; col++) {
int gx = round(col * grid_x);
ofLine(gx, 0, gx, h);
}
// horizontal lines
for(int row = 1; row < hc; row++) {
int gy = round(row * grid_y);
ofLine(0, gy, w, gy);
}
ofPopStyle();
}
//-----------------------------------------------------------------------------
void iApp::logSetup(bool appending) {
if(log_to_file) {
string log_name = app_name + ".log";
if(archive_logs) {
ofFile f("logs/" + log_name);
if(f.exists()) {
uint64_t sz_kb = f.getSize() / 1024;
if(sz_kb >= IAPP_DEF_LOG_SIZE_ARCH_KB_MAX) {
ofFile parent_dir(f.getEnclosingDirectory());
#if defined(TARGET_OSX)
string zip_cmd = "gzip '" + f.getAbsolutePath() + "'";
ofLogNotice("ARCHIVING LOG with") << zip_cmd;
string zip_result = ofSystem(zip_cmd);
ofLogNotice("zip_result") << zip_result;
string rename_cmd = "mv '" + f.getAbsolutePath() + ".gz' '" + parent_dir.getAbsolutePath() + "/" + ofGetTimestampString("%Y-%m-%d-%H-%M-%S") + "_" + app_name + ".log.gz'";
ofLogNotice("RENAMING LOG ARCHIVE with") << rename_cmd;
string rename_result = ofSystem(rename_cmd);
ofLogNotice("rename_result") << rename_result;
#endif
#if defined(TARGET_WIN32)
// TODO: Win could use: win7 cmd option: http://superuser.com/questions/110991/can-you-zip-a-file-from-the-command-prompt-using-only-windows-built-in-capabili
#endif
}
}
}
ofLogToFile("logs/" + log_name, appending);
}
//ofSetLogLevel(OF_LOG_VERBOSE);
}
void iApp::logHeader() {
ofLogNotice("");
ofLogNotice("--------------------------------------");
ofLogNotice("--- START ") << app_name << " app v" << app_version << " @ " << ofGetTimestampString("%H:%M:%S %d-%m-%Y");
ofLogNotice("--- ") << "oF:" << OF_VERSION_MAJOR << "." << OF_VERSION_MINOR << "." << OF_VERSION_PATCH << " platform:" << ofGetTargetPlatform();
// TODO: log OS version and name + opengl properties, free gpu memory?
ofLogNotice("--------------------------------------");
header_logged = true;
}
void iApp::logFooter() {
ofLogNotice("--------------------------------------");
ofLogNotice("--- STOP ") << app_name << " app v" << app_version << " @ " << ofGetTimestampString("%H:%M:%S %d-%m-%Y");
ofLogNotice("--------------------------------------");
}
//-----------------------------------------------------------------------------<commit_msg>iApp implemented external config setting log level<commit_after>#include "iApp.h"
#include "bbcConfig.h"
#include "Poco/DateTimeParser.h"
string iApp::app_name = "iApp";
string iApp::app_version = "1.0.0";
// Archive (compress) logs that are 1MB
#define IAPP_DEF_LOG_SIZE_ARCH_KB_MAX 1024
using namespace bbc::utils;
iApp::iApp(string _app_name, string _app_version, bool _log_to_file, bool _archive_logs) {
if(!Config::instance()->load_success){
ofLogError("Config XML failed to load") << Config::data_file_path;
}else{
ofLogNotice("Config XML loaded!") << Config::data_file_path;
}
auto_hide_cursor = true;
cursor_visible = true;
keep_cursor_hidden = false; // a lock
header_logged = false;
cursor_duration_ms = 3000;
if(_app_name != "") app_name = _app_name;
if(_app_version != "") app_version = _app_version;
log_to_file = _log_to_file;
archive_logs = _archive_logs;
if(CONFIG_GET("log", "to_file", false)) {
if(!log_to_file) { // not already setup
log_to_file = true;
logSetup(CONFIG_GET("log", "append", true));
logHeader(); // relog header so it gets to file
}
}else{
logSetup();
logHeader();
}
ofSetLogLevel((ofLogLevel)CONFIG_GET("log", "level", (int)OF_LOG_NOTICE));
if(Config::instance()->attributeExists("config:window", "fps")) {
int fps = CONFIG_GET("window", "fps", 60);
ofSetFrameRate(fps);
ofLogNotice("iApp set") << "fps=" << fps;
}
bool vs = CONFIG_GET("window", "vertical_sync", true);
ofSetVerticalSync(vs);
ofLogNotice("iApp set") << "vertical_sync=" << vs;
// NOTE: to get full fps, dont specify fps and set vertical_sync="0"
if(CONFIG_GET("window", "fullscreen", true)){
ofToggleFullscreen();
}
cursor_timer = ofGetElapsedTimeMillis() + cursor_duration_ms;
if(CONFIG_GET("mouse", "hide", false)) { // override auto hide cursor
auto_hide_cursor = false;
hideCursor(true);
}
auto_shutdown = CONFIG_GET("shutdown", "enabled", false);
if(auto_shutdown) { // override auto hide cursor
string time_str = CONFIG_GET("shutdown", "time", "20:20");
ofLogNotice("auto_shutdown setting up with time") << time_str;
Poco::LocalDateTime now;
int time_zone_dif = now.tzd();
Poco::DateTime t = Poco::DateTimeParser::parse("%H:%M:%S", time_str, time_zone_dif);
Poco::LocalDateTime next(now.year(), now.month(), now.day(), t.hour(), t.minute(), t.second());
if(next < now) {
ofLogNotice("Shutdown time already elapsed for today making it for tomorrow");
// Add a day
Poco::Timespan dif(0, 24, 0, 0, 0);
shutdown_time = next + dif;
}else{
shutdown_time = next;
}
}
}
void iApp::setup() {
ofBaseApp::setup();
ofLogNotice("iApp:setup");
// NOT SURE THIS WILL WORK?
}
void iApp::draw(ofEventArgs & args) {
ofBaseApp::draw(args);
}
void iApp::update(ofEventArgs& args) {
ofBaseApp::update(args);
if(auto_hide_cursor) cursorCheck();
if(keep_cursor_hidden) hideCursor();
if(auto_shutdown) {
Poco::LocalDateTime now;
if(now > shutdown_time) {
ofLogWarning("iApp: AUTO SHUTDOWN was scheduled for now. Terminating app.");
ofExit();
}
}
}
void iApp::cursorCheck() {
// cout << "check cursor " << ofGetElapsedTimeMillis() << endl;
if(cursor_visible) {
if(ofGetElapsedTimeMillis() >= cursor_timer) { // its been still long enough to auto hide it
hideCursor();
// cout << " hideCursor " << ofGetElapsedTimeMillis() << endl;
cursor_visible = false;
}
}
}
void iApp::hideCursor(bool permanent) {
// Cursor show and hide not working on mac in 0.8.0 : using workaroud from http://forum.openframeworks.cc/t/ofhidecursor-not-working-on-osx-10-8-v0-8-0/13379/3
// Is working in 0.8.1 so do a OF compile check here
#ifdef __APPLE__
CGDisplayHideCursor(NULL);
#else
ofHideCursor();
#endif
if(permanent) keep_cursor_hidden = true;
}
void iApp::showCursor() {
#ifdef __APPLE__
CGDisplayShowCursor(NULL);
#else
ofShowCursor();
#endif
if(keep_cursor_hidden) keep_cursor_hidden = false;
}
void iApp::cursorUpdate() {
// cout << "cursorUpdate " << ofGetElapsedTimeMillis() << endl;
if(!cursor_visible) {
cursor_visible = true;
showCursor();
}
cursor_timer = ofGetElapsedTimeMillis() + cursor_duration_ms; // reset timer hid it after 3 seconds of no movement
}
//------------------------------------------------------------------------------------------------------
void iApp::keyPressed(ofKeyEventArgs & key) {
ofBaseApp::keyPressed(key);
}
void iApp::keyReleased(ofKeyEventArgs & key) {
ofBaseApp::keyReleased(key);
}
//------------------------------------------------------------------------------------------------------
void iApp::mouseMoved( ofMouseEventArgs & mouse ) {
ofBaseApp::mouseMoved(mouse);
if(auto_hide_cursor) cursorUpdate();
}
void iApp::mouseDragged( ofMouseEventArgs & mouse ) {
ofBaseApp::mouseDragged(mouse);
if(auto_hide_cursor) cursorUpdate();
}
void iApp::mousePressed( ofMouseEventArgs & mouse ) {
ofBaseApp::mousePressed(mouse);
if(auto_hide_cursor) cursorUpdate();
}
void iApp::mouseReleased( ofMouseEventArgs & mouse ) {
ofBaseApp::mouseReleased(mouse);
}
//------------------------------------------------------------------------------------------------------
void iApp::windowResized(ofResizeEventArgs & resize) {
ofBaseApp::windowResized(resize);
}
void iApp::dragEvent(ofDragInfo dragInfo) {
ofBaseApp::dragEvent(dragInfo);
}
void iApp::gotMessage(ofMessage msg){
ofBaseApp::gotMessage(msg);
}
void iApp::exit(ofEventArgs & args) {
ofBaseApp::exit(args);
logFooter();
ofLogToConsole(); // reset logging to file
}
//------------------------------------------------------------------------------------------------------
void iApp::drawCalibration(int alpha) {
/*
Draw a screen calibration graphic, useful for projection calibration,
*/
ofPushStyle();
float sw = 2.0f;
ofSetLineWidth(sw);
float w = ofGetWidth();
float h = ofGetHeight();
float cx = w / 2.0;
float cy = h / 2.0;
float hsw = sw / 2.0;
ofSetCircleResolution(36);
ofSetColor(255, alpha);
ofNoFill();
// border
ofRectMode(OF_RECTMODE_CORNER);
ofRect(hsw, hsw, w-sw, h-sw);
// diagonal lines
ofLine(hsw, hsw, w+hsw, h-hsw);
ofLine(-hsw, h-hsw, w-hsw, hsw);
// centre lines
ofLine(cx, 0, cx, h);
ofLine(0, cy, w, cy);
// horizontal 1/4 lines
ofLine(0, h/4, w, h/4);
ofLine(0, h-h/4, w, h-h/4);
// Draw centre rect & circle
ofRectMode(OF_RECTMODE_CENTER);
float dim = min(w, h) * .66f;
ofEllipse(cx, cy, dim, dim);
ofSetLineWidth(1.0f);
// Draw circles at the sides
int n = 8;
float mini_rad = h / n;
float y;
for(int i = 0; i<n-1; i++) {
y = (mini_rad)+(i*mini_rad);
int c = i % 4;
switch(c) {
case 0: ofSetColor(255, alpha); break;
case 1: ofSetColor(255,0,0, alpha); break;
case 2: ofSetColor(0,255,0, alpha); break;
case 3: ofSetColor(0,0,255, alpha); break;
}
ofEllipse(0, y, mini_rad, mini_rad); // LHS
ofEllipse(w, y, mini_rad, mini_rad); // RHS
}
// Draw more comprehensive grid
// do this at the ratio of the screen?
// TODO: make the ratio dynamic too reading getWidth and getHeight
float wc = 16.0f;
float hc = 9.0f;
float grid_x = w / wc;
float grid_y = h / hc;
ofSetColor(255, alpha);
// vertical lines
for(int col = 1; col < wc; col++) {
int gx = round(col * grid_x);
ofLine(gx, 0, gx, h);
}
// horizontal lines
for(int row = 1; row < hc; row++) {
int gy = round(row * grid_y);
ofLine(0, gy, w, gy);
}
ofPopStyle();
}
//-----------------------------------------------------------------------------
void iApp::logSetup(bool appending) {
if(log_to_file) {
string log_name = app_name + ".log";
if(archive_logs) {
ofFile f("logs/" + log_name);
if(f.exists()) {
uint64_t sz_kb = f.getSize() / 1024;
if(sz_kb >= IAPP_DEF_LOG_SIZE_ARCH_KB_MAX) {
ofFile parent_dir(f.getEnclosingDirectory());
#if defined(TARGET_OSX)
string zip_cmd = "gzip '" + f.getAbsolutePath() + "'";
ofLogNotice("ARCHIVING LOG with") << zip_cmd;
string zip_result = ofSystem(zip_cmd);
ofLogNotice("zip_result") << zip_result;
string rename_cmd = "mv '" + f.getAbsolutePath() + ".gz' '" + parent_dir.getAbsolutePath() + "/" + ofGetTimestampString("%Y-%m-%d-%H-%M-%S") + "_" + app_name + ".log.gz'";
ofLogNotice("RENAMING LOG ARCHIVE with") << rename_cmd;
string rename_result = ofSystem(rename_cmd);
ofLogNotice("rename_result") << rename_result;
#endif
#if defined(TARGET_WIN32)
// TODO: Win could use: win7 cmd option: http://superuser.com/questions/110991/can-you-zip-a-file-from-the-command-prompt-using-only-windows-built-in-capabili
#endif
}
}
}
ofLogToFile("logs/" + log_name, appending);
}
int level = CONFIG_GET("log", "level", 1);
// VERBOSE = 0 NOTICE = 1 WARNING = 2 ERROR = 3 FATAL_ERROR = 4 SILENT = 5
if(level >= 0 && level <= (int)OF_LOG_SILENT) {
ofSetLogLevel( (ofLogLevel)level );
}
}
void iApp::logHeader() {
ofLogNotice("");
ofLogNotice("--------------------------------------");
ofLogNotice("--- START ") << app_name << " app v" << app_version << " @ " << ofGetTimestampString("%H:%M:%S %d-%m-%Y");
ofLogNotice("--- ") << "oF:" << OF_VERSION_MAJOR << "." << OF_VERSION_MINOR << "." << OF_VERSION_PATCH << " platform:" << ofGetTargetPlatform();
// TODO: log OS version and name + opengl properties, free gpu memory?
ofLogNotice("--------------------------------------");
header_logged = true;
}
void iApp::logFooter() {
ofLogNotice("--------------------------------------");
ofLogNotice("--- STOP ") << app_name << " app v" << app_version << " @ " << ofGetTimestampString("%H:%M:%S %d-%m-%Y");
ofLogNotice("--------------------------------------");
}
//-----------------------------------------------------------------------------<|endoftext|> |
<commit_before>#include <iostream>
void imageToGround(double sample, double line);
// Simple application to test the CSM imageToGround() method for MDIS-NAC
// i.e. prototyping
int main() {
double sample = 512.0;
double line = 512.0;
std::cout << "Enter a sample: ";
std::cin >> sample;
std::cout << "Enter a line: ";
std::cin >> line;
imageToGround(sample, line);
return 0;
}
void imageToGround(double sample, double line) {
// Convert image sample/line to focal plane x/y
// // Perform affine transformation to get from sample/line to x/y (mm)
const double transX[3] = {0.0, 0.014, 0.0}; // JSON transx
const double transY[3] = {0.0, 0.0, 0.014}; // JSON transy
// center the sample line
// imgSamps / 2, imgLines / 2: 1024x1024
sample -= 512.0; // ISD needs a center sample in CSM coord
line -= 512.0; // ISD needs a center line in CSM coord (.5 .5 pixel centers)
double focalPlaneX = transX[0] + (transX[1] * sample)
+ (transX[2] * line);
double focalPlaneY = transY[0] + (transY[1] * sample)
+ (transY[2] * line);
std::cout << "\nFOCAL PLANE (X, Y) mm: (" << focalPlaneX << ", " << focalPlaneY << ")\n";
//
}
<commit_msg>Don't PR: update to image to ground prototyping to get X,Y,Z (incorrect).<commit_after>#include <cmath>
#include <iostream>
#include <vector>
void imageToGround(double sample, double line);
// Simple application to test the CSM imageToGround() method for MDIS-NAC
// i.e. prototyping
int main() {
double sample = 512.0;
double line = 512.0;
std::cout << "Enter a sample: ";
std::cin >> sample;
std::cout << "Enter a line: ";
std::cin >> line;
imageToGround(sample, line);
return 0;
}
void imageToGround(double sample, double line) {
// Convert image sample/line to focal plane x/y
// // Perform affine transformation to get from sample/line to x/y (mm)
const double transX[3] = {0.0, 0.014, 0.0}; // JSON transx
const double transY[3] = {0.0, 0.0, 0.014}; // JSON transy
// center the sample line
// imgSamps / 2, imgLines / 2: 1024x1024
sample -= 512.0; // ISD needs a center sample in CSM coord
line -= 512.0; // ISD needs a center line in CSM coord (.5 .5 pixel centers)
double focalPlaneX = transX[0] + (transX[1] * sample)
+ (transX[2] * line);
double focalPlaneY = transY[0] + (transY[1] * sample)
+ (transY[2] * line);
std::cout << "\nFOCAL PLANE (X, Y) mm: (" << focalPlaneX << ", " << focalPlaneY << ")\n";
// Rotation stuff
// angles grabbed from isd (generated from mdis2isd)
const double omega = 2.892112982708664;
const double phi = 3.263192693345268;
const double kappa = 149.1628863008221;
// Rotation matrix grabbed from Mikhail's "Introduction to Modern Photogrammetry"
std::vector<double> rotationMatrix(9);
rotationMatrix[0] = cos(phi) * cos(kappa);
rotationMatrix[1] = cos(omega) * sin(kappa) + sin(omega) * sin(phi) * cos(kappa);
rotationMatrix[2] = sin(omega) * sin(kappa) - cos(omega) * sin(phi) * cos(kappa);
rotationMatrix[3] = -1 * cos(phi) * sin(kappa);
rotationMatrix[4] = cos(omega) * cos(kappa) - sin(omega) * sin(phi) * sin(kappa);
rotationMatrix[5] = sin(omega) * cos(kappa) + cos(omega) * sin(phi) * sin(kappa);
rotationMatrix[6] = sin(phi);
rotationMatrix[7] = -1 * sin(omega) * cos(phi);
rotationMatrix[8] = cos(omega) * cos(phi);
// Note that elevation will be the height parameter in CSM's imageToGround.
// For now, assume that ellipsoid has no terrain features
double elevation = 6051800; // mercury ellipsoid
double spacecraftZ = 8536481.287414147; // SENSOR Z from isd
double spacecraftAltitude = elevation - spacecraftZ;
double z = spacecraftAltitude; // temp
double spacecraftX = -6683432.694790688;
double spacecraftY = -27264735.61516516;
double f = 549.3027347624796; // focal length
double x =
( spacecraftAltitude * rotationMatrix[0] * (sample - focalPlaneX) + rotationMatrix[3] * (line - focalPlaneY) + rotationMatrix[6] * (-1 * f) ) /
( rotationMatrix[2] * (sample - focalPlaneX) + rotationMatrix[5] * (line - focalPlaneY) + rotationMatrix[8] * (-1 * f) )
+ spacecraftX;
double y =
( spacecraftAltitude * rotationMatrix[1] * (sample - focalPlaneX) + rotationMatrix[4] * (line - focalPlaneY) + rotationMatrix[7] * (-1 * f) ) /
( rotationMatrix[2] * (sample - focalPlaneX) + rotationMatrix[5] * (line - focalPlaneY) + rotationMatrix[8] * (-1 * f) )
+ spacecraftY;
std::cout << "\n(x, y) = (" << x/1000 << ", " << y/1000 << ", " << z/1000 << ") (km)\n";
}
<|endoftext|> |
<commit_before>/* ************************************************************************* */
/* This file is part of Shard. */
/* */
/* Shard is free software: you can redistribute it and/or modify */
/* it under the terms of the GNU Affero General Public License as */
/* published by the Free Software Foundation. */
/* */
/* This program is distributed in the hope that it will be useful, */
/* but WITHOUT ANY WARRANTY; without even the implied warranty of */
/* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the */
/* GNU Affero General Public License for more details. */
/* */
/* You should have received a copy of the GNU Affero General Public License */
/* along with this program. If not, see <http://www.gnu.org/licenses/>. */
/* ************************************************************************* */
// Declaration
#include "shard/ast/Stmt.hpp"
// Shard
#include "shard/Assert.hpp"
#include "shard/ast/Expr.hpp"
#include "shard/ast/Decl.hpp"
/* ************************************************************************* */
namespace shard {
inline namespace v1 {
namespace ast {
/* ************************************************************************* */
Stmt::~Stmt() = default;
/* ************************************************************************* */
Stmt::Stmt(StmtKind kind, SourceRange range) noexcept
: LocationInfo(moveValue(range))
, m_kind(kind)
{
// Nothing to do
}
/* ************************************************************************* */
ExprStmt::ExprStmt(UniquePtr<Expr> expr, SourceRange range) noexcept
: Stmt(StmtKind::Expr, moveValue(range))
, m_expr(moveValue(expr))
{
// Nothing to do
}
/* ************************************************************************* */
ExprStmt::~ExprStmt() = default;
/* ************************************************************************* */
void ExprStmt::setExpr(UniquePtr<Expr> expr) noexcept
{
SHARD_ASSERT(expr);
m_expr = moveValue(expr);
}
/* ************************************************************************* */
DeclStmt::DeclStmt(UniquePtr<Decl> decl, SourceRange range) noexcept
: Stmt(StmtKind::Decl, moveValue(range))
, m_decl(moveValue(decl))
{
SHARD_ASSERT(m_decl);
}
/* ************************************************************************* */
DeclStmt::~DeclStmt() = default;
/* ************************************************************************* */
void DeclStmt::setDecl(UniquePtr<Decl> decl) noexcept
{
SHARD_ASSERT(decl);
m_decl = moveValue(decl);
}
/* ************************************************************************* */
CompoundStmt::CompoundStmt(PtrDynamicArray<Stmt> stmts, SourceRange range) noexcept
: Stmt(StmtKind::Compound, moveValue(range))
, StmtContainer(moveValue(stmts))
{
// Nothing to do
}
/* ************************************************************************* */
IfStmt::IfStmt(UniquePtr<Expr> condExpr, UniquePtr<Stmt> thenStmt, UniquePtr<Stmt> elseStmt, SourceRange range) noexcept
: Stmt(StmtKind::If, moveValue(range))
, m_condExpr(moveValue(condExpr))
, m_thenStmt(moveValue(thenStmt))
, m_elseStmt(moveValue(elseStmt))
{
SHARD_ASSERT(m_condExpr);
SHARD_ASSERT(m_thenStmt);
}
/* ************************************************************************* */
IfStmt::~IfStmt() = default;
/* ************************************************************************* */
void IfStmt::setCondExpr(UniquePtr<Expr> expr) noexcept
{
SHARD_ASSERT(expr);
m_condExpr = moveValue(expr);
}
/* ************************************************************************* */
void IfStmt::setThenStmt(UniquePtr<Stmt> stmt) noexcept
{
SHARD_ASSERT(stmt);
m_thenStmt = moveValue(stmt);
}
/* ************************************************************************* */
void IfStmt::setElseStmt(UniquePtr<Stmt> stmt) noexcept
{
m_elseStmt = moveValue(stmt);
}
/* ************************************************************************* */
WhileStmt::WhileStmt(UniquePtr<Expr> condExpr, UniquePtr<Stmt> bodyStmt, SourceRange range) noexcept
: Stmt(StmtKind::While, moveValue(range))
, m_condExpr(moveValue(condExpr))
, m_bodyStmt(moveValue(bodyStmt))
{
SHARD_ASSERT(m_condExpr);
SHARD_ASSERT(m_bodyStmt);
}
/* ************************************************************************* */
WhileStmt::~WhileStmt() = default;
/* ************************************************************************* */
void WhileStmt::setCondExpr(UniquePtr<Expr> expr) noexcept
{
SHARD_ASSERT(expr);
m_condExpr = moveValue(expr);
}
/* ************************************************************************* */
void WhileStmt::setBodyStmt(UniquePtr<Stmt> stmt) noexcept
{
SHARD_ASSERT(stmt);
m_bodyStmt = moveValue(stmt);
}
/* ************************************************************************* */
DoWhileStmt::DoWhileStmt(UniquePtr<Expr> condExpr, UniquePtr<CompoundStmt> bodyStmt, SourceRange range) noexcept
: Stmt(StmtKind::DoWhile, moveValue(range))
, m_condExpr(moveValue(condExpr))
, m_bodyStmt(moveValue(bodyStmt))
{
SHARD_ASSERT(m_condExpr);
SHARD_ASSERT(m_bodyStmt);
}
/* ************************************************************************* */
DoWhileStmt::~DoWhileStmt() = default;
/* ************************************************************************* */
void DoWhileStmt::setCondExpr(UniquePtr<Expr> expr) noexcept
{
SHARD_ASSERT(expr);
m_condExpr = moveValue(expr);
}
/* ************************************************************************* */
void DoWhileStmt::setBodyStmt(UniquePtr<CompoundStmt> stmt) noexcept
{
SHARD_ASSERT(stmt);
m_bodyStmt = moveValue(stmt);
}
/* ************************************************************************* */
ForStmt::ForStmt(UniquePtr<Stmt> initStmt, UniquePtr<Expr> condExpr, UniquePtr<Expr> incExpr, UniquePtr<Stmt> bodyStmt, SourceRange range) noexcept
: Stmt(StmtKind::For, moveValue(range))
, m_initStmt(moveValue(initStmt))
, m_condExpr(moveValue(condExpr))
, m_incExpr(moveValue(incExpr))
, m_bodyStmt(moveValue(bodyStmt))
{
SHARD_ASSERT(m_initStmt);
SHARD_ASSERT(m_bodyStmt);
}
/* ************************************************************************* */
ForStmt::~ForStmt() = default;
/* ************************************************************************* */
void ForStmt::setInitStmt(UniquePtr<Stmt> stmt) noexcept
{
SHARD_ASSERT(stmt);
m_initStmt = moveValue(stmt);
}
/* ************************************************************************* */
void ForStmt::setCondExpr(UniquePtr<Expr> expr) noexcept
{
SHARD_ASSERT(expr);
m_condExpr = moveValue(expr);
}
/* ************************************************************************* */
void ForStmt::setIncExpr(UniquePtr<Expr> expr) noexcept
{
SHARD_ASSERT(expr);
m_incExpr = moveValue(expr);
}
/* ************************************************************************* */
void ForStmt::setBodyStmt(UniquePtr<Stmt> stmt) noexcept
{
SHARD_ASSERT(stmt);
m_bodyStmt = moveValue(stmt);
}
/* ************************************************************************* */
SwitchStmt::SwitchStmt(UniquePtr<Expr> condExpr, UniquePtr<CompoundStmt> bodyStmt, SourceRange range) noexcept
: Stmt(StmtKind::Switch, moveValue(range))
, m_condExpr(moveValue(condExpr))
, m_bodyStmt(moveValue(bodyStmt))
{
SHARD_ASSERT(m_condExpr);
SHARD_ASSERT(m_bodyStmt);
}
/* ************************************************************************* */
SwitchStmt::~SwitchStmt() = default;
/* ************************************************************************* */
void SwitchStmt::setCondExpr(UniquePtr<Expr> expr) noexcept
{
SHARD_ASSERT(expr);
m_condExpr = moveValue(expr);
}
/* ************************************************************************* */
void SwitchStmt::setBodyStmt(UniquePtr<CompoundStmt> stmt) noexcept
{
SHARD_ASSERT(stmt);
m_bodyStmt = moveValue(stmt);
}
/* ************************************************************************* */
CaseStmt::CaseStmt(UniquePtr<Expr> expr, UniquePtr<Stmt> bodyStmt, SourceRange range) noexcept
: Stmt(StmtKind::Case, moveValue(range))
, m_expr(moveValue(expr))
, m_bodyStmt(moveValue(bodyStmt))
{
SHARD_ASSERT(m_expr);
}
/* ************************************************************************* */
CaseStmt::~CaseStmt() = default;
/* ************************************************************************* */
void CaseStmt::setExpr(UniquePtr<Expr> expr) noexcept
{
SHARD_ASSERT(expr);
m_expr = moveValue(expr);
}
/* ************************************************************************* */
void CaseStmt::setBodyStmt(UniquePtr<Stmt> stmt) noexcept
{
SHARD_ASSERT(stmt);
m_bodyStmt = moveValue(stmt);
}
/* ************************************************************************* */
DefaultStmt::DefaultStmt(UniquePtr<Stmt> bodyStmt, SourceRange range) noexcept
: Stmt(StmtKind::Default, moveValue(range))
, m_bodyStmt(moveValue(bodyStmt))
{
// Nothing to do
}
/* ************************************************************************* */
DefaultStmt::~DefaultStmt() = default;
/* ************************************************************************* */
void DefaultStmt::setBodyStmt(UniquePtr<Stmt> stmt) noexcept
{
SHARD_ASSERT(stmt);
m_bodyStmt = moveValue(stmt);
}
/* ************************************************************************* */
ContinueStmt::ContinueStmt(SourceRange range) noexcept
: Stmt(StmtKind::Continue, moveValue(range))
{
// Nothing to do
}
/* ************************************************************************* */
BreakStmt::BreakStmt(SourceRange range) noexcept
: Stmt(StmtKind::Break, moveValue(range))
{
// Nothing to do
}
/* ************************************************************************* */
ReturnStmt::ReturnStmt(UniquePtr<Expr> resExpr, SourceRange range) noexcept
: Stmt(StmtKind::Return, moveValue(range))
, m_resExpr(moveValue(resExpr))
{
// Nothing to do
}
/* ************************************************************************* */
ReturnStmt::~ReturnStmt() = default;
/* ************************************************************************* */
void ReturnStmt::setResExpr(UniquePtr<Expr> expr) noexcept
{
m_resExpr = moveValue(expr);
}
/* ************************************************************************* */
}
}
}
/* ************************************************************************* */
<commit_msg>removed invalid assertion<commit_after>/* ************************************************************************* */
/* This file is part of Shard. */
/* */
/* Shard is free software: you can redistribute it and/or modify */
/* it under the terms of the GNU Affero General Public License as */
/* published by the Free Software Foundation. */
/* */
/* This program is distributed in the hope that it will be useful, */
/* but WITHOUT ANY WARRANTY; without even the implied warranty of */
/* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the */
/* GNU Affero General Public License for more details. */
/* */
/* You should have received a copy of the GNU Affero General Public License */
/* along with this program. If not, see <http://www.gnu.org/licenses/>. */
/* ************************************************************************* */
// Declaration
#include "shard/ast/Stmt.hpp"
// Shard
#include "shard/Assert.hpp"
#include "shard/ast/Expr.hpp"
#include "shard/ast/Decl.hpp"
/* ************************************************************************* */
namespace shard {
inline namespace v1 {
namespace ast {
/* ************************************************************************* */
Stmt::~Stmt() = default;
/* ************************************************************************* */
Stmt::Stmt(StmtKind kind, SourceRange range) noexcept
: LocationInfo(moveValue(range))
, m_kind(kind)
{
// Nothing to do
}
/* ************************************************************************* */
ExprStmt::ExprStmt(UniquePtr<Expr> expr, SourceRange range) noexcept
: Stmt(StmtKind::Expr, moveValue(range))
, m_expr(moveValue(expr))
{
// Nothing to do
}
/* ************************************************************************* */
ExprStmt::~ExprStmt() = default;
/* ************************************************************************* */
void ExprStmt::setExpr(UniquePtr<Expr> expr) noexcept
{
SHARD_ASSERT(expr);
m_expr = moveValue(expr);
}
/* ************************************************************************* */
DeclStmt::DeclStmt(UniquePtr<Decl> decl, SourceRange range) noexcept
: Stmt(StmtKind::Decl, moveValue(range))
, m_decl(moveValue(decl))
{
SHARD_ASSERT(m_decl);
}
/* ************************************************************************* */
DeclStmt::~DeclStmt() = default;
/* ************************************************************************* */
void DeclStmt::setDecl(UniquePtr<Decl> decl) noexcept
{
SHARD_ASSERT(decl);
m_decl = moveValue(decl);
}
/* ************************************************************************* */
CompoundStmt::CompoundStmt(PtrDynamicArray<Stmt> stmts, SourceRange range) noexcept
: Stmt(StmtKind::Compound, moveValue(range))
, StmtContainer(moveValue(stmts))
{
// Nothing to do
}
/* ************************************************************************* */
IfStmt::IfStmt(UniquePtr<Expr> condExpr, UniquePtr<Stmt> thenStmt, UniquePtr<Stmt> elseStmt, SourceRange range) noexcept
: Stmt(StmtKind::If, moveValue(range))
, m_condExpr(moveValue(condExpr))
, m_thenStmt(moveValue(thenStmt))
, m_elseStmt(moveValue(elseStmt))
{
SHARD_ASSERT(m_condExpr);
SHARD_ASSERT(m_thenStmt);
}
/* ************************************************************************* */
IfStmt::~IfStmt() = default;
/* ************************************************************************* */
void IfStmt::setCondExpr(UniquePtr<Expr> expr) noexcept
{
SHARD_ASSERT(expr);
m_condExpr = moveValue(expr);
}
/* ************************************************************************* */
void IfStmt::setThenStmt(UniquePtr<Stmt> stmt) noexcept
{
SHARD_ASSERT(stmt);
m_thenStmt = moveValue(stmt);
}
/* ************************************************************************* */
void IfStmt::setElseStmt(UniquePtr<Stmt> stmt) noexcept
{
m_elseStmt = moveValue(stmt);
}
/* ************************************************************************* */
WhileStmt::WhileStmt(UniquePtr<Expr> condExpr, UniquePtr<Stmt> bodyStmt, SourceRange range) noexcept
: Stmt(StmtKind::While, moveValue(range))
, m_condExpr(moveValue(condExpr))
, m_bodyStmt(moveValue(bodyStmt))
{
SHARD_ASSERT(m_condExpr);
SHARD_ASSERT(m_bodyStmt);
}
/* ************************************************************************* */
WhileStmt::~WhileStmt() = default;
/* ************************************************************************* */
void WhileStmt::setCondExpr(UniquePtr<Expr> expr) noexcept
{
SHARD_ASSERT(expr);
m_condExpr = moveValue(expr);
}
/* ************************************************************************* */
void WhileStmt::setBodyStmt(UniquePtr<Stmt> stmt) noexcept
{
SHARD_ASSERT(stmt);
m_bodyStmt = moveValue(stmt);
}
/* ************************************************************************* */
DoWhileStmt::DoWhileStmt(UniquePtr<Expr> condExpr, UniquePtr<CompoundStmt> bodyStmt, SourceRange range) noexcept
: Stmt(StmtKind::DoWhile, moveValue(range))
, m_condExpr(moveValue(condExpr))
, m_bodyStmt(moveValue(bodyStmt))
{
SHARD_ASSERT(m_condExpr);
SHARD_ASSERT(m_bodyStmt);
}
/* ************************************************************************* */
DoWhileStmt::~DoWhileStmt() = default;
/* ************************************************************************* */
void DoWhileStmt::setCondExpr(UniquePtr<Expr> expr) noexcept
{
SHARD_ASSERT(expr);
m_condExpr = moveValue(expr);
}
/* ************************************************************************* */
void DoWhileStmt::setBodyStmt(UniquePtr<CompoundStmt> stmt) noexcept
{
SHARD_ASSERT(stmt);
m_bodyStmt = moveValue(stmt);
}
/* ************************************************************************* */
ForStmt::ForStmt(UniquePtr<Stmt> initStmt, UniquePtr<Expr> condExpr, UniquePtr<Expr> incExpr, UniquePtr<Stmt> bodyStmt, SourceRange range) noexcept
: Stmt(StmtKind::For, moveValue(range))
, m_initStmt(moveValue(initStmt))
, m_condExpr(moveValue(condExpr))
, m_incExpr(moveValue(incExpr))
, m_bodyStmt(moveValue(bodyStmt))
{
//SHARD_ASSERT(m_initStmt);
SHARD_ASSERT(m_bodyStmt);
}
/* ************************************************************************* */
ForStmt::~ForStmt() = default;
/* ************************************************************************* */
void ForStmt::setInitStmt(UniquePtr<Stmt> stmt) noexcept
{
SHARD_ASSERT(stmt);
m_initStmt = moveValue(stmt);
}
/* ************************************************************************* */
void ForStmt::setCondExpr(UniquePtr<Expr> expr) noexcept
{
SHARD_ASSERT(expr);
m_condExpr = moveValue(expr);
}
/* ************************************************************************* */
void ForStmt::setIncExpr(UniquePtr<Expr> expr) noexcept
{
SHARD_ASSERT(expr);
m_incExpr = moveValue(expr);
}
/* ************************************************************************* */
void ForStmt::setBodyStmt(UniquePtr<Stmt> stmt) noexcept
{
SHARD_ASSERT(stmt);
m_bodyStmt = moveValue(stmt);
}
/* ************************************************************************* */
SwitchStmt::SwitchStmt(UniquePtr<Expr> condExpr, UniquePtr<CompoundStmt> bodyStmt, SourceRange range) noexcept
: Stmt(StmtKind::Switch, moveValue(range))
, m_condExpr(moveValue(condExpr))
, m_bodyStmt(moveValue(bodyStmt))
{
SHARD_ASSERT(m_condExpr);
SHARD_ASSERT(m_bodyStmt);
}
/* ************************************************************************* */
SwitchStmt::~SwitchStmt() = default;
/* ************************************************************************* */
void SwitchStmt::setCondExpr(UniquePtr<Expr> expr) noexcept
{
SHARD_ASSERT(expr);
m_condExpr = moveValue(expr);
}
/* ************************************************************************* */
void SwitchStmt::setBodyStmt(UniquePtr<CompoundStmt> stmt) noexcept
{
SHARD_ASSERT(stmt);
m_bodyStmt = moveValue(stmt);
}
/* ************************************************************************* */
CaseStmt::CaseStmt(UniquePtr<Expr> expr, UniquePtr<Stmt> bodyStmt, SourceRange range) noexcept
: Stmt(StmtKind::Case, moveValue(range))
, m_expr(moveValue(expr))
, m_bodyStmt(moveValue(bodyStmt))
{
SHARD_ASSERT(m_expr);
}
/* ************************************************************************* */
CaseStmt::~CaseStmt() = default;
/* ************************************************************************* */
void CaseStmt::setExpr(UniquePtr<Expr> expr) noexcept
{
SHARD_ASSERT(expr);
m_expr = moveValue(expr);
}
/* ************************************************************************* */
void CaseStmt::setBodyStmt(UniquePtr<Stmt> stmt) noexcept
{
SHARD_ASSERT(stmt);
m_bodyStmt = moveValue(stmt);
}
/* ************************************************************************* */
DefaultStmt::DefaultStmt(UniquePtr<Stmt> bodyStmt, SourceRange range) noexcept
: Stmt(StmtKind::Default, moveValue(range))
, m_bodyStmt(moveValue(bodyStmt))
{
// Nothing to do
}
/* ************************************************************************* */
DefaultStmt::~DefaultStmt() = default;
/* ************************************************************************* */
void DefaultStmt::setBodyStmt(UniquePtr<Stmt> stmt) noexcept
{
SHARD_ASSERT(stmt);
m_bodyStmt = moveValue(stmt);
}
/* ************************************************************************* */
ContinueStmt::ContinueStmt(SourceRange range) noexcept
: Stmt(StmtKind::Continue, moveValue(range))
{
// Nothing to do
}
/* ************************************************************************* */
BreakStmt::BreakStmt(SourceRange range) noexcept
: Stmt(StmtKind::Break, moveValue(range))
{
// Nothing to do
}
/* ************************************************************************* */
ReturnStmt::ReturnStmt(UniquePtr<Expr> resExpr, SourceRange range) noexcept
: Stmt(StmtKind::Return, moveValue(range))
, m_resExpr(moveValue(resExpr))
{
// Nothing to do
}
/* ************************************************************************* */
ReturnStmt::~ReturnStmt() = default;
/* ************************************************************************* */
void ReturnStmt::setResExpr(UniquePtr<Expr> expr) noexcept
{
m_resExpr = moveValue(expr);
}
/* ************************************************************************* */
}
}
}
/* ************************************************************************* */
<|endoftext|> |
<commit_before>/*
* #%L
* %%
* Copyright (C) 2011 - 2017 BMW Car IT GmbH
* %%
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* #L%
*/
#include <memory>
#include <string>
#include <cstdint>
#include <gtest/gtest.h>
#include <gmock/gmock.h>
#include "joynr/JoynrClusterControllerRuntime.h"
#include "joynr/tests/testProvider.h"
#include "joynr/tests/testProxy.h"
#include "joynr/vehicle/GpsProxy.h"
#include "joynr/types/ProviderQos.h"
#include "joynr/Future.h"
#include "joynr/OnChangeWithKeepAliveSubscriptionQos.h"
#include "joynr/LibjoynrSettings.h"
#include "joynr/PrivateCopyAssign.h"
#include "tests/JoynrTest.h"
#include "tests/mock/MockGpsProvider.h"
#include "tests/mock/MockSubscriptionListener.h"
#include "tests/mock/MockTestProvider.h"
using namespace ::testing;
using namespace joynr;
class End2EndRPCTest : public TestWithParam< std::string >{
public:
std::string domain;
std::shared_ptr<JoynrClusterControllerRuntime> runtime;
std::shared_ptr<vehicle::GpsProvider> gpsProvider;
End2EndRPCTest() :
domain(),
runtime()
{
runtime = std::make_shared<JoynrClusterControllerRuntime>(
std::make_unique<Settings>(GetParam())
);
runtime->init();
domain = "cppEnd2EndRPCTest_Domain_" + util::createUuid();
discoveryQos.setArbitrationStrategy(DiscoveryQos::ArbitrationStrategy::HIGHEST_PRIORITY);
discoveryQos.setDiscoveryTimeoutMs(3000);
}
// Sets up the test fixture.
void SetUp(){
runtime->start();
}
// Tears down the test fixture.
void TearDown(){
bool deleteChannel = true;
runtime->stop(deleteChannel);
runtime.reset();
// Delete persisted files
std::remove(ClusterControllerSettings::DEFAULT_LOCAL_CAPABILITIES_DIRECTORY_PERSISTENCE_FILENAME().c_str());
std::remove(LibjoynrSettings::DEFAULT_MESSAGE_ROUTER_PERSISTENCE_FILENAME().c_str());
std::remove(LibjoynrSettings::DEFAULT_SUBSCRIPTIONREQUEST_PERSISTENCE_FILENAME().c_str());
std::remove(LibjoynrSettings::DEFAULT_PARTICIPANT_IDS_PERSISTENCE_FILENAME().c_str());
std::this_thread::sleep_for(std::chrono::milliseconds(550));
}
~End2EndRPCTest() = default;
protected:
joynr::DiscoveryQos discoveryQos;
private:
DISALLOW_COPY_AND_ASSIGN(End2EndRPCTest);
};
// leadsm to assert failure in GpsInProcessConnector line 185: not yet implemented in connector
TEST_P(End2EndRPCTest, call_rpc_method_and_get_expected_result)
{
auto mockProvider = std::make_shared<MockGpsProvider>();
types::ProviderQos providerQos;
std::chrono::milliseconds millisSinceEpoch =
std::chrono::duration_cast<std::chrono::milliseconds>(
std::chrono::system_clock::now().time_since_epoch());
providerQos.setPriority(millisSinceEpoch.count());
providerQos.setScope(joynr::types::ProviderScope::GLOBAL);
providerQos.setSupportsOnChangeSubscriptions(true);
std::string participantId = runtime->registerProvider<vehicle::GpsProvider>(domain, mockProvider, providerQos);
std::this_thread::sleep_for(std::chrono::milliseconds(550));
std::shared_ptr<ProxyBuilder<vehicle::GpsProxy>> gpsProxyBuilder =
runtime->createProxyBuilder<vehicle::GpsProxy>(domain);
std::int64_t qosRoundTripTTL = 40000;
std::shared_ptr<vehicle::GpsProxy> gpsProxy = gpsProxyBuilder
->setMessagingQos(MessagingQos(qosRoundTripTTL))
->setDiscoveryQos(discoveryQos)
->build();
std::shared_ptr<Future<int> >gpsFuture (gpsProxy->calculateAvailableSatellitesAsync());
gpsFuture->wait();
int expectedValue = 42; //as defined in MockGpsProvider
int actualValue;
gpsFuture->get(actualValue);
EXPECT_EQ(expectedValue, actualValue);
// This is not yet implemented in CapabilitiesClient
// runtime->unregisterProvider("Fake_ParticipantId_vehicle/gpsDummyProvider");
runtime->unregisterProvider(participantId);
}
TEST_P(End2EndRPCTest, call_void_operation)
{
auto mockProvider = std::make_shared<MockTestProvider>();
types::ProviderQos providerQos;
std::chrono::milliseconds millisSinceEpoch =
std::chrono::duration_cast<std::chrono::milliseconds>(
std::chrono::system_clock::now().time_since_epoch());
providerQos.setPriority(millisSinceEpoch.count());
providerQos.setScope(joynr::types::ProviderScope::GLOBAL);
providerQos.setSupportsOnChangeSubscriptions(true);
std::string participantId = runtime->registerProvider<tests::testProvider>(domain, mockProvider, providerQos);
std::this_thread::sleep_for(std::chrono::milliseconds(550));
std::shared_ptr<ProxyBuilder<tests::testProxy>> testProxyBuilder =
runtime->createProxyBuilder<tests::testProxy>(domain);
std::int64_t qosRoundTripTTL = 40000;
std::shared_ptr<tests::testProxy> testProxy = testProxyBuilder
->setMessagingQos(MessagingQos(qosRoundTripTTL))
->setDiscoveryQos(discoveryQos)
->build();
testProxy->voidOperation();
// EXPECT_EQ(expectedValue, gpsFuture->getValue());
// This is not yet implemented in CapabilitiesClient
// runtime->unregisterProvider("Fake_ParticipantId_vehicle/gpsDummyProvider");
runtime->unregisterProvider(participantId);
}
// tests in process subscription
TEST_P(End2EndRPCTest, _call_subscribeTo_and_get_expected_result)
{
auto mockProvider = std::make_shared<MockTestProvider>();
types::ProviderQos providerQos;
std::chrono::milliseconds millisSinceEpoch =
std::chrono::duration_cast<std::chrono::milliseconds>(
std::chrono::system_clock::now().time_since_epoch());
providerQos.setPriority(millisSinceEpoch.count());
providerQos.setScope(joynr::types::ProviderScope::GLOBAL);
providerQos.setSupportsOnChangeSubscriptions(true);
std::string participantId = runtime->registerProvider<tests::testProvider>(domain, mockProvider, providerQos);
std::this_thread::sleep_for(std::chrono::milliseconds(550));
std::shared_ptr<ProxyBuilder<tests::testProxy>> testProxyBuilder =
runtime->createProxyBuilder<tests::testProxy>(domain);
std::int64_t qosRoundTripTTL = 40000;
std::shared_ptr<tests::testProxy> testProxy = testProxyBuilder
->setMessagingQos(MessagingQos(qosRoundTripTTL))
->setDiscoveryQos(discoveryQos)
->build();
MockGpsSubscriptionListener* mockListener = new MockGpsSubscriptionListener();
std::shared_ptr<ISubscriptionListener<types::Localisation::GpsLocation> > subscriptionListener(
mockListener);
EXPECT_CALL(*mockListener, onReceive(A<const types::Localisation::GpsLocation&>()))
.Times(AtLeast(2));
auto subscriptionQos = std::make_shared<OnChangeWithKeepAliveSubscriptionQos>(
800, // validity_ms
1000, // publication ttl
100, // minInterval_ms
200, // maxInterval_ms
1000 // alertInterval_ms
);
std::shared_ptr<Future<std::string>> subscriptionIdFuture = testProxy->subscribeToLocation(subscriptionListener, subscriptionQos);
std::this_thread::sleep_for(std::chrono::milliseconds(1500));
// This is not yet implemented in CapabilitiesClient
// runtime->unregisterProvider("Fake_ParticipantId_vehicle/gpsDummyProvider");
std::string subscriptionId;
JOYNR_ASSERT_NO_THROW(subscriptionIdFuture->get(5000, subscriptionId));
JOYNR_ASSERT_NO_THROW(testProxy->unsubscribeFromLocation(subscriptionId));
runtime->unregisterProvider(participantId);
}
using namespace std::string_literals;
INSTANTIATE_TEST_CASE_P(Http,
End2EndRPCTest,
testing::Values(
"test-resources/HttpSystemIntegrationTest1.settings"s
)
);
INSTANTIATE_TEST_CASE_P(Mqtt,
End2EndRPCTest,
testing::Values(
"test-resources/MqttSystemIntegrationTest1.settings"s
)
);
<commit_msg>[C++] Fixed End2EndRPCTest<commit_after>/*
* #%L
* %%
* Copyright (C) 2011 - 2017 BMW Car IT GmbH
* %%
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* #L%
*/
#include <memory>
#include <string>
#include <cstdint>
#include <gtest/gtest.h>
#include <gmock/gmock.h>
#include "joynr/JoynrClusterControllerRuntime.h"
#include "joynr/tests/testProvider.h"
#include "joynr/tests/testProxy.h"
#include "joynr/vehicle/GpsProxy.h"
#include "joynr/types/ProviderQos.h"
#include "joynr/Future.h"
#include "joynr/OnChangeWithKeepAliveSubscriptionQos.h"
#include "joynr/LibjoynrSettings.h"
#include "joynr/PrivateCopyAssign.h"
#include "tests/JoynrTest.h"
#include "tests/mock/MockGpsProvider.h"
#include "tests/mock/MockSubscriptionListener.h"
#include "tests/mock/MockTestProvider.h"
#include "tests/utils/PtrUtils.h"
using namespace ::testing;
using namespace joynr;
class End2EndRPCTest : public TestWithParam< std::string >{
public:
std::string domain;
std::shared_ptr<JoynrClusterControllerRuntime> runtime;
std::shared_ptr<vehicle::GpsProvider> gpsProvider;
End2EndRPCTest() :
domain(),
runtime()
{
runtime = std::make_shared<JoynrClusterControllerRuntime>(
std::make_unique<Settings>(GetParam())
);
runtime->init();
domain = "cppEnd2EndRPCTest_Domain_" + util::createUuid();
discoveryQos.setArbitrationStrategy(DiscoveryQos::ArbitrationStrategy::HIGHEST_PRIORITY);
discoveryQos.setDiscoveryTimeoutMs(3000);
}
// Sets up the test fixture.
void SetUp(){
runtime->start();
}
// Tears down the test fixture.
void TearDown(){
bool deleteChannel = true;
runtime->stop(deleteChannel);
test::util::resetAndWaitUntilDestroyed(runtime);
// Delete persisted files
test::util::removeAllCreatedSettingsAndPersistencyFiles();
std::this_thread::sleep_for(std::chrono::milliseconds(550));
}
~End2EndRPCTest() = default;
protected:
joynr::DiscoveryQos discoveryQos;
private:
DISALLOW_COPY_AND_ASSIGN(End2EndRPCTest);
};
// leadsm to assert failure in GpsInProcessConnector line 185: not yet implemented in connector
TEST_P(End2EndRPCTest, call_rpc_method_and_get_expected_result)
{
auto mockProvider = std::make_shared<MockGpsProvider>();
types::ProviderQos providerQos;
std::chrono::milliseconds millisSinceEpoch =
std::chrono::duration_cast<std::chrono::milliseconds>(
std::chrono::system_clock::now().time_since_epoch());
providerQos.setPriority(millisSinceEpoch.count());
providerQos.setScope(joynr::types::ProviderScope::GLOBAL);
providerQos.setSupportsOnChangeSubscriptions(true);
std::string participantId = runtime->registerProvider<vehicle::GpsProvider>(domain, mockProvider, providerQos);
std::this_thread::sleep_for(std::chrono::milliseconds(550));
std::shared_ptr<ProxyBuilder<vehicle::GpsProxy>> gpsProxyBuilder =
runtime->createProxyBuilder<vehicle::GpsProxy>(domain);
std::int64_t qosRoundTripTTL = 40000;
std::shared_ptr<vehicle::GpsProxy> gpsProxy = gpsProxyBuilder
->setMessagingQos(MessagingQos(qosRoundTripTTL))
->setDiscoveryQos(discoveryQos)
->build();
std::shared_ptr<Future<int> >gpsFuture (gpsProxy->calculateAvailableSatellitesAsync());
gpsFuture->wait();
int expectedValue = 42; //as defined in MockGpsProvider
int actualValue;
gpsFuture->get(actualValue);
EXPECT_EQ(expectedValue, actualValue);
// This is not yet implemented in CapabilitiesClient
// runtime->unregisterProvider("Fake_ParticipantId_vehicle/gpsDummyProvider");
runtime->unregisterProvider(participantId);
}
TEST_P(End2EndRPCTest, call_void_operation)
{
auto mockProvider = std::make_shared<MockTestProvider>();
types::ProviderQos providerQos;
std::chrono::milliseconds millisSinceEpoch =
std::chrono::duration_cast<std::chrono::milliseconds>(
std::chrono::system_clock::now().time_since_epoch());
providerQos.setPriority(millisSinceEpoch.count());
providerQos.setScope(joynr::types::ProviderScope::GLOBAL);
providerQos.setSupportsOnChangeSubscriptions(true);
std::string participantId = runtime->registerProvider<tests::testProvider>(domain, mockProvider, providerQos);
std::this_thread::sleep_for(std::chrono::milliseconds(550));
std::shared_ptr<ProxyBuilder<tests::testProxy>> testProxyBuilder =
runtime->createProxyBuilder<tests::testProxy>(domain);
std::int64_t qosRoundTripTTL = 40000;
std::shared_ptr<tests::testProxy> testProxy = testProxyBuilder
->setMessagingQos(MessagingQos(qosRoundTripTTL))
->setDiscoveryQos(discoveryQos)
->build();
testProxy->voidOperation();
// EXPECT_EQ(expectedValue, gpsFuture->getValue());
// This is not yet implemented in CapabilitiesClient
// runtime->unregisterProvider("Fake_ParticipantId_vehicle/gpsDummyProvider");
runtime->unregisterProvider(participantId);
}
// tests in process subscription
TEST_P(End2EndRPCTest, _call_subscribeTo_and_get_expected_result)
{
auto mockProvider = std::make_shared<MockTestProvider>();
types::ProviderQos providerQos;
std::chrono::milliseconds millisSinceEpoch =
std::chrono::duration_cast<std::chrono::milliseconds>(
std::chrono::system_clock::now().time_since_epoch());
providerQos.setPriority(millisSinceEpoch.count());
providerQos.setScope(joynr::types::ProviderScope::GLOBAL);
providerQos.setSupportsOnChangeSubscriptions(true);
std::string participantId = runtime->registerProvider<tests::testProvider>(domain, mockProvider, providerQos);
std::this_thread::sleep_for(std::chrono::milliseconds(550));
std::shared_ptr<ProxyBuilder<tests::testProxy>> testProxyBuilder =
runtime->createProxyBuilder<tests::testProxy>(domain);
std::int64_t qosRoundTripTTL = 40000;
std::shared_ptr<tests::testProxy> testProxy = testProxyBuilder
->setMessagingQos(MessagingQos(qosRoundTripTTL))
->setDiscoveryQos(discoveryQos)
->build();
MockGpsSubscriptionListener* mockListener = new MockGpsSubscriptionListener();
std::shared_ptr<ISubscriptionListener<types::Localisation::GpsLocation> > subscriptionListener(
mockListener);
EXPECT_CALL(*mockListener, onReceive(A<const types::Localisation::GpsLocation&>()))
.Times(AtLeast(2));
auto subscriptionQos = std::make_shared<OnChangeWithKeepAliveSubscriptionQos>(
800, // validity_ms
1000, // publication ttl
100, // minInterval_ms
200, // maxInterval_ms
1000 // alertInterval_ms
);
std::shared_ptr<Future<std::string>> subscriptionIdFuture = testProxy->subscribeToLocation(subscriptionListener, subscriptionQos);
std::this_thread::sleep_for(std::chrono::milliseconds(1500));
// This is not yet implemented in CapabilitiesClient
// runtime->unregisterProvider("Fake_ParticipantId_vehicle/gpsDummyProvider");
std::string subscriptionId;
JOYNR_ASSERT_NO_THROW(subscriptionIdFuture->get(5000, subscriptionId));
JOYNR_ASSERT_NO_THROW(testProxy->unsubscribeFromLocation(subscriptionId));
runtime->unregisterProvider(participantId);
}
using namespace std::string_literals;
INSTANTIATE_TEST_CASE_P(Http,
End2EndRPCTest,
testing::Values(
"test-resources/HttpSystemIntegrationTest1.settings"s
)
);
INSTANTIATE_TEST_CASE_P(Mqtt,
End2EndRPCTest,
testing::Values(
"test-resources/MqttSystemIntegrationTest1.settings"s
)
);
<|endoftext|> |
<commit_before>// Copyright 2010-2013 RethinkDB, all rights reserved.
#include "backtrace.hpp"
#ifdef _WIN32
// TODO WINDOWS
#else
#include <cxxabi.h>
#include <execinfo.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/wait.h>
#include <string>
#include "arch/runtime/coroutines.hpp"
#include "containers/scoped.hpp"
#include "logger.hpp"
#include "rethinkdb_backtrace.hpp"
#include "utils.hpp"
static bool parse_backtrace_line(char *line, char **filename, char **function, char **offset, char **address) {
/*
backtrace() gives us lines in one of the following two forms:
./path/to/the/binary(function+offset) [address]
./path/to/the/binary [address]
*/
*filename = line;
// Check if there is a function present
if (char *paren1 = strchr(line, '(')) {
char *paren2 = strchr(line, ')');
if (!paren2) return false;
*paren1 = *paren2 = '\0'; // Null-terminate the offset and the filename
*function = paren1 + 1;
char *plus = strchr(*function, '+');
if (!plus) return false;
*plus = '\0'; // Null-terminate the function name
*offset = plus + 1;
line = paren2 + 1;
if (*line != ' ') return false;
line += 1;
} else {
*function = NULL;
*offset = NULL;
char *bracket = strchr(line, '[');
if (!bracket) return false;
line = bracket - 1;
if (*line != ' ') return false;
*line = '\0'; // Null-terminate the file name
line += 1;
}
// We are now at the opening bracket of the address
if (*line != '[') return false;
line += 1;
*address = line;
line = strchr(line, ']');
if (!line || line[1] != '\0') return false;
*line = '\0'; // Null-terminate the address
return true;
}
/* There has been some trouble with abi::__cxa_demangle.
Originally, demangle_cpp_name() took a pointer to the mangled name, and returned a
buffer that must be free()ed. It did this by calling __cxa_demangle() and passing NULL
and 0 for the buffer and buffer-size arguments.
There were complaints that print_backtrace() was smashing memory. Shachaf observed that
pieces of the backtrace seemed to be ending up overwriting other structs, and filed
issue #100.
Daniel Mewes suspected that the memory smashing was related to calling malloc().
In December 2010, he changed demangle_cpp_name() to take a static buffer, and fill
this static buffer with the demangled name. See 284246bd.
abi::__cxa_demangle expects a malloc()ed buffer, and if the buffer is too small it
will call realloc() on it. So the static-buffer approach worked except when the name
to be demangled was too large.
In March 2011, Tim and Ivan got tired of the memory allocator complaining that someone
was trying to realloc() an unallocated buffer, and changed demangle_cpp_name() back
to the way it was originally.
Please don't change this function without talking to the people who have already
been involved in this. */
std::string demangle_cpp_name(const char *mangled_name) {
int res;
char *name_as_c_str = abi::__cxa_demangle(mangled_name, NULL, 0, &res);
if (res == 0) {
std::string name_as_std_string(name_as_c_str);
free(name_as_c_str);
return name_as_std_string;
} else {
throw demangle_failed_exc_t();
}
}
int set_o_cloexec(int fd) {
int flags = fcntl(fd, F_GETFD);
if (flags < 0) {
return flags;
}
return fcntl(fd, F_SETFD, flags | FD_CLOEXEC);
}
address_to_line_t::addr2line_t::addr2line_t(const char *executable) : input(NULL), output(NULL), bad(false), pid(-1) {
if (pipe(child_in) || set_o_cloexec(child_in[0]) || set_o_cloexec(child_in[1]) || pipe(child_out) || set_o_cloexec(child_out[0]) || set_o_cloexec(child_out[1])) {
bad = true;
return;
}
if ((pid = fork())) {
input = fdopen(child_in[1], "w");
output = fdopen(child_out[0], "r");
close(child_in[0]);
close(child_out[1]);
} else {
dup2(child_in[0], 0); // stdin
dup2(child_out[1], 1); // stdout
const char *args[] = {"addr2line", "-s", "-e", executable, NULL};
execvp("addr2line", const_cast<char *const *>(args));
exit(EXIT_FAILURE);
}
}
address_to_line_t::addr2line_t::~addr2line_t() {
if (input) {
fclose(input);
}
if (output) {
fclose(output);
}
if (pid != -1) {
waitpid(pid, NULL, 0);
}
}
bool address_to_line_t::run_addr2line(const std::string &executable, const void *address, char *line, int line_size) {
addr2line_t *proc;
std::map<std::string, scoped_ptr_t<addr2line_t> >::iterator iter
= procs.find(executable);
if (iter != procs.end()) {
proc = iter->second.get();
} else {
proc = new addr2line_t(executable.c_str());
auto p = procs.insert(
std::make_pair(executable,
make_scoped<addr2line_t>(executable.c_str()))).first;
proc = p->second.get();
}
if (proc->bad) {
return false;
}
fprintf(proc->input, "%p\n", address);
fflush(proc->input);
char *result = fgets(line, line_size, proc->output);
if (result == NULL) {
proc->bad = true;
return false;
}
line[line_size - 1] = '\0';
int len = strlen(line);
if (line[len - 1] == '\n') {
line[len - 1] = '\0';
}
if (!strcmp(line, "??:0")) return false;
return true;
}
std::string address_to_line_t::address_to_line(const std::string &executable, const void *address) {
char line[255];
bool success = run_addr2line(executable, address, line, sizeof(line));
if (!success) {
return "";
} else {
return std::string(line);
}
}
std::string format_backtrace(bool use_addr2line) {
lazy_backtrace_formatter_t bt;
return use_addr2line ? bt.lines() : bt.addrs();
}
backtrace_t::backtrace_t() {
scoped_array_t<void *> stack_frames(new void*[max_frames], max_frames); // Allocate on heap in case stack space is scarce
int size = rethinkdb_backtrace(stack_frames.data(), max_frames);
#ifdef CROSS_CORO_BACKTRACES
if (coro_t::self() != NULL) {
int space_remaining = max_frames - size;
rassert(space_remaining >= 0);
size += coro_t::self()->copy_spawn_backtrace(stack_frames.data() + size,
space_remaining);
}
#endif
frames.reserve(static_cast<size_t>(size));
for (int i = 0; i < size; ++i) {
frames.push_back(backtrace_frame_t(stack_frames[i]));
}
}
backtrace_frame_t::backtrace_frame_t(const void* _addr) :
symbols_initialized(false),
addr(_addr) {
}
void backtrace_frame_t::initialize_symbols() {
void *addr_array[1] = {const_cast<void *>(addr)};
char **symbols = backtrace_symbols(addr_array, 1);
if (symbols != NULL) {
symbols_line = std::string(symbols[0]);
char *c_filename;
char *c_function;
char *c_offset;
char *c_address;
if (parse_backtrace_line(symbols[0], &c_filename, &c_function, &c_offset, &c_address)) {
if (c_filename != NULL) {
filename = std::string(c_filename);
}
if (c_function != NULL) {
function = std::string(c_function);
}
if (c_offset != NULL) {
offset = std::string(c_offset);
}
}
free(symbols);
}
symbols_initialized = true;
}
std::string backtrace_frame_t::get_name() const {
rassert(symbols_initialized);
return function;
}
std::string backtrace_frame_t::get_symbols_line() const {
rassert(symbols_initialized);
return symbols_line;
}
std::string backtrace_frame_t::get_demangled_name() const {
rassert(symbols_initialized);
return demangle_cpp_name(function.c_str());
}
std::string backtrace_frame_t::get_filename() const {
rassert(symbols_initialized);
return filename;
}
std::string backtrace_frame_t::get_offset() const {
rassert(symbols_initialized);
return offset;
}
const void *backtrace_frame_t::get_addr() const {
return addr;
}
lazy_backtrace_formatter_t::lazy_backtrace_formatter_t() :
backtrace_t(),
timestamp(time(0)),
timestr(time2str(timestamp)) {
}
std::string lazy_backtrace_formatter_t::addrs() {
if (cached_addrs == "") {
cached_addrs = timestr + "\n" + print_frames(false);
}
return cached_addrs;
}
std::string lazy_backtrace_formatter_t::lines() {
if (cached_lines == "") {
cached_lines = timestr + "\n" + print_frames(true);
}
return cached_lines;
}
std::string lazy_backtrace_formatter_t::print_frames(bool use_addr2line) {
address_to_line_t address_to_line;
std::string output;
for (size_t i = 0; i < get_num_frames(); i++) {
backtrace_frame_t current_frame = get_frame(i);
current_frame.initialize_symbols();
output.append(strprintf("%d [%p]: ", static_cast<int>(i+1), current_frame.get_addr()));
try {
output.append(current_frame.get_demangled_name());
} catch (const demangle_failed_exc_t &) {
if (!current_frame.get_name().empty()) {
output.append(current_frame.get_name() + "+" + current_frame.get_offset());
} else if (!current_frame.get_symbols_line().empty()) {
output.append(current_frame.get_symbols_line());
} else {
output.append("<unknown function>");
}
}
output.append(" at ");
std::string some_other_line;
if (use_addr2line) {
if (!current_frame.get_filename().empty()) {
some_other_line = address_to_line.address_to_line(current_frame.get_filename(), current_frame.get_addr());
}
}
if (!some_other_line.empty()) {
output.append(some_other_line);
} else {
output.append(strprintf("%p", current_frame.get_addr()) + " (" + current_frame.get_filename() + ")");
}
output.append("\n");
}
return output;
}
#endif
<commit_msg>Fix for #5321.<commit_after>// Copyright 2010-2013 RethinkDB, all rights reserved.
#include "backtrace.hpp"
#ifdef _WIN32
// TODO WINDOWS
#else
#include <cxxabi.h>
#include <execinfo.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/wait.h>
#include <string>
#include "arch/runtime/coroutines.hpp"
#include "containers/scoped.hpp"
#include "logger.hpp"
#include "rethinkdb_backtrace.hpp"
#include "utils.hpp"
static bool parse_backtrace_line(char *line, char **filename, char **function, char **offset, char **address) {
/*
backtrace() gives us lines in one of the following two forms:
./path/to/the/binary(function+offset) [address]
./path/to/the/binary [address]
*/
*filename = line;
// Check if there is a function present
if (char *paren1 = strchr(line, '(')) {
char *paren2 = strchr(line, ')');
if (!paren2) return false;
*paren1 = *paren2 = '\0'; // Null-terminate the offset and the filename
*function = paren1 + 1;
char *plus = strchr(*function, '+');
if (!plus) return false;
*plus = '\0'; // Null-terminate the function name
*offset = plus + 1;
line = paren2 + 1;
if (*line != ' ') return false;
line += 1;
} else {
*function = NULL;
*offset = NULL;
char *bracket = strchr(line, '[');
if (!bracket) return false;
line = bracket - 1;
if (*line != ' ') return false;
*line = '\0'; // Null-terminate the file name
line += 1;
}
// We are now at the opening bracket of the address
if (*line != '[') return false;
line += 1;
*address = line;
line = strchr(line, ']');
if (!line || line[1] != '\0') return false;
*line = '\0'; // Null-terminate the address
return true;
}
/* There has been some trouble with abi::__cxa_demangle.
Originally, demangle_cpp_name() took a pointer to the mangled name, and returned a
buffer that must be free()ed. It did this by calling __cxa_demangle() and passing NULL
and 0 for the buffer and buffer-size arguments.
There were complaints that print_backtrace() was smashing memory. Shachaf observed that
pieces of the backtrace seemed to be ending up overwriting other structs, and filed
issue #100.
Daniel Mewes suspected that the memory smashing was related to calling malloc().
In December 2010, he changed demangle_cpp_name() to take a static buffer, and fill
this static buffer with the demangled name. See 284246bd.
abi::__cxa_demangle expects a malloc()ed buffer, and if the buffer is too small it
will call realloc() on it. So the static-buffer approach worked except when the name
to be demangled was too large.
In March 2011, Tim and Ivan got tired of the memory allocator complaining that someone
was trying to realloc() an unallocated buffer, and changed demangle_cpp_name() back
to the way it was originally.
Please don't change this function without talking to the people who have already
been involved in this. */
std::string demangle_cpp_name(const char *mangled_name) {
int res;
char *name_as_c_str = abi::__cxa_demangle(mangled_name, NULL, 0, &res);
if (res == 0) {
std::string name_as_std_string(name_as_c_str);
free(name_as_c_str);
return name_as_std_string;
} else {
throw demangle_failed_exc_t();
}
}
int set_o_cloexec(int fd) {
int flags = fcntl(fd, F_GETFD);
if (flags < 0) {
return flags;
}
return fcntl(fd, F_SETFD, flags | FD_CLOEXEC);
}
address_to_line_t::addr2line_t::addr2line_t(const char *executable) : input(NULL), output(NULL), bad(false), pid(-1) {
if (pipe(child_in) || set_o_cloexec(child_in[0]) || set_o_cloexec(child_in[1]) || pipe(child_out) || set_o_cloexec(child_out[0]) || set_o_cloexec(child_out[1])) {
bad = true;
return;
}
if ((pid = fork())) {
input = fdopen(child_in[1], "w");
output = fdopen(child_out[0], "r");
close(child_in[0]);
close(child_out[1]);
} else {
dup2(child_in[0], 0); // stdin
dup2(child_out[1], 1); // stdout
const char *args[] = {"addr2line", "-s", "-e", executable, NULL};
execvp("addr2line", const_cast<char *const *>(args));
// A normal `exit` can get stuck here it seems. Maybe some `atexit` handler?
quick_exit(EXIT_FAILURE);
}
}
address_to_line_t::addr2line_t::~addr2line_t() {
if (input) {
fclose(input);
}
if (output) {
fclose(output);
}
if (pid != -1) {
waitpid(pid, NULL, 0);
}
}
bool address_to_line_t::run_addr2line(const std::string &executable, const void *address, char *line, int line_size) {
addr2line_t *proc;
std::map<std::string, scoped_ptr_t<addr2line_t> >::iterator iter
= procs.find(executable);
if (iter != procs.end()) {
proc = iter->second.get();
} else {
proc = new addr2line_t(executable.c_str());
auto p = procs.insert(
std::make_pair(executable,
make_scoped<addr2line_t>(executable.c_str()))).first;
proc = p->second.get();
}
if (proc->bad) {
return false;
}
fprintf(proc->input, "%p\n", address);
fflush(proc->input);
char *result = fgets(line, line_size, proc->output);
if (result == NULL) {
proc->bad = true;
return false;
}
line[line_size - 1] = '\0';
int len = strlen(line);
if (line[len - 1] == '\n') {
line[len - 1] = '\0';
}
if (!strcmp(line, "??:0")) return false;
return true;
}
std::string address_to_line_t::address_to_line(const std::string &executable, const void *address) {
char line[255];
bool success = run_addr2line(executable, address, line, sizeof(line));
if (!success) {
return "";
} else {
return std::string(line);
}
}
std::string format_backtrace(bool use_addr2line) {
lazy_backtrace_formatter_t bt;
return use_addr2line ? bt.lines() : bt.addrs();
}
backtrace_t::backtrace_t() {
scoped_array_t<void *> stack_frames(new void*[max_frames], max_frames); // Allocate on heap in case stack space is scarce
int size = rethinkdb_backtrace(stack_frames.data(), max_frames);
#ifdef CROSS_CORO_BACKTRACES
if (coro_t::self() != NULL) {
int space_remaining = max_frames - size;
rassert(space_remaining >= 0);
size += coro_t::self()->copy_spawn_backtrace(stack_frames.data() + size,
space_remaining);
}
#endif
frames.reserve(static_cast<size_t>(size));
for (int i = 0; i < size; ++i) {
frames.push_back(backtrace_frame_t(stack_frames[i]));
}
}
backtrace_frame_t::backtrace_frame_t(const void* _addr) :
symbols_initialized(false),
addr(_addr) {
}
void backtrace_frame_t::initialize_symbols() {
void *addr_array[1] = {const_cast<void *>(addr)};
char **symbols = backtrace_symbols(addr_array, 1);
if (symbols != NULL) {
symbols_line = std::string(symbols[0]);
char *c_filename;
char *c_function;
char *c_offset;
char *c_address;
if (parse_backtrace_line(symbols[0], &c_filename, &c_function, &c_offset, &c_address)) {
if (c_filename != NULL) {
filename = std::string(c_filename);
}
if (c_function != NULL) {
function = std::string(c_function);
}
if (c_offset != NULL) {
offset = std::string(c_offset);
}
}
free(symbols);
}
symbols_initialized = true;
}
std::string backtrace_frame_t::get_name() const {
rassert(symbols_initialized);
return function;
}
std::string backtrace_frame_t::get_symbols_line() const {
rassert(symbols_initialized);
return symbols_line;
}
std::string backtrace_frame_t::get_demangled_name() const {
rassert(symbols_initialized);
return demangle_cpp_name(function.c_str());
}
std::string backtrace_frame_t::get_filename() const {
rassert(symbols_initialized);
return filename;
}
std::string backtrace_frame_t::get_offset() const {
rassert(symbols_initialized);
return offset;
}
const void *backtrace_frame_t::get_addr() const {
return addr;
}
lazy_backtrace_formatter_t::lazy_backtrace_formatter_t() :
backtrace_t(),
timestamp(time(0)),
timestr(time2str(timestamp)) {
}
std::string lazy_backtrace_formatter_t::addrs() {
if (cached_addrs == "") {
cached_addrs = timestr + "\n" + print_frames(false);
}
return cached_addrs;
}
std::string lazy_backtrace_formatter_t::lines() {
if (cached_lines == "") {
cached_lines = timestr + "\n" + print_frames(true);
}
return cached_lines;
}
std::string lazy_backtrace_formatter_t::print_frames(bool use_addr2line) {
address_to_line_t address_to_line;
std::string output;
for (size_t i = 0; i < get_num_frames(); i++) {
backtrace_frame_t current_frame = get_frame(i);
current_frame.initialize_symbols();
output.append(strprintf("%d [%p]: ", static_cast<int>(i+1), current_frame.get_addr()));
try {
output.append(current_frame.get_demangled_name());
} catch (const demangle_failed_exc_t &) {
if (!current_frame.get_name().empty()) {
output.append(current_frame.get_name() + "+" + current_frame.get_offset());
} else if (!current_frame.get_symbols_line().empty()) {
output.append(current_frame.get_symbols_line());
} else {
output.append("<unknown function>");
}
}
output.append(" at ");
std::string some_other_line;
if (use_addr2line) {
if (!current_frame.get_filename().empty()) {
some_other_line = address_to_line.address_to_line(current_frame.get_filename(), current_frame.get_addr());
}
}
if (!some_other_line.empty()) {
output.append(some_other_line);
} else {
output.append(strprintf("%p", current_frame.get_addr()) + " (" + current_frame.get_filename() + ")");
}
output.append("\n");
}
return output;
}
#endif
<|endoftext|> |
<commit_before>// The MIT License(MIT)
// Copyright(c) 2016 Jeff Rebacz
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of
// this software and associated documentation files(the "Software"), to deal in
// the Software without restriction, including without limitation the rights to
// use, copy, modify, merge, publish, distribute, sublicense, and / or sell copies
// of the Software, and to permit persons to whom the Software is furnished to do
// so, subject to the following conditions :
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
#ifndef COLORWIN_HPP_INCLUDED
#define COLORWIN_HPP_INCLUDED
#include <Windows.h>
#include <iostream>
#include <stack>
namespace colorwin
{
// mix colors from wincon.h
//#define FOREGROUND_BLUE 0x0001 // text color contains blue.
//#define FOREGROUND_GREEN 0x0002 // text color contains green.
//#define FOREGROUND_RED 0x0004 // text color contains red.
//#define FOREGROUND_INTENSITY 0x0008 // text color is intensified.
enum CW_COLORS
{
red = FOREGROUND_RED | FOREGROUND_INTENSITY,
yellow = FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_INTENSITY,
green = FOREGROUND_GREEN | FOREGROUND_INTENSITY,
cyan = FOREGROUND_GREEN | FOREGROUND_BLUE | FOREGROUND_INTENSITY,
blue = FOREGROUND_BLUE | FOREGROUND_INTENSITY,
magenta = FOREGROUND_BLUE | FOREGROUND_RED | FOREGROUND_INTENSITY,
white = FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE | FOREGROUND_INTENSITY,
gray = FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE,
grey = FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE,
dark_gray = FOREGROUND_INTENSITY,
dark_grey = FOREGROUND_INTENSITY,
/* The following dark colors are unreadable, but comment them in and use them if you want. */
/*
dark_red = FOREGROUND_RED,
dark_yellow = FOREGROUND_RED | FOREGROUND_GREEN,
dark_green = FOREGROUND_GREEN,
dark_cyan = FOREGROUND_GREEN | FOREGROUND_BLUE,
dark_blue = FOREGROUND_BLUE,
dark_magenta = FOREGROUND_BLUE | FOREGROUND_RED,
*/
};
// Example usage: std::cout << color(yellow) << "This is a warning color!\n";
class color
{
public:
color(CW_COLORS color) : m_color(color), m_console_handle(INVALID_HANDLE_VALUE)
{
}
~color()
{
if (m_console_handle != INVALID_HANDLE_VALUE)
{
// Restore the previous color.
SetConsoleTextAttribute(m_console_handle, get_color_stack().top());
get_color_stack().pop();
}
}
private:
void change_color()
{
CONSOLE_SCREEN_BUFFER_INFO console_info;
m_console_handle = GetStdHandle(STD_OUTPUT_HANDLE);
if (!GetConsoleScreenBufferInfo(m_console_handle, &console_info))
{
m_console_handle = GetStdHandle(STD_ERROR_HANDLE);
if (!GetConsoleScreenBufferInfo(m_console_handle, &console_info)) // maybe standard output device has been redirected, try the standard error device
{
m_console_handle = INVALID_HANDLE_VALUE;
return; // Can't get console info, can't change color.
}
}
// save the current attributes, which include color
get_color_stack().push(console_info.wAttributes);
SetConsoleTextAttribute(m_console_handle, 0x0F & m_color);
}
color(color &);
color& operator=(color);
std::stack<int>& get_color_stack()
{
// Use this instead of static member to avoid multiply defined symbols.
static std::stack<int> color_stack;
return color_stack;
}
HANDLE m_console_handle;
const CW_COLORS m_color;
friend class withcolor;
template<typename charT, typename traits> friend std::basic_ostream<charT, traits> & operator<<(std::basic_ostream<charT, traits> &lhs, colorwin::color &rhs);
};
// Example usage :
// {
// withcolor scoped(yellow);
// cout << "This is a yellow warning!\n";
// cout << "This is a second yellow warning!\n";
// }
// -- or --
// withcolor(yellow).printf("This will be yellow\n");
class withcolor
{
public:
withcolor(CW_COLORS color) : m_color(color)
{
m_color.change_color();
}
int printf(const char* format, ...)
{
va_list vlist;
va_start(vlist, format);
int ret = vprintf(format, vlist);
va_end(vlist);
return ret;
}
int printf_s(const char *format, ...)
{
va_list vlist;
va_start(vlist, format);
int ret = vprintf_s(format, vlist);
va_end(vlist);
return ret;
}
private:
withcolor(withcolor &);
withcolor& operator=(withcolor);
color m_color;
};
// cout << color(red) -> operator<<(cout, colorwin::color(red))
template<typename charT, typename traits> std::basic_ostream<charT, traits> & operator<<(std::basic_ostream<charT, traits> &lhs, colorwin::color &rhs)
{
rhs.change_color();
return lhs;
}
}
#endif // COLORWIN_HPP_INCLUDED<commit_msg>Removed two level 4 compiler warnings: *warning C4239: nonstandard extension used *warning C4244: 'argument' : conversion from 'int' to 'WORD', possible loss of data<commit_after>// The MIT License(MIT)
// Copyright(c) 2016 Jeff Rebacz
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of
// this software and associated documentation files(the "Software"), to deal in
// the Software without restriction, including without limitation the rights to
// use, copy, modify, merge, publish, distribute, sublicense, and / or sell copies
// of the Software, and to permit persons to whom the Software is furnished to do
// so, subject to the following conditions :
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
#ifndef COLORWIN_HPP_INCLUDED
#define COLORWIN_HPP_INCLUDED
#include <Windows.h>
#include <iostream>
#include <stack>
namespace colorwin
{
// mix colors from wincon.h
//#define FOREGROUND_BLUE 0x0001 // text color contains blue.
//#define FOREGROUND_GREEN 0x0002 // text color contains green.
//#define FOREGROUND_RED 0x0004 // text color contains red.
//#define FOREGROUND_INTENSITY 0x0008 // text color is intensified.
enum CW_COLORS
{
red = FOREGROUND_RED | FOREGROUND_INTENSITY,
yellow = FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_INTENSITY,
green = FOREGROUND_GREEN | FOREGROUND_INTENSITY,
cyan = FOREGROUND_GREEN | FOREGROUND_BLUE | FOREGROUND_INTENSITY,
blue = FOREGROUND_BLUE | FOREGROUND_INTENSITY,
magenta = FOREGROUND_BLUE | FOREGROUND_RED | FOREGROUND_INTENSITY,
white = FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE | FOREGROUND_INTENSITY,
gray = FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE,
grey = FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE,
dark_gray = FOREGROUND_INTENSITY,
dark_grey = FOREGROUND_INTENSITY,
/* The following dark colors are unreadable, but comment them in and use them if you want. */
/*
dark_red = FOREGROUND_RED,
dark_yellow = FOREGROUND_RED | FOREGROUND_GREEN,
dark_green = FOREGROUND_GREEN,
dark_cyan = FOREGROUND_GREEN | FOREGROUND_BLUE,
dark_blue = FOREGROUND_BLUE,
dark_magenta = FOREGROUND_BLUE | FOREGROUND_RED,
*/
};
// Example usage: std::cout << color(yellow) << "This is a warning color!\n";
class color
{
public:
color(CW_COLORS color) : m_color(color), m_console_handle(INVALID_HANDLE_VALUE)
{
CONSOLE_SCREEN_BUFFER_INFO console_info;
m_console_handle = GetStdHandle(STD_OUTPUT_HANDLE);
if (!GetConsoleScreenBufferInfo(m_console_handle, &console_info))
{
m_console_handle = GetStdHandle(STD_ERROR_HANDLE);
if (!GetConsoleScreenBufferInfo(m_console_handle, &console_info)) // maybe standard output device has been redirected, try the standard error device
{
m_console_handle = INVALID_HANDLE_VALUE;
}
}
}
~color()
{
if (m_console_handle != INVALID_HANDLE_VALUE)
{
// Restore the previous color.
SetConsoleTextAttribute(m_console_handle, get_color_stack().top());
get_color_stack().pop();
}
}
private:
void change_color() const
{
if (m_console_handle == INVALID_HANDLE_VALUE)
return; // Can't get console info, can't change color.
CONSOLE_SCREEN_BUFFER_INFO console_info;
GetConsoleScreenBufferInfo(m_console_handle, &console_info);
// save the current attributes for restoration on destruction.
get_color_stack().push(console_info.wAttributes);
SetConsoleTextAttribute(m_console_handle, 0x0F & m_color);
}
color(color &);
color& operator=(color);
static std::stack<WORD>& get_color_stack()
{
// Use this instead of static member to avoid multiply defined symbols.
static std::stack<WORD> color_stack;
return color_stack;
}
HANDLE m_console_handle;
const CW_COLORS m_color;
friend class withcolor;
template<typename charT, typename traits> friend std::basic_ostream<charT, traits> & operator<<(std::basic_ostream<charT, traits> &lhs, colorwin::color const &rhs);
};
// Example usage :
// {
// withcolor scoped(yellow);
// cout << "This is a yellow warning!\n";
// cout << "This is a second yellow warning!\n";
// }
// -- or --
// withcolor(yellow).printf("This will be yellow\n");
class withcolor
{
public:
withcolor(CW_COLORS color) : m_color(color)
{
m_color.change_color();
}
int printf(const char* format, ...)
{
va_list vlist;
va_start(vlist, format);
int ret = vprintf(format, vlist);
va_end(vlist);
return ret;
}
int printf_s(const char *format, ...)
{
va_list vlist;
va_start(vlist, format);
int ret = vprintf_s(format, vlist);
va_end(vlist);
return ret;
}
private:
withcolor(withcolor &);
withcolor& operator=(withcolor);
color m_color;
};
// cout << color(red) -> operator<<(cout, colorwin::color(red))
template<typename charT, typename traits> std::basic_ostream<charT, traits> & operator<<(std::basic_ostream<charT, traits> &lhs, colorwin::color const &rhs)
{
rhs.change_color();
return lhs;
}
}
#endif // COLORWIN_HPP_INCLUDED<|endoftext|> |
<commit_before>class Solution {
public:
vector<vector<int>> generateMatrix(int n) {
vector<vector<int>> res;
for (int i = 0; i < n; ++i) {
vector<int> tmp(n, 0);
res.push_back(tmp);
}
int k = (n + 1)>>1, num = 1;
for (int i = 0, j = 0; i < k && j < k; ++i, ++j) {
for (int jj = j; jj < n - 1 - j; ++jj) {
res[i][jj] = num++;
}
for (int ii = i; ii < n - 1 - i; ++ii) {
res[ii][n - 1 - j] = num++;
}
if (i != n - 1 - i) {
for (int jj = n - 1 - j; jj > j; --jj) {
res[n - 1 - i][jj] = num++;
}
}
if (j != n - 1 - j) {
for (int ii = n - 1 - i; ii > i; --ii) {
res[ii][j] = num++;
}
}
if (i == n - 1 - i || j == n - 1 - j) {
res[n - 1 - i][n - 1 - j] = num++;
}
}
return res;
}
};
<commit_msg>#59 updated, support mXn<commit_after>class Solution {
private:
vector<vector<int>> generateMatrixDo(int m, int n) {
vector<vector<int>> res;
for (int i = 0; i < m; ++i) {
vector<int> tmp(n, 0);
res.push_back(tmp);
}
int ki = (m + 1)>>1, kj = (n + 1)>>1, mm = m - 1, nn = n - 1, num = 1;
for (int i = 0, j = 0; i < ki && j < kj; ++i, ++j) {
for (int jj = j; jj < nn - j; ++jj) {
res[i][jj] = num++;
}
for (int ii = i; ii < mm - i; ++ii) {
res[ii][nn - j] = num++;
}
if (i != mm - i) {
for (int jj = nn - j; jj > j; --jj) {
res[mm - i][jj] = num++;
}
}
if (j != nn - j) {
for (int ii = mm - i; ii > i; --ii) {
res[ii][j] = num++;
}
}
if (i == mm - i || j == nn - j) {
res[mm - i][nn - j] = num++;
}
}
return res;
}
public:
vector<vector<int>> generateMatrix(int n) {
return generateMatrixDo(n, n);
}
};
<|endoftext|> |
<commit_before>#include <iostream>
#include <gtkmm/box.h>
#include <gtkmm/widget.h>
#include "leftpaneview.hh"
#include "windowbody.hh"
LeftPaneView::LeftPaneView (bool homogeneous, int spacing, Gtk::PackOptions options, int padding) {
set_orientation (Gtk::ORIENTATION_VERTICAL);
set_size_request (200, -1);
//Add the TreeView, inside a ScrolledWindow, with the button underneath:
m_ScrolledWindow.add(m_TreeView);
std::string cssProperties = ".m_TreeView { background-color: #34393D; border-radius: 0; color: white; } "
" .m_TreeView:selected, .m_TreeView:prelight:selected, .m_TreeView.category-expander:hover { color: white; border-style: solid; border-width: 1px 0 1px 0; "
" -unico-inner-stroke-width: 1px 0 1px 0; background-image: -gtk-gradient (linear, left top, left bottom, from (alpha (#000, 0.11)), to (alpha (#000, 0.07))); "
" -unico-border-gradient: -gtk-gradient (linear, left top, left bottom, "
" from (alpha (#fff, 0.070)), "
" to (alpha (#fff, 0.10))); -unico-inner-stroke-gradient: -gtk-gradient (linear, left top, left bottom, "
" from (alpha (#000, 0.03)), to (alpha (#000, 0.10))); } "
" .m_TreeView:selected:backdrop, .m_TreeView:prelight:selected:backdrop { background-image: -gtk-gradient (linear,"
" left top, left bottom, from (alpha (#000, 0.08)), to (alpha (#000, 0.04))); -unico-border-gradient: -gtk-gradient (linear, "
" left top, left bottom, from (alpha (#000, 0.19)), to (alpha (#fff, 0.25))); "
" -unico-inner-stroke-gradient: -gtk-gradient (linear, left top, left bottom, from (alpha (#000, 0.03)), to (alpha (#000, 0.10))); } "
" .m_TreeView:prelight { background-color: shade (@bg_color, 1.10); }"
" .m_TreeView:hover { color: white; border-style: solid; border-width: 1px 0 1px 0; -unico-inner-stroke-width: 1px 0 1px 0; "
" background-image: -gtk-gradient (linear, left top, left bottom, from (alpha (#FFF, 0.2)), to (alpha (#FFF, 0.2))); "
" -unico-border-gradient: -gtk-gradient (linear, left top, left bottom, from (alpha (#fff, 0.3)), to (alpha (#fff, 0.30)));}";
addCss (&m_TreeView, "m_TreeView", cssProperties);
//Only show the scrollbars when they are necessary:
m_ScrolledWindow.set_policy(Gtk::POLICY_AUTOMATIC, Gtk::POLICY_AUTOMATIC);
pack_start(m_ScrolledWindow);
//Create the Tree model:
m_refTreeModel = Gtk::TreeStore::create(m_Columns);
m_TreeView.set_model(m_refTreeModel);
m_TreeView.set_headers_visible (false);
m_TreeView.set_show_expanders (true);
//All the items to be reordered with drag-and-drop:
m_TreeView.set_reorderable(false);
//Fill the TreeView's model
Gtk::TreeModel::Row row = *(m_refTreeModel->append());
row[m_Columns.m_col_id] = 1;
row[m_Columns.m_col_name] = "Notebooks";
Gtk::TreeModel::Row childrow = *(m_refTreeModel->append(row.children()));
childrow[m_Columns.m_col_id] = 11;
childrow[m_Columns.m_col_name] = "Literature";
childrow = *(m_refTreeModel->append(row.children()));
childrow[m_Columns.m_col_id] = 12;
childrow[m_Columns.m_col_name] = "HowTos";
row = *(m_refTreeModel->append());
row[m_Columns.m_col_id] = 2;
row[m_Columns.m_col_name] = "Tags";
childrow = *(m_refTreeModel->append(row.children()));
childrow[m_Columns.m_col_id] = 13;
childrow[m_Columns.m_col_name] = "Tag1";
childrow = *(m_refTreeModel->append(row.children()));
childrow[m_Columns.m_col_id] = 14;
childrow[m_Columns.m_col_name] = "Tag2";
//Add the TreeView's view columns:
m_TreeView.append_column("Name", m_Columns.m_col_name);
//Connect signal:
m_TreeView.signal_row_expanded().connect(sigc::mem_fun(*this,
&LeftPaneView::on_treeview_row_expanded) );
m_TreeView.signal_row_activated().connect(sigc::mem_fun(*this,
&LeftPaneView::on_treeview_row_activated) );
Glib::RefPtr<Gtk::TreeSelection> ts = m_TreeView.get_selection ();
ts->signal_changed().connect(sigc::mem_fun(*this,
&LeftPaneView::on_treeview_row_changed) );
show_all ();
}
void LeftPaneView::on_treeview_row_expanded (const Gtk::TreeModel::iterator& iter, Gtk::TreeModel::Path path){
std::cout << "TreeView Row Expanded" << std::endl;
}
void LeftPaneView::on_treeview_row_activated (const Gtk::TreePath& tp, Gtk::TreeViewColumn* const& tvc){
std::cout << "TreeView Row Activated" << std::endl;
}
void LeftPaneView::on_treeview_row_changed () {
Glib::RefPtr<Gtk::TreeSelection> ts = m_TreeView.get_selection ();
Gtk::TreeModel::iterator iter = ts->get_selected ();
Glib::RefPtr<Gtk::TreeModel> tm = ts->get_model ();
if (iter) {
Gtk::TreeModel::Path path = tm->get_path (iter);
if (path.size () == 1) {
ts->unselect_all ();
} else {
std::cout << "Tree Child Clicked." << std::endl;
}
}
}
LeftPaneView::~LeftPaneView () {
}
<commit_msg>Made leftPane expandable when expanders are hidden.<commit_after>#include <iostream>
#include <gtkmm/box.h>
#include <gtkmm/widget.h>
#include "leftpaneview.hh"
#include "windowbody.hh"
LeftPaneView::LeftPaneView (bool homogeneous, int spacing, Gtk::PackOptions options, int padding) {
set_orientation (Gtk::ORIENTATION_VERTICAL);
set_size_request (200, -1);
//Add the TreeView, inside a ScrolledWindow, with the button underneath:
m_ScrolledWindow.add(m_TreeView);
std::string cssProperties = ".m_TreeView { background-color: #34393D; border-radius: 0; color: white; } "
" .m_TreeView:selected, .m_TreeView:prelight:selected, .m_TreeView.category-expander:hover { color: white; border-style: solid; border-width: 1px 0 1px 0; "
" -unico-inner-stroke-width: 1px 0 1px 0; background-image: -gtk-gradient (linear, left top, left bottom, from (alpha (#000, 0.11)), to (alpha (#000, 0.07))); "
" -unico-border-gradient: -gtk-gradient (linear, left top, left bottom, "
" from (alpha (#fff, 0.070)), "
" to (alpha (#fff, 0.10))); -unico-inner-stroke-gradient: -gtk-gradient (linear, left top, left bottom, "
" from (alpha (#000, 0.03)), to (alpha (#000, 0.10))); } "
" .m_TreeView:selected:backdrop, .m_TreeView:prelight:selected:backdrop { background-image: -gtk-gradient (linear,"
" left top, left bottom, from (alpha (#000, 0.08)), to (alpha (#000, 0.04))); -unico-border-gradient: -gtk-gradient (linear, "
" left top, left bottom, from (alpha (#000, 0.19)), to (alpha (#fff, 0.25))); "
" -unico-inner-stroke-gradient: -gtk-gradient (linear, left top, left bottom, from (alpha (#000, 0.03)), to (alpha (#000, 0.10))); } "
" .m_TreeView:prelight { background-color: shade (@bg_color, 1.10); }"
" .m_TreeView:hover { color: white; border-style: solid; border-width: 1px 0 1px 0; -unico-inner-stroke-width: 1px 0 1px 0; "
" background-image: -gtk-gradient (linear, left top, left bottom, from (alpha (#FFF, 0.2)), to (alpha (#FFF, 0.2))); "
" -unico-border-gradient: -gtk-gradient (linear, left top, left bottom, from (alpha (#fff, 0.3)), to (alpha (#fff, 0.30)));}";
addCss (&m_TreeView, "m_TreeView", cssProperties);
//Only show the scrollbars when they are necessary:
m_ScrolledWindow.set_policy(Gtk::POLICY_AUTOMATIC, Gtk::POLICY_AUTOMATIC);
pack_start(m_ScrolledWindow);
//Create the Tree model:
m_refTreeModel = Gtk::TreeStore::create(m_Columns);
m_TreeView.set_model(m_refTreeModel);
m_TreeView.set_headers_visible (false);
m_TreeView.set_show_expanders (false);
//All the items to be reordered with drag-and-drop:
m_TreeView.set_reorderable(false);
//Fill the TreeView's model
Gtk::TreeModel::Row row = *(m_refTreeModel->append());
row[m_Columns.m_col_id] = 1;
row[m_Columns.m_col_name] = "Notebooks";
Gtk::TreeModel::Row childrow = *(m_refTreeModel->append(row.children()));
childrow[m_Columns.m_col_id] = 11;
childrow[m_Columns.m_col_name] = "\tLiterature";
childrow = *(m_refTreeModel->append(row.children()));
childrow[m_Columns.m_col_id] = 12;
childrow[m_Columns.m_col_name] = "\tHowTos";
row = *(m_refTreeModel->append());
row[m_Columns.m_col_id] = 2;
row[m_Columns.m_col_name] = "Tags";
childrow = *(m_refTreeModel->append(row.children()));
childrow[m_Columns.m_col_id] = 13;
childrow[m_Columns.m_col_name] = "\tTag1";
childrow = *(m_refTreeModel->append(row.children()));
childrow[m_Columns.m_col_id] = 14;
childrow[m_Columns.m_col_name] = "\tTag2";
//Add the TreeView's view columns:
m_TreeView.append_column("Name", m_Columns.m_col_name);
//Connect signal:
m_TreeView.signal_row_expanded().connect(sigc::mem_fun(*this,
&LeftPaneView::on_treeview_row_expanded) );
m_TreeView.signal_row_activated().connect(sigc::mem_fun(*this,
&LeftPaneView::on_treeview_row_activated) );
Glib::RefPtr<Gtk::TreeSelection> ts = m_TreeView.get_selection ();
ts->signal_changed().connect(sigc::mem_fun(*this,
&LeftPaneView::on_treeview_row_changed) );
show_all ();
}
void LeftPaneView::on_treeview_row_expanded (const Gtk::TreeModel::iterator& iter, Gtk::TreeModel::Path path){
std::cout << "TreeView Row Expanded" << std::endl;
}
void LeftPaneView::on_treeview_row_activated (const Gtk::TreePath& tp, Gtk::TreeViewColumn* const& tvc){
std::cout << "TreeView Row Activated" << std::endl;
}
void LeftPaneView::on_treeview_row_changed () {
Glib::RefPtr<Gtk::TreeSelection> ts = m_TreeView.get_selection ();
Gtk::TreeModel::iterator iter = ts->get_selected ();
Glib::RefPtr<Gtk::TreeModel> tm = ts->get_model ();
if (iter) {
Gtk::TreeModel::Path path = tm->get_path (iter);
if (path.size () == 1) {
ts->unselect_all ();
/* Expand tree */
if (m_TreeView.row_expanded (path))
m_TreeView.collapse_row (path);
else {
m_TreeView.expand_to_path (path);
}
} else {
std::cout << "Tree Child Clicked." << std::endl;
}
}
}
LeftPaneView::~LeftPaneView () {
}
<|endoftext|> |
<commit_before>#include "ExtraRenderers.hpp"
#include "wxExtensions.hpp"
#include "GUI.hpp"
#include "I18N.hpp"
#include "BitmapComboBox.hpp"
#include <wx/dc.h>
#ifdef wxHAS_GENERIC_DATAVIEWCTRL
#include "wx/generic/private/markuptext.h"
#include "wx/generic/private/rowheightcache.h"
#include "wx/generic/private/widthcalc.h"
#endif
/*
#ifdef __WXGTK__
#include "wx/gtk/private.h"
#include "wx/gtk/private/value.h"
#endif
*/
#if wxUSE_ACCESSIBILITY
#include "wx/private/markupparser.h"
#endif // wxUSE_ACCESSIBILITY
using Slic3r::GUI::from_u8;
using Slic3r::GUI::into_u8;
//-----------------------------------------------------------------------------
// DataViewBitmapText
//-----------------------------------------------------------------------------
wxIMPLEMENT_DYNAMIC_CLASS(DataViewBitmapText, wxObject)
IMPLEMENT_VARIANT_OBJECT(DataViewBitmapText)
// ---------------------------------------------------------
// BitmapTextRenderer
// ---------------------------------------------------------
#if ENABLE_NONCUSTOM_DATA_VIEW_RENDERING
BitmapTextRenderer::BitmapTextRenderer(wxDataViewCellMode mode /*= wxDATAVIEW_CELL_EDITABLE*/,
int align /*= wxDVR_DEFAULT_ALIGNMENT*/):
wxDataViewRenderer(wxT("PrusaDataViewBitmapText"), mode, align)
{
SetMode(mode);
SetAlignment(align);
}
#endif // ENABLE_NONCUSTOM_DATA_VIEW_RENDERING
BitmapTextRenderer::~BitmapTextRenderer()
{
#ifdef SUPPORTS_MARKUP
#ifdef wxHAS_GENERIC_DATAVIEWCTRL
delete m_markupText;
#endif //wxHAS_GENERIC_DATAVIEWCTRL
#endif // SUPPORTS_MARKUP
}
void BitmapTextRenderer::EnableMarkup(bool enable)
{
#ifdef SUPPORTS_MARKUP
#ifdef wxHAS_GENERIC_DATAVIEWCTRL
if (enable) {
if (!m_markupText)
m_markupText = new wxItemMarkupText(wxString());
}
else {
if (m_markupText) {
delete m_markupText;
m_markupText = nullptr;
}
}
#else
is_markupText = enable;
#endif //wxHAS_GENERIC_DATAVIEWCTRL
#endif // SUPPORTS_MARKUP
}
bool BitmapTextRenderer::SetValue(const wxVariant &value)
{
m_value << value;
#ifdef SUPPORTS_MARKUP
#ifdef wxHAS_GENERIC_DATAVIEWCTRL
if (m_markupText)
m_markupText->SetMarkup(m_value.GetText());
/*
#else
#if defined(__WXGTK__)
GValue gvalue = G_VALUE_INIT;
g_value_init(&gvalue, G_TYPE_STRING);
g_value_set_string(&gvalue, wxGTK_CONV_FONT(str.GetText(), GetOwner()->GetOwner()->GetFont()));
g_object_set_property(G_OBJECT(m_renderer/ *.GetText()* /), is_markupText ? "markup" : "text", &gvalue);
g_value_unset(&gvalue);
#endif // __WXGTK__
*/
#endif // wxHAS_GENERIC_DATAVIEWCTRL
#endif // SUPPORTS_MARKUP
return true;
}
bool BitmapTextRenderer::GetValue(wxVariant& WXUNUSED(value)) const
{
return false;
}
#if ENABLE_NONCUSTOM_DATA_VIEW_RENDERING && wxUSE_ACCESSIBILITY
wxString BitmapTextRenderer::GetAccessibleDescription() const
{
#ifdef SUPPORTS_MARKUP
if (m_markupText)
return wxMarkupParser::Strip(m_text);
#endif // SUPPORTS_MARKUP
return m_value.GetText();
}
#endif // wxUSE_ACCESSIBILITY && ENABLE_NONCUSTOM_DATA_VIEW_RENDERING
bool BitmapTextRenderer::Render(wxRect rect, wxDC *dc, int state)
{
int xoffset = 0;
const wxBitmap& icon = m_value.GetBitmap();
if (icon.IsOk())
{
#ifdef __APPLE__
wxSize icon_sz = icon.GetScaledSize();
#else
wxSize icon_sz = icon.GetSize();
#endif
dc->DrawBitmap(icon, rect.x, rect.y + (rect.height - icon_sz.y) / 2);
xoffset = icon_sz.x + 4;
}
#if defined(SUPPORTS_MARKUP) && defined(wxHAS_GENERIC_DATAVIEWCTRL)
if (m_markupText)
{
rect.x += xoffset;
m_markupText->Render(GetView(), *dc, rect, 0, GetEllipsizeMode());
}
else
#endif // SUPPORTS_MARKUP && wxHAS_GENERIC_DATAVIEWCTRL
#ifdef _WIN32
// workaround for Windows DarkMode : Don't respect to the state & wxDATAVIEW_CELL_SELECTED to avoid update of the text color
RenderText(m_value.GetText(), xoffset, rect, dc, state & wxDATAVIEW_CELL_SELECTED ? 0 :state);
#else
RenderText(m_value.GetText(), xoffset, rect, dc, state);
#endif
return true;
}
wxSize BitmapTextRenderer::GetSize() const
{
if (!m_value.GetText().empty())
{
wxSize size;
#if defined(SUPPORTS_MARKUP) && defined(wxHAS_GENERIC_DATAVIEWCTRL)
if (m_markupText)
{
wxDataViewCtrl* const view = GetView();
wxClientDC dc(view);
if (GetAttr().HasFont())
dc.SetFont(GetAttr().GetEffectiveFont(view->GetFont()));
size = m_markupText->Measure(dc);
int lines = m_value.GetText().Freq('\n') + 1;
size.SetHeight(size.GetHeight() * lines);
}
else
#endif // SUPPORTS_MARKUP && wxHAS_GENERIC_DATAVIEWCTRL
size = GetTextExtent(m_value.GetText());
if (m_value.GetBitmap().IsOk())
size.x += m_value.GetBitmap().GetWidth() + 4;
return size;
}
return wxSize(80, 20);
}
wxWindow* BitmapTextRenderer::CreateEditorCtrl(wxWindow* parent, wxRect labelRect, const wxVariant& value)
{
if (can_create_editor_ctrl && !can_create_editor_ctrl())
return nullptr;
DataViewBitmapText data;
data << value;
m_was_unusable_symbol = false;
wxPoint position = labelRect.GetPosition();
if (data.GetBitmap().IsOk()) {
const int bmp_width = data.GetBitmap().GetWidth();
position.x += bmp_width;
labelRect.SetWidth(labelRect.GetWidth() - bmp_width);
}
wxTextCtrl* text_editor = new wxTextCtrl(parent, wxID_ANY, data.GetText(),
position, labelRect.GetSize(), wxTE_PROCESS_ENTER);
text_editor->SetInsertionPointEnd();
text_editor->SelectAll();
return text_editor;
}
bool BitmapTextRenderer::GetValueFromEditorCtrl(wxWindow* ctrl, wxVariant& value)
{
wxTextCtrl* text_editor = wxDynamicCast(ctrl, wxTextCtrl);
if (!text_editor || text_editor->GetValue().IsEmpty())
return false;
std::string chosen_name = into_u8(text_editor->GetValue());
const char* unusable_symbols = "<>:/\\|?*\"";
for (size_t i = 0; i < std::strlen(unusable_symbols); i++) {
if (chosen_name.find_first_of(unusable_symbols[i]) != std::string::npos) {
m_was_unusable_symbol = true;
return false;
}
}
// The icon can't be edited so get its old value and reuse it.
wxVariant valueOld;
GetView()->GetModel()->GetValue(valueOld, m_item, /*colName*/0);
DataViewBitmapText bmpText;
bmpText << valueOld;
// But replace the text with the value entered by user.
bmpText.SetText(text_editor->GetValue());
value << bmpText;
return true;
}
// ----------------------------------------------------------------------------
// BitmapChoiceRenderer
// ----------------------------------------------------------------------------
bool BitmapChoiceRenderer::SetValue(const wxVariant& value)
{
m_value << value;
return true;
}
bool BitmapChoiceRenderer::GetValue(wxVariant& value) const
{
value << m_value;
return true;
}
bool BitmapChoiceRenderer::Render(wxRect rect, wxDC* dc, int state)
{
int xoffset = 0;
const wxBitmap& icon = m_value.GetBitmap();
if (icon.IsOk())
{
dc->DrawBitmap(icon, rect.x, rect.y + (rect.height - icon.GetHeight()) / 2);
xoffset = icon.GetWidth() + 4;
if (rect.height==0)
rect.height= icon.GetHeight();
}
#ifdef _WIN32
// workaround for Windows DarkMode : Don't respect to the state & wxDATAVIEW_CELL_SELECTED to avoid update of the text color
RenderText(m_value.GetText(), xoffset, rect, dc, state & wxDATAVIEW_CELL_SELECTED ? 0 : state);
#else
RenderText(m_value.GetText(), xoffset, rect, dc, state);
#endif
return true;
}
wxSize BitmapChoiceRenderer::GetSize() const
{
wxSize sz = GetTextExtent(m_value.GetText());
if (m_value.GetBitmap().IsOk())
sz.x += m_value.GetBitmap().GetWidth() + 4;
return sz;
}
wxWindow* BitmapChoiceRenderer::CreateEditorCtrl(wxWindow* parent, wxRect labelRect, const wxVariant& value)
{
if (can_create_editor_ctrl && !can_create_editor_ctrl())
return nullptr;
std::vector<wxBitmap*> icons = get_extruder_color_icons();
if (icons.empty())
return nullptr;
DataViewBitmapText data;
data << value;
#ifdef _WIN32
Slic3r::GUI::BitmapComboBox* c_editor = new Slic3r::GUI::BitmapComboBox(parent, wxID_ANY, wxEmptyString,
#else
auto c_editor = new wxBitmapComboBox(parent, wxID_ANY, wxEmptyString,
#endif
labelRect.GetTopLeft(), wxSize(labelRect.GetWidth(), -1),
0, nullptr , wxCB_READONLY);
int def_id = get_default_extruder_idx ? get_default_extruder_idx() : 0;
c_editor->Append(_L("default"), def_id < 0 ? wxNullBitmap : *icons[def_id]);
for (size_t i = 0; i < icons.size(); i++)
c_editor->Append(wxString::Format("%d", i+1), *icons[i]);
c_editor->SetSelection(atoi(data.GetText().c_str()));
// to avoid event propagation to other sidebar items
c_editor->Bind(wxEVT_COMBOBOX, [this](wxCommandEvent& evt) {
evt.StopPropagation();
// FinishEditing grabs new selection and triggers config update. We better call
// it explicitly, automatic update on KILL_FOCUS didn't work on Linux.
this->FinishEditing();
});
return c_editor;
}
bool BitmapChoiceRenderer::GetValueFromEditorCtrl(wxWindow* ctrl, wxVariant& value)
{
wxBitmapComboBox* c = static_cast<wxBitmapComboBox*>(ctrl);
int selection = c->GetSelection();
if (selection < 0)
return false;
DataViewBitmapText bmpText;
bmpText.SetText(c->GetString(selection));
bmpText.SetBitmap(c->GetItemBitmap(selection));
value << bmpText;
return true;
}
// ----------------------------------------------------------------------------
// TextRenderer
// ----------------------------------------------------------------------------
bool TextRenderer::SetValue(const wxVariant& value)
{
m_value = value.GetString();
return true;
}
bool TextRenderer::GetValue(wxVariant& value) const
{
return false;
}
bool TextRenderer::Render(wxRect rect, wxDC* dc, int state)
{
#ifdef _WIN32
// workaround for Windows DarkMode : Don't respect to the state & wxDATAVIEW_CELL_SELECTED to avoid update of the text color
RenderText(m_value, 0, rect, dc, state & wxDATAVIEW_CELL_SELECTED ? 0 : state);
#else
RenderText(m_value, 0, rect, dc, state);
#endif
return true;
}
wxSize TextRenderer::GetSize() const
{
return GetTextExtent(m_value);
}
<commit_msg>MSW specific: Fixed a crash on change of the extruder using keyboard<commit_after>#include "ExtraRenderers.hpp"
#include "wxExtensions.hpp"
#include "GUI.hpp"
#include "I18N.hpp"
#include "BitmapComboBox.hpp"
#include <wx/dc.h>
#ifdef wxHAS_GENERIC_DATAVIEWCTRL
#include "wx/generic/private/markuptext.h"
#include "wx/generic/private/rowheightcache.h"
#include "wx/generic/private/widthcalc.h"
#endif
/*
#ifdef __WXGTK__
#include "wx/gtk/private.h"
#include "wx/gtk/private/value.h"
#endif
*/
#if wxUSE_ACCESSIBILITY
#include "wx/private/markupparser.h"
#endif // wxUSE_ACCESSIBILITY
using Slic3r::GUI::from_u8;
using Slic3r::GUI::into_u8;
//-----------------------------------------------------------------------------
// DataViewBitmapText
//-----------------------------------------------------------------------------
wxIMPLEMENT_DYNAMIC_CLASS(DataViewBitmapText, wxObject)
IMPLEMENT_VARIANT_OBJECT(DataViewBitmapText)
// ---------------------------------------------------------
// BitmapTextRenderer
// ---------------------------------------------------------
#if ENABLE_NONCUSTOM_DATA_VIEW_RENDERING
BitmapTextRenderer::BitmapTextRenderer(wxDataViewCellMode mode /*= wxDATAVIEW_CELL_EDITABLE*/,
int align /*= wxDVR_DEFAULT_ALIGNMENT*/):
wxDataViewRenderer(wxT("PrusaDataViewBitmapText"), mode, align)
{
SetMode(mode);
SetAlignment(align);
}
#endif // ENABLE_NONCUSTOM_DATA_VIEW_RENDERING
BitmapTextRenderer::~BitmapTextRenderer()
{
#ifdef SUPPORTS_MARKUP
#ifdef wxHAS_GENERIC_DATAVIEWCTRL
delete m_markupText;
#endif //wxHAS_GENERIC_DATAVIEWCTRL
#endif // SUPPORTS_MARKUP
}
void BitmapTextRenderer::EnableMarkup(bool enable)
{
#ifdef SUPPORTS_MARKUP
#ifdef wxHAS_GENERIC_DATAVIEWCTRL
if (enable) {
if (!m_markupText)
m_markupText = new wxItemMarkupText(wxString());
}
else {
if (m_markupText) {
delete m_markupText;
m_markupText = nullptr;
}
}
#else
is_markupText = enable;
#endif //wxHAS_GENERIC_DATAVIEWCTRL
#endif // SUPPORTS_MARKUP
}
bool BitmapTextRenderer::SetValue(const wxVariant &value)
{
m_value << value;
#ifdef SUPPORTS_MARKUP
#ifdef wxHAS_GENERIC_DATAVIEWCTRL
if (m_markupText)
m_markupText->SetMarkup(m_value.GetText());
/*
#else
#if defined(__WXGTK__)
GValue gvalue = G_VALUE_INIT;
g_value_init(&gvalue, G_TYPE_STRING);
g_value_set_string(&gvalue, wxGTK_CONV_FONT(str.GetText(), GetOwner()->GetOwner()->GetFont()));
g_object_set_property(G_OBJECT(m_renderer/ *.GetText()* /), is_markupText ? "markup" : "text", &gvalue);
g_value_unset(&gvalue);
#endif // __WXGTK__
*/
#endif // wxHAS_GENERIC_DATAVIEWCTRL
#endif // SUPPORTS_MARKUP
return true;
}
bool BitmapTextRenderer::GetValue(wxVariant& WXUNUSED(value)) const
{
return false;
}
#if ENABLE_NONCUSTOM_DATA_VIEW_RENDERING && wxUSE_ACCESSIBILITY
wxString BitmapTextRenderer::GetAccessibleDescription() const
{
#ifdef SUPPORTS_MARKUP
if (m_markupText)
return wxMarkupParser::Strip(m_text);
#endif // SUPPORTS_MARKUP
return m_value.GetText();
}
#endif // wxUSE_ACCESSIBILITY && ENABLE_NONCUSTOM_DATA_VIEW_RENDERING
bool BitmapTextRenderer::Render(wxRect rect, wxDC *dc, int state)
{
int xoffset = 0;
const wxBitmap& icon = m_value.GetBitmap();
if (icon.IsOk())
{
#ifdef __APPLE__
wxSize icon_sz = icon.GetScaledSize();
#else
wxSize icon_sz = icon.GetSize();
#endif
dc->DrawBitmap(icon, rect.x, rect.y + (rect.height - icon_sz.y) / 2);
xoffset = icon_sz.x + 4;
}
#if defined(SUPPORTS_MARKUP) && defined(wxHAS_GENERIC_DATAVIEWCTRL)
if (m_markupText)
{
rect.x += xoffset;
m_markupText->Render(GetView(), *dc, rect, 0, GetEllipsizeMode());
}
else
#endif // SUPPORTS_MARKUP && wxHAS_GENERIC_DATAVIEWCTRL
#ifdef _WIN32
// workaround for Windows DarkMode : Don't respect to the state & wxDATAVIEW_CELL_SELECTED to avoid update of the text color
RenderText(m_value.GetText(), xoffset, rect, dc, state & wxDATAVIEW_CELL_SELECTED ? 0 :state);
#else
RenderText(m_value.GetText(), xoffset, rect, dc, state);
#endif
return true;
}
wxSize BitmapTextRenderer::GetSize() const
{
if (!m_value.GetText().empty())
{
wxSize size;
#if defined(SUPPORTS_MARKUP) && defined(wxHAS_GENERIC_DATAVIEWCTRL)
if (m_markupText)
{
wxDataViewCtrl* const view = GetView();
wxClientDC dc(view);
if (GetAttr().HasFont())
dc.SetFont(GetAttr().GetEffectiveFont(view->GetFont()));
size = m_markupText->Measure(dc);
int lines = m_value.GetText().Freq('\n') + 1;
size.SetHeight(size.GetHeight() * lines);
}
else
#endif // SUPPORTS_MARKUP && wxHAS_GENERIC_DATAVIEWCTRL
size = GetTextExtent(m_value.GetText());
if (m_value.GetBitmap().IsOk())
size.x += m_value.GetBitmap().GetWidth() + 4;
return size;
}
return wxSize(80, 20);
}
wxWindow* BitmapTextRenderer::CreateEditorCtrl(wxWindow* parent, wxRect labelRect, const wxVariant& value)
{
if (can_create_editor_ctrl && !can_create_editor_ctrl())
return nullptr;
DataViewBitmapText data;
data << value;
m_was_unusable_symbol = false;
wxPoint position = labelRect.GetPosition();
if (data.GetBitmap().IsOk()) {
const int bmp_width = data.GetBitmap().GetWidth();
position.x += bmp_width;
labelRect.SetWidth(labelRect.GetWidth() - bmp_width);
}
wxTextCtrl* text_editor = new wxTextCtrl(parent, wxID_ANY, data.GetText(),
position, labelRect.GetSize(), wxTE_PROCESS_ENTER);
text_editor->SetInsertionPointEnd();
text_editor->SelectAll();
return text_editor;
}
bool BitmapTextRenderer::GetValueFromEditorCtrl(wxWindow* ctrl, wxVariant& value)
{
wxTextCtrl* text_editor = wxDynamicCast(ctrl, wxTextCtrl);
if (!text_editor || text_editor->GetValue().IsEmpty())
return false;
std::string chosen_name = into_u8(text_editor->GetValue());
const char* unusable_symbols = "<>:/\\|?*\"";
for (size_t i = 0; i < std::strlen(unusable_symbols); i++) {
if (chosen_name.find_first_of(unusable_symbols[i]) != std::string::npos) {
m_was_unusable_symbol = true;
return false;
}
}
// The icon can't be edited so get its old value and reuse it.
wxVariant valueOld;
GetView()->GetModel()->GetValue(valueOld, m_item, /*colName*/0);
DataViewBitmapText bmpText;
bmpText << valueOld;
// But replace the text with the value entered by user.
bmpText.SetText(text_editor->GetValue());
value << bmpText;
return true;
}
// ----------------------------------------------------------------------------
// BitmapChoiceRenderer
// ----------------------------------------------------------------------------
bool BitmapChoiceRenderer::SetValue(const wxVariant& value)
{
m_value << value;
return true;
}
bool BitmapChoiceRenderer::GetValue(wxVariant& value) const
{
value << m_value;
return true;
}
bool BitmapChoiceRenderer::Render(wxRect rect, wxDC* dc, int state)
{
int xoffset = 0;
const wxBitmap& icon = m_value.GetBitmap();
if (icon.IsOk())
{
dc->DrawBitmap(icon, rect.x, rect.y + (rect.height - icon.GetHeight()) / 2);
xoffset = icon.GetWidth() + 4;
if (rect.height==0)
rect.height= icon.GetHeight();
}
#ifdef _WIN32
// workaround for Windows DarkMode : Don't respect to the state & wxDATAVIEW_CELL_SELECTED to avoid update of the text color
RenderText(m_value.GetText(), xoffset, rect, dc, state & wxDATAVIEW_CELL_SELECTED ? 0 : state);
#else
RenderText(m_value.GetText(), xoffset, rect, dc, state);
#endif
return true;
}
wxSize BitmapChoiceRenderer::GetSize() const
{
wxSize sz = GetTextExtent(m_value.GetText());
if (m_value.GetBitmap().IsOk())
sz.x += m_value.GetBitmap().GetWidth() + 4;
return sz;
}
wxWindow* BitmapChoiceRenderer::CreateEditorCtrl(wxWindow* parent, wxRect labelRect, const wxVariant& value)
{
if (can_create_editor_ctrl && !can_create_editor_ctrl())
return nullptr;
std::vector<wxBitmap*> icons = get_extruder_color_icons();
if (icons.empty())
return nullptr;
DataViewBitmapText data;
data << value;
#ifdef _WIN32
Slic3r::GUI::BitmapComboBox* c_editor = new Slic3r::GUI::BitmapComboBox(parent, wxID_ANY, wxEmptyString,
#else
auto c_editor = new wxBitmapComboBox(parent, wxID_ANY, wxEmptyString,
#endif
labelRect.GetTopLeft(), wxSize(labelRect.GetWidth(), -1),
0, nullptr , wxCB_READONLY);
int def_id = get_default_extruder_idx ? get_default_extruder_idx() : 0;
c_editor->Append(_L("default"), def_id < 0 ? wxNullBitmap : *icons[def_id]);
for (size_t i = 0; i < icons.size(); i++)
c_editor->Append(wxString::Format("%d", i+1), *icons[i]);
c_editor->SetSelection(atoi(data.GetText().c_str()));
// to avoid event propagation to other sidebar items
c_editor->Bind(wxEVT_COMBOBOX, [this](wxCommandEvent& evt) {
evt.StopPropagation();
#ifdef __linux__
// FinishEditing grabs new selection and triggers config update. We better call
// it explicitly, automatic update on KILL_FOCUS didn't work on Linux.
this->FinishEditing();
#endif
});
return c_editor;
}
bool BitmapChoiceRenderer::GetValueFromEditorCtrl(wxWindow* ctrl, wxVariant& value)
{
wxBitmapComboBox* c = static_cast<wxBitmapComboBox*>(ctrl);
int selection = c->GetSelection();
if (selection < 0)
return false;
DataViewBitmapText bmpText;
bmpText.SetText(c->GetString(selection));
bmpText.SetBitmap(c->GetItemBitmap(selection));
value << bmpText;
return true;
}
// ----------------------------------------------------------------------------
// TextRenderer
// ----------------------------------------------------------------------------
bool TextRenderer::SetValue(const wxVariant& value)
{
m_value = value.GetString();
return true;
}
bool TextRenderer::GetValue(wxVariant& value) const
{
return false;
}
bool TextRenderer::Render(wxRect rect, wxDC* dc, int state)
{
#ifdef _WIN32
// workaround for Windows DarkMode : Don't respect to the state & wxDATAVIEW_CELL_SELECTED to avoid update of the text color
RenderText(m_value, 0, rect, dc, state & wxDATAVIEW_CELL_SELECTED ? 0 : state);
#else
RenderText(m_value, 0, rect, dc, state);
#endif
return true;
}
wxSize TextRenderer::GetSize() const
{
return GetTextExtent(m_value);
}
<|endoftext|> |
<commit_before>//===========================================
// Lumina Desktop Source Code
// Copyright (c) 2016, Ken Moore
// Available under the 3-clause BSD license
// See the LICENSE file for full details
//===========================================
#include "page_main.h"
#include "ui_page_main.h"
#include "getPage.h"
//==========
// PUBLIC
//==========
page_main::page_main(QWidget *parent) : PageWidget(parent), ui(new Ui::page_main()){
ui->setupUi(this);
connect(ui->treeWidget, SIGNAL(itemActivated(QTreeWidgetItem*,int)), this, SLOT(itemTriggered(QTreeWidgetItem*)) );
connect(ui->lineEdit, SIGNAL(textChanged(QString)), this, SLOT(searchChanged(QString)) );
}
page_main::~page_main(){
}
void page_main::UpdateItems(QString search){
ui->treeWidget->clear();
//First create the categories
QTreeWidgetItem *interface = new QTreeWidgetItem();
interface->setIcon(0, LXDG::findIcon("preferences-desktop",""));
interface->setText(0, tr("Interface Configuration"));
QTreeWidgetItem *appearance = new QTreeWidgetItem();
appearance->setIcon(0, LXDG::findIcon("preferences-desktop-color",""));
appearance->setText(0, tr("Appearance"));
QTreeWidgetItem *session = new QTreeWidgetItem();
session->setIcon(0, LXDG::findIcon("preferences-system-session-services",""));
session->setText(0, tr("Desktop Session Options"));
QTreeWidgetItem *apps = new QTreeWidgetItem();
apps->setIcon(0, LXDG::findIcon("preferences-desktop-filetype-association",""));
apps->setText(0, tr("Application Settings"));
//Now go through and add in the known pages for each category
QStringList SL = search.split(" "); //search list
for(int i=0; i<INFO.length(); i++){
if(!search.isEmpty() ){
//See if this item needs to be included or not
QStringList info; info << INFO[i].name.split(" ") << INFO[i].title.split(" ") << INFO[i].comment.split(" ") << INFO[i].search_tags;
info.removeDuplicates(); //remove any duplicate terms/info first
bool ok = true;
for(int s=0; s<SL.length() && ok; s++){
ok = !info.filter(SL[s]).isEmpty();
}
if(!ok){ continue; } //no duplicates between search terms and available info
}
qDebug() << "Item Found:" << INFO[i].id << INFO[i].title;
QTreeWidgetItem *it = new QTreeWidgetItem();
it->setIcon(0, LXDG::findIcon(INFO[i].icon,"") );
it->setText(0, INFO[i].name);
it->setStatusTip(0, INFO[i].comment);
it->setToolTip(0, INFO[i].comment);
it->setWhatsThis(0, INFO[i].id);
if(INFO[i].category=="interface"){ interface->addChild(it); }
else if(INFO[i].category=="appearance"){ appearance->addChild(it); }
else if(INFO[i].category=="session"){ session->addChild(it); }
else if(INFO[i].category=="apps"){ apps->addChild(it); }
else{ ui->treeWidget->addTopLevelItem(it); }
}
//Now add the categories to the tree widget if they are non-empty
if(interface->childCount()>0){ ui->treeWidget->addTopLevelItem(interface); interface->setExpanded(true); }
if(appearance->childCount()>0){ ui->treeWidget->addTopLevelItem(appearance); appearance->setExpanded(true); }
if(session->childCount()>0){ ui->treeWidget->addTopLevelItem(session); session->setExpanded(true); }
if(apps->childCount()>0){ ui->treeWidget->addTopLevelItem(apps); apps->setExpanded(true); }
}
//================
// PUBLIC SLOTS
//================
void page_main::SaveSettings(){
}
void page_main::LoadSettings(int){
emit HasPendingChanges(false);
emit ChangePageTitle( tr("Desktop Settings") );
INFO.clear();
INFO = KnownPages();
UpdateItems("");
}
void page_main::updateIcons(){
UpdateItems("");
}
//=================
// PRIVATE SLOTS
//=================
void page_main::itemTriggered(QTreeWidgetItem *it){
if(it->childCount()>0){
it->setExpanded( !it->isExpanded() );
}else if(!it->whatsThis(0).isEmpty()){
emit ChangePage(it->whatsThis(0));
}
}
void page_main::searchChanged(QString txt){
UpdateItems(txt.simplified());
}
<commit_msg>Finish up the interactions on the main selection page in the new UI.<commit_after>//===========================================
// Lumina Desktop Source Code
// Copyright (c) 2016, Ken Moore
// Available under the 3-clause BSD license
// See the LICENSE file for full details
//===========================================
#include "page_main.h"
#include "ui_page_main.h"
#include "getPage.h"
//==========
// PUBLIC
//==========
page_main::page_main(QWidget *parent) : PageWidget(parent), ui(new Ui::page_main()){
ui->setupUi(this);
ui->treeWidget->setMouseTracking(true);
connect(ui->treeWidget, SIGNAL(itemActivated(QTreeWidgetItem*,int)), this, SLOT(itemTriggered(QTreeWidgetItem*)) );
connect(ui->treeWidget, SIGNAL(itemClicked(QTreeWidgetItem*,int)), this, SLOT(itemTriggered(QTreeWidgetItem*)) );
connect(ui->lineEdit, SIGNAL(textChanged(QString)), this, SLOT(searchChanged(QString)) );
}
page_main::~page_main(){
}
void page_main::UpdateItems(QString search){
ui->treeWidget->clear();
//First create the categories
QTreeWidgetItem *interface = new QTreeWidgetItem();
interface->setIcon(0, LXDG::findIcon("preferences-desktop",""));
interface->setText(0, tr("Interface Configuration"));
QTreeWidgetItem *appearance = new QTreeWidgetItem();
appearance->setIcon(0, LXDG::findIcon("preferences-desktop-color",""));
appearance->setText(0, tr("Appearance"));
QTreeWidgetItem *session = new QTreeWidgetItem();
session->setIcon(0, LXDG::findIcon("preferences-system-session-services",""));
session->setText(0, tr("Desktop Session Options"));
QTreeWidgetItem *apps = new QTreeWidgetItem();
apps->setIcon(0, LXDG::findIcon("preferences-desktop-filetype-association",""));
apps->setText(0, tr("Application Settings"));
//Now go through and add in the known pages for each category
QStringList SL = search.split(" "); //search list
for(int i=0; i<INFO.length(); i++){
if(!search.isEmpty() ){
//See if this item needs to be included or not
QStringList info; info << INFO[i].name.split(" ") << INFO[i].title.split(" ") << INFO[i].comment.split(" ") << INFO[i].search_tags;
info.removeDuplicates(); //remove any duplicate terms/info first
bool ok = true;
for(int s=0; s<SL.length() && ok; s++){
ok = !info.filter(SL[s]).isEmpty();
}
if(!ok){ continue; } //no duplicates between search terms and available info
}
qDebug() << "Item Found:" << INFO[i].id << INFO[i].title;
QTreeWidgetItem *it = new QTreeWidgetItem();
it->setIcon(0, LXDG::findIcon(INFO[i].icon,"") );
it->setText(0, INFO[i].name);
it->setStatusTip(0, INFO[i].comment);
it->setToolTip(0, INFO[i].comment);
it->setWhatsThis(0, INFO[i].id);
if(INFO[i].category=="interface"){ interface->addChild(it); }
else if(INFO[i].category=="appearance"){ appearance->addChild(it); }
else if(INFO[i].category=="session"){ session->addChild(it); }
else if(INFO[i].category=="apps"){ apps->addChild(it); }
else{ ui->treeWidget->addTopLevelItem(it); }
}
//Now add the categories to the tree widget if they are non-empty
if(interface->childCount()>0){ ui->treeWidget->addTopLevelItem(interface); interface->setExpanded(true); }
if(appearance->childCount()>0){ ui->treeWidget->addTopLevelItem(appearance); appearance->setExpanded(true); }
if(session->childCount()>0){ ui->treeWidget->addTopLevelItem(session); session->setExpanded(true); }
if(apps->childCount()>0){ ui->treeWidget->addTopLevelItem(apps); apps->setExpanded(true); }
}
//================
// PUBLIC SLOTS
//================
void page_main::SaveSettings(){
}
void page_main::LoadSettings(int){
emit HasPendingChanges(false);
emit ChangePageTitle( tr("Desktop Settings") );
INFO.clear();
INFO = KnownPages();
UpdateItems("");
}
void page_main::updateIcons(){
UpdateItems("");
}
//=================
// PRIVATE SLOTS
//=================
void page_main::itemTriggered(QTreeWidgetItem *it){
if(it->childCount()>0){
it->setExpanded( !it->isExpanded() );
}else if(!it->whatsThis(0).isEmpty()){
emit ChangePage(it->whatsThis(0));
}
}
void page_main::searchChanged(QString txt){
UpdateItems(txt.simplified());
}
<|endoftext|> |
<commit_before><commit_msg>[SWDEV-345750] Fix Tensorflow pooling test failure (#1659)<commit_after><|endoftext|> |
<commit_before>/***********************************************************************************************************************
* *
* SPLASH build system v0.2 *
* *
* Copyright (c) 2016 Andrew D. Zonenberg *
* 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 any contributors may be used to endorse or promote products *
* derived from this software without specific prior written permission. *
* *
* THIS SOFTWARE IS PROVIDED BY THE AUTHORS "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 AUTHORS BE HELD 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 "splashcore.h"
using namespace std;
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Construction / destruction
/**
@brief Default constructor (for non-targets)
TODO: how do we use this? Disallow?
*/
BuildGraphNode::BuildGraphNode()
{
m_ref = false;
m_job = NULL;
}
/**
@brief Constructor for nodes which are source files
*/
BuildGraphNode::BuildGraphNode(
BuildGraph* graph,
BuildFlag::FlagUsage usage,
string path,
string hash)
: m_ref(false)
, m_graph(graph)
, m_toolchain("")
, m_hash(hash)
, m_arch("generic")
, m_config("generic")
, m_name(GetBasenameOfFile(path))
, m_script("")
, m_path(path)
, m_invalidInput(false)
, m_usage(usage)
, m_job(NULL)
{
//No toolchain
m_toolchainHash = "";
}
/**
@brief Constructor for nodes which are object files or equivalent
*/
BuildGraphNode::BuildGraphNode(
BuildGraph* graph,
BuildFlag::FlagUsage usage,
string toolchain,
string arch,
string name,
string path,
set<BuildFlag> flags)
: m_ref(false)
, m_graph(graph)
, m_toolchain(toolchain)
, m_arch(arch)
, m_config("generic")
, m_name(name)
, m_script("")
, m_path(path)
, m_flags(flags)
, m_invalidInput(false)
, m_usage(usage)
, m_job(NULL)
{
//Look up the hash of our toolchain
m_toolchainHash = g_nodeManager->GetToolchainHash(m_arch, m_toolchain);
}
/**
@brief Constructor for nodes which are targets or tests
*/
BuildGraphNode::BuildGraphNode(
BuildGraph* graph,
BuildFlag::FlagUsage usage,
string toolchain,
string arch,
string config,
string name,
string scriptpath,
string path,
YAML::Node& node)
: m_ref(false)
, m_graph(graph)
, m_toolchain(toolchain)
, m_arch(arch)
, m_config(config)
, m_name(name)
, m_script(scriptpath)
, m_path(path)
, m_usage(usage)
, m_job(NULL)
{
//Ignore the toolchain and arches sections, they're already taken care of
//Read the flags section
if(node["flags"])
{
auto nflags = node["flags"];
for(auto it : nflags)
{
//If the flag is "global" pull in the upstream flags
string flag = it.as<std::string>();
if(flag == "global")
graph->GetFlags(toolchain, config, path, m_flags);
else
m_flags.emplace(BuildFlag(flag));
}
}
//anything else is handled in base class (source files etc)
//Look up the hash of our toolchain
m_toolchainHash = g_nodeManager->GetToolchainHash(m_arch, m_toolchain);
}
BuildGraphNode::~BuildGraphNode()
{
//If we have a job, we no longer need if
if(m_job != NULL)
{
m_job->Unref();
m_job = NULL;
}
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// GC reference marking
/**
@brief Mark the node as referenced
*/
void BuildGraphNode::SetRef()
{
lock_guard<recursive_mutex> lock(m_mutex);
if(m_ref)
return;
m_ref = true;
//Mark our dependencies as referenced (if they're not already)
//Sources are a subset of dependencies, no need to process that
auto wc = m_graph->GetWorkingCopy();
for(auto x : m_dependencies)
{
auto h = wc->GetFileHash(x);
if(m_graph->HasNodeWithHash(h))
m_graph->GetNodeWithHash(h)->SetRef();
else
LogError("Node with hash %s is a dependency of us, but not in graph\n", h.c_str());
}
}
/// @brief Mark the node as unreferenced (do not propagate)
void BuildGraphNode::SetUnref()
{
lock_guard<recursive_mutex> lock(m_mutex);
m_ref = false;
}
/// @brief Checks if the node is referenced (do not propagate)
bool BuildGraphNode::IsReferenced()
{
lock_guard<recursive_mutex> lock(m_mutex);
return m_ref;
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Accessors
string BuildGraphNode::GetIndent(int level)
{
string ret;
for(int i=0; i<level; i++)
ret += " ";
return ret;
}
void BuildGraphNode::PrintInfo(int indentLevel)
{
lock_guard<recursive_mutex> lock(m_mutex);
string padded_path = GetIndent(indentLevel) + m_path;
LogDebug("%-85s [%s]\n", padded_path.c_str(), m_hash.c_str());
for(auto d : m_dependencies)
m_graph->GetNodeWithPath(d)->PrintInfo(indentLevel + 1);
}
/**
@brief Figures out what flags are applicable to a particular point in the build process
*/
void BuildGraphNode::GetFlagsForUseAt(
BuildFlag::FlagUsage when,
set<BuildFlag>& flags)
{
lock_guard<recursive_mutex> lock(m_mutex);
for(auto f : m_flags)
{
if(f.IsUsedAt(when))
flags.emplace(f);
}
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Building
/**
@brief Actually start building this node
*/
Job* BuildGraphNode::Build(Job::Priority prio)
{
lock_guard<recursive_mutex> lock(m_mutex);
//If we're already building, return a new reference to the existing job
if(m_job != NULL)
{
m_job->Ref();
return m_job;
}
//Create a new job for us
//Ref it again (implicit creation ref for us, second ref for the caller)
m_job = new BuildJob(prio, m_usage, this, m_toolchainHash);
m_job->Ref();
//Build each of our dependencies, if needed
set<Job*> deps;
auto wc = m_graph->GetWorkingCopy();
for(auto d : m_dependencies)
{
//Look up the graph node
auto h = wc->GetFileHash(d);
if(h == "")
{
LogError("Dependency \"%s\" is not in working copy\n", d.c_str());
return NULL;
}
auto n = m_graph->GetNodeWithHash(h);
//If the node has already been built, no action required
auto state = n->GetOutputState();
if(state == NodeInfo::READY)
continue;
//If not, build it
deps.emplace(n->Build());
}
//Add dependencies to our job
for(auto j : deps)
m_job->AddDependency(j);
//Submit the job to the scheduler
g_scheduler->SubmitJob(m_job);
//and done
return m_job;
}
<commit_msg>splashcore: Fixed bug where flags were not inherited from parent scope if not explicitly pulled<commit_after>/***********************************************************************************************************************
* *
* SPLASH build system v0.2 *
* *
* Copyright (c) 2016 Andrew D. Zonenberg *
* 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 any contributors may be used to endorse or promote products *
* derived from this software without specific prior written permission. *
* *
* THIS SOFTWARE IS PROVIDED BY THE AUTHORS "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 AUTHORS BE HELD 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 "splashcore.h"
using namespace std;
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Construction / destruction
/**
@brief Default constructor (for non-targets)
TODO: how do we use this? Disallow?
*/
BuildGraphNode::BuildGraphNode()
{
m_ref = false;
m_job = NULL;
}
/**
@brief Constructor for nodes which are source files
*/
BuildGraphNode::BuildGraphNode(
BuildGraph* graph,
BuildFlag::FlagUsage usage,
string path,
string hash)
: m_ref(false)
, m_graph(graph)
, m_toolchain("")
, m_hash(hash)
, m_arch("generic")
, m_config("generic")
, m_name(GetBasenameOfFile(path))
, m_script("")
, m_path(path)
, m_invalidInput(false)
, m_usage(usage)
, m_job(NULL)
{
//No toolchain
m_toolchainHash = "";
}
/**
@brief Constructor for nodes which are object files or equivalent
*/
BuildGraphNode::BuildGraphNode(
BuildGraph* graph,
BuildFlag::FlagUsage usage,
string toolchain,
string arch,
string name,
string path,
set<BuildFlag> flags)
: m_ref(false)
, m_graph(graph)
, m_toolchain(toolchain)
, m_arch(arch)
, m_config("generic")
, m_name(name)
, m_script("")
, m_path(path)
, m_flags(flags)
, m_invalidInput(false)
, m_usage(usage)
, m_job(NULL)
{
//Look up the hash of our toolchain
m_toolchainHash = g_nodeManager->GetToolchainHash(m_arch, m_toolchain);
}
/**
@brief Constructor for nodes which are targets or tests
*/
BuildGraphNode::BuildGraphNode(
BuildGraph* graph,
BuildFlag::FlagUsage usage,
string toolchain,
string arch,
string config,
string name,
string scriptpath,
string path,
YAML::Node& node)
: m_ref(false)
, m_graph(graph)
, m_toolchain(toolchain)
, m_arch(arch)
, m_config(config)
, m_name(name)
, m_script(scriptpath)
, m_path(path)
, m_usage(usage)
, m_job(NULL)
{
//Ignore the toolchain and arches sections, they're already taken care of
//Read the flags section
if(node["flags"])
{
auto nflags = node["flags"];
for(auto it : nflags)
{
//If the flag is "global" pull in the upstream flags
string flag = it.as<std::string>();
if(flag == "global")
graph->GetFlags(toolchain, config, path, m_flags);
else
m_flags.emplace(BuildFlag(flag));
}
}
//No flags specified, import base flags
else
graph->GetFlags(toolchain, config, path, m_flags);
//anything else is handled in base class (source files etc)
//Look up the hash of our toolchain
m_toolchainHash = g_nodeManager->GetToolchainHash(m_arch, m_toolchain);
}
BuildGraphNode::~BuildGraphNode()
{
//If we have a job, we no longer need if
if(m_job != NULL)
{
m_job->Unref();
m_job = NULL;
}
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// GC reference marking
/**
@brief Mark the node as referenced
*/
void BuildGraphNode::SetRef()
{
lock_guard<recursive_mutex> lock(m_mutex);
if(m_ref)
return;
m_ref = true;
//Mark our dependencies as referenced (if they're not already)
//Sources are a subset of dependencies, no need to process that
auto wc = m_graph->GetWorkingCopy();
for(auto x : m_dependencies)
{
auto h = wc->GetFileHash(x);
if(m_graph->HasNodeWithHash(h))
m_graph->GetNodeWithHash(h)->SetRef();
else
LogError("Node with hash %s is a dependency of us, but not in graph\n", h.c_str());
}
}
/// @brief Mark the node as unreferenced (do not propagate)
void BuildGraphNode::SetUnref()
{
lock_guard<recursive_mutex> lock(m_mutex);
m_ref = false;
}
/// @brief Checks if the node is referenced (do not propagate)
bool BuildGraphNode::IsReferenced()
{
lock_guard<recursive_mutex> lock(m_mutex);
return m_ref;
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Accessors
string BuildGraphNode::GetIndent(int level)
{
string ret;
for(int i=0; i<level; i++)
ret += " ";
return ret;
}
void BuildGraphNode::PrintInfo(int indentLevel)
{
lock_guard<recursive_mutex> lock(m_mutex);
string padded_path = GetIndent(indentLevel) + m_path;
LogDebug("%-85s [%s]\n", padded_path.c_str(), m_hash.c_str());
for(auto d : m_dependencies)
m_graph->GetNodeWithPath(d)->PrintInfo(indentLevel + 1);
}
/**
@brief Figures out what flags are applicable to a particular point in the build process
*/
void BuildGraphNode::GetFlagsForUseAt(
BuildFlag::FlagUsage when,
set<BuildFlag>& flags)
{
lock_guard<recursive_mutex> lock(m_mutex);
for(auto f : m_flags)
{
if(f.IsUsedAt(when))
flags.emplace(f);
}
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Building
/**
@brief Actually start building this node
*/
Job* BuildGraphNode::Build(Job::Priority prio)
{
lock_guard<recursive_mutex> lock(m_mutex);
//If we're already building, return a new reference to the existing job
if(m_job != NULL)
{
m_job->Ref();
return m_job;
}
//Create a new job for us
//Ref it again (implicit creation ref for us, second ref for the caller)
m_job = new BuildJob(prio, m_usage, this, m_toolchainHash);
m_job->Ref();
//Build each of our dependencies, if needed
set<Job*> deps;
auto wc = m_graph->GetWorkingCopy();
for(auto d : m_dependencies)
{
//Look up the graph node
auto h = wc->GetFileHash(d);
if(h == "")
{
LogError("Dependency \"%s\" is not in working copy\n", d.c_str());
return NULL;
}
auto n = m_graph->GetNodeWithHash(h);
//If the node has already been built, no action required
auto state = n->GetOutputState();
if(state == NodeInfo::READY)
continue;
//If not, build it
deps.emplace(n->Build());
}
//Add dependencies to our job
for(auto j : deps)
m_job->AddDependency(j);
//Submit the job to the scheduler
g_scheduler->SubmitJob(m_job);
//and done
return m_job;
}
<|endoftext|> |
<commit_before>// Copyright 2018 The SwiftShader Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "VkBuffer.hpp"
#include "VkConfig.h"
#include "VkDeviceMemory.hpp"
#include <cstring>
namespace vk
{
const size_t Buffer::DataOffset = offsetof(Buffer, memory);
Buffer::Buffer(const VkBufferCreateInfo* pCreateInfo, void* mem) :
flags(pCreateInfo->flags), size(pCreateInfo->size), usage(pCreateInfo->usage),
sharingMode(pCreateInfo->sharingMode), queueFamilyIndexCount(pCreateInfo->queueFamilyIndexCount),
queueFamilyIndices(reinterpret_cast<uint32_t*>(mem))
{
size_t queueFamilyIndicesSize = sizeof(uint32_t) * queueFamilyIndexCount;
memcpy(queueFamilyIndices, pCreateInfo->pQueueFamilyIndices, queueFamilyIndicesSize);
}
void Buffer::destroy(const VkAllocationCallbacks* pAllocator)
{
vk::deallocate(queueFamilyIndices, pAllocator);
}
size_t Buffer::ComputeRequiredAllocationSize(const VkBufferCreateInfo* pCreateInfo)
{
return sizeof(uint32_t) * pCreateInfo->queueFamilyIndexCount;
}
const VkMemoryRequirements Buffer::getMemoryRequirements() const
{
VkMemoryRequirements memoryRequirements = {};
if(usage & (VK_BUFFER_USAGE_STORAGE_TEXEL_BUFFER_BIT | VK_BUFFER_USAGE_UNIFORM_TEXEL_BUFFER_BIT))
{
memoryRequirements.alignment = vk::MIN_TEXEL_BUFFER_OFFSET_ALIGNMENT;
}
else if(usage & VK_BUFFER_USAGE_STORAGE_BUFFER_BIT)
{
memoryRequirements.alignment = vk::MIN_STORAGE_BUFFER_OFFSET_ALIGNMENT;
}
else if(usage & VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT)
{
memoryRequirements.alignment = vk::MIN_UNIFORM_BUFFER_OFFSET_ALIGNMENT;
}
else
{
memoryRequirements.alignment = REQUIRED_MEMORY_ALIGNMENT;
}
memoryRequirements.memoryTypeBits = vk::MEMORY_TYPE_GENERIC_BIT;
memoryRequirements.size = size; // TODO: also reserve space for a header containing
// the size of the buffer (for robust buffer access)
return memoryRequirements;
}
void Buffer::bind(VkDeviceMemory pDeviceMemory, VkDeviceSize pMemoryOffset)
{
memory = Cast(pDeviceMemory)->getOffsetPointer(pMemoryOffset);
}
void Buffer::copyFrom(const void* srcMemory, VkDeviceSize pSize, VkDeviceSize pOffset)
{
ASSERT((pSize + pOffset) <= size);
memcpy(getOffsetPointer(pOffset), srcMemory, pSize);
}
void Buffer::copyTo(void* dstMemory, VkDeviceSize pSize, VkDeviceSize pOffset) const
{
ASSERT((pSize + pOffset) <= size);
memcpy(dstMemory, getOffsetPointer(pOffset), pSize);
}
void Buffer::copyTo(Buffer* dstBuffer, const VkBufferCopy& pRegion) const
{
copyTo(dstBuffer->getOffsetPointer(pRegion.dstOffset), pRegion.size, pRegion.srcOffset);
}
void Buffer::fill(VkDeviceSize dstOffset, VkDeviceSize fillSize, uint32_t data)
{
size_t bytes = (fillSize == VK_WHOLE_SIZE) ? (size - dstOffset) : fillSize;
ASSERT((bytes + dstOffset) <= size);
uint32_t* memToWrite = static_cast<uint32_t*>(getOffsetPointer(dstOffset));
// Vulkan 1.1 spec: "If VK_WHOLE_SIZE is used and the remaining size of the buffer is
// not a multiple of 4, then the nearest smaller multiple is used."
for(; bytes >= 4; bytes -= 4, memToWrite++)
{
*memToWrite = data;
}
}
void Buffer::update(VkDeviceSize dstOffset, VkDeviceSize dataSize, const void* pData)
{
ASSERT((dataSize + dstOffset) <= size);
memcpy(getOffsetPointer(dstOffset), pData, dataSize);
}
void* Buffer::getOffsetPointer(VkDeviceSize offset) const
{
return reinterpret_cast<uint8_t*>(memory) + offset;
}
uint8_t* Buffer::end() const
{
return reinterpret_cast<uint8_t*>(getOffsetPointer(size + 1));
}
} // namespace vk
<commit_msg>Fix creating Buffer objects in VK_SHARING_MODE_EXCLUSIVE mode<commit_after>// Copyright 2018 The SwiftShader Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "VkBuffer.hpp"
#include "VkConfig.h"
#include "VkDeviceMemory.hpp"
#include <cstring>
namespace vk
{
const size_t Buffer::DataOffset = offsetof(Buffer, memory);
Buffer::Buffer(const VkBufferCreateInfo* pCreateInfo, void* mem) :
flags(pCreateInfo->flags), size(pCreateInfo->size), usage(pCreateInfo->usage),
sharingMode(pCreateInfo->sharingMode)
{
if(pCreateInfo->sharingMode == VK_SHARING_MODE_CONCURRENT)
{
queueFamilyIndexCount = pCreateInfo->queueFamilyIndexCount;
queueFamilyIndices = reinterpret_cast<uint32_t*>(mem);
memcpy(queueFamilyIndices, pCreateInfo->pQueueFamilyIndices, sizeof(uint32_t) * queueFamilyIndexCount);
}
}
void Buffer::destroy(const VkAllocationCallbacks* pAllocator)
{
vk::deallocate(queueFamilyIndices, pAllocator);
}
size_t Buffer::ComputeRequiredAllocationSize(const VkBufferCreateInfo* pCreateInfo)
{
return (pCreateInfo->sharingMode == VK_SHARING_MODE_CONCURRENT) ? sizeof(uint32_t) * pCreateInfo->queueFamilyIndexCount : 0;
}
const VkMemoryRequirements Buffer::getMemoryRequirements() const
{
VkMemoryRequirements memoryRequirements = {};
if(usage & (VK_BUFFER_USAGE_STORAGE_TEXEL_BUFFER_BIT | VK_BUFFER_USAGE_UNIFORM_TEXEL_BUFFER_BIT))
{
memoryRequirements.alignment = vk::MIN_TEXEL_BUFFER_OFFSET_ALIGNMENT;
}
else if(usage & VK_BUFFER_USAGE_STORAGE_BUFFER_BIT)
{
memoryRequirements.alignment = vk::MIN_STORAGE_BUFFER_OFFSET_ALIGNMENT;
}
else if(usage & VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT)
{
memoryRequirements.alignment = vk::MIN_UNIFORM_BUFFER_OFFSET_ALIGNMENT;
}
else
{
memoryRequirements.alignment = REQUIRED_MEMORY_ALIGNMENT;
}
memoryRequirements.memoryTypeBits = vk::MEMORY_TYPE_GENERIC_BIT;
memoryRequirements.size = size; // TODO: also reserve space for a header containing
// the size of the buffer (for robust buffer access)
return memoryRequirements;
}
void Buffer::bind(VkDeviceMemory pDeviceMemory, VkDeviceSize pMemoryOffset)
{
memory = Cast(pDeviceMemory)->getOffsetPointer(pMemoryOffset);
}
void Buffer::copyFrom(const void* srcMemory, VkDeviceSize pSize, VkDeviceSize pOffset)
{
ASSERT((pSize + pOffset) <= size);
memcpy(getOffsetPointer(pOffset), srcMemory, pSize);
}
void Buffer::copyTo(void* dstMemory, VkDeviceSize pSize, VkDeviceSize pOffset) const
{
ASSERT((pSize + pOffset) <= size);
memcpy(dstMemory, getOffsetPointer(pOffset), pSize);
}
void Buffer::copyTo(Buffer* dstBuffer, const VkBufferCopy& pRegion) const
{
copyTo(dstBuffer->getOffsetPointer(pRegion.dstOffset), pRegion.size, pRegion.srcOffset);
}
void Buffer::fill(VkDeviceSize dstOffset, VkDeviceSize fillSize, uint32_t data)
{
size_t bytes = (fillSize == VK_WHOLE_SIZE) ? (size - dstOffset) : fillSize;
ASSERT((bytes + dstOffset) <= size);
uint32_t* memToWrite = static_cast<uint32_t*>(getOffsetPointer(dstOffset));
// Vulkan 1.1 spec: "If VK_WHOLE_SIZE is used and the remaining size of the buffer is
// not a multiple of 4, then the nearest smaller multiple is used."
for(; bytes >= 4; bytes -= 4, memToWrite++)
{
*memToWrite = data;
}
}
void Buffer::update(VkDeviceSize dstOffset, VkDeviceSize dataSize, const void* pData)
{
ASSERT((dataSize + dstOffset) <= size);
memcpy(getOffsetPointer(dstOffset), pData, dataSize);
}
void* Buffer::getOffsetPointer(VkDeviceSize offset) const
{
return reinterpret_cast<uint8_t*>(memory) + offset;
}
uint8_t* Buffer::end() const
{
return reinterpret_cast<uint8_t*>(getOffsetPointer(size + 1));
}
} // namespace vk
<|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 "otbVectorData.h"
#include "otbImageFileReader.h"
#include "otbVectorDataFileWriter.h"
#include "otbMeanShiftSmoothingImageFilter.h"
#include "otbStreamingConnectedComponentSegmentationOBIAToVectorDataFilter.h"
typedef float InputPixelType;
const unsigned int Dimension = 2;
typedef otb::Image<unsigned int, Dimension> LabelImageType;
typedef otb::Image<unsigned int, Dimension> MaskImageType;
typedef otb::VectorData<double, Dimension> VectorDataType;
typedef VectorDataType::Pointer VectorDataPointerType;
typedef otb::VectorDataFileWriter<VectorDataType> VectorDataFileWriterType;
typedef VectorDataFileWriterType::Pointer VectorDataFileWriterPointerType;
typedef otb::VectorImage<InputPixelType, Dimension> ImageType;
typedef otb::ImageFileReader<ImageType> ReaderType;
typedef otb::StreamingConnectedComponentSegmentationOBIAToVectorDataFilter
< ImageType,
LabelImageType,
MaskImageType,
VectorDataType > ConnectedComponentSegmentationOBIAToVectorDataFilterType;
typedef otb::MeanShiftSmoothingImageFilter<ImageType, ImageType> MeanShiftFilterType;
int otbMeanShiftStreamingConnectedComponentSegmentationOBIAToVectorDataFilter(int itkNotUsed(argc), char * argv[])
{
/* mean shift parameters */
const char * infname = argv[1];
const char * outputFilename = argv[2];
/* mean shift parameters */
const double spatialBandwidth = atof(argv[3]);
const double rangeBandwidth = atof(argv[4]);
const double threshold = atof(argv[5]);
/* conencted component parameters */
const char * segmentationexpression = argv[6];
unsigned int minobjectsize = atoi(argv[7]);
const char * obiaexpression = argv[8];
unsigned int nbstreams = atoi(argv[9]);
// add meanshift options
// Instantiating object
MeanShiftFilterType::Pointer meanShiftFilter = MeanShiftFilterType::New();
ReaderType::Pointer reader = ReaderType::New();
reader->SetFileName(infname);
meanShiftFilter->SetSpatialBandwidth(spatialBandwidth);
meanShiftFilter->SetRangeBandwidth(rangeBandwidth);
meanShiftFilter->SetThreshold(threshold);
meanShiftFilter->SetInput(reader->GetOutput());
meanShiftFilter->GetRangeOutput();
ConnectedComponentSegmentationOBIAToVectorDataFilterType::FilterType::Pointer
connected = ConnectedComponentSegmentationOBIAToVectorDataFilterType::FilterType::New();
connected->GetFilter()->SetInput(meanShiftFilter->GetRangeOutput());
connected->GetFilter()->SetMaskExpression(maskexpression);
connected->GetFilter()->SetConnectedComponentExpression(segmentationexpression);
connected->GetFilter()->SetMinimumObjectSize(minobjectsize);
connected->GetFilter()->SetOBIAExpression(obiaexpression);
connected->GetStreamer()->SetNumberOfDivisionsStrippedStreaming(nbstreams);
connected->Update();
VectorDataFileWriterPointerType vdwriter = VectorDataFileWriterType::New();
vdwriter->SetInput(connected->GetFilter()->GetOutputVectorData());
vdwriter->SetFileName(outputFilename);
vdwriter->Update();
return EXIT_SUCCESS;
}
<commit_msg>TEST: Wrong handling of empty string in otb_add_test<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 "otbVectorData.h"
#include "otbImageFileReader.h"
#include "otbVectorDataFileWriter.h"
#include "otbMeanShiftSmoothingImageFilter.h"
#include "otbStreamingConnectedComponentSegmentationOBIAToVectorDataFilter.h"
typedef float InputPixelType;
const unsigned int Dimension = 2;
typedef otb::Image<unsigned int, Dimension> LabelImageType;
typedef otb::Image<unsigned int, Dimension> MaskImageType;
typedef otb::VectorData<double, Dimension> VectorDataType;
typedef VectorDataType::Pointer VectorDataPointerType;
typedef otb::VectorDataFileWriter<VectorDataType> VectorDataFileWriterType;
typedef VectorDataFileWriterType::Pointer VectorDataFileWriterPointerType;
typedef otb::VectorImage<InputPixelType, Dimension> ImageType;
typedef otb::ImageFileReader<ImageType> ReaderType;
typedef otb::StreamingConnectedComponentSegmentationOBIAToVectorDataFilter
< ImageType,
LabelImageType,
MaskImageType,
VectorDataType > ConnectedComponentSegmentationOBIAToVectorDataFilterType;
typedef otb::MeanShiftSmoothingImageFilter<ImageType, ImageType> MeanShiftFilterType;
int otbMeanShiftStreamingConnectedComponentSegmentationOBIAToVectorDataFilter(int itkNotUsed(argc), char * argv[])
{
/* mean shift parameters */
const char * infname = argv[1];
const char * outputFilename = argv[2];
/* mean shift parameters */
const double spatialBandwidth = atof(argv[3]);
const double rangeBandwidth = atof(argv[4]);
const double threshold = atof(argv[5]);
/* conencted component parameters */
const char * segmentationexpression = argv[6];
unsigned int minobjectsize = atoi(argv[7]);
const char * obiaexpression = argv[8];
unsigned int nbstreams = atoi(argv[9]);
// add meanshift options
// Instantiating object
MeanShiftFilterType::Pointer meanShiftFilter = MeanShiftFilterType::New();
ReaderType::Pointer reader = ReaderType::New();
reader->SetFileName(infname);
meanShiftFilter->SetSpatialBandwidth(spatialBandwidth);
meanShiftFilter->SetRangeBandwidth(rangeBandwidth);
meanShiftFilter->SetThreshold(threshold);
meanShiftFilter->SetInput(reader->GetOutput());
meanShiftFilter->GetRangeOutput();
ConnectedComponentSegmentationOBIAToVectorDataFilterType::FilterType::Pointer
connected = ConnectedComponentSegmentationOBIAToVectorDataFilterType::FilterType::New();
connected->GetFilter()->SetInput(meanShiftFilter->GetRangeOutput());
connected->GetFilter()->SetConnectedComponentExpression(segmentationexpression);
connected->GetFilter()->SetMinimumObjectSize(minobjectsize);
connected->GetFilter()->SetOBIAExpression(obiaexpression);
connected->GetStreamer()->SetNumberOfDivisionsStrippedStreaming(nbstreams);
connected->Update();
VectorDataFileWriterPointerType vdwriter = VectorDataFileWriterType::New();
vdwriter->SetInput(connected->GetFilter()->GetOutputVectorData());
vdwriter->SetFileName(outputFilename);
vdwriter->Update();
return EXIT_SUCCESS;
}
<|endoftext|> |
<commit_before>#include <windows.h>
#include <winsock.h>
#include <string>
using std::string;
#include <iostream>
using std::cout; using std::endl; using std::cin;
namespace as3
{
class Socket
{
public:
explicit Socket(SOCKET s)
: socket_{ s }
{}
Socket(int address_family, int type, int protocol)
: socket_{ ::socket(address_family, type, protocol) }
{}
auto get() const -> SOCKET { return socket_; }
auto is_failed() const -> bool { return socket_ < 0; }
~Socket(){ ::closesocket(socket_); cout << "clearing socket\n"; }
private:
const SOCKET socket_;
};
const int WSVERS = MAKEWORD(2, 0);
auto make_remote_address(char* arr[]) -> sockaddr_in
{
struct sockaddr_in address;
memset(&address, 0, sizeof(address));
address.sin_addr.s_addr = inet_addr(arr[1]); //IP address
address.sin_port = htons((u_short)atoi(arr[2]));//Port number
address.sin_family = AF_INET;
return address;
}
auto handle_user_input(int arguments_count) -> void
{
if (arguments_count != 3)
{
cout << "USAGE: client IP-address port" << endl;
exit(1);
}
}
auto setup_win_sock_api(WORD version_required) -> WSADATA
{
WSADATA wsadata;
if (WSAStartup(WSVERS, &wsadata) != 0)
{
WSACleanup();
cout << "WSAStartup failed\n";
exit(1);
}
return wsadata;
}
auto connect(as3::Socket const& s, sockaddr_in const& remote_addr) -> void
{
if (0 != ::connect(s.get(), (sockaddr*)&remote_addr, sizeof(remote_addr)))
{
cout << "connect failed\n";
exit(1);
}
}
//return the string received
auto receive(SOCKET s) -> string
{
auto received = string();
for (auto ch = char(0); true; /* */)//receive char by char, end on an LF, ignore CR's
{
if (0 >= recv(s, &ch, 1, 0)) { cout << "recv failed\n"; exit(1); }
if (ch == '\n') break; else if (ch == '\r') continue; else received.push_back(ch);
}
return received;
}
auto send(SOCKET sock, string const& send_buffer) -> void
{
auto bytes_sent = ::send(sock, send_buffer.c_str(), send_buffer.size(), 0);
if (bytes_sent < 0) { cout << "send failed\n"; exit(1); }
}
}//namespace rsa
auto main(int argc, char *argv[]) -> int
{
//handle arugments
as3::handle_user_input(argc);
//init
auto wsa_data = as3::setup_win_sock_api(as3::WSVERS);
auto remote_addr = as3::make_remote_address(argv);
auto sock = as3::Socket{ AF_INET, SOCK_STREAM, 0 };
//connect
as3::connect(sock, remote_addr);
for (auto input = string{}; cin >> input && input != "."; /* */)
{
as3::send(sock.get(), input + "\r\n");
cout << as3::receive(sock.get()) << endl;
}
return 0;
}<commit_msg> modified: src/2015a3/rsa/client/client.cpp<commit_after>#include <windows.h>
#include <winsock.h>
#include <string>
using std::string;
#include <iostream>
using std::cout; using std::endl; using std::cin;
namespace as3
{
const int WSVERS = MAKEWORD(2, 0);
class Socket
{
public:
explicit Socket(SOCKET s)
: socket_{ s }
{}
Socket(int address_family, int type, int protocol)
: socket_{ ::socket(address_family, type, protocol) }
{}
auto get() const -> SOCKET { return socket_; }
auto is_failed() const -> bool { return socket_ < 0; }
~Socket(){ ::closesocket(socket_); }
private:
const SOCKET socket_;
};
auto make_remote_address(char* arr[]) -> sockaddr_in
{
struct sockaddr_in address;
memset(&address, 0, sizeof(address));
address.sin_addr.s_addr = inet_addr(arr[1]); //IP address
address.sin_port = htons((u_short)atoi(arr[2]));//Port number
address.sin_family = AF_INET;
return address;
}
auto handle_user_input(int arguments_count) -> void
{
if (arguments_count != 3)
{
cout << "USAGE: client IP-address port" << endl;
exit(1);
}
}
auto setup_win_sock_api(WORD version_required) -> WSADATA
{
WSADATA wsadata;
if (WSAStartup(WSVERS, &wsadata) != 0)
{
WSACleanup();
cout << "WSAStartup failed\n";
exit(1);
}
return wsadata;
}
auto connect(as3::Socket const& s, sockaddr_in const& remote_addr) -> void
{
if (0 != ::connect(s.get(), (sockaddr*)&remote_addr, sizeof(remote_addr)))
{
cout << "connect failed\n";
exit(1);
}
}
//return the string received
auto receive(SOCKET s) -> string
{
auto received = string();
for (auto ch = char(0); true; /* */)//receive char by char, end on an LF, ignore CR's
{
if (0 >= recv(s, &ch, 1, 0)) { cout << "recv failed\n"; exit(1); }
if (ch == '\n') break; else if (ch == '\r') continue; else received.push_back(ch);
}
return received;
}
auto send(SOCKET sock, string const& send_buffer) -> void
{
auto bytes_sent = ::send(sock, send_buffer.c_str(), send_buffer.size(), 0);
if (bytes_sent < 0) { cout << "send failed\n"; exit(1); }
}
}//namespace rsa
auto main(int argc, char *argv[]) -> int
{
//handle arugments
as3::handle_user_input(argc);
//init
auto wsa_data = as3::setup_win_sock_api(as3::WSVERS);
auto remote_addr = as3::make_remote_address(argv);
auto sock = as3::Socket{ AF_INET, SOCK_STREAM, 0 };
//connect
as3::connect(sock, remote_addr);
for (auto input = string{}; cin >> input && input != "."; /* */)
{
as3::send(sock.get(), input + "\r\n");
cout << as3::receive(sock.get()) << endl;
}
return 0;
}<|endoftext|> |
<commit_before>/*
* $Id: field.cc,v 2.7 2005/10/20 11:24:12 martin Exp $
* Copyright (c) 2004, 2005, Voidsoft AB
*/
#include <iostream>
#include "field.hh"
#include "tdspp.hh" // for TDSPP::Exception
/** Class Field */
/** Constructor */
Field::Field()
: data(NULL) {
}
Field::Field(string name, int size) {
colname = name;
data = new char[size];
data[0] = 0;
}
/** Destructor */
Field::~Field() {
delete [] data;
}
string Field::tostr() {
if (!data) throw TDSPP::Exception("Field::tostr: Data not initialized");
return data;
}
/* Not implemented */
long Field::toint() {
if (!data) throw TDSPP::Exception("Field::toint: Data not initialized");
return 0;
}
/** Class Rows */
/** Constructor */
Rows::Rows()
: currentrow(0) {
}
/** Destructor */
Rows::~Rows() {
clear();
}
void Rows::clear(void) {
while (rows.size()) {
while (rows[rows.size()-1].size()) {
delete rows[rows.size()-1].back();
rows[rows.size()-1].pop_back();
}
rows.pop_back();
}
}
void Rows::printheader(void) {
cout << "| ";
for (unsigned int i=0; i < rows[currentrow].size(); i++) {
cout << rows[currentrow][i]->colname << " | ";
}
cout << endl;
}
void Rows::print(void) {
for (unsigned int i=0; i < rows[currentrow].size(); i++) {
cout << rows[currentrow][i]->colname <<
"=" << rows[currentrow][i]->tostr() << endl;
}
}
<commit_msg>Print rows with format like printheader()<commit_after>/*
* $Id: field.cc,v 2.7 2005/10/20 11:24:12 martin Exp $
* Copyright (c) 2004, 2005, Voidsoft AB
*/
#include <iostream>
#include "field.hh"
#include "tdspp.hh" // for TDSPP::Exception
/** Class Field */
/** Constructor */
Field::Field()
: data(NULL) {
}
Field::Field(string name, int size) {
colname = name;
data = new char[size];
data[0] = 0;
}
/** Destructor */
Field::~Field() {
delete [] data;
}
string Field::tostr() {
if (!data) throw TDSPP::Exception("Field::tostr: Data not initialized");
return data;
}
/* Not implemented */
long Field::toint() {
if (!data) throw TDSPP::Exception("Field::toint: Data not initialized");
return 0;
}
/** Class Rows */
/** Constructor */
Rows::Rows()
: currentrow(0) {
}
/** Destructor */
Rows::~Rows() {
clear();
}
void Rows::clear(void) {
while (rows.size()) {
while (rows[rows.size()-1].size()) {
delete rows[rows.size()-1].back();
rows[rows.size()-1].pop_back();
}
rows.pop_back();
}
}
void Rows::printheader(void) {
cout << "| ";
for (unsigned int i=0; i < rows[currentrow].size(); i++) {
cout << rows[currentrow][i]->colname << " | ";
}
cout << endl;
}
void Rows::print(void) {
cout << "| ";
for (unsigned int i=0; i < rows[currentrow].size(); i++) {
cout << rows[currentrow][i]->tostr() << " | ";
}
cout << endl;
}
<|endoftext|> |
<commit_before>
#include "precompiled.h"
void WarpZone::setDistination(const ofVec2f& pos) {
destPos_ = pos;
x_.animateFromTo(pos_.x, destPos_.x);
y_.animateFromTo(pos_.y, destPos_.y);
x_.setDuration(1);
y_.setDuration(1);
x_.setCurve(EASE_IN);
y_.setCurve(EASE_IN);
}
WarpZone::WarpZone() {
name_ = "WarpZone";
tag_ = WARPZONE;
color_ = ofColor(100, 100, 100, 255);
size_ = ofVec2f(100, 50);
tex_.load("Texture/warphole.png");
tex_.mirror(true, false);
player_ = nullptr;
}
void WarpZone::setup() {
enableCollision();
}
void WarpZone::update(float deltaTime) {
if (!player_) { return; }
x_.update(deltaTime);
y_.update(deltaTime);
player_->setPos(ofVec2f(x_, y_));
if (destPos_ == ofVec2f(x_, y_)) {
player_->canControl(true);
player_->addVelocity(true);
destroy();
}
}
void WarpZone::draw() {
ofPushMatrix();
ofPushStyle();
ofSetColor(color_);
tex_.draw(ofPoint(pos_.x, pos_.y), size_.x, size_.y);
ofPopStyle();
ofPopMatrix();
}
void WarpZone::onCollision(Actor* c_actor) {
if (player_) { return; }
if (c_actor->getTag() == PLAYER) {
color_ = ofFloatColor(0, 0, 0, 0);
player_ = dynamic_cast<Player*>(c_actor);
player_->canControl(false);
player_->addVelocity(false);
enableUpdate();
}
}<commit_msg>warpZone すいません、一個前のを上げてしまいました<commit_after>
#include "precompiled.h"
void WarpZone::setDistination(const ofVec2f& pos) {
destPos_ = pos;
x_.animateFromTo(pos_.x, destPos_.x);
y_.animateFromTo(pos_.y, destPos_.y);
x_.setDuration(1);
y_.setDuration(1);
x_.setCurve(EASE_IN);
y_.setCurve(EASE_IN);
}
WarpZone::WarpZone() {
name_ = "WarpZone";
tag_ = WARPZONE;
color_ = ofColor(100, 100, 100, 255);
size_ = ofVec2f(100, 50);
tex_.load("Texture/warphole.png");
tex_.mirror(true, false);
player_ = nullptr;
}
void WarpZone::setup() {
enableCollision();
}
void WarpZone::update(float deltaTime) {
if (!player_) { return; }
x_.update(deltaTime);
y_.update(deltaTime);
player_->setPos(ofVec2f(x_, y_));
if (destPos_ == ofVec2f(x_, y_)) {
player_->canControl(true);
player_->addVelocity(true);
destroy();
}
}
void WarpZone::draw() {
ofSetColor(color_);
tex_.draw(ofPoint(pos_.x, pos_.y), size_.x, size_.y);
}
void WarpZone::onCollision(Actor* c_actor) {
if (player_) { return; }
if (c_actor->getTag() == PLAYER) {
color_ = ofFloatColor(0, 0, 0, 0);
player_ = dynamic_cast<Player*>(c_actor);
player_->canControl(false);
player_->addVelocity(false);
enableUpdate();
}
}<|endoftext|> |
<commit_before>// Copyright (c) 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/extensions/user_script_master.h"
#include <string>
#include <vector>
#include "base/file_path.h"
#include "base/file_util.h"
#include "base/path_service.h"
#include "base/pickle.h"
#include "base/stl_util-inl.h"
#include "base/string_util.h"
#include "base/thread.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/extensions/extensions_service.h"
#include "chrome/common/extensions/extension.h"
#include "chrome/common/notification_service.h"
#include "chrome/common/url_constants.h"
#include "net/base/net_util.h"
// Helper function to parse greasesmonkey headers
static bool GetDeclarationValue(const StringPiece& line,
const StringPiece& prefix,
std::string* value) {
if (!line.starts_with(prefix))
return false;
std::string temp(line.data() + prefix.length(),
line.length() - prefix.length());
TrimWhitespace(temp, TRIM_ALL, value);
return true;
}
UserScriptMaster::ScriptReloader::ScriptReloader(UserScriptMaster* master)
: master_(master),
master_message_loop_(MessageLoop::current()) {
}
// static
bool UserScriptMaster::ScriptReloader::ParseMetadataHeader(
const StringPiece& script_text, UserScript* script) {
// http://wiki.greasespot.net/Metadata_block
StringPiece line;
size_t line_start = 0;
size_t line_end = 0;
bool in_metadata = false;
static const StringPiece kUserScriptBegin("// ==UserScript==");
static const StringPiece kUserScriptEng("// ==/UserScript==");
static const StringPiece kIncludeDeclaration("// @include ");
static const StringPiece kMatchDeclaration("// @match ");
static const StringPiece kRunAtDeclaration("// @run-at ");
static const StringPiece kRunAtDocumentStartValue("document-start");
static const StringPiece kRunAtDocumentEndValue("document-end");
while (line_start < script_text.length()) {
line_end = script_text.find('\n', line_start);
// Handle the case where there is no trailing newline in the file.
if (line_end == std::string::npos) {
line_end = script_text.length() - 1;
}
line.set(script_text.data() + line_start, line_end - line_start);
if (!in_metadata) {
if (line.starts_with(kUserScriptBegin)) {
in_metadata = true;
}
} else {
if (line.starts_with(kUserScriptEng)) {
break;
}
std::string value;
if (GetDeclarationValue(line, kIncludeDeclaration, &value)) {
// We escape some characters that MatchPattern() considers special.
ReplaceSubstringsAfterOffset(&value, 0, "\\", "\\\\");
ReplaceSubstringsAfterOffset(&value, 0, "?", "\\?");
script->add_glob(value);
} else if (GetDeclarationValue(line, kMatchDeclaration, &value)) {
URLPattern pattern;
if (!pattern.Parse(value))
return false;
script->add_url_pattern(pattern);
} else if (GetDeclarationValue(line, kRunAtDeclaration, &value)) {
if (value == kRunAtDocumentStartValue)
script->set_run_location(UserScript::DOCUMENT_START);
else if (value != kRunAtDocumentEndValue)
return false;
}
// TODO(aa): Handle more types of metadata.
}
line_start = line_end + 1;
}
// It is probably a mistake to declare both @include and @match rules.
if (script->globs().size() > 0 && script->url_patterns().size() > 0)
return false;
// If no patterns were specified, default to @include *. This is what
// Greasemonkey does.
if (script->globs().size() == 0 && script->url_patterns().size() == 0)
script->add_glob("*");
return true;
}
void UserScriptMaster::ScriptReloader::StartScan(
MessageLoop* work_loop, const FilePath& script_dir,
const UserScriptList& lone_scripts) {
// Add a reference to ourselves to keep ourselves alive while we're running.
// Balanced by NotifyMaster().
AddRef();
work_loop->PostTask(FROM_HERE,
NewRunnableMethod(this,
&UserScriptMaster::ScriptReloader::RunScan,
script_dir, lone_scripts));
}
void UserScriptMaster::ScriptReloader::NotifyMaster(
base::SharedMemory* memory) {
if (!master_) {
// The master went away, so these new scripts aren't useful anymore.
delete memory;
} else {
master_->NewScriptsAvailable(memory);
}
// Drop our self-reference.
// Balances StartScan().
Release();
}
static void LoadScriptContent(UserScript::File* script_file) {
std::string content;
file_util::ReadFileToString(script_file->path(), &content);
script_file->set_content(content);
LOG(INFO) << "Loaded user script file: " << script_file->path().value();
}
void UserScriptMaster::ScriptReloader::LoadScriptsFromDirectory(
const FilePath& script_dir, UserScriptList* result) {
// Clear the list. We will populate it with the scrips found in script_dir.
result->clear();
// Find all the scripts in |script_dir|.
if (!script_dir.value().empty()) {
// Create the "<Profile>/User Scripts" directory if it doesn't exist
if (!file_util::DirectoryExists(script_dir))
file_util::CreateDirectory(script_dir);
file_util::FileEnumerator enumerator(script_dir, false,
file_util::FileEnumerator::FILES,
FILE_PATH_LITERAL("*.user.js"));
for (FilePath file = enumerator.Next(); !file.value().empty();
file = enumerator.Next()) {
result->push_back(UserScript());
UserScript& user_script = result->back();
// Push single js file in this UserScript.
GURL url(std::string(chrome::kUserScriptScheme) + ":/" +
net::FilePathToFileURL(file).ExtractFileName());
user_script.js_scripts().push_back(UserScript::File(file, url));
UserScript::File& script_file = user_script.js_scripts().back();
LoadScriptContent(&script_file);
ParseMetadataHeader(script_file.GetContent(), &user_script);
}
}
}
static void LoadLoneScripts(UserScriptList* lone_scripts) {
for (size_t i = 0; i < lone_scripts->size(); ++i) {
UserScript& script = lone_scripts->at(i);
for (size_t k = 0; k < script.js_scripts().size(); ++k) {
UserScript::File& script_file = script.js_scripts()[k];
if (script_file.GetContent().empty()) {
LoadScriptContent(&script_file);
}
}
for (size_t k = 0; k < script.css_scripts().size(); ++k) {
UserScript::File& script_file = script.css_scripts()[k];
if (script_file.GetContent().empty()) {
LoadScriptContent(&script_file);
}
}
}
}
// Pickle user scripts and return pointer to the shared memory.
static base::SharedMemory* Serialize(UserScriptList& scripts) {
Pickle pickle;
pickle.WriteSize(scripts.size());
for (size_t i = 0; i < scripts.size(); i++) {
UserScript& script = scripts[i];
script.Pickle(&pickle);
// Write scripts as 'data' so that we can read it out in the slave without
// allocating a new string.
for (size_t j = 0; j < script.js_scripts().size(); j++) {
StringPiece contents = script.js_scripts()[j].GetContent();
pickle.WriteData(contents.data(), contents.length());
}
for (size_t j = 0; j < script.css_scripts().size(); j++) {
StringPiece contents = script.css_scripts()[j].GetContent();
pickle.WriteData(contents.data(), contents.length());
}
}
// Create the shared memory object.
scoped_ptr<base::SharedMemory> shared_memory(new base::SharedMemory());
if (!shared_memory->Create(std::wstring(), // anonymous
false, // read-only
false, // open existing
pickle.size())) {
return NULL;
}
// Map into our process.
if (!shared_memory->Map(pickle.size()))
return NULL;
// Copy the pickle to shared memory.
memcpy(shared_memory->memory(), pickle.data(), pickle.size());
return shared_memory.release();
}
// This method will be called from the file thread
void UserScriptMaster::ScriptReloader::RunScan(
const FilePath script_dir, UserScriptList lone_script) {
UserScriptList scripts;
// Get list of user scripts.
if (!script_dir.empty())
LoadScriptsFromDirectory(script_dir, &scripts);
LoadLoneScripts(&lone_script);
// Merge with the explicit scripts
scripts.reserve(scripts.size() + lone_script.size());
scripts.insert(scripts.end(),
lone_script.begin(), lone_script.end());
// Scripts now contains list of up-to-date scripts. Load the content in the
// shared memory and let the master know it's ready. We need to post the task
// back even if no scripts ware found to balance the AddRef/Release calls
master_message_loop_->PostTask(FROM_HERE,
NewRunnableMethod(this,
&ScriptReloader::NotifyMaster,
Serialize(scripts)));
}
UserScriptMaster::UserScriptMaster(MessageLoop* worker_loop,
const FilePath& script_dir)
: user_script_dir_(script_dir),
worker_loop_(worker_loop),
extensions_service_ready_(false),
pending_scan_(false) {
if (!user_script_dir_.value().empty())
AddWatchedPath(script_dir);
registrar_.Add(this, NotificationType::EXTENSIONS_READY,
NotificationService::AllSources());
registrar_.Add(this, NotificationType::EXTENSIONS_LOADED,
NotificationService::AllSources());
registrar_.Add(this, NotificationType::EXTENSION_UNLOADED,
NotificationService::AllSources());
}
UserScriptMaster::~UserScriptMaster() {
if (script_reloader_)
script_reloader_->DisownMaster();
// TODO(aa): Enable this when DirectoryWatcher is implemented for linux.
#if defined(OS_WIN) || defined(OS_MACOSX)
STLDeleteElements(&dir_watchers_);
#endif
}
void UserScriptMaster::AddWatchedPath(const FilePath& path) {
// TODO(aa): Enable this when DirectoryWatcher is implemented for linux.
#if defined(OS_WIN) || defined(OS_MACOSX)
DirectoryWatcher* watcher = new DirectoryWatcher();
base::Thread* file_thread = g_browser_process->file_thread();
watcher->Watch(path, this, file_thread ? file_thread->message_loop() : NULL,
true);
dir_watchers_.push_back(watcher);
#endif
}
void UserScriptMaster::NewScriptsAvailable(base::SharedMemory* handle) {
// Ensure handle is deleted or released.
scoped_ptr<base::SharedMemory> handle_deleter(handle);
if (pending_scan_) {
// While we were scanning, there were further changes. Don't bother
// notifying about these scripts and instead just immediately rescan.
pending_scan_ = false;
StartScan();
} else {
// We're no longer scanning.
script_reloader_ = NULL;
// We've got scripts ready to go.
shared_memory_.swap(handle_deleter);
NotificationService::current()->Notify(
NotificationType::USER_SCRIPTS_UPDATED,
NotificationService::AllSources(),
Details<base::SharedMemory>(handle));
}
}
void UserScriptMaster::OnDirectoryChanged(const FilePath& path) {
if (script_reloader_.get()) {
// We're already scanning for scripts. We note that we should rescan when
// we get the chance.
pending_scan_ = true;
return;
}
StartScan();
}
void UserScriptMaster::Observe(NotificationType type,
const NotificationSource& source,
const NotificationDetails& details) {
switch (type.value) {
case NotificationType::EXTENSIONS_READY:
extensions_service_ready_ = true;
StartScan();
break;
case NotificationType::EXTENSIONS_LOADED: {
// TODO(aa): Fix race here. A page could need a content script on startup,
// before the extension has loaded. We need to freeze the renderer in
// that case.
// See: http://code.google.com/p/chromium/issues/detail?id=11547.
// Add any content scripts inside the extension.
ExtensionList* extensions = Details<ExtensionList>(details).ptr();
for (ExtensionList::iterator extension_iterator = extensions->begin();
extension_iterator != extensions->end(); ++extension_iterator) {
Extension* extension = *extension_iterator;
const UserScriptList& scripts = extension->content_scripts();
for (UserScriptList::const_iterator iter = scripts.begin();
iter != scripts.end(); ++iter) {
lone_scripts_.push_back(*iter);
}
}
if (extensions_service_ready_)
StartScan();
break;
}
case NotificationType::EXTENSION_UNLOADED: {
// Remove any content scripts.
Extension* extension = Details<Extension>(details).ptr();
UserScriptList new_lone_scripts;
for (UserScriptList::iterator iter = lone_scripts_.begin();
iter != lone_scripts_.end(); ++iter) {
if (iter->extension_id() != extension->id()) {
new_lone_scripts.push_back(*iter);
}
}
lone_scripts_ = new_lone_scripts;
StartScan();
// TODO(aa): Do we want to do something smarter for the scripts that have
// already been injected?
break;
}
default:
DCHECK(false);
}
}
void UserScriptMaster::StartScan() {
if (!script_reloader_)
script_reloader_ = new ScriptReloader(this);
script_reloader_->StartScan(worker_loop_, user_script_dir_, lone_scripts_);
}
<commit_msg>Coverity: Check the return value of file_util::ReadFileToString. It's possible that the file will be removed from the filesystem inbetween the enumeration and reading of the file. In this instance, the script is removed from the script list.<commit_after>// Copyright (c) 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/extensions/user_script_master.h"
#include <string>
#include <vector>
#include "base/file_path.h"
#include "base/file_util.h"
#include "base/path_service.h"
#include "base/pickle.h"
#include "base/stl_util-inl.h"
#include "base/string_util.h"
#include "base/thread.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/extensions/extensions_service.h"
#include "chrome/common/extensions/extension.h"
#include "chrome/common/notification_service.h"
#include "chrome/common/url_constants.h"
#include "net/base/net_util.h"
// Helper function to parse greasesmonkey headers
static bool GetDeclarationValue(const StringPiece& line,
const StringPiece& prefix,
std::string* value) {
if (!line.starts_with(prefix))
return false;
std::string temp(line.data() + prefix.length(),
line.length() - prefix.length());
TrimWhitespace(temp, TRIM_ALL, value);
return true;
}
UserScriptMaster::ScriptReloader::ScriptReloader(UserScriptMaster* master)
: master_(master),
master_message_loop_(MessageLoop::current()) {
}
// static
bool UserScriptMaster::ScriptReloader::ParseMetadataHeader(
const StringPiece& script_text, UserScript* script) {
// http://wiki.greasespot.net/Metadata_block
StringPiece line;
size_t line_start = 0;
size_t line_end = 0;
bool in_metadata = false;
static const StringPiece kUserScriptBegin("// ==UserScript==");
static const StringPiece kUserScriptEng("// ==/UserScript==");
static const StringPiece kIncludeDeclaration("// @include ");
static const StringPiece kMatchDeclaration("// @match ");
static const StringPiece kRunAtDeclaration("// @run-at ");
static const StringPiece kRunAtDocumentStartValue("document-start");
static const StringPiece kRunAtDocumentEndValue("document-end");
while (line_start < script_text.length()) {
line_end = script_text.find('\n', line_start);
// Handle the case where there is no trailing newline in the file.
if (line_end == std::string::npos) {
line_end = script_text.length() - 1;
}
line.set(script_text.data() + line_start, line_end - line_start);
if (!in_metadata) {
if (line.starts_with(kUserScriptBegin)) {
in_metadata = true;
}
} else {
if (line.starts_with(kUserScriptEng)) {
break;
}
std::string value;
if (GetDeclarationValue(line, kIncludeDeclaration, &value)) {
// We escape some characters that MatchPattern() considers special.
ReplaceSubstringsAfterOffset(&value, 0, "\\", "\\\\");
ReplaceSubstringsAfterOffset(&value, 0, "?", "\\?");
script->add_glob(value);
} else if (GetDeclarationValue(line, kMatchDeclaration, &value)) {
URLPattern pattern;
if (!pattern.Parse(value))
return false;
script->add_url_pattern(pattern);
} else if (GetDeclarationValue(line, kRunAtDeclaration, &value)) {
if (value == kRunAtDocumentStartValue)
script->set_run_location(UserScript::DOCUMENT_START);
else if (value != kRunAtDocumentEndValue)
return false;
}
// TODO(aa): Handle more types of metadata.
}
line_start = line_end + 1;
}
// It is probably a mistake to declare both @include and @match rules.
if (script->globs().size() > 0 && script->url_patterns().size() > 0)
return false;
// If no patterns were specified, default to @include *. This is what
// Greasemonkey does.
if (script->globs().size() == 0 && script->url_patterns().size() == 0)
script->add_glob("*");
return true;
}
void UserScriptMaster::ScriptReloader::StartScan(
MessageLoop* work_loop, const FilePath& script_dir,
const UserScriptList& lone_scripts) {
// Add a reference to ourselves to keep ourselves alive while we're running.
// Balanced by NotifyMaster().
AddRef();
work_loop->PostTask(FROM_HERE,
NewRunnableMethod(this,
&UserScriptMaster::ScriptReloader::RunScan,
script_dir, lone_scripts));
}
void UserScriptMaster::ScriptReloader::NotifyMaster(
base::SharedMemory* memory) {
if (!master_) {
// The master went away, so these new scripts aren't useful anymore.
delete memory;
} else {
master_->NewScriptsAvailable(memory);
}
// Drop our self-reference.
// Balances StartScan().
Release();
}
static bool LoadScriptContent(UserScript::File* script_file) {
std::string content;
if (!file_util::ReadFileToString(script_file->path(), &content)) {
LOG(WARNING) << "Failed to load user script file: "
<< script_file->path().value();
return false;
}
script_file->set_content(content);
LOG(INFO) << "Loaded user script file: " << script_file->path().value();
return true;
}
void UserScriptMaster::ScriptReloader::LoadScriptsFromDirectory(
const FilePath& script_dir, UserScriptList* result) {
// Clear the list. We will populate it with the scrips found in script_dir.
result->clear();
// Find all the scripts in |script_dir|.
if (!script_dir.value().empty()) {
// Create the "<Profile>/User Scripts" directory if it doesn't exist
if (!file_util::DirectoryExists(script_dir))
file_util::CreateDirectory(script_dir);
file_util::FileEnumerator enumerator(script_dir, false,
file_util::FileEnumerator::FILES,
FILE_PATH_LITERAL("*.user.js"));
for (FilePath file = enumerator.Next(); !file.value().empty();
file = enumerator.Next()) {
result->push_back(UserScript());
UserScript& user_script = result->back();
// Push single js file in this UserScript.
GURL url(std::string(chrome::kUserScriptScheme) + ":/" +
net::FilePathToFileURL(file).ExtractFileName());
user_script.js_scripts().push_back(UserScript::File(file, url));
UserScript::File& script_file = user_script.js_scripts().back();
if (!LoadScriptContent(&script_file)) {
result->erase(result->end());
} else {
ParseMetadataHeader(script_file.GetContent(), &user_script);
}
}
}
}
static void LoadLoneScripts(UserScriptList* lone_scripts) {
for (size_t i = 0; i < lone_scripts->size(); ++i) {
UserScript& script = lone_scripts->at(i);
for (size_t k = 0; k < script.js_scripts().size(); ++k) {
UserScript::File& script_file = script.js_scripts()[k];
if (script_file.GetContent().empty()) {
LoadScriptContent(&script_file);
}
}
for (size_t k = 0; k < script.css_scripts().size(); ++k) {
UserScript::File& script_file = script.css_scripts()[k];
if (script_file.GetContent().empty()) {
LoadScriptContent(&script_file);
}
}
}
}
// Pickle user scripts and return pointer to the shared memory.
static base::SharedMemory* Serialize(UserScriptList& scripts) {
Pickle pickle;
pickle.WriteSize(scripts.size());
for (size_t i = 0; i < scripts.size(); i++) {
UserScript& script = scripts[i];
script.Pickle(&pickle);
// Write scripts as 'data' so that we can read it out in the slave without
// allocating a new string.
for (size_t j = 0; j < script.js_scripts().size(); j++) {
StringPiece contents = script.js_scripts()[j].GetContent();
pickle.WriteData(contents.data(), contents.length());
}
for (size_t j = 0; j < script.css_scripts().size(); j++) {
StringPiece contents = script.css_scripts()[j].GetContent();
pickle.WriteData(contents.data(), contents.length());
}
}
// Create the shared memory object.
scoped_ptr<base::SharedMemory> shared_memory(new base::SharedMemory());
if (!shared_memory->Create(std::wstring(), // anonymous
false, // read-only
false, // open existing
pickle.size())) {
return NULL;
}
// Map into our process.
if (!shared_memory->Map(pickle.size()))
return NULL;
// Copy the pickle to shared memory.
memcpy(shared_memory->memory(), pickle.data(), pickle.size());
return shared_memory.release();
}
// This method will be called from the file thread
void UserScriptMaster::ScriptReloader::RunScan(
const FilePath script_dir, UserScriptList lone_script) {
UserScriptList scripts;
// Get list of user scripts.
if (!script_dir.empty())
LoadScriptsFromDirectory(script_dir, &scripts);
LoadLoneScripts(&lone_script);
// Merge with the explicit scripts
scripts.reserve(scripts.size() + lone_script.size());
scripts.insert(scripts.end(),
lone_script.begin(), lone_script.end());
// Scripts now contains list of up-to-date scripts. Load the content in the
// shared memory and let the master know it's ready. We need to post the task
// back even if no scripts ware found to balance the AddRef/Release calls
master_message_loop_->PostTask(FROM_HERE,
NewRunnableMethod(this,
&ScriptReloader::NotifyMaster,
Serialize(scripts)));
}
UserScriptMaster::UserScriptMaster(MessageLoop* worker_loop,
const FilePath& script_dir)
: user_script_dir_(script_dir),
worker_loop_(worker_loop),
extensions_service_ready_(false),
pending_scan_(false) {
if (!user_script_dir_.value().empty())
AddWatchedPath(script_dir);
registrar_.Add(this, NotificationType::EXTENSIONS_READY,
NotificationService::AllSources());
registrar_.Add(this, NotificationType::EXTENSIONS_LOADED,
NotificationService::AllSources());
registrar_.Add(this, NotificationType::EXTENSION_UNLOADED,
NotificationService::AllSources());
}
UserScriptMaster::~UserScriptMaster() {
if (script_reloader_)
script_reloader_->DisownMaster();
// TODO(aa): Enable this when DirectoryWatcher is implemented for linux.
#if defined(OS_WIN) || defined(OS_MACOSX)
STLDeleteElements(&dir_watchers_);
#endif
}
void UserScriptMaster::AddWatchedPath(const FilePath& path) {
// TODO(aa): Enable this when DirectoryWatcher is implemented for linux.
#if defined(OS_WIN) || defined(OS_MACOSX)
DirectoryWatcher* watcher = new DirectoryWatcher();
base::Thread* file_thread = g_browser_process->file_thread();
watcher->Watch(path, this, file_thread ? file_thread->message_loop() : NULL,
true);
dir_watchers_.push_back(watcher);
#endif
}
void UserScriptMaster::NewScriptsAvailable(base::SharedMemory* handle) {
// Ensure handle is deleted or released.
scoped_ptr<base::SharedMemory> handle_deleter(handle);
if (pending_scan_) {
// While we were scanning, there were further changes. Don't bother
// notifying about these scripts and instead just immediately rescan.
pending_scan_ = false;
StartScan();
} else {
// We're no longer scanning.
script_reloader_ = NULL;
// We've got scripts ready to go.
shared_memory_.swap(handle_deleter);
NotificationService::current()->Notify(
NotificationType::USER_SCRIPTS_UPDATED,
NotificationService::AllSources(),
Details<base::SharedMemory>(handle));
}
}
void UserScriptMaster::OnDirectoryChanged(const FilePath& path) {
if (script_reloader_.get()) {
// We're already scanning for scripts. We note that we should rescan when
// we get the chance.
pending_scan_ = true;
return;
}
StartScan();
}
void UserScriptMaster::Observe(NotificationType type,
const NotificationSource& source,
const NotificationDetails& details) {
switch (type.value) {
case NotificationType::EXTENSIONS_READY:
extensions_service_ready_ = true;
StartScan();
break;
case NotificationType::EXTENSIONS_LOADED: {
// TODO(aa): Fix race here. A page could need a content script on startup,
// before the extension has loaded. We need to freeze the renderer in
// that case.
// See: http://code.google.com/p/chromium/issues/detail?id=11547.
// Add any content scripts inside the extension.
ExtensionList* extensions = Details<ExtensionList>(details).ptr();
for (ExtensionList::iterator extension_iterator = extensions->begin();
extension_iterator != extensions->end(); ++extension_iterator) {
Extension* extension = *extension_iterator;
const UserScriptList& scripts = extension->content_scripts();
for (UserScriptList::const_iterator iter = scripts.begin();
iter != scripts.end(); ++iter) {
lone_scripts_.push_back(*iter);
}
}
if (extensions_service_ready_)
StartScan();
break;
}
case NotificationType::EXTENSION_UNLOADED: {
// Remove any content scripts.
Extension* extension = Details<Extension>(details).ptr();
UserScriptList new_lone_scripts;
for (UserScriptList::iterator iter = lone_scripts_.begin();
iter != lone_scripts_.end(); ++iter) {
if (iter->extension_id() != extension->id()) {
new_lone_scripts.push_back(*iter);
}
}
lone_scripts_ = new_lone_scripts;
StartScan();
// TODO(aa): Do we want to do something smarter for the scripts that have
// already been injected?
break;
}
default:
DCHECK(false);
}
}
void UserScriptMaster::StartScan() {
if (!script_reloader_)
script_reloader_ = new ScriptReloader(this);
script_reloader_->StartScan(worker_loop_, user_script_dir_, lone_scripts_);
}
<|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 "chrome/browser/renderer_host/backing_store.h"
#include <stdlib.h>
#include <utility>
#include "base/compiler_specific.h"
#include "base/logging.h"
#include "chrome/common/transport_dib.h"
#include "chrome/common/x11_util.h"
#include "chrome/common/x11_util_internal.h"
#include "third_party/skia/include/core/SkBitmap.h"
// X Backing Stores:
//
// Unlike Windows, where the backing store is kept in heap memory, we keep our
// backing store in the X server, as a pixmap. Thus expose events just require
// instructing the X server to copy from the backing store to the window.
//
// The backing store is in the same format as the visual which our main window
// is using. Bitmaps from the renderer are uploaded to the X server, either via
// shared memory or over the wire, and XRENDER is used to convert them to the
// correct format for the backing store.
BackingStore::BackingStore(RenderWidgetHost* widget,
const gfx::Size& size,
void* visual,
int depth)
: render_widget_host_(widget),
size_(size),
display_(x11_util::GetXDisplay()),
use_shared_memory_(x11_util::QuerySharedMemorySupport(display_)),
use_render_(x11_util::QueryRenderSupport(display_)),
visual_depth_(depth),
root_window_(x11_util::GetX11RootWindow()) {
COMPILE_ASSERT(__BYTE_ORDER == __LITTLE_ENDIAN, assumes_little_endian);
pixmap_ = XCreatePixmap(display_, root_window_,
size.width(), size.height(), depth);
if (use_render_) {
picture_ = XRenderCreatePicture(
display_, pixmap_,
x11_util::GetRenderVisualFormat(display_,
static_cast<Visual*>(visual)),
0, NULL);
} else {
picture_ = 0;
pixmap_bpp_ = x11_util::BitsPerPixelForPixmapDepth(display_, depth);
}
pixmap_gc_ = XCreateGC(display_, pixmap_, 0, NULL);
}
BackingStore::BackingStore(RenderWidgetHost* widget, const gfx::Size& size)
: render_widget_host_(widget),
size_(size),
display_(NULL),
use_shared_memory_(false),
use_render_(false),
visual_depth_(-1),
root_window_(0) {
}
BackingStore::~BackingStore() {
// In unit tests, display_ may be NULL.
if (!display_)
return;
XRenderFreePicture(display_, picture_);
XFreePixmap(display_, pixmap_);
XFreeGC(display_, static_cast<GC>(pixmap_gc_));
}
void BackingStore::PaintRectWithoutXrender(TransportDIB* bitmap,
const gfx::Rect &bitmap_rect) {
const int width = bitmap_rect.width();
const int height = bitmap_rect.height();
Pixmap pixmap = XCreatePixmap(display_, root_window_, width, height,
visual_depth_);
XImage image;
memset(&image, 0, sizeof(image));
image.width = width;
image.height = height;
image.format = ZPixmap;
image.byte_order = LSBFirst;
image.bitmap_unit = 8;
image.bitmap_bit_order = LSBFirst;
image.red_mask = 0xff;
image.green_mask = 0xff00;
image.blue_mask = 0xff0000;
if (pixmap_bpp_ == 32) {
// If the X server depth is already 32-bits, then our job is easy.
image.depth = visual_depth_;
image.bits_per_pixel = 32;
image.bytes_per_line = width * 4;
image.data = static_cast<char*>(bitmap->memory());
XPutImage(display_, pixmap, static_cast<GC>(pixmap_gc_), &image,
0, 0 /* source x, y */, 0, 0 /* dest x, y */,
width, height);
} else if (pixmap_bpp_ == 24) {
// In this case we just need to strip the alpha channel out of each
// pixel. This is the case which covers VNC servers since they don't
// support Xrender but typically have 24-bit visuals.
//
// It's possible to use some fancy SSE tricks here, but since this is the
// slow path anyway, we do it slowly.
uint8_t* bitmap24 = static_cast<uint8_t*>(malloc(3 * width * height));
if (!bitmap24)
return;
const uint32_t* bitmap_in = static_cast<const uint32_t*>(bitmap->memory());
for (int y = 0; y < height; ++y) {
for (int x = 0; x < width; ++x) {
const uint32_t pixel = *(bitmap_in++);
bitmap24[0] = (pixel >> 16) & 0xff;
bitmap24[1] = (pixel >> 8) & 0xff;
bitmap24[2] = pixel & 0xff;
bitmap24 += 3;
}
}
image.depth = visual_depth_;
image.bits_per_pixel = 24;
image.bytes_per_line = width * 3;
image.data = reinterpret_cast<char*>(bitmap24);
XPutImage(display_, pixmap, static_cast<GC>(pixmap_gc_), &image,
0, 0 /* source x, y */, 0, 0 /* dest x, y */,
width, height);
free(bitmap24);
} else if (pixmap_bpp_ == 16) {
// Some folks have VNC setups which still use 16-bit visuals and VNC
// doesn't include Xrender.
uint16_t* bitmap16 = static_cast<uint16_t*>(malloc(2 * width * height));
if (!bitmap16)
return;
uint16_t* const orig_bitmap16 = bitmap16;
const uint32_t* bitmap_in = static_cast<const uint32_t*>(bitmap->memory());
for (int y = 0; y < height; ++y) {
for (int x = 0; x < width; ++x) {
const uint32_t pixel = *(bitmap_in++);
uint16_t out_pixel = ((pixel >> 8) & 0xf800) |
((pixel >> 5) & 0x07e0) |
((pixel >> 3) & 0x001f);
*(bitmap16++) = out_pixel;
}
}
image.depth = visual_depth_;
image.bits_per_pixel = 16;
image.bytes_per_line = width * 2;
image.data = reinterpret_cast<char*>(orig_bitmap16);
image.red_mask = 0xf800;
image.green_mask = 0x07e0;
image.blue_mask = 0x001f;
XPutImage(display_, pixmap, static_cast<GC>(pixmap_gc_), &image,
0, 0 /* source x, y */, 0, 0 /* dest x, y */,
width, height);
free(orig_bitmap16);
} else {
CHECK(false) << "Sorry, we don't support your visual depth without "
"Xrender support (depth:" << visual_depth_
<< " bpp:" << pixmap_bpp_ << ")";
}
XCopyArea(display_, pixmap /* source */, pixmap_ /* target */,
static_cast<GC>(pixmap_gc_),
0, 0 /* source x, y */, bitmap_rect.width(), bitmap_rect.height(),
bitmap_rect.x(), bitmap_rect.y() /* dest x, y */);
XFreePixmap(display_, pixmap);
}
void BackingStore::PaintRect(base::ProcessHandle process,
TransportDIB* bitmap,
const gfx::Rect& bitmap_rect) {
if (!display_)
return;
if (bitmap_rect.IsEmpty())
return;
const int width = bitmap_rect.width();
const int height = bitmap_rect.height();
// Assume that somewhere along the line, someone will do width * height * 4
// with signed numbers. If the maximum value is 2**31, then 2**31 / 4 =
// 2**29 and floor(sqrt(2**29)) = 23170.
if (width > 23170 || height > 23170)
return;
if (!use_render_)
return PaintRectWithoutXrender(bitmap, bitmap_rect);
Picture picture;
Pixmap pixmap;
if (use_shared_memory_) {
const XID shmseg = bitmap->MapToX(display_);
XShmSegmentInfo shminfo;
memset(&shminfo, 0, sizeof(shminfo));
shminfo.shmseg = shmseg;
// The NULL in the following is the |data| pointer: this is an artifact of
// Xlib trying to be helpful, rather than just exposing the X protocol. It
// assumes that we have the shared memory segment mapped into our memory,
// which we don't, and it's trying to calculate an offset by taking the
// difference between the |data| pointer and the address of the mapping in
// |shminfo|. Since both are NULL, the offset will be calculated to be 0,
// which is correct for us.
pixmap = XShmCreatePixmap(display_, root_window_, NULL, &shminfo, width,
height, 32);
} else {
// No shared memory support, we have to copy the bitmap contents to the X
// server. Xlib wraps the underlying PutImage call behind several layers of
// functions which try to convert the image into the format which the X
// server expects. The following values hopefully disable all conversions.
XImage image;
memset(&image, 0, sizeof(image));
image.width = width;
image.height = height;
image.depth = 32;
image.bits_per_pixel = 32;
image.format = ZPixmap;
image.byte_order = LSBFirst;
image.bitmap_unit = 8;
image.bitmap_bit_order = LSBFirst;
image.bytes_per_line = width * 4;
image.red_mask = 0xff;
image.green_mask = 0xff00;
image.blue_mask = 0xff0000;
image.data = static_cast<char*>(bitmap->memory());
pixmap = XCreatePixmap(display_, root_window_, width, height, 32);
GC gc = XCreateGC(display_, pixmap, 0, NULL);
XPutImage(display_, pixmap, gc, &image,
0, 0 /* source x, y */, 0, 0 /* dest x, y */,
width, height);
XFreeGC(display_, gc);
}
picture = x11_util::CreatePictureFromSkiaPixmap(display_, pixmap);
XRenderComposite(display_, PictOpSrc, picture /* source */, 0 /* mask */,
picture_ /* dest */, 0, 0 /* source x, y */,
0, 0 /* mask x, y */,
bitmap_rect.x(), bitmap_rect.y() /* target x, y */,
width, height);
// In the case of shared memory, we wait for the composite to complete so that
// we are sure that the X server has finished reading.
if (use_shared_memory_)
XSync(display_, False);
XRenderFreePicture(display_, picture);
XFreePixmap(display_, pixmap);
}
void BackingStore::ScrollRect(base::ProcessHandle process,
TransportDIB* bitmap,
const gfx::Rect& bitmap_rect,
int dx, int dy,
const gfx::Rect& clip_rect,
const gfx::Size& view_size) {
if (!display_)
return;
// We only support scrolling in one direction at a time.
DCHECK(dx == 0 || dy == 0);
if (dy) {
// Positive values of |dy| scroll up
if (abs(dy) < clip_rect.height()) {
XCopyArea(display_, pixmap_, pixmap_, static_cast<GC>(pixmap_gc_),
clip_rect.x() /* source x */,
std::max(clip_rect.y(), clip_rect.y() - dy),
clip_rect.width(),
clip_rect.height() - abs(dy),
clip_rect.x() /* dest x */,
std::max(clip_rect.y(), clip_rect.y() + dy) /* dest y */);
}
} else if (dx) {
// Positive values of |dx| scroll right
if (abs(dx) < clip_rect.width()) {
XCopyArea(display_, pixmap_, pixmap_, static_cast<GC>(pixmap_gc_),
std::max(clip_rect.x(), clip_rect.x() - dx),
clip_rect.y() /* source y */,
clip_rect.width() - abs(dx),
clip_rect.height(),
std::max(clip_rect.x(), clip_rect.x() + dx) /* dest x */,
clip_rect.y() /* dest x */);
}
}
PaintRect(process, bitmap, bitmap_rect);
}
void BackingStore::ShowRect(const gfx::Rect& rect, XID target) {
XCopyArea(display_, pixmap_, target, static_cast<GC>(pixmap_gc_),
rect.x(), rect.y(), rect.width(), rect.height(),
rect.x(), rect.y());
}
SkBitmap* BackingStore::PaintRectToBitmap(const gfx::Rect& rect) {
static const int kBytesPerPixel = 4;
const int width = rect.width();
const int height = rect.height();
XImage* image = XGetImage(display_, pixmap_,
rect.x(), rect.y(),
width, height,
AllPlanes, ZPixmap);
// TODO(jhawkins): Need to convert the image data if the image bits per pixel
// is not 32.
if (image->bits_per_pixel != 32)
return NULL;
SkBitmap* bitmap = new SkBitmap();
bitmap->setConfig(SkBitmap::kARGB_8888_Config, width, height);
bitmap->allocPixels();
unsigned char* bitmap_data =
reinterpret_cast<unsigned char*>(bitmap->getAddr32(0, 0));
memcpy(bitmap_data, image->data, width * height * kBytesPerPixel);
XFree(image);
return bitmap;
}
<commit_msg>Fix a leak when we bail out early because of the wrong bpp.<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/renderer_host/backing_store.h"
#include <stdlib.h>
#include <utility>
#include "base/compiler_specific.h"
#include "base/logging.h"
#include "chrome/common/transport_dib.h"
#include "chrome/common/x11_util.h"
#include "chrome/common/x11_util_internal.h"
#include "third_party/skia/include/core/SkBitmap.h"
// X Backing Stores:
//
// Unlike Windows, where the backing store is kept in heap memory, we keep our
// backing store in the X server, as a pixmap. Thus expose events just require
// instructing the X server to copy from the backing store to the window.
//
// The backing store is in the same format as the visual which our main window
// is using. Bitmaps from the renderer are uploaded to the X server, either via
// shared memory or over the wire, and XRENDER is used to convert them to the
// correct format for the backing store.
BackingStore::BackingStore(RenderWidgetHost* widget,
const gfx::Size& size,
void* visual,
int depth)
: render_widget_host_(widget),
size_(size),
display_(x11_util::GetXDisplay()),
use_shared_memory_(x11_util::QuerySharedMemorySupport(display_)),
use_render_(x11_util::QueryRenderSupport(display_)),
visual_depth_(depth),
root_window_(x11_util::GetX11RootWindow()) {
COMPILE_ASSERT(__BYTE_ORDER == __LITTLE_ENDIAN, assumes_little_endian);
pixmap_ = XCreatePixmap(display_, root_window_,
size.width(), size.height(), depth);
if (use_render_) {
picture_ = XRenderCreatePicture(
display_, pixmap_,
x11_util::GetRenderVisualFormat(display_,
static_cast<Visual*>(visual)),
0, NULL);
} else {
picture_ = 0;
pixmap_bpp_ = x11_util::BitsPerPixelForPixmapDepth(display_, depth);
}
pixmap_gc_ = XCreateGC(display_, pixmap_, 0, NULL);
}
BackingStore::BackingStore(RenderWidgetHost* widget, const gfx::Size& size)
: render_widget_host_(widget),
size_(size),
display_(NULL),
use_shared_memory_(false),
use_render_(false),
visual_depth_(-1),
root_window_(0) {
}
BackingStore::~BackingStore() {
// In unit tests, display_ may be NULL.
if (!display_)
return;
XRenderFreePicture(display_, picture_);
XFreePixmap(display_, pixmap_);
XFreeGC(display_, static_cast<GC>(pixmap_gc_));
}
void BackingStore::PaintRectWithoutXrender(TransportDIB* bitmap,
const gfx::Rect &bitmap_rect) {
const int width = bitmap_rect.width();
const int height = bitmap_rect.height();
Pixmap pixmap = XCreatePixmap(display_, root_window_, width, height,
visual_depth_);
XImage image;
memset(&image, 0, sizeof(image));
image.width = width;
image.height = height;
image.format = ZPixmap;
image.byte_order = LSBFirst;
image.bitmap_unit = 8;
image.bitmap_bit_order = LSBFirst;
image.red_mask = 0xff;
image.green_mask = 0xff00;
image.blue_mask = 0xff0000;
if (pixmap_bpp_ == 32) {
// If the X server depth is already 32-bits, then our job is easy.
image.depth = visual_depth_;
image.bits_per_pixel = 32;
image.bytes_per_line = width * 4;
image.data = static_cast<char*>(bitmap->memory());
XPutImage(display_, pixmap, static_cast<GC>(pixmap_gc_), &image,
0, 0 /* source x, y */, 0, 0 /* dest x, y */,
width, height);
} else if (pixmap_bpp_ == 24) {
// In this case we just need to strip the alpha channel out of each
// pixel. This is the case which covers VNC servers since they don't
// support Xrender but typically have 24-bit visuals.
//
// It's possible to use some fancy SSE tricks here, but since this is the
// slow path anyway, we do it slowly.
uint8_t* bitmap24 = static_cast<uint8_t*>(malloc(3 * width * height));
if (!bitmap24)
return;
const uint32_t* bitmap_in = static_cast<const uint32_t*>(bitmap->memory());
for (int y = 0; y < height; ++y) {
for (int x = 0; x < width; ++x) {
const uint32_t pixel = *(bitmap_in++);
bitmap24[0] = (pixel >> 16) & 0xff;
bitmap24[1] = (pixel >> 8) & 0xff;
bitmap24[2] = pixel & 0xff;
bitmap24 += 3;
}
}
image.depth = visual_depth_;
image.bits_per_pixel = 24;
image.bytes_per_line = width * 3;
image.data = reinterpret_cast<char*>(bitmap24);
XPutImage(display_, pixmap, static_cast<GC>(pixmap_gc_), &image,
0, 0 /* source x, y */, 0, 0 /* dest x, y */,
width, height);
free(bitmap24);
} else if (pixmap_bpp_ == 16) {
// Some folks have VNC setups which still use 16-bit visuals and VNC
// doesn't include Xrender.
uint16_t* bitmap16 = static_cast<uint16_t*>(malloc(2 * width * height));
if (!bitmap16)
return;
uint16_t* const orig_bitmap16 = bitmap16;
const uint32_t* bitmap_in = static_cast<const uint32_t*>(bitmap->memory());
for (int y = 0; y < height; ++y) {
for (int x = 0; x < width; ++x) {
const uint32_t pixel = *(bitmap_in++);
uint16_t out_pixel = ((pixel >> 8) & 0xf800) |
((pixel >> 5) & 0x07e0) |
((pixel >> 3) & 0x001f);
*(bitmap16++) = out_pixel;
}
}
image.depth = visual_depth_;
image.bits_per_pixel = 16;
image.bytes_per_line = width * 2;
image.data = reinterpret_cast<char*>(orig_bitmap16);
image.red_mask = 0xf800;
image.green_mask = 0x07e0;
image.blue_mask = 0x001f;
XPutImage(display_, pixmap, static_cast<GC>(pixmap_gc_), &image,
0, 0 /* source x, y */, 0, 0 /* dest x, y */,
width, height);
free(orig_bitmap16);
} else {
CHECK(false) << "Sorry, we don't support your visual depth without "
"Xrender support (depth:" << visual_depth_
<< " bpp:" << pixmap_bpp_ << ")";
}
XCopyArea(display_, pixmap /* source */, pixmap_ /* target */,
static_cast<GC>(pixmap_gc_),
0, 0 /* source x, y */, bitmap_rect.width(), bitmap_rect.height(),
bitmap_rect.x(), bitmap_rect.y() /* dest x, y */);
XFreePixmap(display_, pixmap);
}
void BackingStore::PaintRect(base::ProcessHandle process,
TransportDIB* bitmap,
const gfx::Rect& bitmap_rect) {
if (!display_)
return;
if (bitmap_rect.IsEmpty())
return;
const int width = bitmap_rect.width();
const int height = bitmap_rect.height();
// Assume that somewhere along the line, someone will do width * height * 4
// with signed numbers. If the maximum value is 2**31, then 2**31 / 4 =
// 2**29 and floor(sqrt(2**29)) = 23170.
if (width > 23170 || height > 23170)
return;
if (!use_render_)
return PaintRectWithoutXrender(bitmap, bitmap_rect);
Picture picture;
Pixmap pixmap;
if (use_shared_memory_) {
const XID shmseg = bitmap->MapToX(display_);
XShmSegmentInfo shminfo;
memset(&shminfo, 0, sizeof(shminfo));
shminfo.shmseg = shmseg;
// The NULL in the following is the |data| pointer: this is an artifact of
// Xlib trying to be helpful, rather than just exposing the X protocol. It
// assumes that we have the shared memory segment mapped into our memory,
// which we don't, and it's trying to calculate an offset by taking the
// difference between the |data| pointer and the address of the mapping in
// |shminfo|. Since both are NULL, the offset will be calculated to be 0,
// which is correct for us.
pixmap = XShmCreatePixmap(display_, root_window_, NULL, &shminfo, width,
height, 32);
} else {
// No shared memory support, we have to copy the bitmap contents to the X
// server. Xlib wraps the underlying PutImage call behind several layers of
// functions which try to convert the image into the format which the X
// server expects. The following values hopefully disable all conversions.
XImage image;
memset(&image, 0, sizeof(image));
image.width = width;
image.height = height;
image.depth = 32;
image.bits_per_pixel = 32;
image.format = ZPixmap;
image.byte_order = LSBFirst;
image.bitmap_unit = 8;
image.bitmap_bit_order = LSBFirst;
image.bytes_per_line = width * 4;
image.red_mask = 0xff;
image.green_mask = 0xff00;
image.blue_mask = 0xff0000;
image.data = static_cast<char*>(bitmap->memory());
pixmap = XCreatePixmap(display_, root_window_, width, height, 32);
GC gc = XCreateGC(display_, pixmap, 0, NULL);
XPutImage(display_, pixmap, gc, &image,
0, 0 /* source x, y */, 0, 0 /* dest x, y */,
width, height);
XFreeGC(display_, gc);
}
picture = x11_util::CreatePictureFromSkiaPixmap(display_, pixmap);
XRenderComposite(display_, PictOpSrc, picture /* source */, 0 /* mask */,
picture_ /* dest */, 0, 0 /* source x, y */,
0, 0 /* mask x, y */,
bitmap_rect.x(), bitmap_rect.y() /* target x, y */,
width, height);
// In the case of shared memory, we wait for the composite to complete so that
// we are sure that the X server has finished reading.
if (use_shared_memory_)
XSync(display_, False);
XRenderFreePicture(display_, picture);
XFreePixmap(display_, pixmap);
}
void BackingStore::ScrollRect(base::ProcessHandle process,
TransportDIB* bitmap,
const gfx::Rect& bitmap_rect,
int dx, int dy,
const gfx::Rect& clip_rect,
const gfx::Size& view_size) {
if (!display_)
return;
// We only support scrolling in one direction at a time.
DCHECK(dx == 0 || dy == 0);
if (dy) {
// Positive values of |dy| scroll up
if (abs(dy) < clip_rect.height()) {
XCopyArea(display_, pixmap_, pixmap_, static_cast<GC>(pixmap_gc_),
clip_rect.x() /* source x */,
std::max(clip_rect.y(), clip_rect.y() - dy),
clip_rect.width(),
clip_rect.height() - abs(dy),
clip_rect.x() /* dest x */,
std::max(clip_rect.y(), clip_rect.y() + dy) /* dest y */);
}
} else if (dx) {
// Positive values of |dx| scroll right
if (abs(dx) < clip_rect.width()) {
XCopyArea(display_, pixmap_, pixmap_, static_cast<GC>(pixmap_gc_),
std::max(clip_rect.x(), clip_rect.x() - dx),
clip_rect.y() /* source y */,
clip_rect.width() - abs(dx),
clip_rect.height(),
std::max(clip_rect.x(), clip_rect.x() + dx) /* dest x */,
clip_rect.y() /* dest x */);
}
}
PaintRect(process, bitmap, bitmap_rect);
}
void BackingStore::ShowRect(const gfx::Rect& rect, XID target) {
XCopyArea(display_, pixmap_, target, static_cast<GC>(pixmap_gc_),
rect.x(), rect.y(), rect.width(), rect.height(),
rect.x(), rect.y());
}
SkBitmap* BackingStore::PaintRectToBitmap(const gfx::Rect& rect) {
static const int kBytesPerPixel = 4;
const int width = rect.width();
const int height = rect.height();
XImage* image = XGetImage(display_, pixmap_,
rect.x(), rect.y(),
width, height,
AllPlanes, ZPixmap);
// TODO(jhawkins): Need to convert the image data if the image bits per pixel
// is not 32.
if (image->bits_per_pixel != 32) {
XFree(image);
return NULL;
}
SkBitmap* bitmap = new SkBitmap();
bitmap->setConfig(SkBitmap::kARGB_8888_Config, width, height);
bitmap->allocPixels();
unsigned char* bitmap_data =
reinterpret_cast<unsigned char*>(bitmap->getAddr32(0, 0));
memcpy(bitmap_data, image->data, width * height * kBytesPerPixel);
XFree(image);
return bitmap;
}
<|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/sessions/base_session_service.h"
#include "base/bind.h"
#include "base/pickle.h"
#include "base/stl_util.h"
#include "base/threading/thread.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/sessions/session_backend.h"
#include "chrome/browser/sessions/session_types.h"
#include "chrome/common/url_constants.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/browser/navigation_entry.h"
#include "content/public/common/referrer.h"
#include "webkit/glue/webkit_glue.h"
using WebKit::WebReferrerPolicy;
using content::BrowserThread;
using content::NavigationEntry;
// InternalGetCommandsRequest -------------------------------------------------
BaseSessionService::InternalGetCommandsRequest::~InternalGetCommandsRequest() {
STLDeleteElements(&commands);
}
// BaseSessionService ---------------------------------------------------------
namespace {
// Helper used by CreateUpdateTabNavigationCommand(). It writes |str| to
// |pickle|, if and only if |str| fits within (|max_bytes| - |*bytes_written|).
// |bytes_written| is incremented to reflect the data written.
void WriteStringToPickle(Pickle& pickle, int* bytes_written, int max_bytes,
const std::string& str) {
int num_bytes = str.size() * sizeof(char);
if (*bytes_written + num_bytes < max_bytes) {
*bytes_written += num_bytes;
pickle.WriteString(str);
} else {
pickle.WriteString(std::string());
}
}
// string16 version of WriteStringToPickle.
void WriteString16ToPickle(Pickle& pickle, int* bytes_written, int max_bytes,
const string16& str) {
int num_bytes = str.size() * sizeof(char16);
if (*bytes_written + num_bytes < max_bytes) {
*bytes_written += num_bytes;
pickle.WriteString16(str);
} else {
pickle.WriteString16(string16());
}
}
} // namespace
// Delay between when a command is received, and when we save it to the
// backend.
static const int kSaveDelayMS = 2500;
// static
const int BaseSessionService::max_persist_navigation_count = 6;
BaseSessionService::BaseSessionService(SessionType type,
Profile* profile,
const FilePath& path)
: profile_(profile),
path_(path),
ALLOW_THIS_IN_INITIALIZER_LIST(weak_factory_(this)),
pending_reset_(false),
commands_since_reset_(0) {
if (profile) {
// We should never be created when incognito.
DCHECK(!profile->IsOffTheRecord());
}
backend_ = new SessionBackend(type,
profile_ ? profile_->GetPath() : path_);
DCHECK(backend_.get());
RunTaskOnBackendThread(FROM_HERE,
base::Bind(&SessionBackend::Init, backend_));
}
BaseSessionService::~BaseSessionService() {
}
void BaseSessionService::DeleteLastSession() {
RunTaskOnBackendThread(
FROM_HERE,
base::Bind(&SessionBackend::DeleteLastSession, backend()));
}
void BaseSessionService::ScheduleCommand(SessionCommand* command) {
DCHECK(command);
commands_since_reset_++;
pending_commands_.push_back(command);
StartSaveTimer();
}
void BaseSessionService::StartSaveTimer() {
// Don't start a timer when testing (profile == NULL or
// MessageLoop::current() is NULL).
if (MessageLoop::current() && profile() && !weak_factory_.HasWeakPtrs()) {
MessageLoop::current()->PostDelayedTask(
FROM_HERE,
base::Bind(&BaseSessionService::Save, weak_factory_.GetWeakPtr()),
kSaveDelayMS);
}
}
void BaseSessionService::Save() {
DCHECK(backend());
if (pending_commands_.empty())
return;
RunTaskOnBackendThread(
FROM_HERE,
base::Bind(&SessionBackend::AppendCommands, backend(),
new std::vector<SessionCommand*>(pending_commands_),
pending_reset_));
// Backend took ownership of commands.
pending_commands_.clear();
if (pending_reset_) {
commands_since_reset_ = 0;
pending_reset_ = false;
}
}
SessionCommand* BaseSessionService::CreateUpdateTabNavigationCommand(
SessionID::id_type command_id,
SessionID::id_type tab_id,
int index,
const NavigationEntry& entry) {
// Use pickle to handle marshalling.
Pickle pickle;
pickle.WriteInt(tab_id);
pickle.WriteInt(index);
// We only allow navigations up to 63k (which should be completely
// reasonable). On the off chance we get one that is too big, try to
// keep the url.
// Bound the string data (which is variable length) to
// |max_state_size bytes| bytes.
static const SessionCommand::size_type max_state_size =
std::numeric_limits<SessionCommand::size_type>::max() - 1024;
int bytes_written = 0;
WriteStringToPickle(pickle, &bytes_written, max_state_size,
entry.GetVirtualURL().spec());
WriteString16ToPickle(pickle, &bytes_written, max_state_size,
entry.GetTitle());
if (entry.GetHasPostData()) {
// Remove the form data, it may contain sensitive information.
WriteStringToPickle(pickle, &bytes_written, max_state_size,
webkit_glue::RemoveFormDataFromHistoryState(entry.GetContentState()));
} else {
WriteStringToPickle(pickle, &bytes_written, max_state_size,
entry.GetContentState());
}
pickle.WriteInt(entry.GetTransitionType());
int type_mask = entry.GetHasPostData() ? TabNavigation::HAS_POST_DATA : 0;
pickle.WriteInt(type_mask);
WriteStringToPickle(pickle, &bytes_written, max_state_size,
entry.GetReferrer().url.is_valid() ?
entry.GetReferrer().url.spec() : std::string());
pickle.WriteInt(entry.GetReferrer().policy);
// Adding more data? Be sure and update TabRestoreService too.
return new SessionCommand(command_id, pickle);
}
SessionCommand* BaseSessionService::CreateSetTabExtensionAppIDCommand(
SessionID::id_type command_id,
SessionID::id_type tab_id,
const std::string& extension_id) {
// Use pickle to handle marshalling.
Pickle pickle;
pickle.WriteInt(tab_id);
// Enforce a max for ids. They should never be anywhere near this size.
static const SessionCommand::size_type max_id_size =
std::numeric_limits<SessionCommand::size_type>::max() - 1024;
int bytes_written = 0;
WriteStringToPickle(pickle, &bytes_written, max_id_size, extension_id);
return new SessionCommand(command_id, pickle);
}
bool BaseSessionService::RestoreUpdateTabNavigationCommand(
const SessionCommand& command,
TabNavigation* navigation,
SessionID::id_type* tab_id) {
scoped_ptr<Pickle> pickle(command.PayloadAsPickle());
if (!pickle.get())
return false;
void* iterator = NULL;
std::string url_spec;
if (!pickle->ReadInt(&iterator, tab_id) ||
!pickle->ReadInt(&iterator, &(navigation->index_)) ||
!pickle->ReadString(&iterator, &url_spec) ||
!pickle->ReadString16(&iterator, &(navigation->title_)) ||
!pickle->ReadString(&iterator, &(navigation->state_)) ||
!pickle->ReadInt(&iterator,
reinterpret_cast<int*>(&(navigation->transition_))))
return false;
// type_mask did not always exist in the written stream. As such, we
// don't fail if it can't be read.
bool has_type_mask = pickle->ReadInt(&iterator, &(navigation->type_mask_));
if (has_type_mask) {
// the "referrer" property was added after type_mask to the written
// stream. As such, we don't fail if it can't be read.
std::string referrer_spec;
pickle->ReadString(&iterator, &referrer_spec);
// The "referrer policy" property was added even later, so we fall back to
// the default policy if the property is not present.
int policy_int;
WebReferrerPolicy policy;
if (pickle->ReadInt(&iterator, &policy_int))
policy = static_cast<WebReferrerPolicy>(policy_int);
else
policy = WebKit::WebReferrerPolicyDefault;
navigation->referrer_ = content::Referrer(
referrer_spec.empty() ? GURL() : GURL(referrer_spec),
policy);
}
navigation->virtual_url_ = GURL(url_spec);
return true;
}
bool BaseSessionService::RestoreSetTabExtensionAppIDCommand(
const SessionCommand& command,
SessionID::id_type* tab_id,
std::string* extension_app_id) {
scoped_ptr<Pickle> pickle(command.PayloadAsPickle());
if (!pickle.get())
return false;
void* iterator = NULL;
return pickle->ReadInt(&iterator, tab_id) &&
pickle->ReadString(&iterator, extension_app_id);
}
bool BaseSessionService::ShouldTrackEntry(const GURL& url) {
// NOTE: Do not track print preview tab because re-opening that page will
// just display a non-functional print preview page.
return url.is_valid() && url != GURL(chrome::kChromeUIPrintURL);
}
BaseSessionService::Handle BaseSessionService::ScheduleGetLastSessionCommands(
InternalGetCommandsRequest* request,
CancelableRequestConsumerBase* consumer) {
scoped_refptr<InternalGetCommandsRequest> request_wrapper(request);
AddRequest(request, consumer);
RunTaskOnBackendThread(
FROM_HERE,
base::Bind(&SessionBackend::ReadLastSessionCommands, backend(),
request_wrapper));
return request->handle();
}
bool BaseSessionService::RunTaskOnBackendThread(
const tracked_objects::Location& from_here,
const base::Closure& task) {
if (profile_ && BrowserThread::IsMessageLoopValid(BrowserThread::FILE)) {
return BrowserThread::PostTask(BrowserThread::FILE, from_here, task);
} else {
// Fall back to executing on the main thread if the file thread
// has gone away (around shutdown time) or if we're running as
// part of a unit test that does not set profile_.
task.Run();
return true;
}
}
<commit_msg>Adding UMA metrics for recording the size of content state saved by the BaseSessionService.<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 "chrome/browser/sessions/base_session_service.h"
#include "base/bind.h"
#include "base/metrics/histogram.h"
#include "base/pickle.h"
#include "base/stl_util.h"
#include "base/threading/thread.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/sessions/session_backend.h"
#include "chrome/browser/sessions/session_types.h"
#include "chrome/common/url_constants.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/browser/navigation_entry.h"
#include "content/public/common/referrer.h"
#include "webkit/glue/webkit_glue.h"
using WebKit::WebReferrerPolicy;
using content::BrowserThread;
using content::NavigationEntry;
// InternalGetCommandsRequest -------------------------------------------------
BaseSessionService::InternalGetCommandsRequest::~InternalGetCommandsRequest() {
STLDeleteElements(&commands);
}
// BaseSessionService ---------------------------------------------------------
namespace {
// Helper used by CreateUpdateTabNavigationCommand(). It writes |str| to
// |pickle|, if and only if |str| fits within (|max_bytes| - |*bytes_written|).
// |bytes_written| is incremented to reflect the data written.
void WriteStringToPickle(Pickle& pickle, int* bytes_written, int max_bytes,
const std::string& str) {
int num_bytes = str.size() * sizeof(char);
if (*bytes_written + num_bytes < max_bytes) {
*bytes_written += num_bytes;
pickle.WriteString(str);
} else {
pickle.WriteString(std::string());
}
}
// string16 version of WriteStringToPickle.
void WriteString16ToPickle(Pickle& pickle, int* bytes_written, int max_bytes,
const string16& str) {
int num_bytes = str.size() * sizeof(char16);
if (*bytes_written + num_bytes < max_bytes) {
*bytes_written += num_bytes;
pickle.WriteString16(str);
} else {
pickle.WriteString16(string16());
}
}
} // namespace
// Delay between when a command is received, and when we save it to the
// backend.
static const int kSaveDelayMS = 2500;
// static
const int BaseSessionService::max_persist_navigation_count = 6;
BaseSessionService::BaseSessionService(SessionType type,
Profile* profile,
const FilePath& path)
: profile_(profile),
path_(path),
ALLOW_THIS_IN_INITIALIZER_LIST(weak_factory_(this)),
pending_reset_(false),
commands_since_reset_(0) {
if (profile) {
// We should never be created when incognito.
DCHECK(!profile->IsOffTheRecord());
}
backend_ = new SessionBackend(type,
profile_ ? profile_->GetPath() : path_);
DCHECK(backend_.get());
RunTaskOnBackendThread(FROM_HERE,
base::Bind(&SessionBackend::Init, backend_));
}
BaseSessionService::~BaseSessionService() {
}
void BaseSessionService::DeleteLastSession() {
RunTaskOnBackendThread(
FROM_HERE,
base::Bind(&SessionBackend::DeleteLastSession, backend()));
}
void BaseSessionService::ScheduleCommand(SessionCommand* command) {
DCHECK(command);
commands_since_reset_++;
pending_commands_.push_back(command);
StartSaveTimer();
}
void BaseSessionService::StartSaveTimer() {
// Don't start a timer when testing (profile == NULL or
// MessageLoop::current() is NULL).
if (MessageLoop::current() && profile() && !weak_factory_.HasWeakPtrs()) {
MessageLoop::current()->PostDelayedTask(
FROM_HERE,
base::Bind(&BaseSessionService::Save, weak_factory_.GetWeakPtr()),
kSaveDelayMS);
}
}
void BaseSessionService::Save() {
DCHECK(backend());
if (pending_commands_.empty())
return;
RunTaskOnBackendThread(
FROM_HERE,
base::Bind(&SessionBackend::AppendCommands, backend(),
new std::vector<SessionCommand*>(pending_commands_),
pending_reset_));
// Backend took ownership of commands.
pending_commands_.clear();
if (pending_reset_) {
commands_since_reset_ = 0;
pending_reset_ = false;
}
}
SessionCommand* BaseSessionService::CreateUpdateTabNavigationCommand(
SessionID::id_type command_id,
SessionID::id_type tab_id,
int index,
const NavigationEntry& entry) {
// Use pickle to handle marshalling.
Pickle pickle;
pickle.WriteInt(tab_id);
pickle.WriteInt(index);
// We only allow navigations up to 63k (which should be completely
// reasonable). On the off chance we get one that is too big, try to
// keep the url.
// Bound the string data (which is variable length) to
// |max_state_size bytes| bytes.
static const SessionCommand::size_type max_state_size =
std::numeric_limits<SessionCommand::size_type>::max() - 1024;
int bytes_written = 0;
WriteStringToPickle(pickle, &bytes_written, max_state_size,
entry.GetVirtualURL().spec());
WriteString16ToPickle(pickle, &bytes_written, max_state_size,
entry.GetTitle());
if (entry.GetHasPostData()) {
UMA_HISTOGRAM_MEMORY_KB("SessionService.ContentStateSizeWithPost",
entry.GetContentState().size() / 1024);
// Remove the form data, it may contain sensitive information.
WriteStringToPickle(pickle, &bytes_written, max_state_size,
webkit_glue::RemoveFormDataFromHistoryState(entry.GetContentState()));
} else {
UMA_HISTOGRAM_MEMORY_KB("SessionService.ContentStateSize",
entry.GetContentState().size() / 1024);
WriteStringToPickle(pickle, &bytes_written, max_state_size,
entry.GetContentState());
}
pickle.WriteInt(entry.GetTransitionType());
int type_mask = entry.GetHasPostData() ? TabNavigation::HAS_POST_DATA : 0;
pickle.WriteInt(type_mask);
WriteStringToPickle(pickle, &bytes_written, max_state_size,
entry.GetReferrer().url.is_valid() ?
entry.GetReferrer().url.spec() : std::string());
pickle.WriteInt(entry.GetReferrer().policy);
// Adding more data? Be sure and update TabRestoreService too.
return new SessionCommand(command_id, pickle);
}
SessionCommand* BaseSessionService::CreateSetTabExtensionAppIDCommand(
SessionID::id_type command_id,
SessionID::id_type tab_id,
const std::string& extension_id) {
// Use pickle to handle marshalling.
Pickle pickle;
pickle.WriteInt(tab_id);
// Enforce a max for ids. They should never be anywhere near this size.
static const SessionCommand::size_type max_id_size =
std::numeric_limits<SessionCommand::size_type>::max() - 1024;
int bytes_written = 0;
WriteStringToPickle(pickle, &bytes_written, max_id_size, extension_id);
return new SessionCommand(command_id, pickle);
}
bool BaseSessionService::RestoreUpdateTabNavigationCommand(
const SessionCommand& command,
TabNavigation* navigation,
SessionID::id_type* tab_id) {
scoped_ptr<Pickle> pickle(command.PayloadAsPickle());
if (!pickle.get())
return false;
void* iterator = NULL;
std::string url_spec;
if (!pickle->ReadInt(&iterator, tab_id) ||
!pickle->ReadInt(&iterator, &(navigation->index_)) ||
!pickle->ReadString(&iterator, &url_spec) ||
!pickle->ReadString16(&iterator, &(navigation->title_)) ||
!pickle->ReadString(&iterator, &(navigation->state_)) ||
!pickle->ReadInt(&iterator,
reinterpret_cast<int*>(&(navigation->transition_))))
return false;
// type_mask did not always exist in the written stream. As such, we
// don't fail if it can't be read.
bool has_type_mask = pickle->ReadInt(&iterator, &(navigation->type_mask_));
if (has_type_mask) {
// the "referrer" property was added after type_mask to the written
// stream. As such, we don't fail if it can't be read.
std::string referrer_spec;
pickle->ReadString(&iterator, &referrer_spec);
// The "referrer policy" property was added even later, so we fall back to
// the default policy if the property is not present.
int policy_int;
WebReferrerPolicy policy;
if (pickle->ReadInt(&iterator, &policy_int))
policy = static_cast<WebReferrerPolicy>(policy_int);
else
policy = WebKit::WebReferrerPolicyDefault;
navigation->referrer_ = content::Referrer(
referrer_spec.empty() ? GURL() : GURL(referrer_spec),
policy);
}
navigation->virtual_url_ = GURL(url_spec);
return true;
}
bool BaseSessionService::RestoreSetTabExtensionAppIDCommand(
const SessionCommand& command,
SessionID::id_type* tab_id,
std::string* extension_app_id) {
scoped_ptr<Pickle> pickle(command.PayloadAsPickle());
if (!pickle.get())
return false;
void* iterator = NULL;
return pickle->ReadInt(&iterator, tab_id) &&
pickle->ReadString(&iterator, extension_app_id);
}
bool BaseSessionService::ShouldTrackEntry(const GURL& url) {
// NOTE: Do not track print preview tab because re-opening that page will
// just display a non-functional print preview page.
return url.is_valid() && url != GURL(chrome::kChromeUIPrintURL);
}
BaseSessionService::Handle BaseSessionService::ScheduleGetLastSessionCommands(
InternalGetCommandsRequest* request,
CancelableRequestConsumerBase* consumer) {
scoped_refptr<InternalGetCommandsRequest> request_wrapper(request);
AddRequest(request, consumer);
RunTaskOnBackendThread(
FROM_HERE,
base::Bind(&SessionBackend::ReadLastSessionCommands, backend(),
request_wrapper));
return request->handle();
}
bool BaseSessionService::RunTaskOnBackendThread(
const tracked_objects::Location& from_here,
const base::Closure& task) {
if (profile_ && BrowserThread::IsMessageLoopValid(BrowserThread::FILE)) {
return BrowserThread::PostTask(BrowserThread::FILE, from_here, task);
} else {
// Fall back to executing on the main thread if the file thread
// has gone away (around shutdown time) or if we're running as
// part of a unit test that does not set profile_.
task.Run();
return true;
}
}
<|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 "chrome/browser/ui/tabs/dock_info.h"
#include "chrome/browser/ui/views/tabs/tab.h"
#include "build/build_config.h"
#if !defined(OS_WIN)
// static
int DockInfo::GetHotSpotDeltaY() {
return Tab::GetMinimumUnselectedSize().height() - 1;
}
#endif
<commit_msg>views/tabs: Fix win_aura build enabling GetHotSpotDeltaY() in aura too.<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 "chrome/browser/ui/tabs/dock_info.h"
#include "chrome/browser/ui/views/tabs/tab.h"
#include "build/build_config.h"
#if defined(USE_AURA) || defined(USE_ASH) || defined(OS_CHROMEOS)
// static
int DockInfo::GetHotSpotDeltaY() {
return Tab::GetMinimumUnselectedSize().height() - 1;
}
#endif
<|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/fileicon_source_cros.h"
#include <map>
#include <utility>
#include <vector>
#include "base/file_util.h"
#include "base/memory/singleton.h"
#include "base/string_split.h"
#include "base/string_util.h"
#include "base/threading/thread_restrictions.h"
#include "chrome/browser/icon_loader.h"
#include "chrome/browser/io_thread.h"
#include "chrome/browser/ui/webui/chrome_url_data_manager.h"
#include "chrome/common/url_constants.h"
#include "content/browser/browser_thread.h"
#include "googleurl/src/gurl.h"
#include "grit/app_resources.h"
#include "grit/component_extension_resources.h"
#include "grit/component_extension_resources_map.h"
#include "grit/generated_resources.h"
#include "grit/theme_resources.h"
#include "net/base/mime_util.h"
#include "ui/base/resource/resource_bundle.h"
namespace {
struct IdrBySize {
int idr_small_;
int idr_normal_;
int idr_large_;
};
typedef std::map<std::string, IconLoader::IconSize> QueryIconSizeMap;
typedef std::map<std::string, IdrBySize> ExtensionIconSizeMap;
const char *kIconSize = "iconsize";
QueryIconSizeMap::value_type kQueryIconSizeData[] = {
std::make_pair("small", IconLoader::SMALL),
std::make_pair("normal", IconLoader::NORMAL),
std::make_pair("large", IconLoader::LARGE)
};
const IdrBySize kAudioIdrs = {
IDR_FILE_MANAGER_IMG_FILETYPE_AUDIO,
IDR_FILE_MANAGER_IMG_FILETYPE_LARGE_AUDIO,
IDR_FILE_MANAGER_IMG_FILETYPE_LARGE_AUDIO
};
const IdrBySize kDocIdrs = {
IDR_FILE_MANAGER_IMG_FILETYPE_DOC,
IDR_FILE_MANAGER_IMG_FILETYPE_DOC,
IDR_FILE_MANAGER_IMG_FILETYPE_DOC
};
const IdrBySize kFolderIdrs = {
IDR_FILE_MANAGER_IMG_FILETYPE_FOLDER,
IDR_FILE_MANAGER_IMG_FILETYPE_LARGE_FOLDER,
IDR_FILE_MANAGER_IMG_FILETYPE_LARGE_FOLDER
};
const IdrBySize kGenericIdrs = {
IDR_FILE_MANAGER_IMG_FILETYPE_GENERIC,
IDR_FILE_MANAGER_IMG_FILETYPE_LARGE_GENERIC,
IDR_FILE_MANAGER_IMG_FILETYPE_LARGE_GENERIC
};
const IdrBySize kHtmlIdrs = {
IDR_FILE_MANAGER_IMG_FILETYPE_HTML,
IDR_FILE_MANAGER_IMG_FILETYPE_HTML,
IDR_FILE_MANAGER_IMG_FILETYPE_HTML
};
const IdrBySize kImageIdrs = {
IDR_FILE_MANAGER_IMG_FILETYPE_IMAGE,
IDR_FILE_MANAGER_IMG_FILETYPE_IMAGE,
IDR_FILE_MANAGER_IMG_FILETYPE_IMAGE
};
const IdrBySize kPdfIdrs = {
IDR_FILE_MANAGER_IMG_FILETYPE_PDF,
IDR_FILE_MANAGER_IMG_FILETYPE_PDF,
IDR_FILE_MANAGER_IMG_FILETYPE_PDF
};
const IdrBySize kPresentationIdrs = {
IDR_FILE_MANAGER_IMG_FILETYPE_PRESENTATION,
IDR_FILE_MANAGER_IMG_FILETYPE_PRESENTATION,
IDR_FILE_MANAGER_IMG_FILETYPE_PRESENTATION
};
const IdrBySize kSpreadsheetIdrs = {
IDR_FILE_MANAGER_IMG_FILETYPE_SPREADSHEET,
IDR_FILE_MANAGER_IMG_FILETYPE_SPREADSHEET,
IDR_FILE_MANAGER_IMG_FILETYPE_SPREADSHEET
};
const IdrBySize kTextIdrs = {
IDR_FILE_MANAGER_IMG_FILETYPE_TEXT,
IDR_FILE_MANAGER_IMG_FILETYPE_TEXT,
IDR_FILE_MANAGER_IMG_FILETYPE_TEXT
};
const IdrBySize kVideoIdrs = {
IDR_FILE_MANAGER_IMG_FILETYPE_VIDEO,
IDR_FILE_MANAGER_IMG_FILETYPE_LARGE_VIDEO,
IDR_FILE_MANAGER_IMG_FILETYPE_LARGE_VIDEO
};
// The code below should match translation in
// chrome/browser/resources/file_manager/js/file_manager.js
// chrome/browser/resources/file_manager/css/file_manager.css
// 'audio': /\.(mp3|m4a|oga|ogg|wav)$/i,
// 'html': /\.(html?)$/i,
// 'image': /\.(bmp|gif|jpe?g|ico|png|webp)$/i,
// 'pdf' : /\.(pdf)$/i,
// 'text': /\.(pod|rst|txt|log)$/i,
// 'video': /\.(mov|mp4|m4v|mpe?g4?|ogm|ogv|ogx|webm)$/i
const ExtensionIconSizeMap::value_type kExtensionIdrBySizeData[] = {
std::make_pair(".m4a", kAudioIdrs),
std::make_pair(".mp3", kAudioIdrs),
std::make_pair(".oga", kAudioIdrs),
std::make_pair(".ogg", kAudioIdrs),
std::make_pair(".wav", kAudioIdrs),
// std::make_pair(".doc", kIdrDoc),
std::make_pair(".htm", kHtmlIdrs),
std::make_pair(".html", kHtmlIdrs),
std::make_pair(".bmp", kImageIdrs),
std::make_pair(".gif", kImageIdrs),
std::make_pair(".ico", kImageIdrs),
std::make_pair(".jpeg", kImageIdrs),
std::make_pair(".jpg", kImageIdrs),
std::make_pair(".png", kImageIdrs),
std::make_pair(".webp", kImageIdrs),
std::make_pair(".pdf", kPdfIdrs),
std::make_pair(".log", kTextIdrs),
std::make_pair(".pod", kTextIdrs),
std::make_pair(".rst", kTextIdrs),
std::make_pair(".txt", kTextIdrs),
std::make_pair(".m4v", kVideoIdrs),
std::make_pair(".mov", kVideoIdrs),
std::make_pair(".mp4", kVideoIdrs),
std::make_pair(".mpeg", kVideoIdrs),
std::make_pair(".mpg", kVideoIdrs),
std::make_pair(".mpeg4", kVideoIdrs),
std::make_pair(".mpg4", kVideoIdrs),
std::make_pair(".ogm", kVideoIdrs),
std::make_pair(".ogv", kVideoIdrs),
std::make_pair(".ogx", kVideoIdrs),
std::make_pair(".webm", kVideoIdrs),
};
const size_t kQSize = arraysize(kQueryIconSizeData);
const QueryIconSizeMap kQueryIconSizeMap(&kQueryIconSizeData[0],
&kQueryIconSizeData[kQSize]);
const size_t kESize = arraysize(kExtensionIdrBySizeData);
const ExtensionIconSizeMap kExtensionIdrSizeMap(
&kExtensionIdrBySizeData[0],
&kExtensionIdrBySizeData[kESize]);
// Split on the very first &. The first part is path, the rest query.
void GetExtensionAndQuery(const std::string& url,
std::string* extension,
std::string* query) {
// We receive the url with chrome://fileicon/ stripped but GURL expects it.
const GURL gurl("chrome://fileicon/" + url);
const std::string path = gurl.path();
*extension = StringToLowerASCII(FilePath().AppendASCII(path).Extension());
*query = gurl.query();
}
// Simple parser for data on the query.
IconLoader::IconSize QueryToIconSize(const std::string& query) {
typedef std::pair<std::string, std::string> KVPair;
std::vector<KVPair> parameters;
if (base::SplitStringIntoKeyValuePairs(query, '=', '&', ¶meters)) {
for (std::vector<KVPair>::const_iterator itk = parameters.begin();
itk != parameters.end(); ++itk) {
if (itk->first == kIconSize) {
QueryIconSizeMap::const_iterator itq(
kQueryIconSizeMap.find(itk->second));
if (itq != kQueryIconSizeMap.end())
return itq->second;
}
}
}
return IconLoader::NORMAL;
}
// Finds matching resource of proper size. Fallback to generic.
int UrlToIDR(const std::string& url) {
std::string extension, query;
int idr = -1;
GetExtensionAndQuery(url, &extension, &query);
const IconLoader::IconSize size = QueryToIconSize(query);
ExtensionIconSizeMap::const_iterator it =
kExtensionIdrSizeMap.find(extension);
if (it != kExtensionIdrSizeMap.end()) {
IdrBySize idrbysize = it->second;
if (size == IconLoader::SMALL) {
idr = idrbysize.idr_small_;
} else if (size == IconLoader::NORMAL) {
idr = idrbysize.idr_normal_;
} else if (size == IconLoader::LARGE) {
idr = idrbysize.idr_large_;
}
}
DCHECK_NE(-1, idr) << " Missing fileicon for: " << url;
if (idr == -1) {
if (size == IconLoader::SMALL) {
idr = kGenericIdrs.idr_small_;
} else if (size == IconLoader::NORMAL) {
idr = kGenericIdrs.idr_normal_;
} else {
idr = kGenericIdrs.idr_large_;
}
}
return idr;
}
} // namespace
FileIconSourceCros::FileIconSourceCros()
: DataSource("fileicon", NULL) {
}
FileIconSourceCros::~FileIconSourceCros() {
}
void FileIconSourceCros::StartDataRequest(const std::string& url,
bool is_incognito,
int request_id) {
int idr = UrlToIDR(url);
const ResourceBundle& rb = ResourceBundle::GetSharedInstance();
scoped_refptr<RefCountedStaticMemory> bytes(rb.LoadDataResourceBytes(idr));
SendResponse(request_id, bytes);
}
// The mime type refers to the type of the response/icon served.
std::string FileIconSourceCros::GetMimeType(
const std::string& url) const {
return "image/png";
}
<commit_msg>Fix debug failures in fileicon_source_cros<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/fileicon_source_cros.h"
#include <map>
#include <utility>
#include <vector>
#include "base/file_util.h"
#include "base/memory/singleton.h"
#include "base/string_split.h"
#include "base/string_util.h"
#include "base/threading/thread_restrictions.h"
#include "chrome/browser/icon_loader.h"
#include "chrome/browser/io_thread.h"
#include "chrome/browser/ui/webui/chrome_url_data_manager.h"
#include "chrome/common/url_constants.h"
#include "content/browser/browser_thread.h"
#include "googleurl/src/gurl.h"
#include "grit/app_resources.h"
#include "grit/component_extension_resources.h"
#include "grit/component_extension_resources_map.h"
#include "grit/generated_resources.h"
#include "grit/theme_resources.h"
#include "net/base/mime_util.h"
#include "ui/base/resource/resource_bundle.h"
namespace {
struct IdrBySize {
int idr_small_;
int idr_normal_;
int idr_large_;
};
typedef std::map<std::string, IconLoader::IconSize> QueryIconSizeMap;
typedef std::map<std::string, IdrBySize> ExtensionIconSizeMap;
const char *kIconSize = "iconsize";
QueryIconSizeMap::value_type kQueryIconSizeData[] = {
std::make_pair("small", IconLoader::SMALL),
std::make_pair("normal", IconLoader::NORMAL),
std::make_pair("large", IconLoader::LARGE)
};
const IdrBySize kAudioIdrs = {
IDR_FILE_MANAGER_IMG_FILETYPE_AUDIO,
IDR_FILE_MANAGER_IMG_FILETYPE_LARGE_AUDIO,
IDR_FILE_MANAGER_IMG_FILETYPE_LARGE_AUDIO
};
const IdrBySize kDocIdrs = {
IDR_FILE_MANAGER_IMG_FILETYPE_DOC,
IDR_FILE_MANAGER_IMG_FILETYPE_DOC,
IDR_FILE_MANAGER_IMG_FILETYPE_DOC
};
const IdrBySize kFolderIdrs = {
IDR_FILE_MANAGER_IMG_FILETYPE_FOLDER,
IDR_FILE_MANAGER_IMG_FILETYPE_LARGE_FOLDER,
IDR_FILE_MANAGER_IMG_FILETYPE_LARGE_FOLDER
};
const IdrBySize kGenericIdrs = {
IDR_FILE_MANAGER_IMG_FILETYPE_GENERIC,
IDR_FILE_MANAGER_IMG_FILETYPE_LARGE_GENERIC,
IDR_FILE_MANAGER_IMG_FILETYPE_LARGE_GENERIC
};
const IdrBySize kHtmlIdrs = {
IDR_FILE_MANAGER_IMG_FILETYPE_HTML,
IDR_FILE_MANAGER_IMG_FILETYPE_HTML,
IDR_FILE_MANAGER_IMG_FILETYPE_HTML
};
const IdrBySize kImageIdrs = {
IDR_FILE_MANAGER_IMG_FILETYPE_IMAGE,
IDR_FILE_MANAGER_IMG_FILETYPE_IMAGE,
IDR_FILE_MANAGER_IMG_FILETYPE_IMAGE
};
const IdrBySize kPdfIdrs = {
IDR_FILE_MANAGER_IMG_FILETYPE_PDF,
IDR_FILE_MANAGER_IMG_FILETYPE_PDF,
IDR_FILE_MANAGER_IMG_FILETYPE_PDF
};
const IdrBySize kPresentationIdrs = {
IDR_FILE_MANAGER_IMG_FILETYPE_PRESENTATION,
IDR_FILE_MANAGER_IMG_FILETYPE_PRESENTATION,
IDR_FILE_MANAGER_IMG_FILETYPE_PRESENTATION
};
const IdrBySize kSpreadsheetIdrs = {
IDR_FILE_MANAGER_IMG_FILETYPE_SPREADSHEET,
IDR_FILE_MANAGER_IMG_FILETYPE_SPREADSHEET,
IDR_FILE_MANAGER_IMG_FILETYPE_SPREADSHEET
};
const IdrBySize kTextIdrs = {
IDR_FILE_MANAGER_IMG_FILETYPE_TEXT,
IDR_FILE_MANAGER_IMG_FILETYPE_TEXT,
IDR_FILE_MANAGER_IMG_FILETYPE_TEXT
};
const IdrBySize kVideoIdrs = {
IDR_FILE_MANAGER_IMG_FILETYPE_VIDEO,
IDR_FILE_MANAGER_IMG_FILETYPE_LARGE_VIDEO,
IDR_FILE_MANAGER_IMG_FILETYPE_LARGE_VIDEO
};
// The code below should match translation in
// chrome/browser/resources/file_manager/js/file_manager.js
// chrome/browser/resources/file_manager/css/file_manager.css
// 'audio': /\.(mp3|m4a|oga|ogg|wav)$/i,
// 'html': /\.(html?)$/i,
// 'image': /\.(bmp|gif|jpe?g|ico|png|webp)$/i,
// 'pdf' : /\.(pdf)$/i,
// 'text': /\.(pod|rst|txt|log)$/i,
// 'video': /\.(mov|mp4|m4v|mpe?g4?|ogm|ogv|ogx|webm)$/i
const ExtensionIconSizeMap::value_type kExtensionIdrBySizeData[] = {
std::make_pair(".m4a", kAudioIdrs),
std::make_pair(".mp3", kAudioIdrs),
std::make_pair(".oga", kAudioIdrs),
std::make_pair(".ogg", kAudioIdrs),
std::make_pair(".wav", kAudioIdrs),
// std::make_pair(".doc", kIdrDoc),
std::make_pair(".htm", kHtmlIdrs),
std::make_pair(".html", kHtmlIdrs),
std::make_pair(".bmp", kImageIdrs),
std::make_pair(".gif", kImageIdrs),
std::make_pair(".ico", kImageIdrs),
std::make_pair(".jpeg", kImageIdrs),
std::make_pair(".jpg", kImageIdrs),
std::make_pair(".png", kImageIdrs),
std::make_pair(".webp", kImageIdrs),
std::make_pair(".pdf", kPdfIdrs),
std::make_pair(".log", kTextIdrs),
std::make_pair(".pod", kTextIdrs),
std::make_pair(".rst", kTextIdrs),
std::make_pair(".txt", kTextIdrs),
std::make_pair(".m4v", kVideoIdrs),
std::make_pair(".mov", kVideoIdrs),
std::make_pair(".mp4", kVideoIdrs),
std::make_pair(".mpeg", kVideoIdrs),
std::make_pair(".mpg", kVideoIdrs),
std::make_pair(".mpeg4", kVideoIdrs),
std::make_pair(".mpg4", kVideoIdrs),
std::make_pair(".ogm", kVideoIdrs),
std::make_pair(".ogv", kVideoIdrs),
std::make_pair(".ogx", kVideoIdrs),
std::make_pair(".webm", kVideoIdrs),
};
const size_t kQSize = arraysize(kQueryIconSizeData);
const QueryIconSizeMap kQueryIconSizeMap(&kQueryIconSizeData[0],
&kQueryIconSizeData[kQSize]);
const size_t kESize = arraysize(kExtensionIdrBySizeData);
const ExtensionIconSizeMap kExtensionIdrSizeMap(
&kExtensionIdrBySizeData[0],
&kExtensionIdrBySizeData[kESize]);
// Split on the very first &. The first part is path, the rest query.
void GetExtensionAndQuery(const std::string& url,
std::string* extension,
std::string* query) {
// We receive the url with chrome://fileicon/ stripped but GURL expects it.
const GURL gurl("chrome://fileicon/" + url);
const std::string path = gurl.path();
*extension = StringToLowerASCII(FilePath(path).Extension());
*query = gurl.query();
}
// Simple parser for data on the query.
IconLoader::IconSize QueryToIconSize(const std::string& query) {
typedef std::pair<std::string, std::string> KVPair;
std::vector<KVPair> parameters;
if (base::SplitStringIntoKeyValuePairs(query, '=', '&', ¶meters)) {
for (std::vector<KVPair>::const_iterator itk = parameters.begin();
itk != parameters.end(); ++itk) {
if (itk->first == kIconSize) {
QueryIconSizeMap::const_iterator itq(
kQueryIconSizeMap.find(itk->second));
if (itq != kQueryIconSizeMap.end())
return itq->second;
}
}
}
return IconLoader::NORMAL;
}
// Finds matching resource of proper size. Fallback to generic.
int UrlToIDR(const std::string& url) {
std::string extension, query;
int idr = -1;
GetExtensionAndQuery(url, &extension, &query);
const IconLoader::IconSize size = QueryToIconSize(query);
ExtensionIconSizeMap::const_iterator it =
kExtensionIdrSizeMap.find(extension);
if (it != kExtensionIdrSizeMap.end()) {
IdrBySize idrbysize = it->second;
if (size == IconLoader::SMALL) {
idr = idrbysize.idr_small_;
} else if (size == IconLoader::NORMAL) {
idr = idrbysize.idr_normal_;
} else if (size == IconLoader::LARGE) {
idr = idrbysize.idr_large_;
}
}
if (idr == -1) {
if (size == IconLoader::SMALL) {
idr = kGenericIdrs.idr_small_;
} else if (size == IconLoader::NORMAL) {
idr = kGenericIdrs.idr_normal_;
} else {
idr = kGenericIdrs.idr_large_;
}
}
return idr;
}
} // namespace
FileIconSourceCros::FileIconSourceCros()
: DataSource("fileicon", NULL) {
}
FileIconSourceCros::~FileIconSourceCros() {
}
void FileIconSourceCros::StartDataRequest(const std::string& url,
bool is_incognito,
int request_id) {
int idr = UrlToIDR(url);
const ResourceBundle& rb = ResourceBundle::GetSharedInstance();
scoped_refptr<RefCountedStaticMemory> bytes(rb.LoadDataResourceBytes(idr));
SendResponse(request_id, bytes);
}
// The mime type refers to the type of the response/icon served.
std::string FileIconSourceCros::GetMimeType(
const std::string& url) const {
return "image/png";
}
<|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 "base/utf_string_conversions.h"
#include "chrome/common/render_messages.h"
#include "chrome/common/render_messages_params.h"
#include "chrome/test/render_view_test.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "third_party/WebKit/WebKit/chromium/public/WebSize.h"
#include "third_party/WebKit/WebKit/chromium/public/WebView.h"
// Tests for the external select popup menu (Mac specific).
namespace {
const char* const kSelectID = "mySelect";
} // namespace
class ExternalPopupMenuTest : public RenderViewTest {
public:
ExternalPopupMenuTest() {}
virtual void SetUp() {
RenderViewTest::SetUp();
// We need to set this explictly as RenderMain is not run.
WebKit::WebView::setUseExternalPopupMenus(true);
std::string html = "<select id='mySelect' onchange='selectChanged(this)'>"
" <option>zero</option>"
" <option selected='1'>one</option>"
" <option>two</option>"
"</select>";
if (ShouldRemoveSelectOnChange()) {
html += "<script>"
" function selectChanged(select) {"
" select.parentNode.removeChild(select);"
" }"
"</script>";
}
// Load the test page.
LoadHTML(html.c_str());
// Set a minimum size and give focus so simulated events work.
view_->webwidget()->resize(WebKit::WebSize(500, 500));
view_->webwidget()->setFocus(true);
}
int GetSelectedIndex() {
string16 script(ASCIIToUTF16(kSelectID));
script.append(ASCIIToUTF16(".selectedIndex"));
int selected_index = -1;
ExecuteJavaScriptAndReturnIntValue(script, &selected_index);
return selected_index;
}
protected:
virtual bool ShouldRemoveSelectOnChange() const { return false; }
DISALLOW_COPY_AND_ASSIGN(ExternalPopupMenuTest);
};
// Normal case: test showing a select popup, canceling/selecting an item.
TEST_F(ExternalPopupMenuTest, NormalCase) {
IPC::TestSink& sink = render_thread_.sink();
// Click the text field once.
EXPECT_TRUE(SimulateElementClick(kSelectID));
// We should have sent a message to the browser to show the popup menu.
const IPC::Message* message =
sink.GetUniqueMessageMatching(ViewHostMsg_ShowPopup::ID);
ASSERT_TRUE(message != NULL);
Tuple1<ViewHostMsg_ShowPopup_Params> param;
ViewHostMsg_ShowPopup::Read(message, ¶m);
ASSERT_EQ(3U, param.a.popup_items.size());
EXPECT_EQ(1, param.a.selected_item);
// Simulate the user canceling the popup, the index should not have changed.
view_->OnSelectPopupMenuItem(-1);
EXPECT_EQ(1, GetSelectedIndex());
// Show the pop-up again and this time make a selection.
EXPECT_TRUE(SimulateElementClick(kSelectID));
view_->OnSelectPopupMenuItem(0);
EXPECT_EQ(0, GetSelectedIndex());
// Show the pop-up again and make another selection.
sink.ClearMessages();
EXPECT_TRUE(SimulateElementClick(kSelectID));
message = sink.GetUniqueMessageMatching(ViewHostMsg_ShowPopup::ID);
ASSERT_TRUE(message != NULL);
ViewHostMsg_ShowPopup::Read(message, ¶m);
ASSERT_EQ(3U, param.a.popup_items.size());
EXPECT_EQ(0, param.a.selected_item);
}
// Page shows popup, then navigates away while popup showing, then select.
TEST_F(ExternalPopupMenuTest, ShowPopupThenNavigate) {
// Click the text field once.
EXPECT_TRUE(SimulateElementClick(kSelectID));
// Now we navigate to another pager.
LoadHTML("<blink>Awesome page!</blink>");
// Now the user selects something, we should not crash.
view_->OnSelectPopupMenuItem(-1);
}
class ExternalPopupMenuRemoveTest : public ExternalPopupMenuTest {
public:
ExternalPopupMenuRemoveTest() {}
protected:
virtual bool ShouldRemoveSelectOnChange() const { return true; }
};
// Tests that nothing bad happen when the page removes the select when it
// changes. (http://crbug.com/61997)
TEST_F(ExternalPopupMenuRemoveTest, RemoveOnChange) {
// Click the text field once to show the popup.
EXPECT_TRUE(SimulateElementClick(kSelectID));
// Select something, it causes the select to be removed from the page.
view_->OnSelectPopupMenuItem(0);
// Just to check the soundness of the test, call SimulateElementClick again.
// It should return false as the select has been removed.
EXPECT_FALSE(SimulateElementClick(kSelectID));
}
<commit_msg>Adding a test to validate that we don't crash on empty selects. That bug is fixed on the WebKit side with: https://bugs.webkit.org/show_bug.cgi?id=49937<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 "base/utf_string_conversions.h"
#include "chrome/common/render_messages.h"
#include "chrome/common/render_messages_params.h"
#include "chrome/test/render_view_test.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "third_party/WebKit/WebKit/chromium/public/WebSize.h"
#include "third_party/WebKit/WebKit/chromium/public/WebView.h"
// Tests for the external select popup menu (Mac specific).
namespace {
const char* const kSelectID = "mySelect";
const char* const kEmptySelectID = "myEmptySelect";
} // namespace
class ExternalPopupMenuTest : public RenderViewTest {
public:
ExternalPopupMenuTest() {}
virtual void SetUp() {
RenderViewTest::SetUp();
// We need to set this explictly as RenderMain is not run.
WebKit::WebView::setUseExternalPopupMenus(true);
std::string html = "<select id='mySelect' onchange='selectChanged(this)'>"
" <option>zero</option>"
" <option selected='1'>one</option>"
" <option>two</option>"
"</select>"
"<select id='myEmptySelect'>"
"</select>";
if (ShouldRemoveSelectOnChange()) {
html += "<script>"
" function selectChanged(select) {"
" select.parentNode.removeChild(select);"
" }"
"</script>";
}
// Load the test page.
LoadHTML(html.c_str());
// Set a minimum size and give focus so simulated events work.
view_->webwidget()->resize(WebKit::WebSize(500, 500));
view_->webwidget()->setFocus(true);
}
int GetSelectedIndex() {
string16 script(ASCIIToUTF16(kSelectID));
script.append(ASCIIToUTF16(".selectedIndex"));
int selected_index = -1;
ExecuteJavaScriptAndReturnIntValue(script, &selected_index);
return selected_index;
}
protected:
virtual bool ShouldRemoveSelectOnChange() const { return false; }
DISALLOW_COPY_AND_ASSIGN(ExternalPopupMenuTest);
};
// Normal case: test showing a select popup, canceling/selecting an item.
TEST_F(ExternalPopupMenuTest, NormalCase) {
IPC::TestSink& sink = render_thread_.sink();
// Click the text field once.
EXPECT_TRUE(SimulateElementClick(kSelectID));
// We should have sent a message to the browser to show the popup menu.
const IPC::Message* message =
sink.GetUniqueMessageMatching(ViewHostMsg_ShowPopup::ID);
ASSERT_TRUE(message != NULL);
Tuple1<ViewHostMsg_ShowPopup_Params> param;
ViewHostMsg_ShowPopup::Read(message, ¶m);
ASSERT_EQ(3U, param.a.popup_items.size());
EXPECT_EQ(1, param.a.selected_item);
// Simulate the user canceling the popup, the index should not have changed.
view_->OnSelectPopupMenuItem(-1);
EXPECT_EQ(1, GetSelectedIndex());
// Show the pop-up again and this time make a selection.
EXPECT_TRUE(SimulateElementClick(kSelectID));
view_->OnSelectPopupMenuItem(0);
EXPECT_EQ(0, GetSelectedIndex());
// Show the pop-up again and make another selection.
sink.ClearMessages();
EXPECT_TRUE(SimulateElementClick(kSelectID));
message = sink.GetUniqueMessageMatching(ViewHostMsg_ShowPopup::ID);
ASSERT_TRUE(message != NULL);
ViewHostMsg_ShowPopup::Read(message, ¶m);
ASSERT_EQ(3U, param.a.popup_items.size());
EXPECT_EQ(0, param.a.selected_item);
}
// Page shows popup, then navigates away while popup showing, then select.
TEST_F(ExternalPopupMenuTest, ShowPopupThenNavigate) {
// Click the text field once.
EXPECT_TRUE(SimulateElementClick(kSelectID));
// Now we navigate to another pager.
LoadHTML("<blink>Awesome page!</blink>");
// Now the user selects something, we should not crash.
view_->OnSelectPopupMenuItem(-1);
}
// An empty select should not cause a crash when clicked.
// http://crbug.com/63774
TEST_F(ExternalPopupMenuTest, EmptySelect) {
EXPECT_TRUE(SimulateElementClick(kEmptySelectID));
}
class ExternalPopupMenuRemoveTest : public ExternalPopupMenuTest {
public:
ExternalPopupMenuRemoveTest() {}
protected:
virtual bool ShouldRemoveSelectOnChange() const { return true; }
};
// Tests that nothing bad happen when the page removes the select when it
// changes. (http://crbug.com/61997)
TEST_F(ExternalPopupMenuRemoveTest, RemoveOnChange) {
// Click the text field once to show the popup.
EXPECT_TRUE(SimulateElementClick(kSelectID));
// Select something, it causes the select to be removed from the page.
view_->OnSelectPopupMenuItem(0);
// Just to check the soundness of the test, call SimulateElementClick again.
// It should return false as the select has been removed.
EXPECT_FALSE(SimulateElementClick(kSelectID));
}
<|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 <map>
#include "base/command_line.h"
#include "base/file_util.h"
#include "base/path_service.h"
#include "base/string_number_conversions.h"
#include "base/test/test_timeouts.h"
#include "base/test/trace_event_analyzer.h"
#include "base/utf_string_conversions.h"
#include "chrome/common/chrome_paths.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/test/automation/automation_proxy.h"
#include "chrome/test/automation/tab_proxy.h"
#include "chrome/test/ui/javascript_test_util.h"
#include "chrome/test/ui/ui_perf_test.h"
#include "net/base/net_util.h"
#include "ui/gfx/gl/gl_implementation.h"
#include "ui/gfx/gl/gl_switches.h"
namespace {
enum FrameRateTestFlags {
kUseGpu = 1 << 0, // Only execute test if --enable-gpu, and verify
// that test ran on GPU. This is required for
// tests that run on GPU.
kForceGpuComposited = 1 << 1, // Force the test to use the compositor.
kDisableVsync = 1 << 2, // Do not limit framerate to vertical refresh.
// when on GPU, nor to 60hz when not on GPU.
kUseReferenceBuild = 1 << 3, // Run test using the reference chrome build.
kInternal = 1 << 4, // Test uses internal test data.
kHasRedirect = 1 << 5, // Test page contains an HTML redirect.
};
class FrameRateTest
: public UIPerfTest
, public ::testing::WithParamInterface<int> {
public:
FrameRateTest() {
show_window_ = true;
dom_automation_enabled_ = true;
}
bool HasFlag(FrameRateTestFlags flag) const {
return (GetParam() & flag) == flag;
}
bool IsGpuAvailable() const {
return CommandLine::ForCurrentProcess()->HasSwitch("enable-gpu");
}
std::string GetSuffixForTestFlags() {
std::string suffix;
if (HasFlag(kForceGpuComposited))
suffix += "_comp";
if (HasFlag(kUseGpu))
suffix += "_gpu";
if (HasFlag(kDisableVsync))
suffix += "_novsync";
if (HasFlag(kUseReferenceBuild))
suffix += "_ref";
return suffix;
}
virtual FilePath GetDataPath(const std::string& name) {
// Make sure the test data is checked out.
FilePath test_path;
PathService::Get(chrome::DIR_TEST_DATA, &test_path);
test_path = test_path.Append(FILE_PATH_LITERAL("perf"));
test_path = test_path.Append(FILE_PATH_LITERAL("frame_rate"));
if (HasFlag(kInternal)) {
test_path = test_path.Append(FILE_PATH_LITERAL("private"));
} else {
test_path = test_path.Append(FILE_PATH_LITERAL("content"));
}
test_path = test_path.AppendASCII(name);
return test_path;
}
virtual void SetUp() {
if (HasFlag(kUseReferenceBuild))
UseReferenceBuild();
// Turn on chrome.Interval to get higher-resolution timestamps on frames.
launch_arguments_.AppendSwitch(switches::kEnableBenchmarking);
// Required additional argument to make the kEnableBenchmarking switch work.
launch_arguments_.AppendSwitch(switches::kEnableStatsTable);
// UI tests boot up render views starting from about:blank. This causes
// the renderer to start up thinking it cannot use the GPU. To work
// around that, and allow the frame rate test to use the GPU, we must
// pass kAllowWebUICompositing.
launch_arguments_.AppendSwitch(switches::kAllowWebUICompositing);
// Some of the tests may launch http requests through JSON or AJAX
// which causes a security error (cross domain request) when the page
// is loaded from the local file system ( file:// ). The following switch
// fixes that error.
launch_arguments_.AppendSwitch(switches::kAllowFileAccessFromFiles);
if (!HasFlag(kUseGpu)) {
launch_arguments_.AppendSwitch(switches::kDisableAcceleratedCompositing);
launch_arguments_.AppendSwitch(switches::kDisableExperimentalWebGL);
launch_arguments_.AppendSwitch(switches::kDisableAccelerated2dCanvas);
} else {
// This switch is required for enabling the accelerated 2d canvas on
// Chrome versions prior to Chrome 15, which may be the case for the
// reference build.
launch_arguments_.AppendSwitch(switches::kEnableAccelerated2dCanvas);
}
if (HasFlag(kDisableVsync))
launch_arguments_.AppendSwitch(switches::kDisableGpuVsync);
UIPerfTest::SetUp();
}
bool DidRunOnGpu(const std::string& json_events) {
using namespace trace_analyzer;
// Check trace for GPU accleration.
scoped_ptr<TraceAnalyzer> analyzer(TraceAnalyzer::Create(json_events));
gfx::GLImplementation gl_impl = gfx::kGLImplementationNone;
const TraceEvent* gpu_event = analyzer->FindOneEvent(
Query(EVENT_NAME) == Query::String("SwapBuffers") &&
Query(EVENT_HAS_NUMBER_ARG, "GLImpl"));
if (gpu_event)
gl_impl = static_cast<gfx::GLImplementation>(
gpu_event->GetKnownArgAsInt("GLImpl"));
return (gl_impl == gfx::kGLImplementationDesktopGL ||
gl_impl == gfx::kGLImplementationEGLGLES2);
}
void RunTest(const std::string& name) {
if (HasFlag(kUseGpu) && !IsGpuAvailable()) {
printf("Test skipped: requires gpu. Pass --enable-gpu on the command "
"line if use of GPU is desired.\n");
return;
}
// Verify flag combinations.
ASSERT_TRUE(HasFlag(kUseGpu) || !HasFlag(kForceGpuComposited));
ASSERT_TRUE(!HasFlag(kUseGpu) || IsGpuAvailable());
FilePath test_path = GetDataPath(name);
ASSERT_TRUE(file_util::DirectoryExists(test_path))
<< "Missing test directory: " << test_path.value();
test_path = test_path.Append(FILE_PATH_LITERAL("test.html"));
scoped_refptr<TabProxy> tab(GetActiveTab());
ASSERT_TRUE(tab.get());
// TODO(jbates): remove this check when ref builds are updated.
if (!HasFlag(kUseReferenceBuild))
ASSERT_TRUE(automation()->BeginTracing("test_gpu"));
if (HasFlag(kHasRedirect)) {
// If the test file is known to contain an html redirect, we must block
// until the second navigation is complete and reacquire the active tab
// in order to avoid a race condition.
// If the following assertion is triggered due to a timeout, it is
// possible that the current test does not re-direct and therefore should
// not have the kHasRedirect flag turned on.
ASSERT_EQ(AUTOMATION_MSG_NAVIGATION_SUCCESS,
tab->NavigateToURLBlockUntilNavigationsComplete(
net::FilePathToFileURL(test_path), 2));
tab = GetActiveTab();
ASSERT_TRUE(tab.get());
} else {
ASSERT_EQ(AUTOMATION_MSG_NAVIGATION_SUCCESS,
tab->NavigateToURL(net::FilePathToFileURL(test_path)));
}
// Block until initialization completes
// If the following assertion fails intermittently, it could be due to a
// race condition caused by an html redirect. If that is the case, verify
// that flag kHasRedirect is enabled for the current test.
ASSERT_TRUE(WaitUntilJavaScriptCondition(
tab, L"", L"window.domAutomationController.send(__initialized);",
TestTimeouts::large_test_timeout_ms()));
if (HasFlag(kForceGpuComposited)) {
ASSERT_TRUE(tab->NavigateToURLAsync(
GURL("javascript:__make_body_composited();")));
}
// Start the tests.
ASSERT_TRUE(tab->NavigateToURLAsync(GURL("javascript:__start_all();")));
// Block until the tests completes.
ASSERT_TRUE(WaitUntilJavaScriptCondition(
tab, L"", L"window.domAutomationController.send(!__running_all);",
TestTimeouts::large_test_timeout_ms()));
// TODO(jbates): remove this check when ref builds are updated.
if (!HasFlag(kUseReferenceBuild)) {
std::string json_events;
ASSERT_TRUE(automation()->EndTracing(&json_events));
bool did_run_on_gpu = DidRunOnGpu(json_events);
bool expect_gpu = HasFlag(kUseGpu);
EXPECT_EQ(expect_gpu, did_run_on_gpu);
}
// Read out the results.
std::wstring json;
ASSERT_TRUE(tab->ExecuteAndExtractString(
L"",
L"window.domAutomationController.send("
L"JSON.stringify(__calc_results_total()));",
&json));
std::map<std::string, std::string> results;
ASSERT_TRUE(JsonDictionaryToMap(WideToUTF8(json), &results));
ASSERT_TRUE(results.find("mean") != results.end());
ASSERT_TRUE(results.find("sigma") != results.end());
ASSERT_TRUE(results.find("gestures") != results.end());
ASSERT_TRUE(results.find("means") != results.end());
ASSERT_TRUE(results.find("sigmas") != results.end());
std::string trace_name = "interval" + GetSuffixForTestFlags();
printf("GESTURES %s: %s= [%s] [%s] [%s]\n", name.c_str(),
trace_name.c_str(),
results["gestures"].c_str(),
results["means"].c_str(),
results["sigmas"].c_str());
std::string mean_and_error = results["mean"] + "," + results["sigma"];
PrintResultMeanAndError(name, "", trace_name, mean_and_error,
"frames-per-second", true);
}
};
// Must use a different class name to avoid test instantiation conflicts
// with FrameRateTest. An alias is good enough. The alias names must match
// the pattern FrameRate*Test* for them to get picked up by the test bots.
typedef FrameRateTest FrameRateCompositingTest;
// Tests that trigger compositing with a -webkit-translateZ(0)
#define FRAME_RATE_TEST_WITH_AND_WITHOUT_ACCELERATED_COMPOSITING(content) \
TEST_P(FrameRateCompositingTest, content) { \
RunTest(#content); \
}
INSTANTIATE_TEST_CASE_P(, FrameRateCompositingTest, ::testing::Values(
0,
kUseGpu | kForceGpuComposited,
kUseReferenceBuild,
kUseReferenceBuild | kUseGpu | kForceGpuComposited));
FRAME_RATE_TEST_WITH_AND_WITHOUT_ACCELERATED_COMPOSITING(blank);
FRAME_RATE_TEST_WITH_AND_WITHOUT_ACCELERATED_COMPOSITING(googleblog);
typedef FrameRateTest FrameRateNoVsyncCanvasInternalTest;
// Tests for animated 2D canvas content with and without disabling vsync
#define INTERNAL_FRAME_RATE_TEST_CANVAS_WITH_AND_WITHOUT_NOVSYNC(content) \
TEST_P(FrameRateNoVsyncCanvasInternalTest, content) { \
RunTest(#content); \
}
INSTANTIATE_TEST_CASE_P(, FrameRateNoVsyncCanvasInternalTest, ::testing::Values(
kInternal | kHasRedirect,
kInternal | kHasRedirect | kUseGpu,
kInternal | kHasRedirect | kUseGpu | kDisableVsync,
kUseReferenceBuild | kInternal | kHasRedirect,
kUseReferenceBuild | kInternal | kHasRedirect | kUseGpu,
kUseReferenceBuild | kInternal | kHasRedirect | kUseGpu | kDisableVsync));
INTERNAL_FRAME_RATE_TEST_CANVAS_WITH_AND_WITHOUT_NOVSYNC(DISABLED_fishbowl)
typedef FrameRateTest FrameRateGpuCanvasInternalTest;
// Tests for animated 2D canvas content to be tested only with GPU
// acceleration.
// tests are run with and without Vsync
#define INTERNAL_FRAME_RATE_TEST_CANVAS_GPU(content) \
TEST_P(FrameRateGpuCanvasInternalTest, content) { \
RunTest(#content); \
}
INSTANTIATE_TEST_CASE_P(, FrameRateGpuCanvasInternalTest, ::testing::Values(
kInternal | kHasRedirect | kUseGpu,
kInternal | kHasRedirect | kUseGpu | kDisableVsync,
kUseReferenceBuild | kInternal | kHasRedirect | kUseGpu,
kUseReferenceBuild | kInternal | kHasRedirect | kUseGpu | kDisableVsync));
INTERNAL_FRAME_RATE_TEST_CANVAS_GPU(fireflies)
INTERNAL_FRAME_RATE_TEST_CANVAS_GPU(FishIE)
INTERNAL_FRAME_RATE_TEST_CANVAS_GPU(speedreading)
} // namespace
<commit_msg>Disable gpu_frame_rate_test fireflies as it TIMEOUT on gpu bots.<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 <map>
#include "base/command_line.h"
#include "base/file_util.h"
#include "base/path_service.h"
#include "base/string_number_conversions.h"
#include "base/test/test_timeouts.h"
#include "base/test/trace_event_analyzer.h"
#include "base/utf_string_conversions.h"
#include "chrome/common/chrome_paths.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/test/automation/automation_proxy.h"
#include "chrome/test/automation/tab_proxy.h"
#include "chrome/test/ui/javascript_test_util.h"
#include "chrome/test/ui/ui_perf_test.h"
#include "net/base/net_util.h"
#include "ui/gfx/gl/gl_implementation.h"
#include "ui/gfx/gl/gl_switches.h"
namespace {
enum FrameRateTestFlags {
kUseGpu = 1 << 0, // Only execute test if --enable-gpu, and verify
// that test ran on GPU. This is required for
// tests that run on GPU.
kForceGpuComposited = 1 << 1, // Force the test to use the compositor.
kDisableVsync = 1 << 2, // Do not limit framerate to vertical refresh.
// when on GPU, nor to 60hz when not on GPU.
kUseReferenceBuild = 1 << 3, // Run test using the reference chrome build.
kInternal = 1 << 4, // Test uses internal test data.
kHasRedirect = 1 << 5, // Test page contains an HTML redirect.
};
class FrameRateTest
: public UIPerfTest
, public ::testing::WithParamInterface<int> {
public:
FrameRateTest() {
show_window_ = true;
dom_automation_enabled_ = true;
}
bool HasFlag(FrameRateTestFlags flag) const {
return (GetParam() & flag) == flag;
}
bool IsGpuAvailable() const {
return CommandLine::ForCurrentProcess()->HasSwitch("enable-gpu");
}
std::string GetSuffixForTestFlags() {
std::string suffix;
if (HasFlag(kForceGpuComposited))
suffix += "_comp";
if (HasFlag(kUseGpu))
suffix += "_gpu";
if (HasFlag(kDisableVsync))
suffix += "_novsync";
if (HasFlag(kUseReferenceBuild))
suffix += "_ref";
return suffix;
}
virtual FilePath GetDataPath(const std::string& name) {
// Make sure the test data is checked out.
FilePath test_path;
PathService::Get(chrome::DIR_TEST_DATA, &test_path);
test_path = test_path.Append(FILE_PATH_LITERAL("perf"));
test_path = test_path.Append(FILE_PATH_LITERAL("frame_rate"));
if (HasFlag(kInternal)) {
test_path = test_path.Append(FILE_PATH_LITERAL("private"));
} else {
test_path = test_path.Append(FILE_PATH_LITERAL("content"));
}
test_path = test_path.AppendASCII(name);
return test_path;
}
virtual void SetUp() {
if (HasFlag(kUseReferenceBuild))
UseReferenceBuild();
// Turn on chrome.Interval to get higher-resolution timestamps on frames.
launch_arguments_.AppendSwitch(switches::kEnableBenchmarking);
// Required additional argument to make the kEnableBenchmarking switch work.
launch_arguments_.AppendSwitch(switches::kEnableStatsTable);
// UI tests boot up render views starting from about:blank. This causes
// the renderer to start up thinking it cannot use the GPU. To work
// around that, and allow the frame rate test to use the GPU, we must
// pass kAllowWebUICompositing.
launch_arguments_.AppendSwitch(switches::kAllowWebUICompositing);
// Some of the tests may launch http requests through JSON or AJAX
// which causes a security error (cross domain request) when the page
// is loaded from the local file system ( file:// ). The following switch
// fixes that error.
launch_arguments_.AppendSwitch(switches::kAllowFileAccessFromFiles);
if (!HasFlag(kUseGpu)) {
launch_arguments_.AppendSwitch(switches::kDisableAcceleratedCompositing);
launch_arguments_.AppendSwitch(switches::kDisableExperimentalWebGL);
launch_arguments_.AppendSwitch(switches::kDisableAccelerated2dCanvas);
} else {
// This switch is required for enabling the accelerated 2d canvas on
// Chrome versions prior to Chrome 15, which may be the case for the
// reference build.
launch_arguments_.AppendSwitch(switches::kEnableAccelerated2dCanvas);
}
if (HasFlag(kDisableVsync))
launch_arguments_.AppendSwitch(switches::kDisableGpuVsync);
UIPerfTest::SetUp();
}
bool DidRunOnGpu(const std::string& json_events) {
using namespace trace_analyzer;
// Check trace for GPU accleration.
scoped_ptr<TraceAnalyzer> analyzer(TraceAnalyzer::Create(json_events));
gfx::GLImplementation gl_impl = gfx::kGLImplementationNone;
const TraceEvent* gpu_event = analyzer->FindOneEvent(
Query(EVENT_NAME) == Query::String("SwapBuffers") &&
Query(EVENT_HAS_NUMBER_ARG, "GLImpl"));
if (gpu_event)
gl_impl = static_cast<gfx::GLImplementation>(
gpu_event->GetKnownArgAsInt("GLImpl"));
return (gl_impl == gfx::kGLImplementationDesktopGL ||
gl_impl == gfx::kGLImplementationEGLGLES2);
}
void RunTest(const std::string& name) {
if (HasFlag(kUseGpu) && !IsGpuAvailable()) {
printf("Test skipped: requires gpu. Pass --enable-gpu on the command "
"line if use of GPU is desired.\n");
return;
}
// Verify flag combinations.
ASSERT_TRUE(HasFlag(kUseGpu) || !HasFlag(kForceGpuComposited));
ASSERT_TRUE(!HasFlag(kUseGpu) || IsGpuAvailable());
FilePath test_path = GetDataPath(name);
ASSERT_TRUE(file_util::DirectoryExists(test_path))
<< "Missing test directory: " << test_path.value();
test_path = test_path.Append(FILE_PATH_LITERAL("test.html"));
scoped_refptr<TabProxy> tab(GetActiveTab());
ASSERT_TRUE(tab.get());
// TODO(jbates): remove this check when ref builds are updated.
if (!HasFlag(kUseReferenceBuild))
ASSERT_TRUE(automation()->BeginTracing("test_gpu"));
if (HasFlag(kHasRedirect)) {
// If the test file is known to contain an html redirect, we must block
// until the second navigation is complete and reacquire the active tab
// in order to avoid a race condition.
// If the following assertion is triggered due to a timeout, it is
// possible that the current test does not re-direct and therefore should
// not have the kHasRedirect flag turned on.
ASSERT_EQ(AUTOMATION_MSG_NAVIGATION_SUCCESS,
tab->NavigateToURLBlockUntilNavigationsComplete(
net::FilePathToFileURL(test_path), 2));
tab = GetActiveTab();
ASSERT_TRUE(tab.get());
} else {
ASSERT_EQ(AUTOMATION_MSG_NAVIGATION_SUCCESS,
tab->NavigateToURL(net::FilePathToFileURL(test_path)));
}
// Block until initialization completes
// If the following assertion fails intermittently, it could be due to a
// race condition caused by an html redirect. If that is the case, verify
// that flag kHasRedirect is enabled for the current test.
ASSERT_TRUE(WaitUntilJavaScriptCondition(
tab, L"", L"window.domAutomationController.send(__initialized);",
TestTimeouts::large_test_timeout_ms()));
if (HasFlag(kForceGpuComposited)) {
ASSERT_TRUE(tab->NavigateToURLAsync(
GURL("javascript:__make_body_composited();")));
}
// Start the tests.
ASSERT_TRUE(tab->NavigateToURLAsync(GURL("javascript:__start_all();")));
// Block until the tests completes.
ASSERT_TRUE(WaitUntilJavaScriptCondition(
tab, L"", L"window.domAutomationController.send(!__running_all);",
TestTimeouts::large_test_timeout_ms()));
// TODO(jbates): remove this check when ref builds are updated.
if (!HasFlag(kUseReferenceBuild)) {
std::string json_events;
ASSERT_TRUE(automation()->EndTracing(&json_events));
bool did_run_on_gpu = DidRunOnGpu(json_events);
bool expect_gpu = HasFlag(kUseGpu);
EXPECT_EQ(expect_gpu, did_run_on_gpu);
}
// Read out the results.
std::wstring json;
ASSERT_TRUE(tab->ExecuteAndExtractString(
L"",
L"window.domAutomationController.send("
L"JSON.stringify(__calc_results_total()));",
&json));
std::map<std::string, std::string> results;
ASSERT_TRUE(JsonDictionaryToMap(WideToUTF8(json), &results));
ASSERT_TRUE(results.find("mean") != results.end());
ASSERT_TRUE(results.find("sigma") != results.end());
ASSERT_TRUE(results.find("gestures") != results.end());
ASSERT_TRUE(results.find("means") != results.end());
ASSERT_TRUE(results.find("sigmas") != results.end());
std::string trace_name = "interval" + GetSuffixForTestFlags();
printf("GESTURES %s: %s= [%s] [%s] [%s]\n", name.c_str(),
trace_name.c_str(),
results["gestures"].c_str(),
results["means"].c_str(),
results["sigmas"].c_str());
std::string mean_and_error = results["mean"] + "," + results["sigma"];
PrintResultMeanAndError(name, "", trace_name, mean_and_error,
"frames-per-second", true);
}
};
// Must use a different class name to avoid test instantiation conflicts
// with FrameRateTest. An alias is good enough. The alias names must match
// the pattern FrameRate*Test* for them to get picked up by the test bots.
typedef FrameRateTest FrameRateCompositingTest;
// Tests that trigger compositing with a -webkit-translateZ(0)
#define FRAME_RATE_TEST_WITH_AND_WITHOUT_ACCELERATED_COMPOSITING(content) \
TEST_P(FrameRateCompositingTest, content) { \
RunTest(#content); \
}
INSTANTIATE_TEST_CASE_P(, FrameRateCompositingTest, ::testing::Values(
0,
kUseGpu | kForceGpuComposited,
kUseReferenceBuild,
kUseReferenceBuild | kUseGpu | kForceGpuComposited));
FRAME_RATE_TEST_WITH_AND_WITHOUT_ACCELERATED_COMPOSITING(blank);
FRAME_RATE_TEST_WITH_AND_WITHOUT_ACCELERATED_COMPOSITING(googleblog);
typedef FrameRateTest FrameRateNoVsyncCanvasInternalTest;
// Tests for animated 2D canvas content with and without disabling vsync
#define INTERNAL_FRAME_RATE_TEST_CANVAS_WITH_AND_WITHOUT_NOVSYNC(content) \
TEST_P(FrameRateNoVsyncCanvasInternalTest, content) { \
RunTest(#content); \
}
INSTANTIATE_TEST_CASE_P(, FrameRateNoVsyncCanvasInternalTest, ::testing::Values(
kInternal | kHasRedirect,
kInternal | kHasRedirect | kUseGpu,
kInternal | kHasRedirect | kUseGpu | kDisableVsync,
kUseReferenceBuild | kInternal | kHasRedirect,
kUseReferenceBuild | kInternal | kHasRedirect | kUseGpu,
kUseReferenceBuild | kInternal | kHasRedirect | kUseGpu | kDisableVsync));
INTERNAL_FRAME_RATE_TEST_CANVAS_WITH_AND_WITHOUT_NOVSYNC(DISABLED_fishbowl)
typedef FrameRateTest FrameRateGpuCanvasInternalTest;
// Tests for animated 2D canvas content to be tested only with GPU
// acceleration.
// tests are run with and without Vsync
#define INTERNAL_FRAME_RATE_TEST_CANVAS_GPU(content) \
TEST_P(FrameRateGpuCanvasInternalTest, content) { \
RunTest(#content); \
}
INSTANTIATE_TEST_CASE_P(, FrameRateGpuCanvasInternalTest, ::testing::Values(
kInternal | kHasRedirect | kUseGpu,
kInternal | kHasRedirect | kUseGpu | kDisableVsync,
kUseReferenceBuild | kInternal | kHasRedirect | kUseGpu,
kUseReferenceBuild | kInternal | kHasRedirect | kUseGpu | kDisableVsync));
INTERNAL_FRAME_RATE_TEST_CANVAS_GPU(DISABLED_fireflies)
INTERNAL_FRAME_RATE_TEST_CANVAS_GPU(FishIE)
INTERNAL_FRAME_RATE_TEST_CANVAS_GPU(speedreading)
} // namespace
<|endoftext|> |
<commit_before>//--------------------------------------------------------------------*- C++ -*-
// CLING - the C++ LLVM-based InterpreterG :)
// version: $Id$
// author: Axel Naumann <axel@cern.ch>
//------------------------------------------------------------------------------
#include "ExecutionContext.h"
#include "cling/Interpreter/Value.h"
#include "llvm/Module.h"
#include "llvm/PassManager.h"
#include "llvm/Analysis/Verifier.h"
#include "llvm/Assembly/PrintModulePass.h"
#include "llvm/ExecutionEngine/JIT.h"
#include "llvm/ExecutionEngine/JITEventListener.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/Support/DynamicLibrary.h"
#include <cstdio>
#include <iostream>
using namespace cling;
namespace {
class JITtedFunctionCollector : public llvm::JITEventListener {
private:
std::vector<llvm::Function *> m_vec_functions;
llvm::ExecutionEngine *m_engine;
public:
JITtedFunctionCollector(): m_vec_functions(), m_engine(0) { }
virtual ~JITtedFunctionCollector() { }
virtual void NotifyFunctionEmitted(const llvm::Function&, void *, size_t,
const JITEventListener::EmittedFunctionDetails&);
virtual void NotifyFreeingMachineCode(void *OldPtr) {}
void CleanupList();
void UnregisterFunctionMapping(llvm::ExecutionEngine&);
};
}
void JITtedFunctionCollector::NotifyFunctionEmitted(const llvm::Function &F,
void *Code, size_t Size,
const JITEventListener::EmittedFunctionDetails &Details)
{
//BB std::cerr << "JITtedFunctionCollector::NotifyFunctionEmitted: "
//BB "m_vec_functions.push_back("
//BB << F.getName().data() << "); Code @ " << Code << std::endl;
m_vec_functions.push_back(const_cast<llvm::Function *>(&F));
}
void JITtedFunctionCollector::CleanupList()
{
m_vec_functions.clear();
}
void JITtedFunctionCollector::UnregisterFunctionMapping(
llvm::ExecutionEngine &engine)
{
std::vector<llvm::Function *>::reverse_iterator it;
for (it=m_vec_functions.rbegin(); it < m_vec_functions.rend(); it++) {
llvm::Function *ff = (llvm::Function *)*it;
//BB std::cerr << "JITtedFunctionCollector::UnregisterFunctionMapping: "
//BB "updateGlobalMapping("
//BB << ff->getName().data() << ", 0); Global @"
//BB << engine.getPointerToGlobalIfAvailable(ff) << std::endl;
engine.freeMachineCodeForFunction(ff);
engine.updateGlobalMapping(ff, 0);
//BB std::cerr << "Global after delete @"
//BB << engine.getPointerToGlobalIfAvailable(ff) << std::endl;
}
m_vec_functions.clear();
}
std::vector<std::string> ExecutionContext::m_vec_unresolved;
std::vector<ExecutionContext::LazyFunctionCreatorFunc_t>
ExecutionContext::m_vec_lazy_function;
ExecutionContext::ExecutionContext():
m_engine(0),
m_posInitGlobals(0),
m_RunningStaticInits(false)
{
}
void
ExecutionContext::InitializeBuilder(llvm::Module* m)
{
//
// Create an execution engine to use.
//
// Note: Engine takes ownership of the module.
assert(m && "Module cannot be null");
llvm::EngineBuilder builder(m);
builder.setOptLevel(llvm::CodeGenOpt::Less);
std::string errMsg;
builder.setErrorStr(&errMsg);
builder.setEngineKind(llvm::EngineKind::JIT);
builder.setAllocateGVsWithCode(false);
m_engine = builder.create();
assert(m_engine && "Cannot initialize builder without module!");
//m_engine->addModule(m); // Note: The engine takes ownership of the module.
// install lazy function
m_engine->InstallLazyFunctionCreator(NotifyLazyFunctionCreators);
}
ExecutionContext::~ExecutionContext()
{
}
void unresolvedSymbol()
{
// throw exception?
std::cerr << "Error: calling unresolved symbol (should never happen)!"
<< std::endl;
}
void* ExecutionContext::HandleMissingFunction(const std::string& mangled_name)
{
// Not found in the map, add the symbol in the list of unresolved symbols
std::vector<std::string>::iterator it;
it = find (m_vec_unresolved.begin(), m_vec_unresolved.end(), mangled_name);
if (it == m_vec_unresolved.end())
m_vec_unresolved.push_back(mangled_name);
// Avoid "ISO C++ forbids casting between pointer-to-function and
// pointer-to-object":
return (void*)reinterpret_cast<size_t>(unresolvedSymbol);
}
void ExecutionContext::ResetUnresolved()
{
m_vec_unresolved.clear();
}
void*
ExecutionContext::NotifyLazyFunctionCreators(const std::string& mangled_name)
{
void *ret = 0;
std::vector<LazyFunctionCreatorFunc_t>::iterator it;
for (it=m_vec_lazy_function.begin(); it < m_vec_lazy_function.end(); it++) {
ret = (void*)((LazyFunctionCreatorFunc_t)*it)(mangled_name);
if (ret != 0) return ret;
}
return HandleMissingFunction(mangled_name);
}
void
ExecutionContext::executeFunction(llvm::StringRef funcname,
llvm::GenericValue* returnValue)
{
// Call a function without arguments, or with an SRet argument, see SRet below
// Rewire atexit:
llvm::Function* atExit = m_engine->FindFunctionNamed("__cxa_atexit");
llvm::Function* clingAtExit = m_engine->FindFunctionNamed("cling_cxa_atexit");
if (atExit && clingAtExit) {
void* clingAtExitAddr = m_engine->getPointerToFunction(clingAtExit);
if (clingAtExitAddr) {
m_engine->updateGlobalMapping(atExit, clingAtExitAddr);
}
}
llvm::Function* f = m_engine->FindFunctionNamed(funcname.data());
if (!f) {
fprintf(stderr, "executeFunction: Could not find function named: %s\n",
funcname.data()
);
return;
}
JITtedFunctionCollector listener;
// register the listener
m_engine->RegisterJITEventListener(&listener);
m_engine->getPointerToFunction(f);
// check if there is any unresolved symbol in the list
if (!m_vec_unresolved.empty()) {
std::cerr << "ExecutionContext::executeFunction:" << std::endl;
for (size_t i = 0, e = m_vec_unresolved.size(); i != e; ++i) {
std::cerr << "Error: Symbol \'" << m_vec_unresolved[i] <<
"\' unresolved!" << std::endl;
llvm::Function *ff
= m_engine->FindFunctionNamed(m_vec_unresolved[i].c_str());
if (ff) {
m_engine->updateGlobalMapping(ff, 0);
m_engine->freeMachineCodeForFunction(ff);
}
else {
std::cerr << "Error: Canot find symbol \'" << m_vec_unresolved[i] <<
std::endl;
}
}
m_vec_unresolved.clear();
// cleanup functions
listener.UnregisterFunctionMapping(*m_engine);
m_engine->UnregisterJITEventListener(&listener);
return;
}
// cleanup list and unregister our listener
listener.CleanupList();
m_engine->UnregisterJITEventListener(&listener);
std::vector<llvm::GenericValue> args;
bool wantReturn = (returnValue);
if (f->hasStructRetAttr()) {
// Function expects to receive the storage for the returned aggregate as
// first argument. Make sure returnValue is able to receive it, i.e.
// that it has the pointer set:
assert(returnValue && GVTOP(*returnValue) || "must call function returning aggregate with returnValue pointing to the storage space for return value!");
args.push_back(*returnValue);
// will get set as arg0, must not assign.
wantReturn = false;
}
if (wantReturn) {
*returnValue = m_engine->runFunction(f, args);
} else {
m_engine->runFunction(f, args);
}
m_engine->freeMachineCodeForFunction(f);
}
void
ExecutionContext::runStaticInitializersOnce(llvm::Module* m) {
assert(m && "Module must not be null");
if (!m_engine)
InitializeBuilder(m);
assert(m_engine && "Code generation did not create an engine!");
if (!m_RunningStaticInits) {
m_RunningStaticInits = true;
llvm::GlobalVariable* gctors
= m->getGlobalVariable("llvm.global_ctors", true);
if (gctors) {
m_engine->runStaticConstructorsDestructors(false);
gctors->eraseFromParent();
}
m_RunningStaticInits = false;
}
}
void
ExecutionContext::runStaticDestructorsOnce(llvm::Module* m) {
assert(m && "Module must not be null");
assert(m_engine && "Code generation did not create an engine!");
llvm::GlobalVariable* gdtors
= m->getGlobalVariable("llvm.global_dtors", true);
if (gdtors) {
m_engine->runStaticConstructorsDestructors(true);
}
}
int
ExecutionContext::verifyModule(llvm::Module* m)
{
//
// Verify generated module.
//
bool mod_has_errs = llvm::verifyModule(*m, llvm::PrintMessageAction);
if (mod_has_errs) {
return 1;
}
return 0;
}
void
ExecutionContext::printModule(llvm::Module* m)
{
//
// Print module LLVM code in human-readable form.
//
llvm::PassManager PM;
PM.add(llvm::createPrintModulePass(&llvm::outs()));
PM.run(*m);
}
void
ExecutionContext::installLazyFunctionCreator(LazyFunctionCreatorFunc_t fp)
{
m_vec_lazy_function.push_back(fp);
//m_engine->InstallLazyFunctionCreator(fp);
}
bool ExecutionContext::addSymbol(const char* symbolName, void* symbolAddress){
void* actualAdress
= llvm::sys::DynamicLibrary::SearchForAddressOfSymbol(symbolName);
if (actualAdress)
return false;
llvm::sys::DynamicLibrary::AddSymbol(symbolName, symbolAddress);
return true;
}
<commit_msg>Fix assert (o logic...) and 80 cols)<commit_after>//--------------------------------------------------------------------*- C++ -*-
// CLING - the C++ LLVM-based InterpreterG :)
// version: $Id$
// author: Axel Naumann <axel@cern.ch>
//------------------------------------------------------------------------------
#include "ExecutionContext.h"
#include "cling/Interpreter/Value.h"
#include "llvm/Module.h"
#include "llvm/PassManager.h"
#include "llvm/Analysis/Verifier.h"
#include "llvm/Assembly/PrintModulePass.h"
#include "llvm/ExecutionEngine/JIT.h"
#include "llvm/ExecutionEngine/JITEventListener.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/Support/DynamicLibrary.h"
#include <cstdio>
#include <iostream>
using namespace cling;
namespace {
class JITtedFunctionCollector : public llvm::JITEventListener {
private:
std::vector<llvm::Function *> m_vec_functions;
llvm::ExecutionEngine *m_engine;
public:
JITtedFunctionCollector(): m_vec_functions(), m_engine(0) { }
virtual ~JITtedFunctionCollector() { }
virtual void NotifyFunctionEmitted(const llvm::Function&, void *, size_t,
const JITEventListener::EmittedFunctionDetails&);
virtual void NotifyFreeingMachineCode(void *OldPtr) {}
void CleanupList();
void UnregisterFunctionMapping(llvm::ExecutionEngine&);
};
}
void JITtedFunctionCollector::NotifyFunctionEmitted(const llvm::Function &F,
void *Code, size_t Size,
const JITEventListener::EmittedFunctionDetails &Details)
{
//BB std::cerr << "JITtedFunctionCollector::NotifyFunctionEmitted: "
//BB "m_vec_functions.push_back("
//BB << F.getName().data() << "); Code @ " << Code << std::endl;
m_vec_functions.push_back(const_cast<llvm::Function *>(&F));
}
void JITtedFunctionCollector::CleanupList()
{
m_vec_functions.clear();
}
void JITtedFunctionCollector::UnregisterFunctionMapping(
llvm::ExecutionEngine &engine)
{
std::vector<llvm::Function *>::reverse_iterator it;
for (it=m_vec_functions.rbegin(); it < m_vec_functions.rend(); it++) {
llvm::Function *ff = (llvm::Function *)*it;
//BB std::cerr << "JITtedFunctionCollector::UnregisterFunctionMapping: "
//BB "updateGlobalMapping("
//BB << ff->getName().data() << ", 0); Global @"
//BB << engine.getPointerToGlobalIfAvailable(ff) << std::endl;
engine.freeMachineCodeForFunction(ff);
engine.updateGlobalMapping(ff, 0);
//BB std::cerr << "Global after delete @"
//BB << engine.getPointerToGlobalIfAvailable(ff) << std::endl;
}
m_vec_functions.clear();
}
std::vector<std::string> ExecutionContext::m_vec_unresolved;
std::vector<ExecutionContext::LazyFunctionCreatorFunc_t>
ExecutionContext::m_vec_lazy_function;
ExecutionContext::ExecutionContext():
m_engine(0),
m_posInitGlobals(0),
m_RunningStaticInits(false)
{
}
void
ExecutionContext::InitializeBuilder(llvm::Module* m)
{
//
// Create an execution engine to use.
//
// Note: Engine takes ownership of the module.
assert(m && "Module cannot be null");
llvm::EngineBuilder builder(m);
builder.setOptLevel(llvm::CodeGenOpt::Less);
std::string errMsg;
builder.setErrorStr(&errMsg);
builder.setEngineKind(llvm::EngineKind::JIT);
builder.setAllocateGVsWithCode(false);
m_engine = builder.create();
assert(m_engine && "Cannot initialize builder without module!");
//m_engine->addModule(m); // Note: The engine takes ownership of the module.
// install lazy function
m_engine->InstallLazyFunctionCreator(NotifyLazyFunctionCreators);
}
ExecutionContext::~ExecutionContext()
{
}
void unresolvedSymbol()
{
// throw exception?
std::cerr << "Error: calling unresolved symbol (should never happen)!"
<< std::endl;
}
void* ExecutionContext::HandleMissingFunction(const std::string& mangled_name)
{
// Not found in the map, add the symbol in the list of unresolved symbols
std::vector<std::string>::iterator it;
it = find (m_vec_unresolved.begin(), m_vec_unresolved.end(), mangled_name);
if (it == m_vec_unresolved.end())
m_vec_unresolved.push_back(mangled_name);
// Avoid "ISO C++ forbids casting between pointer-to-function and
// pointer-to-object":
return (void*)reinterpret_cast<size_t>(unresolvedSymbol);
}
void ExecutionContext::ResetUnresolved()
{
m_vec_unresolved.clear();
}
void*
ExecutionContext::NotifyLazyFunctionCreators(const std::string& mangled_name)
{
void *ret = 0;
std::vector<LazyFunctionCreatorFunc_t>::iterator it;
for (it=m_vec_lazy_function.begin(); it < m_vec_lazy_function.end(); it++) {
ret = (void*)((LazyFunctionCreatorFunc_t)*it)(mangled_name);
if (ret != 0) return ret;
}
return HandleMissingFunction(mangled_name);
}
void
ExecutionContext::executeFunction(llvm::StringRef funcname,
llvm::GenericValue* returnValue)
{
// Call a function without arguments, or with an SRet argument, see SRet below
// Rewire atexit:
llvm::Function* atExit = m_engine->FindFunctionNamed("__cxa_atexit");
llvm::Function* clingAtExit = m_engine->FindFunctionNamed("cling_cxa_atexit");
if (atExit && clingAtExit) {
void* clingAtExitAddr = m_engine->getPointerToFunction(clingAtExit);
if (clingAtExitAddr) {
m_engine->updateGlobalMapping(atExit, clingAtExitAddr);
}
}
llvm::Function* f = m_engine->FindFunctionNamed(funcname.data());
if (!f) {
fprintf(stderr, "executeFunction: Could not find function named: %s\n",
funcname.data()
);
return;
}
JITtedFunctionCollector listener;
// register the listener
m_engine->RegisterJITEventListener(&listener);
m_engine->getPointerToFunction(f);
// check if there is any unresolved symbol in the list
if (!m_vec_unresolved.empty()) {
std::cerr << "ExecutionContext::executeFunction:" << std::endl;
for (size_t i = 0, e = m_vec_unresolved.size(); i != e; ++i) {
std::cerr << "Error: Symbol \'" << m_vec_unresolved[i] <<
"\' unresolved!" << std::endl;
llvm::Function *ff
= m_engine->FindFunctionNamed(m_vec_unresolved[i].c_str());
if (ff) {
m_engine->updateGlobalMapping(ff, 0);
m_engine->freeMachineCodeForFunction(ff);
}
else {
std::cerr << "Error: Canot find symbol \'" << m_vec_unresolved[i] <<
std::endl;
}
}
m_vec_unresolved.clear();
// cleanup functions
listener.UnregisterFunctionMapping(*m_engine);
m_engine->UnregisterJITEventListener(&listener);
return;
}
// cleanup list and unregister our listener
listener.CleanupList();
m_engine->UnregisterJITEventListener(&listener);
std::vector<llvm::GenericValue> args;
bool wantReturn = (returnValue);
if (f->hasStructRetAttr()) {
// Function expects to receive the storage for the returned aggregate as
// first argument. Make sure returnValue is able to receive it, i.e.
// that it has the pointer set:
assert(returnValue && GVTOP(*returnValue) && \
"must call function returning aggregate with returnValue pointing " \
"to the storage space for return value!");
args.push_back(*returnValue);
// will get set as arg0, must not assign.
wantReturn = false;
}
if (wantReturn) {
*returnValue = m_engine->runFunction(f, args);
} else {
m_engine->runFunction(f, args);
}
m_engine->freeMachineCodeForFunction(f);
}
void
ExecutionContext::runStaticInitializersOnce(llvm::Module* m) {
assert(m && "Module must not be null");
if (!m_engine)
InitializeBuilder(m);
assert(m_engine && "Code generation did not create an engine!");
if (!m_RunningStaticInits) {
m_RunningStaticInits = true;
llvm::GlobalVariable* gctors
= m->getGlobalVariable("llvm.global_ctors", true);
if (gctors) {
m_engine->runStaticConstructorsDestructors(false);
gctors->eraseFromParent();
}
m_RunningStaticInits = false;
}
}
void
ExecutionContext::runStaticDestructorsOnce(llvm::Module* m) {
assert(m && "Module must not be null");
assert(m_engine && "Code generation did not create an engine!");
llvm::GlobalVariable* gdtors
= m->getGlobalVariable("llvm.global_dtors", true);
if (gdtors) {
m_engine->runStaticConstructorsDestructors(true);
}
}
int
ExecutionContext::verifyModule(llvm::Module* m)
{
//
// Verify generated module.
//
bool mod_has_errs = llvm::verifyModule(*m, llvm::PrintMessageAction);
if (mod_has_errs) {
return 1;
}
return 0;
}
void
ExecutionContext::printModule(llvm::Module* m)
{
//
// Print module LLVM code in human-readable form.
//
llvm::PassManager PM;
PM.add(llvm::createPrintModulePass(&llvm::outs()));
PM.run(*m);
}
void
ExecutionContext::installLazyFunctionCreator(LazyFunctionCreatorFunc_t fp)
{
m_vec_lazy_function.push_back(fp);
//m_engine->InstallLazyFunctionCreator(fp);
}
bool ExecutionContext::addSymbol(const char* symbolName, void* symbolAddress){
void* actualAdress
= llvm::sys::DynamicLibrary::SearchForAddressOfSymbol(symbolName);
if (actualAdress)
return false;
llvm::sys::DynamicLibrary::AddSymbol(symbolName, symbolAddress);
return true;
}
<|endoftext|> |
<commit_before>/* Vsevolod Ivanov
*
* TODO:
* - set connection timeout
* - implement sessions
*/
#include "proxy_restinio.h"
DhtProxyServer::DhtProxyServer(std::shared_ptr<dht::DhtRunner> dhtNode,
in_port_t port):
dhtNode(dhtNode)
{
this->jsonBuilder["commentStyle"] = "None";
this->jsonBuilder["indentation"] = "";
this->serverThread = std::thread([this, port](){
using namespace std::chrono;
auto maxThreads = std::thread::hardware_concurrency() - 1;
auto restThreads = maxThreads > 1 ? maxThreads : 1;
printf("Running on restinio on %i threads\n", restThreads);
auto settings = restinio::on_thread_pool<RestRouterTraits>(restThreads);
settings.address("0.0.0.0");
settings.port(port);
settings.request_handler(this->createRestRouter());
settings.read_next_http_message_timelimit(10s);
settings.write_http_response_timelimit(1s);
settings.handle_request_timeout(1s);
try {
restinio::run(std::move(settings));
}
catch(const std::exception &ex) {
std::cerr << "Error: " << ex.what() << std::endl;
}
});
}
DhtProxyServer::~DhtProxyServer()
{
if (this->serverThread.joinable())
this->dhtNode->join();
}
std::unique_ptr<RestRouter> DhtProxyServer::createRestRouter()
{
auto restRouter = std::make_unique<RestRouter>();
using namespace std::placeholders;
restRouter->http_get("/",
std::bind(&DhtProxyServer::getNodeInfo, this, _1, _2));
restRouter->http_get("/:hash",
std::bind(&DhtProxyServer::get, this, _1, _2));
restRouter->http_put("/:hash",
std::bind(&DhtProxyServer::put, this, _1, _2));
return restRouter;
}
template <typename HttpResponse>
HttpResponse DhtProxyServer::initHttpResponse(HttpResponse response)
{
response.append_header("Server", "RESTinio");
response.append_header(restinio::http_field::content_type, "application/json");
response.append_header(restinio::http_field::access_control_allow_origin, "*");
response.connection_keep_alive();
return response;
}
request_status DhtProxyServer::getNodeInfo(
restinio::request_handle_t request, restinio::router::route_params_t params)
{
printf("Connection Id: %lu\n", request->connection_id());
Json::Value result;
std::lock_guard<std::mutex> lck(statsMutex);
if (this->dhtNodeInfo.ipv4.good_nodes == 0 &&
this->dhtNodeInfo.ipv6.good_nodes == 0){
this->dhtNodeInfo = this->dhtNode->getNodeInfo();
}
result = this->dhtNodeInfo.toJson();
// [ipv6:ipv4]:port or ipv4:port
result["public_ip"] = request->remote_endpoint().address().to_string();
auto output = Json::writeString(this->jsonBuilder, result) + "\n";
auto response = this->initHttpResponse(request->create_response());
response.append_body(output);
return response.done();
}
request_status DhtProxyServer::get(restinio::request_handle_t request,
restinio::router::route_params_t params)
{
printf("Connection Id: %lu\n", request->connection_id());
auto response = this->initHttpResponse(request->create_response());
dht::InfoHash infoHash(params["hash"].to_string());
if (!infoHash)
infoHash = dht::InfoHash::get(params["hash"].to_string());
std::mutex done_mutex;
std::condition_variable done_cv;
std::unique_lock<std::mutex> done_lock(done_mutex);
this->dhtNode->get(infoHash, [&](const dht::Sp<dht::Value>& value){
auto output = Json::writeString(this->jsonBuilder, value->toJson()) + "\n";
response.append_body(output);
return true;
}, [&] (bool /*ok*/){
done_cv.notify_all();
});
done_cv.wait_for(done_lock, std::chrono::seconds(10));
return response.done();
}
request_status DhtProxyServer::put(restinio::request_handle_t request,
restinio::router::route_params_t params)
{
printf("Connection Id: %lu\n", request->connection_id());
int content_length = request->header().content_length();
dht::InfoHash infoHash(params["hash"].to_string());
if (!infoHash)
infoHash = dht::InfoHash::get(params["hash"].to_string());
std::cout << "request body: " << request->body() << std::endl;
if (request->body().empty()) {
auto response = this->initHttpResponse(
request->create_response(restinio::status_bad_request()));
response.set_body(this->RESP_MSG_MISSING_PARAMS);
return response.done();
}
std::string err;
Json::Value root;
Json::CharReaderBuilder rbuilder;
auto* char_data = reinterpret_cast<const char*>(request->body().data());
auto reader = std::unique_ptr<Json::CharReader>(rbuilder.newCharReader());
if (reader->parse(char_data, char_data + request->body().size(), &root, &err)){
// build the Value from json
auto value = std::make_shared<dht::Value>(root);
bool permanent = root.isMember("permanent");
std::cout << "Got put " << infoHash << " " << *value <<
" " << (permanent ? "permanent" : "") << std::endl;
/*
if (permanent){
}
else {
}
*/
this->dhtNode->put(infoHash, value, [this, value, request](bool ok){
if (ok){
Json::StreamWriterBuilder wbuilder;
wbuilder["commentStyle"] = "None";
wbuilder["indentation"] = "";
auto output = Json::writeString(this->jsonBuilder,
value->toJson()) + "\n";
auto response = this->initHttpResponse(request->create_response());
response.append_body(output);
}
else {
auto response = this->initHttpResponse(
request->create_response(restinio::status_bad_gateway()));
response.set_body(this->RESP_MSG_PUT_FAILED);
return response.done();
}
});
}
auto response = this->initHttpResponse(request->create_response());
response.append_body("Content-Length: " + std::to_string(content_length) + "\n");
return response.done();
}
int main()
{
auto dhtNode = std::make_shared<dht::DhtRunner>();
dhtNode->run(4444, dht::crypto::generateIdentity(), true);
dhtNode->bootstrap("bootstrap.jami.net", "4222");
DhtProxyServer dhtproxy {dhtNode, 8080};
while (true) {
std::this_thread::sleep_for(std::chrono::seconds(1));
};
}
<commit_msg>cpp/opendht: implement threadsafe proxy put<commit_after>/* Vsevolod Ivanov
*
* TODO:
* - set connection timeout
* - implement sessions
*/
#include "proxy_restinio.h"
DhtProxyServer::DhtProxyServer(std::shared_ptr<dht::DhtRunner> dhtNode,
in_port_t port):
dhtNode(dhtNode)
{
this->jsonBuilder["commentStyle"] = "None";
this->jsonBuilder["indentation"] = "";
this->serverThread = std::thread([this, port](){
using namespace std::chrono;
auto maxThreads = std::thread::hardware_concurrency() - 1;
auto restThreads = maxThreads > 1 ? maxThreads : 1;
printf("Running on restinio on %i threads\n", restThreads);
auto settings = restinio::on_thread_pool<RestRouterTraits>(restThreads);
settings.address("0.0.0.0");
settings.port(port);
settings.request_handler(this->createRestRouter());
settings.read_next_http_message_timelimit(10s);
settings.write_http_response_timelimit(1s);
settings.handle_request_timeout(1s);
try {
restinio::run(std::move(settings));
}
catch(const std::exception &ex) {
std::cerr << "Error: " << ex.what() << std::endl;
}
catch(const restinio::exception_t &ex) {
std::cerr << "Error: " << ex.what() << std::endl;
}
});
}
DhtProxyServer::~DhtProxyServer()
{
if (this->serverThread.joinable())
this->dhtNode->join();
}
std::unique_ptr<RestRouter> DhtProxyServer::createRestRouter()
{
auto restRouter = std::make_unique<RestRouter>();
using namespace std::placeholders;
restRouter->http_get("/",
std::bind(&DhtProxyServer::getNodeInfo, this, _1, _2));
restRouter->http_get("/:hash",
std::bind(&DhtProxyServer::get, this, _1, _2));
restRouter->http_put("/:hash",
std::bind(&DhtProxyServer::put, this, _1, _2));
return restRouter;
}
template <typename HttpResponse>
HttpResponse DhtProxyServer::initHttpResponse(HttpResponse response)
{
response.append_header("Server", "RESTinio");
response.append_header(restinio::http_field::content_type, "application/json");
response.append_header(restinio::http_field::access_control_allow_origin, "*");
response.connection_keep_alive();
return response;
}
request_status DhtProxyServer::getNodeInfo(
restinio::request_handle_t request, restinio::router::route_params_t params)
{
printf("Connection Id: %lu\n", request->connection_id());
Json::Value result;
std::lock_guard<std::mutex> lck(statsMutex);
if (this->dhtNodeInfo.ipv4.good_nodes == 0 &&
this->dhtNodeInfo.ipv6.good_nodes == 0){
this->dhtNodeInfo = this->dhtNode->getNodeInfo();
}
result = this->dhtNodeInfo.toJson();
// [ipv6:ipv4]:port or ipv4:port
result["public_ip"] = request->remote_endpoint().address().to_string();
auto output = Json::writeString(this->jsonBuilder, result) + "\n";
auto response = this->initHttpResponse(request->create_response());
response.append_body(output);
return response.done();
}
request_status DhtProxyServer::get(restinio::request_handle_t request,
restinio::router::route_params_t params)
{
printf("Connection Id: %lu\n", request->connection_id());
auto response = this->initHttpResponse(request->create_response());
dht::InfoHash infoHash(params["hash"].to_string());
if (!infoHash)
infoHash = dht::InfoHash::get(params["hash"].to_string());
std::mutex done_mutex;
std::condition_variable done_cv;
std::unique_lock<std::mutex> done_lock(done_mutex);
this->dhtNode->get(infoHash, [&](const dht::Sp<dht::Value>& value){
auto output = Json::writeString(this->jsonBuilder, value->toJson()) + "\n";
response.append_body(output);
return true;
}, [&] (bool /*ok*/){
done_cv.notify_all();
});
done_cv.wait_for(done_lock, std::chrono::seconds(10));
return response.done();
}
request_status DhtProxyServer::put(restinio::request_handle_t request,
restinio::router::route_params_t params)
{
printf("Connection Id: %lu\n", request->connection_id());
int content_length = request->header().content_length();
dht::InfoHash infoHash(params["hash"].to_string());
if (!infoHash)
infoHash = dht::InfoHash::get(params["hash"].to_string());
if (request->body().empty()) {
auto response = this->initHttpResponse(
request->create_response(restinio::status_bad_request()));
response.set_body(this->RESP_MSG_MISSING_PARAMS);
return response.done();
}
bool putSuccess;
std::string output;
std::mutex done_mutex;
std::condition_variable done_cv;
std::unique_lock<std::mutex> done_lock(done_mutex);
std::string err;
Json::Value root;
Json::CharReaderBuilder rbuilder;
auto* char_data = reinterpret_cast<const char*>(request->body().data());
auto reader = std::unique_ptr<Json::CharReader>(rbuilder.newCharReader());
if (reader->parse(char_data, char_data + request->body().size(), &root, &err)){
// Build the dht::Value from json, NOTE: {"data": "base64value", ...}
auto value = std::make_shared<dht::Value>(root);
bool permanent = root.isMember("permanent");
std::cout << "Got put " << infoHash << " " << *value <<
" " << (permanent ? "permanent" : "") << std::endl;
/*
if (permanent){
}
else {
}
*/
this->dhtNode->put(infoHash, value,
//done callback
[this, value, &putSuccess, &output](bool ok){
putSuccess = ok;
if (ok){
Json::StreamWriterBuilder wbuilder;
wbuilder["commentStyle"] = "None";
wbuilder["indentation"] = "";
output = Json::writeString(this->jsonBuilder, value->toJson()) + "\n";
std::cout << output << std::endl;
}
}, dht::time_point::max(), permanent);
}
done_cv.wait_for(done_lock, std::chrono::seconds(10));
if (!putSuccess){
auto response = this->initHttpResponse(
request->create_response(restinio::status_bad_gateway()));
response.set_body(this->RESP_MSG_PUT_FAILED);
return response.done();
}
auto response = this->initHttpResponse(request->create_response());
response.append_body(output);
return response.done();
}
int main()
{
auto dhtNode = std::make_shared<dht::DhtRunner>();
dhtNode->run(4444, dht::crypto::generateIdentity(), true);
dhtNode->bootstrap("bootstrap.jami.net", "4222");
DhtProxyServer dhtproxy {dhtNode, 8080};
while (true) {
std::this_thread::sleep_for(std::chrono::seconds(1));
};
}
<|endoftext|> |
<commit_before>// Copyright (c) 2018 Chris Ohk, Youngjoong Kim, SeungHyun Jeon
// We are making my contributions/submissions to this project solely in our
// personal capacity and are not conveying any rights to any intellectual
// property of any third parties.
#include <hspp/Cards/Cards.hpp>
#include <hspp/Games/Game.hpp>
#include <hspp/Games/GameManager.hpp>
#include <effolkronium/random.hpp>
#include <algorithm>
using Random = effolkronium::random_static;
namespace Hearthstonepp
{
Game::Game(GameConfig& gameConfig) : m_gameConfig(gameConfig)
{
// Add hero and hero power
GetPlayer1().AddHeroAndPower(
Cards::GetInstance().GetHeroCard(gameConfig.player1Class),
Cards::GetInstance().GetDefaultHeroPower(gameConfig.player1Class));
GetPlayer2().AddHeroAndPower(
Cards::GetInstance().GetHeroCard(gameConfig.player2Class),
Cards::GetInstance().GetDefaultHeroPower(gameConfig.player2Class));
// Set opponent player
GetPlayer1().SetOpponent(&GetPlayer2());
GetPlayer2().SetOpponent(&GetPlayer1());
}
Player& Game::GetPlayer1()
{
return m_players[0];
}
Player& Game::GetPlayer2()
{
return m_players[1];
}
Player& Game::GetCurrentPlayer()
{
return *m_currentPlayer;
}
Player& Game::GetOpponentPlayer()
{
return m_currentPlayer->GetOpponent();
}
void Game::BeginFirst()
{
// Set next step
nextStep = Step::BEGIN_SHUFFLE;
GameManager::ProcessNextStep(*this, nextStep);
}
void Game::BeginShuffle()
{
// Do nothing
}
void Game::BeginDraw()
{
// Do nothing
}
void Game::BeginMulligan()
{
// Do nothing
}
void Game::MainBegin()
{
// Do nothing
}
void Game::MainReady()
{
// Do nothing
}
void Game::MainStartTriggers()
{
// Do nothing
}
void Game::MainResource()
{
// Do nothing
}
void Game::MainDraw()
{
// Do nothing
}
void Game::MainStart()
{
// Do nothing
}
void Game::MainAction()
{
// Do nothing
}
void Game::MainCombat()
{
// Do nothing
}
void Game::MainEnd()
{
// Do nothing
}
void Game::MainCleanUp()
{
// Do nothing
}
void Game::MainNext()
{
// Do nothing
}
void Game::FinalWrapUp()
{
// Do nothing
}
void Game::FinalGameOver()
{
// Do nothing
}
void Game::StartGame()
{
// Reverse card order in deck
if (!m_gameConfig.doShuffle)
{
std::reverse(m_gameConfig.player1Deck.begin(),
m_gameConfig.player1Deck.end());
std::reverse(m_gameConfig.player2Deck.begin(),
m_gameConfig.player2Deck.end());
}
// Set up decks
for (auto& card : m_gameConfig.player1Deck)
{
Entity* entity = Entity::GetFromCard(GetPlayer1(), std::move(card));
GetPlayer1().GetDeck().AddCard(*entity);
}
for (auto& card : m_gameConfig.player2Deck)
{
Entity* entity = Entity::GetFromCard(GetPlayer2(), std::move(card));
GetPlayer2().GetDeck().AddCard(*entity);
}
// Determine first player
switch (m_gameConfig.startPlayer)
{
case PlayerType::RANDOM:
{
auto val = Random::get(0, 1);
m_firstPlayer = &m_players[val];
break;
}
case PlayerType::PLAYER1:
m_firstPlayer = &m_players[0];
break;
case PlayerType::PLAYER2:
m_firstPlayer = &m_players[1];
break;
}
m_currentPlayer = m_firstPlayer;
// Set first turn
m_turn = 1;
// Set next step
nextStep = Step::BEGIN_FIRST;
GameManager::ProcessNextStep(*this, nextStep);
}
} // namespace Hearthstonepp<commit_msg>[ci skip] feat(game-state): Implement BeginShuffle() method<commit_after>// Copyright (c) 2018 Chris Ohk, Youngjoong Kim, SeungHyun Jeon
// We are making my contributions/submissions to this project solely in our
// personal capacity and are not conveying any rights to any intellectual
// property of any third parties.
#include <hspp/Cards/Cards.hpp>
#include <hspp/Games/Game.hpp>
#include <hspp/Games/GameManager.hpp>
#include <effolkronium/random.hpp>
#include <algorithm>
using Random = effolkronium::random_static;
namespace Hearthstonepp
{
Game::Game(GameConfig& gameConfig) : m_gameConfig(gameConfig)
{
// Add hero and hero power
GetPlayer1().AddHeroAndPower(
Cards::GetInstance().GetHeroCard(gameConfig.player1Class),
Cards::GetInstance().GetDefaultHeroPower(gameConfig.player1Class));
GetPlayer2().AddHeroAndPower(
Cards::GetInstance().GetHeroCard(gameConfig.player2Class),
Cards::GetInstance().GetDefaultHeroPower(gameConfig.player2Class));
// Set opponent player
GetPlayer1().SetOpponent(&GetPlayer2());
GetPlayer2().SetOpponent(&GetPlayer1());
}
Player& Game::GetPlayer1()
{
return m_players[0];
}
Player& Game::GetPlayer2()
{
return m_players[1];
}
Player& Game::GetCurrentPlayer()
{
return *m_currentPlayer;
}
Player& Game::GetOpponentPlayer()
{
return m_currentPlayer->GetOpponent();
}
void Game::BeginFirst()
{
// Set next step
nextStep = Step::BEGIN_SHUFFLE;
GameManager::ProcessNextStep(*this, nextStep);
}
void Game::BeginShuffle()
{
// Shuffle cards in deck
if (m_gameConfig.doShuffle)
{
GetPlayer1().GetDeck().Shuffle();
GetPlayer2().GetDeck().Shuffle();
}
// Set next step
nextStep = Step::BEGIN_DRAW;
GameManager::ProcessNextStep(*this, nextStep);
}
void Game::BeginDraw()
{
// Do nothing
}
void Game::BeginMulligan()
{
// Do nothing
}
void Game::MainBegin()
{
// Do nothing
}
void Game::MainReady()
{
// Do nothing
}
void Game::MainStartTriggers()
{
// Do nothing
}
void Game::MainResource()
{
// Do nothing
}
void Game::MainDraw()
{
// Do nothing
}
void Game::MainStart()
{
// Do nothing
}
void Game::MainAction()
{
// Do nothing
}
void Game::MainCombat()
{
// Do nothing
}
void Game::MainEnd()
{
// Do nothing
}
void Game::MainCleanUp()
{
// Do nothing
}
void Game::MainNext()
{
// Do nothing
}
void Game::FinalWrapUp()
{
// Do nothing
}
void Game::FinalGameOver()
{
// Do nothing
}
void Game::StartGame()
{
// Reverse card order in deck
if (!m_gameConfig.doShuffle)
{
std::reverse(m_gameConfig.player1Deck.begin(),
m_gameConfig.player1Deck.end());
std::reverse(m_gameConfig.player2Deck.begin(),
m_gameConfig.player2Deck.end());
}
// Set up decks
for (auto& card : m_gameConfig.player1Deck)
{
Entity* entity = Entity::GetFromCard(GetPlayer1(), std::move(card));
GetPlayer1().GetDeck().AddCard(*entity);
}
for (auto& card : m_gameConfig.player2Deck)
{
Entity* entity = Entity::GetFromCard(GetPlayer2(), std::move(card));
GetPlayer2().GetDeck().AddCard(*entity);
}
// Determine first player
switch (m_gameConfig.startPlayer)
{
case PlayerType::RANDOM:
{
auto val = Random::get(0, 1);
m_firstPlayer = &m_players[val];
break;
}
case PlayerType::PLAYER1:
m_firstPlayer = &m_players[0];
break;
case PlayerType::PLAYER2:
m_firstPlayer = &m_players[1];
break;
}
m_currentPlayer = m_firstPlayer;
// Set first turn
m_turn = 1;
// Set next step
nextStep = Step::BEGIN_FIRST;
GameManager::ProcessNextStep(*this, nextStep);
}
} // namespace Hearthstonepp<|endoftext|> |
<commit_before>void MakeT0FullMisAlignment(){
// Create TClonesArray of full misalignment objects for T0
//
TClonesArray *array = new TClonesArray("AliAlignObjParams",30);
TClonesArray &alobj = *array;
Double_t dx, dy, dz, dpsi, dtheta, dphi;
TRandom *rnd = new TRandom(4321);
Double_t sigmatr = 0.05; // sigma for shifts in cm
Double_t sigmarot = 0.3; // sigma for tilts in degrees
TString symName, sn;
Int_t iIndex=0;
AliGeomManager::ELayerID iLayer = AliGeomManager::kInvalidLayer;
UShort_t volid = AliGeomManager::LayerToVolUID(iLayer,iIndex);
Int_t j=0;
for (Int_t imod=0; imod<24; imod++){
if (imod < 12){
sn="T0/C/PMT";
}else{
sn="T0/A/PMT";
}
symName = sn;
symName += imod+1;
dx = rnd->Gaus(0.,sigmatr);
dy = rnd->Gaus(0.,sigmatr);
dz = rnd->Gaus(0.,sigmatr);
dpsi = rnd->Gaus(0.,sigmarot);
dtheta = rnd->Gaus(0.,sigmarot);
dphi = rnd->Gaus(0.,sigmarot);
new(alobj[j++]) AliAlignObjParams(symName.Data(), volid, dx, dy, dz, dpsi,
dtheta, dphi, kTRUE);
}
const char* macroname = "MakeT0FullMisAlignment.C";
if( TString(gSystem->Getenv("TOCDB")) != TString("kTRUE") ){
// save on file
const char* filename = "T0fullMisalignment.root";
TFile f(filename,"RECREATE");
if(!f){
Error(macroname,"cannot open file for output\n");
return;
}
Info(macroname,"Saving alignment objects to the file %s", filename);
f.cd();
f.WriteObject(array,"T0AlignObjs","kSingleKey");
f.Close();
}else{
// save in CDB storage
TString Storage = gSystem->Getenv("STORAGE");
if(!Storage.BeginsWith("local://") && !Storage.BeginsWith("alien://")) {
Error(macroname,"STORAGE variable set to %s is not valid.
Exiting\n",Storage.Data());
return;
}
Info(macroname,"Saving alignment objects in CDB storage %s",
Storage.Data());
AliCDBManager* cdb = AliCDBManager::Instance();
AliCDBStorage* storage = cdb->GetStorage(Storage.Data());
if(!storage){
Error(macroname,"Unable to open storage %s\n",Storage.Data());
return;
}
AliCDBMetaData* md = new AliCDBMetaData();
md->SetResponsible("Tomasz Malkiewicz");
md->SetComment("Full misalignment for T0, produced with sigmatr=0.05 and
sigmarot=0.3 in the local RS");
md->SetAliRootVersion(gSystem->Getenv("$ARVERSION"));
AliCDBId id("T0/Align/Data",0,AliCDBRunRange::Infinity());
storage->Put(array,id,md);
}
array->Delete();
}
void MakeT0FullMisAlignment(){
// Create TClonesArray of full misalignment objects for T0
//
TClonesArray *array = new TClonesArray("AliAlignObjParams",30);
TClonesArray &alobj = *array;
Double_t dx, dy, dz, dpsi, dtheta, dphi;
TRandom *rnd = new TRandom(4321);
Double_t sigmatr = 0.05; // sigma for shifts in cm
Double_t sigmarot = 0.3; // sigma for tilts in degrees
TString symName, sn;
Int_t iIndex=0;
AliGeomManager::ELayerID iLayer = AliGeomManager::kInvalidLayer;
UShort_t volid = AliGeomManager::LayerToVolUID(iLayer,iIndex);
Int_t j=0;
for (Int_t imod=0; imod<24; imod++){
if (imod < 12){
sn="T0/C/PMT";
}else{
sn="T0/A/PMT";
}
symName = sn;
symName += imod+1;
dx = rnd->Gaus(0.,sigmatr);
dy = rnd->Gaus(0.,sigmatr);
dz = rnd->Gaus(0.,sigmatr);
dpsi = rnd->Gaus(0.,sigmarot);
dtheta = rnd->Gaus(0.,sigmarot);
dphi = rnd->Gaus(0.,sigmarot);
new(alobj[j++]) AliAlignObjParams(symName.Data(), volid, dx, dy, dz, dpsi, dtheta, dphi, kTRUE);
}
const char* macroname = "MakeT0FullMisAlignment.C";
if( TString(gSystem->Getenv("TOCDB")) != TString("kTRUE") ){
// save on file
const char* filename = "T0fullMisalignment.root";
TFile f(filename,"RECREATE");
if(!f){
Error(macroname,"cannot open file for output\n");
return;
}
Info(macroname,"Saving alignment objects to the file %s", filename);
f.cd();
f.WriteObject(array,"T0AlignObjs","kSingleKey");
f.Close(); TFile f(filename,"RECREATE");
}else{
// save in CDB storage
TString Storage = gSystem->Getenv("STORAGE");
if(!Storage.BeginsWith("local://") && !Storage.BeginsWith("alien://")) {
Error(macroname,"STORAGE variable set to %s is not valid. Exiting\n",Storage.Data());
return;
}
Info(macroname,"Saving alignment objects in CDB storage %s",
Storage.Data());
AliCDBManager* cdb = AliCDBManager::Instance();
AliCDBStorage* storage = cdb->GetStorage(Storage.Data());
if(!storage){
Error(macroname,"Unable to open storage %s\n",Storage.Data());
return;
}
AliCDBMetaData* md = new AliCDBMetaData();
md->SetResponsible("Tomasz Malkiewicz");
md->SetComment("Full misalignment for T0, produced with sigmatr=0.05 and sigmarot=0.3 in the local RS");
md->SetAliRootVersion(gSystem->Getenv("$ARVERSION"));
AliCDBId id("T0/Align/Data",0,AliCDBRunRange::Infinity());
storage->Put(array,id,md);
}
array->Delete();
}
<commit_msg>misalignment macros with fixed typo from tomek<commit_after>void MakeT0FullMisAlignment(){
// Create TClonesArray of full misalignment objects for T0
//
TClonesArray *array = new TClonesArray("AliAlignObjParams",30);
TClonesArray &alobj = *array;
Double_t dx, dy, dz, dpsi, dtheta, dphi;
TRandom *rnd = new TRandom(4321);
Double_t sigmatr = 0.05; // sigma for shifts in cm
Double_t sigmarot = 0.3; // sigma for tilts in degrees
TString symName, sn;
Int_t iIndex=0;
AliGeomManager::ELayerID iLayer = AliGeomManager::kInvalidLayer;
UShort_t volid = AliGeomManager::LayerToVolUID(iLayer,iIndex);
Int_t j=0;
for (Int_t imod=0; imod<24; imod++){
if (imod < 12){
sn="T0/C/PMT";
}else{
sn="T0/A/PMT";
}
symName = sn;
symName += imod+1;
dx = rnd->Gaus(0.,sigmatr);
dy = rnd->Gaus(0.,sigmatr);
dz = rnd->Gaus(0.,sigmatr);
dpsi = rnd->Gaus(0.,sigmarot);
dtheta = rnd->Gaus(0.,sigmarot);
dphi = rnd->Gaus(0.,sigmarot);
new(alobj[j++]) AliAlignObjParams(symName.Data(), volid, dx, dy, dz, dpsi, dtheta, dphi, kTRUE);
}
const char* macroname = "MakeT0FullMisAlignment.C";
if( TString(gSystem->Getenv("TOCDB")) != TString("kTRUE") ){
// save on file
const char* filename = "T0fullMisalignment.root";
TFile f(filename,"RECREATE");
if(!f){
Error(macroname,"cannot open file for output\n");
return;
}
Info(macroname,"Saving alignment objects to the file %s", filename);
f.cd();
f.WriteObject(array,"T0AlignObjs","kSingleKey");
f.Close();
}else{
// save in CDB storage
TString Storage = gSystem->Getenv("STORAGE");
if(!Storage.BeginsWith("local://") && !Storage.BeginsWith("alien://")) {
Error(macroname,"STORAGE variable set to %s is not valid. Exiting\n",Storage.Data());
return;
}
Info(macroname,"Saving alignment objects in CDB storage %s",
Storage.Data());
AliCDBManager* cdb = AliCDBManager::Instance();
AliCDBStorage* storage = cdb->GetStorage(Storage.Data());
if(!storage){
Error(macroname,"Unable to open storage %s\n",Storage.Data());
return;
}
AliCDBMetaData* md = new AliCDBMetaData();
md->SetResponsible("Tomasz Malkiewicz");
md->SetComment("Full misalignment for T0, produced with sigmatr=0.05 and sigmarot=0.3 in the local RS");
md->SetAliRootVersion(gSystem->Getenv("$ARVERSION"));
AliCDBId id("T0/Align/Data",0,AliCDBRunRange::Infinity());
storage->Put(array,id,md);
}
array->Delete();
}
<|endoftext|> |
<commit_before>#include "Crypto/CppDsaPrivateKey.hpp"
#include "Crypto/CppDsaPublicKey.hpp"
#include "Utils/QRunTimeError.hpp"
#include "Utils/Timer.hpp"
#include "Utils/TimerCallback.hpp"
#include "NeffKeyShuffle.hpp"
namespace Dissent {
using Crypto::CppDsaPrivateKey;
using Crypto::CppDsaPublicKey;
using Utils::QRunTimeError;
namespace Anonymity {
NeffKeyShuffle::NeffKeyShuffle(const Group &group,
const PrivateIdentity &ident, const Id &round_id,
QSharedPointer<Network> network,
GetDataCallback &get_data) :
Round(group, ident, round_id, network, get_data),
_state_machine(this)
{
_state_machine.AddState(OFFLINE);
_state_machine.AddState(KEY_GENERATION, -1, 0, &NeffKeyShuffle::GenerateKey);
_state_machine.AddState(KEY_SUBMISSION, -1, 0, &NeffKeyShuffle::SubmitKey);
_state_machine.AddState(WAITING_FOR_ANONYMIZED_KEYS, ANONYMIZED_KEYS,
&NeffKeyShuffle::HandleAnonymizedKeys);
_state_machine.AddState(PROCESSING_ANONYMIZED_KEYS, -1, 0,
&NeffKeyShuffle::ProcessAnonymizedKeys);
_state_machine.AddState(FINISHED);
_state_machine.SetState(OFFLINE);
_state_machine.AddTransition(OFFLINE, KEY_GENERATION);
_state_machine.AddTransition(KEY_GENERATION, KEY_SUBMISSION);
_state_machine.AddTransition(WAITING_FOR_ANONYMIZED_KEYS,
PROCESSING_ANONYMIZED_KEYS);
if(group.GetSubgroup().Contains(ident.GetLocalId())) {
InitServer();
} else {
InitClient();
}
}
NeffKeyShuffle::~NeffKeyShuffle()
{
}
void NeffKeyShuffle::InitServer()
{
_server_state = QSharedPointer<ServerState>(new ServerState());
_state = _server_state;
_state_machine.AddState(SHUFFLING, -1, 0, &NeffKeyShuffle::ShuffleKeys);
if(GetGroup().GetSubgroup().GetIndex(GetLocalId()) == 0) {
_state_machine.AddState(WAITING_FOR_KEYS, KEY_SUBMIT,
&NeffKeyShuffle::HandleKeySubmission,
&NeffKeyShuffle::PrepareForKeySubmissions);
_state_machine.AddTransition(KEY_SUBMISSION, WAITING_FOR_KEYS);
_state_machine.AddTransition(WAITING_FOR_KEYS, SHUFFLING);
} else {
_state_machine.AddState(WAITING_FOR_SHUFFLE, KEY_SHUFFLE,
&NeffKeyShuffle::HandleShuffle);
_state_machine.AddTransition(KEY_SUBMISSION, WAITING_FOR_SHUFFLE);
_state_machine.AddTransition(WAITING_FOR_SHUFFLE, SHUFFLING);
}
_state_machine.AddTransition(SHUFFLING, WAITING_FOR_ANONYMIZED_KEYS);
}
void NeffKeyShuffle::InitClient()
{
_state = QSharedPointer<State>(new State());
_state_machine.AddTransition(KEY_SUBMISSION,
WAITING_FOR_ANONYMIZED_KEYS);
}
void NeffKeyShuffle::OnStart()
{
Round::OnStart();
_state_machine.StateComplete();
}
void NeffKeyShuffle::OnStop()
{
_state_machine.SetState(FINISHED);
Round::OnStop();
}
void NeffKeyShuffle::HandleDisconnect(const Id &id)
{
if(!GetGroup().Contains(id)) {
return;
}
if(GetGroup().GetSubgroup().Contains(id)) {
qDebug() << "A server (" << id << ") disconnected.";
SetInterrupted();
Stop("A server (" + id.ToString() +") disconnected.");
} else {
qDebug() << "A client (" << id << ") disconnected, ignoring.";
}
}
void NeffKeyShuffle::HandleKeySubmission(const Id &from, QDataStream &stream)
{
int gidx = GetGroup().GetIndex(from);
if(_server_state->shuffle_input[gidx] != 0) {
throw QRunTimeError("Received multiples data messages.");
}
Integer key;
stream >> key;
if(key == 0) {
throw QRunTimeError("Received a 0 key");
} else if(GetModulus() <= key) {
throw QRunTimeError("Key is not valid in this modulus");
}
_server_state->shuffle_input[gidx] = key;
++_server_state->keys_received;
qDebug() << GetGroup().GetIndex(GetLocalId()) << GetLocalId() <<
": received key from" << GetGroup().GetIndex(from) << from <<
"Have:" << _server_state->keys_received << "expect:" << GetGroup().Count();
if(_server_state->keys_received == GetGroup().Count()) {
_server_state->key_receive_period.Stop();
_state_machine.StateComplete();
}
}
void NeffKeyShuffle::HandleShuffle(const Id &from, QDataStream &stream)
{
if(GetGroup().GetSubgroup().Previous(GetLocalId()) != from) {
throw QRunTimeError("Received a shuffle out of order");
}
Integer generator_input;
QVector<Integer> shuffle_input;
stream >> generator_input >> shuffle_input;
if(generator_input == 0) {
throw QRunTimeError("Invalid generator found");
} else if(shuffle_input.count() <= GetGroup().GetSubgroup().Count()) {
throw QRunTimeError("Missing public keys");
}
_server_state->generator_input = generator_input;
_server_state->shuffle_input = shuffle_input;
qDebug() << GetGroup().GetIndex(GetLocalId()) << GetLocalId() <<
": received shuffle data from" << GetGroup().GetIndex(from) << from;
_state_machine.StateComplete();
}
void NeffKeyShuffle::HandleAnonymizedKeys(const Id &from,
QDataStream &stream)
{
if(GetGroup().GetSubgroup().Last() != from) {
throw QRunTimeError("Received from wrong server");
}
Integer new_generator;
QVector<Integer> new_public_elements;
stream >> new_generator >> new_public_elements;
if(new_generator == 0) {
throw QRunTimeError("Invalid generator found");
} else if(new_public_elements.count() <= GetGroup().GetSubgroup().Count()) {
throw QRunTimeError("Missing public keys");
}
_state->new_generator = new_generator;
_state->new_public_elements = new_public_elements;
qDebug() << GetGroup().GetIndex(GetLocalId()) << GetLocalId() <<
": received keys from" << GetGroup().GetIndex(from) << from;
_state_machine.StateComplete();
}
void NeffKeyShuffle::GenerateKey()
{
QSharedPointer<CppDsaPrivateKey> base_key(
CppDsaPrivateKey::GenerateKey(GetRoundId().GetByteArray()));
_state->input_private_key = QSharedPointer<CppDsaPrivateKey>(
new CppDsaPrivateKey(base_key->GetModulus(), base_key->GetSubgroup(),
base_key->GetGenerator()));
_state_machine.StateComplete();
}
void NeffKeyShuffle::SubmitKey()
{
QByteArray msg;
QDataStream stream(&msg, QIODevice::WriteOnly);
QSharedPointer<CppDsaPrivateKey> key(
_state->input_private_key.dynamicCast<CppDsaPrivateKey>());
Q_ASSERT(key);
stream << KEY_SUBMIT << GetRoundId() << key->GetPublicElement();
VerifiableSend(GetGroup().GetSubgroup().GetId(0), msg);
_state_machine.StateComplete();
}
void NeffKeyShuffle::PrepareForKeySubmissions()
{
_server_state->shuffle_input = QVector<Integer>(GetGroup().Count(), 0);
_server_state->generator_input = GetGenerator();
Utils::TimerCallback *cb = new Utils::TimerMethod<NeffKeyShuffle, int>(
this, &NeffKeyShuffle::ConcludeKeySubmission, 0);
_server_state->key_receive_period =
Utils::Timer::GetInstance().QueueCallback(cb, KEY_SUBMISSION_WINDOW);
}
void NeffKeyShuffle::ShuffleKeys()
{
_state->blame = !CheckShuffleOrder(_server_state->shuffle_input);
QSharedPointer<CppDsaPrivateKey> tmp_key(
new CppDsaPrivateKey(GetModulus(), GetSubgroup(), GetGenerator()));
_server_state->exponent = tmp_key->GetPrivateExponent();
_server_state->generator_output = _server_state->generator_input.Pow(
_server_state->exponent, GetModulus());
foreach(const Integer &key, _server_state->shuffle_input) {
_server_state->shuffle_output.append(
key.Pow(_server_state->exponent, GetModulus()));
}
qSort(_server_state->shuffle_output);
const Id &next = GetGroup().GetSubgroup().Next(GetLocalId());
MessageType mtype = (next == Id::Zero()) ? ANONYMIZED_KEYS : KEY_SHUFFLE;
QByteArray msg;
QDataStream out_stream(&msg, QIODevice::WriteOnly);
out_stream << mtype << GetRoundId() << _server_state->generator_output <<
_server_state->shuffle_output;
if(mtype == ANONYMIZED_KEYS) {
VerifiableBroadcast(msg);
} else {
VerifiableSend(next, msg);
}
_state_machine.StateComplete();
}
void NeffKeyShuffle::ProcessAnonymizedKeys()
{
_state->blame = !CheckShuffleOrder(_state->new_public_elements);
if(_state->blame) {
return;
}
Integer my_element = _state->new_generator.Pow(GetPrivateExponent(),
GetModulus());
for(int idx = 0; idx < _state->new_public_elements.count(); idx++) {
if(_state->new_public_elements[idx] == my_element) {
_state->user_key_index = idx;
_state->output_private_key = QSharedPointer<AsymmetricKey>(
new CppDsaPrivateKey(GetModulus(), GetSubgroup(),
_state->new_generator, GetPrivateExponent()));
qDebug() << "Found my key at" << idx;
}
_state->output_keys.append(QSharedPointer<AsymmetricKey>(
new CppDsaPublicKey(GetModulus(), GetSubgroup(),
_state->new_generator, _state->new_public_elements[idx])));
}
if(_state->user_key_index == -1) {
_state->blame = true;
qDebug() << "Did not find my key";
} else {
SetSuccessful(true);
}
Stop("Round finished");
}
bool NeffKeyShuffle::CheckShuffleOrder(const QVector<Crypto::Integer> &keys)
{
Integer pkey(0);
foreach(const Integer &key, keys) {
if(key <= pkey) {
qDebug() << "Duplicate keys or unordered, blaming.";
return false;
}
}
return true;
}
void NeffKeyShuffle::ConcludeKeySubmission(const int &)
{
qDebug() << "Key window has closed, unfortunately some keys may not"
<< "have transmitted in time.";
QVector<Integer> pruned_keys;
foreach(const Integer &key, _server_state->shuffle_input) {
if(key != 0) {
pruned_keys.append(key);
}
}
_server_state->shuffle_input = pruned_keys;
_state_machine.StateComplete();
}
}
}
<commit_msg>[Anonymity] NeffKeyShuffle did not work if all members were servers<commit_after>#include "Crypto/CppDsaPrivateKey.hpp"
#include "Crypto/CppDsaPublicKey.hpp"
#include "Utils/QRunTimeError.hpp"
#include "Utils/Timer.hpp"
#include "Utils/TimerCallback.hpp"
#include "NeffKeyShuffle.hpp"
namespace Dissent {
using Crypto::CppDsaPrivateKey;
using Crypto::CppDsaPublicKey;
using Utils::QRunTimeError;
namespace Anonymity {
NeffKeyShuffle::NeffKeyShuffle(const Group &group,
const PrivateIdentity &ident, const Id &round_id,
QSharedPointer<Network> network,
GetDataCallback &get_data) :
Round(group, ident, round_id, network, get_data),
_state_machine(this)
{
_state_machine.AddState(OFFLINE);
_state_machine.AddState(KEY_GENERATION, -1, 0, &NeffKeyShuffle::GenerateKey);
_state_machine.AddState(KEY_SUBMISSION, -1, 0, &NeffKeyShuffle::SubmitKey);
_state_machine.AddState(WAITING_FOR_ANONYMIZED_KEYS, ANONYMIZED_KEYS,
&NeffKeyShuffle::HandleAnonymizedKeys);
_state_machine.AddState(PROCESSING_ANONYMIZED_KEYS, -1, 0,
&NeffKeyShuffle::ProcessAnonymizedKeys);
_state_machine.AddState(FINISHED);
_state_machine.SetState(OFFLINE);
_state_machine.AddTransition(OFFLINE, KEY_GENERATION);
_state_machine.AddTransition(KEY_GENERATION, KEY_SUBMISSION);
_state_machine.AddTransition(WAITING_FOR_ANONYMIZED_KEYS,
PROCESSING_ANONYMIZED_KEYS);
if(group.GetSubgroup().Contains(ident.GetLocalId())) {
InitServer();
} else {
InitClient();
}
}
NeffKeyShuffle::~NeffKeyShuffle()
{
}
void NeffKeyShuffle::InitServer()
{
_server_state = QSharedPointer<ServerState>(new ServerState());
_state = _server_state;
_state_machine.AddState(SHUFFLING, -1, 0, &NeffKeyShuffle::ShuffleKeys);
if(GetGroup().GetSubgroup().GetIndex(GetLocalId()) == 0) {
_state_machine.AddState(WAITING_FOR_KEYS, KEY_SUBMIT,
&NeffKeyShuffle::HandleKeySubmission,
&NeffKeyShuffle::PrepareForKeySubmissions);
_state_machine.AddTransition(KEY_SUBMISSION, WAITING_FOR_KEYS);
_state_machine.AddTransition(WAITING_FOR_KEYS, SHUFFLING);
} else {
_state_machine.AddState(WAITING_FOR_SHUFFLE, KEY_SHUFFLE,
&NeffKeyShuffle::HandleShuffle);
_state_machine.AddTransition(KEY_SUBMISSION, WAITING_FOR_SHUFFLE);
_state_machine.AddTransition(WAITING_FOR_SHUFFLE, SHUFFLING);
}
_state_machine.AddTransition(SHUFFLING, WAITING_FOR_ANONYMIZED_KEYS);
}
void NeffKeyShuffle::InitClient()
{
_state = QSharedPointer<State>(new State());
_state_machine.AddTransition(KEY_SUBMISSION,
WAITING_FOR_ANONYMIZED_KEYS);
}
void NeffKeyShuffle::OnStart()
{
Round::OnStart();
_state_machine.StateComplete();
}
void NeffKeyShuffle::OnStop()
{
_state_machine.SetState(FINISHED);
Round::OnStop();
}
void NeffKeyShuffle::HandleDisconnect(const Id &id)
{
if(!GetGroup().Contains(id)) {
return;
}
if(GetGroup().GetSubgroup().Contains(id)) {
qDebug() << "A server (" << id << ") disconnected.";
SetInterrupted();
Stop("A server (" + id.ToString() +") disconnected.");
} else {
qDebug() << "A client (" << id << ") disconnected, ignoring.";
}
}
void NeffKeyShuffle::HandleKeySubmission(const Id &from, QDataStream &stream)
{
int gidx = GetGroup().GetIndex(from);
if(_server_state->shuffle_input[gidx] != 0) {
throw QRunTimeError("Received multiples data messages.");
}
Integer key;
stream >> key;
if(key == 0) {
throw QRunTimeError("Received a 0 key");
} else if(GetModulus() <= key) {
throw QRunTimeError("Key is not valid in this modulus");
}
_server_state->shuffle_input[gidx] = key;
++_server_state->keys_received;
qDebug() << GetGroup().GetIndex(GetLocalId()) << GetLocalId() <<
": received key from" << GetGroup().GetIndex(from) << from <<
"Have:" << _server_state->keys_received << "expect:" << GetGroup().Count();
if(_server_state->keys_received == GetGroup().Count()) {
_server_state->key_receive_period.Stop();
_state_machine.StateComplete();
}
}
void NeffKeyShuffle::HandleShuffle(const Id &from, QDataStream &stream)
{
if(GetGroup().GetSubgroup().Previous(GetLocalId()) != from) {
throw QRunTimeError("Received a shuffle out of order");
}
Integer generator_input;
QVector<Integer> shuffle_input;
stream >> generator_input >> shuffle_input;
if(generator_input == 0) {
throw QRunTimeError("Invalid generator found");
} else if(shuffle_input.count() < GetGroup().GetSubgroup().Count()) {
throw QRunTimeError("Missing public keys");
}
_server_state->generator_input = generator_input;
_server_state->shuffle_input = shuffle_input;
qDebug() << GetGroup().GetIndex(GetLocalId()) << GetLocalId() <<
": received shuffle data from" << GetGroup().GetIndex(from) << from;
_state_machine.StateComplete();
}
void NeffKeyShuffle::HandleAnonymizedKeys(const Id &from,
QDataStream &stream)
{
if(GetGroup().GetSubgroup().Last() != from) {
throw QRunTimeError("Received from wrong server");
}
Integer new_generator;
QVector<Integer> new_public_elements;
stream >> new_generator >> new_public_elements;
if(new_generator == 0) {
throw QRunTimeError("Invalid generator found");
} else if(new_public_elements.count() < GetGroup().GetSubgroup().Count()) {
throw QRunTimeError("Missing public keys");
}
_state->new_generator = new_generator;
_state->new_public_elements = new_public_elements;
qDebug() << GetGroup().GetIndex(GetLocalId()) << GetLocalId() <<
": received keys from" << GetGroup().GetIndex(from) << from;
_state_machine.StateComplete();
}
void NeffKeyShuffle::GenerateKey()
{
QSharedPointer<CppDsaPrivateKey> base_key(
CppDsaPrivateKey::GenerateKey(GetRoundId().GetByteArray()));
_state->input_private_key = QSharedPointer<CppDsaPrivateKey>(
new CppDsaPrivateKey(base_key->GetModulus(), base_key->GetSubgroup(),
base_key->GetGenerator()));
_state_machine.StateComplete();
}
void NeffKeyShuffle::SubmitKey()
{
QByteArray msg;
QDataStream stream(&msg, QIODevice::WriteOnly);
QSharedPointer<CppDsaPrivateKey> key(
_state->input_private_key.dynamicCast<CppDsaPrivateKey>());
Q_ASSERT(key);
stream << KEY_SUBMIT << GetRoundId() << key->GetPublicElement();
VerifiableSend(GetGroup().GetSubgroup().GetId(0), msg);
_state_machine.StateComplete();
}
void NeffKeyShuffle::PrepareForKeySubmissions()
{
_server_state->shuffle_input = QVector<Integer>(GetGroup().Count(), 0);
_server_state->generator_input = GetGenerator();
Utils::TimerCallback *cb = new Utils::TimerMethod<NeffKeyShuffle, int>(
this, &NeffKeyShuffle::ConcludeKeySubmission, 0);
_server_state->key_receive_period =
Utils::Timer::GetInstance().QueueCallback(cb, KEY_SUBMISSION_WINDOW);
}
void NeffKeyShuffle::ShuffleKeys()
{
_state->blame = !CheckShuffleOrder(_server_state->shuffle_input);
QSharedPointer<CppDsaPrivateKey> tmp_key(
new CppDsaPrivateKey(GetModulus(), GetSubgroup(), GetGenerator()));
_server_state->exponent = tmp_key->GetPrivateExponent();
_server_state->generator_output = _server_state->generator_input.Pow(
_server_state->exponent, GetModulus());
foreach(const Integer &key, _server_state->shuffle_input) {
_server_state->shuffle_output.append(
key.Pow(_server_state->exponent, GetModulus()));
}
qSort(_server_state->shuffle_output);
const Id &next = GetGroup().GetSubgroup().Next(GetLocalId());
MessageType mtype = (next == Id::Zero()) ? ANONYMIZED_KEYS : KEY_SHUFFLE;
QByteArray msg;
QDataStream out_stream(&msg, QIODevice::WriteOnly);
out_stream << mtype << GetRoundId() << _server_state->generator_output <<
_server_state->shuffle_output;
if(mtype == ANONYMIZED_KEYS) {
VerifiableBroadcast(msg);
} else {
VerifiableSend(next, msg);
}
_state_machine.StateComplete();
}
void NeffKeyShuffle::ProcessAnonymizedKeys()
{
_state->blame = !CheckShuffleOrder(_state->new_public_elements);
if(_state->blame) {
return;
}
Integer my_element = _state->new_generator.Pow(GetPrivateExponent(),
GetModulus());
for(int idx = 0; idx < _state->new_public_elements.count(); idx++) {
if(_state->new_public_elements[idx] == my_element) {
_state->user_key_index = idx;
_state->output_private_key = QSharedPointer<AsymmetricKey>(
new CppDsaPrivateKey(GetModulus(), GetSubgroup(),
_state->new_generator, GetPrivateExponent()));
qDebug() << "Found my key at" << idx;
}
_state->output_keys.append(QSharedPointer<AsymmetricKey>(
new CppDsaPublicKey(GetModulus(), GetSubgroup(),
_state->new_generator, _state->new_public_elements[idx])));
}
if(_state->user_key_index == -1) {
_state->blame = true;
qDebug() << "Did not find my key";
} else {
SetSuccessful(true);
}
Stop("Round finished");
}
bool NeffKeyShuffle::CheckShuffleOrder(const QVector<Crypto::Integer> &keys)
{
Integer pkey(0);
foreach(const Integer &key, keys) {
if(key <= pkey) {
qDebug() << "Duplicate keys or unordered, blaming.";
return false;
}
}
return true;
}
void NeffKeyShuffle::ConcludeKeySubmission(const int &)
{
qDebug() << "Key window has closed, unfortunately some keys may not"
<< "have transmitted in time.";
QVector<Integer> pruned_keys;
foreach(const Integer &key, _server_state->shuffle_input) {
if(key != 0) {
pruned_keys.append(key);
}
}
_server_state->shuffle_input = pruned_keys;
_state_machine.StateComplete();
}
}
}
<|endoftext|> |
<commit_before>/**
* kernel.hpp -
* @author: Jonathan Beard
* @version: Thu Sep 11 15:34:24 2014
*
* Copyright 2014 Jonathan Beard
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef _KERNEL_HPP_
#define _KERNEL_HPP_ 1
#include <functional>
#include <utility>
#include <cstdint>
#include <queue>
#include <string>
#include "kernelexception.hpp"
#include "port.hpp"
#include "signalvars.hpp"
#include "rafttypes.hpp"
/** pre-declare for friends **/
class MapBase;
class Schedule;
class kernel_container;
class Map;
class basic_parallel;
class kpair;
#ifndef CLONE
namespace raft
{
class kernel;
}
#define CLONE() \
virtual raft::kernel* clone()\
{ \
auto *ptr( \
new typename std::remove_reference< decltype( *this ) >::type( ( *(\
(typename std::decay< decltype( *this ) >::type * ) \
this ) ) ) );\
/** RL needs to dealloc this one **/\
ptr->internal_alloc = true;\
return( ptr );\
}
#endif
namespace raft {
class kernel
{
public:
/** default constructor **/
kernel();
/** in-place allocation **/
kernel( void * const ptr,
const std::size_t nbytes );
virtual ~kernel() = default;
/**
* run - function to be extended for the actual execution.
* Code can be executed outside of the run function, i.e.,
* with any function call, however the scheduler will only
* call the run function so it must initiate any follow-on
* behavior desired by the user.
*/
virtual raft::kstatus run() = 0;
template < class T /** kernel type **/,
class ... Args >
static kernel* make( Args&&... params )
{
auto *output( new T( std::forward< Args >( params )... ) );
output->internal_alloc = true;
return( output );
}
/**
* clone - used for parallelization of kernels, if necessary
* sub-kernels should include an appropriate copy
* constructor so all class member variables can be
* set.
* @param other, T& - reference to object to be cloned
* @return kernel* - takes base type, however is same as
* allocated by copy constructor for T.
*/
virtual raft::kernel* clone()
{
throw CloneNotImplementedException( "Sub-class has failed to implement clone function, please use the CLONE() macro to add functionality" );
/** won't be reached **/
return( nullptr );
}
std::size_t get_id();
/**
* operator[] - returns the current kernel with the
* specified port name enabled for linking.
* @param portname - const std::string&&
* @return raft::kernel&&
*/
raft::kernel& operator []( const std::string &&portname );
protected:
/**
*
*/
virtual std::size_t addPort();
virtual void lock();
virtual void unlock();
/**
* PORTS - input and output, use these to interact with the
* outside world.
*/
Port input = { this };
Port output = { this };
std::string getEnabledPort();
/** in namespace raft **/
friend class map;
/** in global namespace **/
friend class ::MapBase;
friend class ::Schedule;
friend class ::GraphTools;
friend class ::kernel_container;
friend class ::basic_parallel;
friend class ::kpair;
/**
* NOTE: doesn't need to be atomic since only one thread
* will have responsibility to to create new compute
* kernels.
*/
static std::size_t kernel_count;
bool internal_alloc = false;
constexpr void retire() noexcept
{
(this)->execution_done = true;
}
constexpr bool isRetired() noexcept
{
return( (this)->execution_done );
}
private:
/** TODO, replace dup with bit vector **/
bool dup_enabled = false;
bool dup_candidate = false;
const std::size_t kernel_id;
bool execution_done = false;
/** for operator syntax **/
std::queue< std::string > enabled_port;
};
} /** end namespace raft */
#endif /* END _KERNEL_HPP_ */
<commit_msg>updates<commit_after>/**
* kernel.hpp -
* @author: Jonathan Beard
* @version: Thu Sep 11 15:34:24 2014
*
* Copyright 2014 Jonathan Beard
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef _KERNEL_HPP_
#define _KERNEL_HPP_ 1
#include <functional>
#include <utility>
#include <cstdint>
#include <queue>
#include <string>
#include "kernelexception.hpp"
#include "port.hpp"
#include "signalvars.hpp"
#include "rafttypes.hpp"
/** pre-declare for friends **/
class MapBase;
class Schedule;
class kernel_container;
class Map;
class basic_parallel;
class kpair;
#ifndef CLONE
namespace raft
{
class kernel;
}
#define CLONE() \
virtual raft::kernel* clone()\
{ \
auto *ptr( \
new typename std::remove_reference< decltype( *this ) >::type( ( *(\
(typename std::decay< decltype( *this ) >::type * ) \
this ) ) ) );\
/** RL needs to dealloc this one **/\
ptr->internal_alloc = true;\
return( ptr );\
}
#endif
namespace raft {
class kernel
{
public:
/** default constructor **/
kernel();
/** in-place allocation **/
kernel( void * const ptr,
const std::size_t nbytes );
virtual ~kernel() = default;
/**
* run - function to be extended for the actual execution.
* Code can be executed outside of the run function, i.e.,
* with any function call, however the scheduler will only
* call the run function so it must initiate any follow-on
* behavior desired by the user.
*/
virtual raft::kstatus run() = 0;
template < class T /** kernel type **/,
class ... Args >
static kernel* make( Args&&... params )
{
auto *output( new T( std::forward< Args >( params )... ) );
output->internal_alloc = true;
return( output );
}
/**
* clone - used for parallelization of kernels, if necessary
* sub-kernels should include an appropriate copy
* constructor so all class member variables can be
* set.
* @param other, T& - reference to object to be cloned
* @return kernel* - takes base type, however is same as
* allocated by copy constructor for T.
*/
virtual raft::kernel* clone()
{
throw CloneNotImplementedException( "Sub-class has failed to implement clone function, please use the CLONE() macro to add functionality" );
/** won't be reached **/
return( nullptr );
}
std::size_t get_id();
/**
* operator[] - returns the current kernel with the
* specified port name enabled for linking.
* @param portname - const std::string&&
* @return raft::kernel&&
*/
raft::kernel& operator []( const std::string &&portname );
protected:
/**
*
*/
virtual std::size_t addPort();
virtual void lock();
virtual void unlock();
/**
* PORTS - input and output, use these to interact with the
* outside world.
*/
Port input = { this };
Port output = { this };
std::string getEnabledPort();
/** in namespace raft **/
friend class map;
/** in global namespace **/
friend class ::MapBase;
friend class ::Schedule;
friend class ::GraphTools;
friend class ::kernel_container;
friend class ::basic_parallel;
friend class ::kpair;
/**
* NOTE: doesn't need to be atomic since only one thread
* will have responsibility to to create new compute
* kernels.
*/
static std::size_t kernel_count;
bool internal_alloc = false;
void retire() noexcept
{
(this)->execution_done = true;
}
bool isRetired() noexcept
{
return( (this)->execution_done );
}
private:
/** TODO, replace dup with bit vector **/
bool dup_enabled = false;
bool dup_candidate = false;
const std::size_t kernel_id;
bool execution_done = false;
/** for operator syntax **/
std::queue< std::string > enabled_port;
};
} /** end namespace raft */
#endif /* END _KERNEL_HPP_ */
<|endoftext|> |
<commit_before>#include "SoloReadFeature.h"
#include "serviceFuns.cpp"
#include "SequenceFuns.h"
uint32 outputReadCB(fstream *streamOut, int32 featureType, uint32 umiB, uint32 gene, vector<array<uint64,2>> &readSJs, const string &stringCB, const uint64 iRead)
{
//feature
uint64 nout=1;
if (featureType==0 || featureType==2) {//genes
*streamOut << umiB <<' ';//UMI
if ( iRead < (uint64)-1 )
*streamOut << iRead <<' ';//iRead
*streamOut << gene <<' '<< stringCB <<'\n';;
} else if (featureType==1) {//sjs
for (auto &sj : readSJs) {
*streamOut << umiB <<' ';//UMI
if ( iRead < (uint64)-1 )
*streamOut << iRead <<' ';//iRead
*streamOut << sj[0] <<' '<< sj[1] <<' '<< stringCB <<'\n';;
};
nout=readSJs.size();
};
return nout;
};
void SoloReadFeature::record(SoloReadBarcode &soloBar, uint nTr, set<uint32> &readGene, set<uint32> &readGeneFull, Transcript *alignOut, uint64 iRead)
{
if (pSolo.type==0 || soloBar.cbMatch<0)
return;
//unmapped
if (nTr==0) {
stats.V[stats.nUnmapped]++;
return;
};
vector<array<uint64,2>> readSJs;
set<uint32> *readGe;
if (featureType==0) {
readGe = &readGene;
} else if (featureType==2) {
readGe = &readGeneFull;
};
if (featureType==0 || featureType==2) {//genes
//check genes, return if no gene of multimapping
if (readGe->size()==0) {
stats.V[stats.nNoFeature]++;
return;
};
if (readGe->size()>1) {
stats.V[stats.nAmbigFeature]++;
if (nTr>1)
stats.V[stats.nAmbigFeatureMultimap]++;
return;
};
} else if (featureType==1) {//SJs
if (nTr>1) {//reject all multimapping junctions
stats.V[stats.nAmbigFeatureMultimap]++;
return;
};
//for SJs, still check genes, return if multi-gene
if (readGene.size()>1) {
stats.V[stats.nAmbigFeature]++;
return;
};
bool sjAnnot;
alignOut->extractSpliceJunctions(readSJs, sjAnnot);
if ( readSJs.empty() || (sjAnnot && readGene.size()==0) ) {//no junctions, or annotated junction buy no gene (i.e. read does not fully match transcript)
stats.V[stats.nNoFeature]++;
return;
};
};
if (!readInfoYes)
iRead=(uint64)-1;
if (soloBar.cbMatch==0) {//exact match
uint32 n1 = outputReadCB(strU_0, featureType, soloBar.umiB, *readGe->begin(), readSJs, to_string(soloBar.cbI), iRead);
if (pSolo.cbWL.size()>0) {//WL
cbReadCount[soloBar.cbI] += n1;
} else {//no WL
cbReadCountMap[soloBar.cbI] += n1;
};
return;
} else if (soloBar.cbMatch==1) {//1 match with 1MM
cbReadCount[soloBar.cbI]+= outputReadCB(strU_1, featureType, soloBar.umiB, *readGe->begin(), readSJs, to_string(soloBar.cbI), iRead);
return;
} else {//>1 matches
uint32 nfeat=outputReadCB(strU_2, featureType, soloBar.umiB, *readGe->begin(), readSJs, to_string(soloBar.cbMatch) + soloBar.cbMatchString, iRead);
for (auto &cbi : soloBar.cbMatchInd)
cbReadCount[cbi] += nfeat;
return;
};
};
<commit_msg>Implementing solo BAM tags: debugging.<commit_after>#include "SoloReadFeature.h"
#include "serviceFuns.cpp"
#include "SequenceFuns.h"
uint32 outputReadCB(fstream *streamOut, int32 featureType, uint32 umiB, uint32 gene, vector<array<uint64,2>> &readSJs, const string &stringCB, const uint64 iRead)
{
//feature
uint64 nout=1;
if (featureType==0 || featureType==2) {//genes
*streamOut << umiB <<' ';//UMI
if ( iRead != (uint64)-1 )
*streamOut << iRead <<' ';//iRead
*streamOut << gene <<' '<< stringCB <<'\n';;
} else if (featureType==1) {//sjs
for (auto &sj : readSJs) {
*streamOut << umiB <<' ';//UMI
if ( iRead != (uint64)-1 )
*streamOut << iRead <<' ';//iRead
*streamOut << sj[0] <<' '<< sj[1] <<' '<< stringCB <<'\n';;
};
nout=readSJs.size();
};
return nout;
};
void SoloReadFeature::record(SoloReadBarcode &soloBar, uint nTr, set<uint32> &readGene, set<uint32> &readGeneFull, Transcript *alignOut, uint64 iRead)
{
if (pSolo.type==0 || soloBar.cbMatch<0)
return;
//unmapped
if (nTr==0) {
stats.V[stats.nUnmapped]++;
return;
};
vector<array<uint64,2>> readSJs;
set<uint32> *readGe;
if (featureType==0) {
readGe = &readGene;
} else if (featureType==2) {
readGe = &readGeneFull;
};
if (featureType==0 || featureType==2) {//genes
//check genes, return if no gene of multimapping
if (readGe->size()==0) {
stats.V[stats.nNoFeature]++;
return;
};
if (readGe->size()>1) {
stats.V[stats.nAmbigFeature]++;
if (nTr>1)
stats.V[stats.nAmbigFeatureMultimap]++;
return;
};
} else if (featureType==1) {//SJs
if (nTr>1) {//reject all multimapping junctions
stats.V[stats.nAmbigFeatureMultimap]++;
return;
};
//for SJs, still check genes, return if multi-gene
if (readGene.size()>1) {
stats.V[stats.nAmbigFeature]++;
return;
};
bool sjAnnot;
alignOut->extractSpliceJunctions(readSJs, sjAnnot);
if ( readSJs.empty() || (sjAnnot && readGene.size()==0) ) {//no junctions, or annotated junction buy no gene (i.e. read does not fully match transcript)
stats.V[stats.nNoFeature]++;
return;
};
};
if (!readInfoYes)
iRead=(uint64)-1;
if (soloBar.cbMatch==0) {//exact match
uint32 n1 = outputReadCB(strU_0, featureType, soloBar.umiB, *readGe->begin(), readSJs, to_string(soloBar.cbI), iRead);
if (pSolo.cbWL.size()>0) {//WL
cbReadCount[soloBar.cbI] += n1;
} else {//no WL
cbReadCountMap[soloBar.cbI] += n1;
};
return;
} else if (soloBar.cbMatch==1) {//1 match with 1MM
cbReadCount[soloBar.cbI]+= outputReadCB(strU_1, featureType, soloBar.umiB, *readGe->begin(), readSJs, to_string(soloBar.cbI), iRead);
return;
} else {//>1 matches
uint32 nfeat=outputReadCB(strU_2, featureType, soloBar.umiB, *readGe->begin(), readSJs, to_string(soloBar.cbMatch) + soloBar.cbMatchString, iRead);
for (auto &cbi : soloBar.cbMatchInd)
cbReadCount[cbi] += nfeat;
return;
};
};
<|endoftext|> |
<commit_before>#include "messagedirector.h"
#include "../core/config.h"
ConfigVariable<std::string> bind_addr("messagedirector/bind", "unspecified");
MessageDirector MessageDirector::singleton;
void MessageDirector::InitializeMD()
{
if(!m_initialized)
{
if(bind_addr.get_val() != "unspecified")
{
}
}
}
MessageDirector::MessageDirector() : m_acceptor(NULL), m_initialized(false)
{
}<commit_msg>Put in some placeholder synhronous accept code<commit_after>#include "../core/global.h"
#include "messagedirector.h"
#include "../core/config.h"
using boost::asio::ip::tcp; // I don't want to type all of that god damned shit
ConfigVariable<std::string> bind_addr("messagedirector/bind", "unspecified");
MessageDirector MessageDirector::singleton;
void MessageDirector::InitializeMD()
{
if(!m_initialized)
{
if(bind_addr.get_val() != "unspecified")
{
std::string str_ip = bind_addr.get_val();
std::string str_port = str_ip.substr(str_ip.find(':', 0)+1, std::string::npos);
str_ip = str_ip.substr(0, str_ip.find(':', 0));
tcp::resolver resolver(io_service);
tcp::resolver::query query(str_ip, str_port);
tcp::resolver::iterator it = resolver.resolve(query);
m_acceptor = new tcp::acceptor(io_service, *it, true);
tcp::socket socket(io_service);
tcp::endpoint peerEndpoint;
m_acceptor->accept(socket);
}
}
}
MessageDirector::MessageDirector() : m_acceptor(NULL), m_initialized(false)
{
}<|endoftext|> |
<commit_before>//=======================================================================
// Copyright Baptiste Wicht 2011-2013.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
//=======================================================================
#include <map>
#include <unordered_map>
#include "iterators.hpp"
#include "VisitorUtils.hpp"
#include "Type.hpp"
#include "GlobalContext.hpp"
#include "FunctionContext.hpp"
#include "logging.hpp"
#include "Variable.hpp"
#include "mtac/loop.hpp"
#include "mtac/loop_invariant_code_motion.hpp"
#include "mtac/Function.hpp"
#include "mtac/ControlFlowGraph.hpp"
#include "mtac/Utils.hpp"
#include "mtac/variable_usage.hpp"
#include "mtac/Quadruple.hpp"
using namespace eddic;
namespace {
bool is_invariant(boost::optional<mtac::Argument>& argument, mtac::Usage& usage){
if(argument){
if(auto* ptr = boost::get<std::shared_ptr<Variable>>(&*argument)){
return usage.written[*ptr] == 0;
}
}
return true;
}
bool is_invariant(mtac::Quadruple& quadruple, mtac::Usage& usage){
if(mtac::erase_result(quadruple.op)){
//If there are more than one write to this variable, the computation is not invariant
if(usage.written[quadruple.result] > 1){
return false;
}
return is_invariant(quadruple.arg1, usage) && is_invariant(quadruple.arg2, usage);
}
return false;
}
/*!
* \brief Test if an invariant is valid or not.
* An invariant defining v is valid if:
* 1. It is in a basic block that dominates all other uses of v
* 2. It is in a basic block that dominates all exit blocks of the loop
* 3. It is not an NOP
*/
bool is_valid_invariant(mtac::basic_block_p source_bb, mtac::Quadruple& quadruple, mtac::loop& loop){
//It is not necessary to move statements with no effects.
if(quadruple.op == mtac::Operator::NOP){
return false;
}
auto var = quadruple.result;
for(auto& bb : loop){
//A bb always dominates itself => no need to consider the source basic block
if(bb != source_bb){
if(use_variable(bb, var)){
auto dominator = bb->dominator;
//If the bb is not dominated by the source bb, it is not valid
if(dominator != source_bb){
return false;
}
}
}
}
auto exit_block = *loop.blocks().rbegin();
if(exit_block == source_bb){
return true;
}
auto dominator = exit_block->dominator;
//If the exit bb is not dominated by the source bb, it is not valid
if(dominator != source_bb){
return false;
}
return true;
}
bool loop_invariant_code_motion(mtac::loop& loop, mtac::Function& function){
mtac::basic_block_p pre_header;
bool optimized = false;
auto usage = compute_write_usage(loop);
for(auto& bb : loop){
auto it = iterate(bb->statements);
while(it.has_next()){
auto& statement = *it;
if(is_invariant(statement, usage)){
if(is_valid_invariant(bb, statement, loop)){
//Create the preheader if necessary
if(!pre_header){
pre_header = loop.find_safe_preheader(function, true);
}
function.context->global()->stats().inc_counter("invariant_moved");
pre_header->statements.push_back(std::move(statement));
it.erase();
optimized = true;
continue;
}
}
++it;
}
}
return optimized;
}
} //end of anonymous namespace
bool mtac::loop_invariant_code_motion::operator()(mtac::Function& function){
if(function.loops().empty()){
return false;
}
bool optimized = false;
for(auto& loop : function.loops()){
optimized |= ::loop_invariant_code_motion(loop, function);
}
return optimized;
}
<commit_msg>The current algorithm is not able to correctly move invariant in loops bigger than one basic blocks<commit_after>//=======================================================================
// Copyright Baptiste Wicht 2011-2013.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
//=======================================================================
#include <map>
#include <unordered_map>
#include "iterators.hpp"
#include "VisitorUtils.hpp"
#include "Type.hpp"
#include "GlobalContext.hpp"
#include "FunctionContext.hpp"
#include "logging.hpp"
#include "Variable.hpp"
#include "mtac/loop.hpp"
#include "mtac/loop_invariant_code_motion.hpp"
#include "mtac/Function.hpp"
#include "mtac/ControlFlowGraph.hpp"
#include "mtac/Utils.hpp"
#include "mtac/variable_usage.hpp"
#include "mtac/Quadruple.hpp"
using namespace eddic;
namespace {
bool is_invariant(boost::optional<mtac::Argument>& argument, mtac::Usage& usage){
if(argument){
if(auto* ptr = boost::get<std::shared_ptr<Variable>>(&*argument)){
return usage.written[*ptr] == 0;
}
}
return true;
}
bool is_invariant(mtac::Quadruple& quadruple, mtac::Usage& usage){
if(mtac::erase_result(quadruple.op)){
//If there are more than one write to this variable, the computation is not invariant
if(usage.written[quadruple.result] > 1){
return false;
}
return is_invariant(quadruple.arg1, usage) && is_invariant(quadruple.arg2, usage);
}
return false;
}
/*!
* \brief Test if an invariant is valid or not.
* An invariant defining v is valid if:
* 1. It is in a basic block that dominates all other uses of v
* 2. It is in a basic block that dominates all exit blocks of the loop
* 3. It is not an NOP
*/
bool is_valid_invariant(mtac::basic_block_p source_bb, mtac::Quadruple& quadruple, mtac::loop& loop){
//It is not necessary to move statements with no effects.
if(quadruple.op == mtac::Operator::NOP){
return false;
}
auto var = quadruple.result;
for(auto& bb : loop){
//A bb always dominates itself => no need to consider the source basic block
if(bb != source_bb){
if(use_variable(bb, var)){
auto dominator = bb->dominator;
//If the bb is not dominated by the source bb, it is not valid
if(dominator != source_bb){
return false;
}
}
}
}
auto exit_block = *loop.blocks().rbegin();
if(exit_block == source_bb){
return true;
}
auto dominator = exit_block->dominator;
//If the exit bb is not dominated by the source bb, it is not valid
if(dominator != source_bb){
return false;
}
return true;
}
bool loop_invariant_code_motion(mtac::loop& loop, mtac::Function& function){
mtac::basic_block_p pre_header;
bool optimized = false;
auto usage = compute_write_usage(loop);
for(auto& bb : loop){
auto it = iterate(bb->statements);
while(it.has_next()){
auto& statement = *it;
if(is_invariant(statement, usage)){
if(is_valid_invariant(bb, statement, loop)){
//Create the preheader if necessary
if(!pre_header){
pre_header = loop.find_safe_preheader(function, true);
}
function.context->global()->stats().inc_counter("invariant_moved");
pre_header->statements.push_back(std::move(statement));
it.erase();
optimized = true;
continue;
}
}
++it;
}
}
return optimized;
}
} //end of anonymous namespace
bool mtac::loop_invariant_code_motion::operator()(mtac::Function& function){
if(function.loops().empty()){
return false;
}
bool optimized = false;
for(auto& loop : function.loops()){
if(loop.blocks().size() == 1){
optimized |= ::loop_invariant_code_motion(loop, function);
}
}
return optimized;
}
<|endoftext|> |
<commit_before>/****************************************************************************
**
** Copyright (C) 2012 Nokia Corporation and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/
**
** This file is part of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** GNU Lesser General Public License Usage
** This file may be used under the terms of the GNU Lesser General Public
** License version 2.1 as published by the Free Software Foundation and
** appearing in the file LICENSE.LGPL included in the packaging of this
** file. Please review the following information to ensure the GNU Lesser
** General Public License version 2.1 requirements will be met:
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU General
** Public License version 3.0 as published by the Free Software Foundation
** and appearing in the file LICENSE.GPL included in the packaging of this
** file. Please review the following information to ensure the GNU General
** Public License version 3.0 requirements will be met:
** http://www.gnu.org/copyleft/gpl.html.
**
** Other Usage
** Alternatively, this file may be used in accordance with the terms and
** conditions contained in a signed written agreement between you and Nokia.
**
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include "qsamplecache_p.h"
#include "qwavedecoder_p.h"
#include <QtNetwork>
//#define QT_SAMPLECACHE_DEBUG
QT_BEGIN_NAMESPACE
/*!
\class QSampleCache
\internal
When you want to get a sound sample data, you need to request the QSample reference from QSampleCache.
\code
QSample *m_sample; // class member.
private Q_SLOTS:
void decoderError();
void sampleReady();
\endcode
\code
Q_GLOBAL_STATIC(QSampleCache, sampleCache) //declare a singleton manager
\endcode
\code
m_sample = sampleCache()->requestSample(url);
switch(m_sample->state()) {
case QSample::Ready:
sampleReady();
break;
case QSample::Error:
decoderError();
break;
default:
connect(m_sample, SIGNAL(error()), this, SLOT(decoderError()));
connect(m_sample, SIGNAL(ready()), this, SLOT(sampleReady()));
break;
}
\endcode
When you no longer need the sound sample data, you need to release it:
\code
if (m_sample) {
m_sample->release();
m_sample = 0;
}
\endcode
*/
QSampleCache::QSampleCache(QObject *parent)
: QObject(parent)
, m_networkAccessManager(0)
, m_mutex(QMutex::Recursive)
, m_capacity(0)
, m_usage(0)
, m_loadingRefCount(0)
{
m_loadingThread.setObjectName(QLatin1String("QSampleCache::LoadingThread"));
connect(&m_loadingThread, SIGNAL(finished()), this, SIGNAL(isLoadingChanged()));
connect(&m_loadingThread, SIGNAL(started()), this, SIGNAL(isLoadingChanged()));
}
QNetworkAccessManager& QSampleCache::networkAccessManager()
{
if (!m_networkAccessManager)
m_networkAccessManager = new QNetworkAccessManager();
return *m_networkAccessManager;
}
QSampleCache::~QSampleCache()
{
QMutexLocker m(&m_mutex);
m_loadingThread.quit();
m_loadingThread.wait();
// Killing the loading thread means that no samples can be
// deleted using deleteLater. And some samples that had deleteLater
// already called won't have been processed (m_staleSamples)
foreach (QSample* sample, m_samples)
delete sample;
foreach (QSample* sample, m_staleSamples)
delete sample; // deleting a sample does affect the m_staleSamples list, but foreach copies it
delete m_networkAccessManager;
}
void QSampleCache::loadingRelease()
{
QMutexLocker locker(&m_loadingMutex);
m_loadingRefCount--;
if (m_loadingRefCount == 0) {
if (m_loadingThread.isRunning())
m_loadingThread.exit();
}
}
bool QSampleCache::isLoading() const
{
return m_loadingThread.isRunning();
}
QSample* QSampleCache::requestSample(const QUrl& url)
{
//lock and add first to make sure live loadingThread will not be killed during this function call
m_loadingMutex.lock();
m_loadingRefCount++;
m_loadingMutex.unlock();
if (!m_loadingThread.isRunning())
m_loadingThread.start();
#ifdef QT_SAMPLECACHE_DEBUG
qDebug() << "QSampleCache: request sample [" << url << "]";
#endif
QMutexLocker locker(&m_mutex);
QMap<QUrl, QSample*>::iterator it = m_samples.find(url);
QSample* sample;
if (it == m_samples.end()) {
sample = new QSample(url, this);
m_samples.insert(url, sample);
sample->moveToThread(&m_loadingThread);
} else {
sample = *it;
}
sample->addRef();
locker.unlock();
sample->loadIfNecessary();
return sample;
}
void QSampleCache::setCapacity(qint64 capacity)
{
QMutexLocker locker(&m_mutex);
if (m_capacity == capacity)
return;
#ifdef QT_SAMPLECACHE_DEBUG
qDebug() << "QSampleCache: capacity changes from " << m_capacity << "to " << capacity;
#endif
if (m_capacity > 0 && capacity <= 0) { //memory management strategy changed
for (QMap<QUrl, QSample*>::iterator it = m_samples.begin(); it != m_samples.end();) {
QSample* sample = *it;
if (sample->m_ref == 0) {
unloadSample(sample);
it = m_samples.erase(it);
} else
it++;
}
}
m_capacity = capacity;
refresh(0);
}
// Called locked
void QSampleCache::unloadSample(QSample *sample)
{
m_usage -= sample->m_soundData.size();
m_staleSamples.insert(sample);
sample->deleteLater();
}
// Called in both threads
void QSampleCache::refresh(qint64 usageChange)
{
QMutexLocker locker(&m_mutex);
m_usage += usageChange;
if (m_capacity <= 0 || m_usage <= m_capacity)
return;
#ifdef QT_SAMPLECACHE_DEBUG
qint64 recoveredSize = 0;
#endif
//free unused samples to keep usage under capacity limit.
for (QMap<QUrl, QSample*>::iterator it = m_samples.begin(); it != m_samples.end();) {
QSample* sample = *it;
if (sample->m_ref > 0) {
++it;
continue;
}
#ifdef QT_SAMPLECACHE_DEBUG
recoveredSize += sample->m_soundData.size();
#endif
unloadSample(sample);
it = m_samples.erase(it);
if (m_usage <= m_capacity)
return;
}
#ifdef QT_SAMPLECACHE_DEBUG
qDebug() << "QSampleCache: refresh(" << usageChange
<< ") recovered size =" << recoveredSize
<< "new usage =" << m_usage;
#endif
if (m_usage > m_capacity)
qWarning() << "QSampleCache: usage[" << m_usage << " out of limit[" << m_capacity << "]";
}
// Called in both threads
void QSampleCache::removeUnreferencedSample(QSample *sample)
{
QMutexLocker m(&m_mutex);
m_staleSamples.remove(sample);
}
// Called in loader thread (since this lives in that thread)
// Also called from application thread after loader thread dies.
QSample::~QSample()
{
// Remove ourselves from our parent
m_parent->removeUnreferencedSample(this);
QMutexLocker locker(&m_mutex);
#ifdef QT_SAMPLECACHE_DEBUG
qDebug() << "~QSample" << this << ": deleted [" << m_url << "]" << QThread::currentThread();
#endif
cleanup();
}
// Called in application thread
void QSample::loadIfNecessary()
{
QMutexLocker locker(&m_mutex);
if (m_state == QSample::Error || m_state == QSample::Creating) {
m_state = QSample::Loading;
QMetaObject::invokeMethod(this, "load", Qt::QueuedConnection);
} else {
qobject_cast<QSampleCache*>(m_parent)->loadingRelease();
}
}
// Called in both threads
bool QSampleCache::notifyUnreferencedSample(QSample* sample)
{
QMutexLocker locker(&m_mutex);
if (m_capacity > 0)
return false;
m_samples.remove(sample->m_url);
m_staleSamples.insert(sample);
sample->deleteLater();
return true;
}
// Called in application threadd
void QSample::release()
{
QMutexLocker locker(&m_mutex);
#ifdef QT_SAMPLECACHE_DEBUG
qDebug() << "Sample:: release" << this << QThread::currentThread() << m_ref;
#endif
m_ref--;
if (m_ref == 0)
m_parent->notifyUnreferencedSample(this);
}
// Called in dtor and when stream is loaded
// must be called locked.
void QSample::cleanup()
{
if (m_waveDecoder)
m_waveDecoder->deleteLater();
if (m_stream)
m_stream->deleteLater();
m_waveDecoder = 0;
m_stream = 0;
}
// Called in application thread
void QSample::addRef()
{
m_ref++;
}
// Called in loading thread
void QSample::readSample()
{
Q_ASSERT(QThread::currentThread()->objectName() == QLatin1String("QSampleCache::LoadingThread"));
QMutexLocker m(&m_mutex);
#ifdef QT_SAMPLECACHE_DEBUG
qDebug() << "QSample: readSample";
#endif
qint64 read = m_waveDecoder->read(m_soundData.data() + m_sampleReadLength,
qMin(m_waveDecoder->bytesAvailable(),
qint64(m_waveDecoder->size() - m_sampleReadLength)));
if (read > 0)
m_sampleReadLength += read;
if (m_sampleReadLength < m_waveDecoder->size())
return;
Q_ASSERT(m_sampleReadLength == qint64(m_soundData.size()));
onReady();
}
// Called in loading thread
void QSample::decoderReady()
{
Q_ASSERT(QThread::currentThread()->objectName() == QLatin1String("QSampleCache::LoadingThread"));
QMutexLocker m(&m_mutex);
#ifdef QT_SAMPLECACHE_DEBUG
qDebug() << "QSample: decoder ready";
#endif
m_parent->refresh(m_waveDecoder->size());
m_soundData.resize(m_waveDecoder->size());
m_sampleReadLength = 0;
qint64 read = m_waveDecoder->read(m_soundData.data(), m_waveDecoder->size());
if (read > 0)
m_sampleReadLength += read;
if (m_sampleReadLength >= m_waveDecoder->size())
onReady();
}
// Called in all threads
QSample::State QSample::state() const
{
QMutexLocker m(&m_mutex);
return m_state;
}
// Called in loading thread
// Essentially a second ctor, doesn't need locks (?)
void QSample::load()
{
Q_ASSERT(QThread::currentThread()->objectName() == QLatin1String("QSampleCache::LoadingThread"));
#ifdef QT_SAMPLECACHE_DEBUG
qDebug() << "QSample: load [" << m_url << "]";
#endif
m_stream = m_parent->networkAccessManager().get(QNetworkRequest(m_url));
connect(m_stream, SIGNAL(error(QNetworkReply::NetworkError)), SLOT(decoderError()));
m_waveDecoder = new QWaveDecoder(m_stream);
connect(m_waveDecoder, SIGNAL(formatKnown()), SLOT(decoderReady()));
connect(m_waveDecoder, SIGNAL(parsingError()), SLOT(decoderError()));
connect(m_waveDecoder, SIGNAL(readyRead()), SLOT(readSample()));
}
// Called in loading thread
void QSample::decoderError()
{
Q_ASSERT(QThread::currentThread()->objectName() == QLatin1String("QSampleCache::LoadingThread"));
QMutexLocker m(&m_mutex);
#ifdef QT_SAMPLECACHE_DEBUG
qDebug() << "QSample: decoder error";
#endif
cleanup();
m_state = QSample::Error;
qobject_cast<QSampleCache*>(m_parent)->loadingRelease();
emit error();
}
// Called in loading thread from decoder when sample is done. Locked already.
void QSample::onReady()
{
Q_ASSERT(QThread::currentThread()->objectName() == QLatin1String("QSampleCache::LoadingThread"));
#ifdef QT_SAMPLECACHE_DEBUG
qDebug() << "QSample: load ready";
#endif
m_audioFormat = m_waveDecoder->audioFormat();
cleanup();
m_state = QSample::Ready;
qobject_cast<QSampleCache*>(m_parent)->loadingRelease();
emit ready();
}
// Called in application thread, then moved to loader thread
QSample::QSample(const QUrl& url, QSampleCache *parent)
: m_parent(parent)
, m_stream(0)
, m_waveDecoder(0)
, m_url(url)
, m_sampleReadLength(0)
, m_state(Creating)
, m_ref(0)
{
}
QT_END_NAMESPACE
#include "moc_qsamplecache_p.cpp"
<commit_msg>Still need to count usage even when capacity is zero.<commit_after>/****************************************************************************
**
** Copyright (C) 2012 Nokia Corporation and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/
**
** This file is part of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** GNU Lesser General Public License Usage
** This file may be used under the terms of the GNU Lesser General Public
** License version 2.1 as published by the Free Software Foundation and
** appearing in the file LICENSE.LGPL included in the packaging of this
** file. Please review the following information to ensure the GNU Lesser
** General Public License version 2.1 requirements will be met:
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU General
** Public License version 3.0 as published by the Free Software Foundation
** and appearing in the file LICENSE.GPL included in the packaging of this
** file. Please review the following information to ensure the GNU General
** Public License version 3.0 requirements will be met:
** http://www.gnu.org/copyleft/gpl.html.
**
** Other Usage
** Alternatively, this file may be used in accordance with the terms and
** conditions contained in a signed written agreement between you and Nokia.
**
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include "qsamplecache_p.h"
#include "qwavedecoder_p.h"
#include <QtNetwork>
//#define QT_SAMPLECACHE_DEBUG
QT_BEGIN_NAMESPACE
/*!
\class QSampleCache
\internal
When you want to get a sound sample data, you need to request the QSample reference from QSampleCache.
\code
QSample *m_sample; // class member.
private Q_SLOTS:
void decoderError();
void sampleReady();
\endcode
\code
Q_GLOBAL_STATIC(QSampleCache, sampleCache) //declare a singleton manager
\endcode
\code
m_sample = sampleCache()->requestSample(url);
switch(m_sample->state()) {
case QSample::Ready:
sampleReady();
break;
case QSample::Error:
decoderError();
break;
default:
connect(m_sample, SIGNAL(error()), this, SLOT(decoderError()));
connect(m_sample, SIGNAL(ready()), this, SLOT(sampleReady()));
break;
}
\endcode
When you no longer need the sound sample data, you need to release it:
\code
if (m_sample) {
m_sample->release();
m_sample = 0;
}
\endcode
*/
QSampleCache::QSampleCache(QObject *parent)
: QObject(parent)
, m_networkAccessManager(0)
, m_mutex(QMutex::Recursive)
, m_capacity(0)
, m_usage(0)
, m_loadingRefCount(0)
{
m_loadingThread.setObjectName(QLatin1String("QSampleCache::LoadingThread"));
connect(&m_loadingThread, SIGNAL(finished()), this, SIGNAL(isLoadingChanged()));
connect(&m_loadingThread, SIGNAL(started()), this, SIGNAL(isLoadingChanged()));
}
QNetworkAccessManager& QSampleCache::networkAccessManager()
{
if (!m_networkAccessManager)
m_networkAccessManager = new QNetworkAccessManager();
return *m_networkAccessManager;
}
QSampleCache::~QSampleCache()
{
QMutexLocker m(&m_mutex);
m_loadingThread.quit();
m_loadingThread.wait();
// Killing the loading thread means that no samples can be
// deleted using deleteLater. And some samples that had deleteLater
// already called won't have been processed (m_staleSamples)
foreach (QSample* sample, m_samples)
delete sample;
foreach (QSample* sample, m_staleSamples)
delete sample; // deleting a sample does affect the m_staleSamples list, but foreach copies it
delete m_networkAccessManager;
}
void QSampleCache::loadingRelease()
{
QMutexLocker locker(&m_loadingMutex);
m_loadingRefCount--;
if (m_loadingRefCount == 0) {
if (m_loadingThread.isRunning())
m_loadingThread.exit();
}
}
bool QSampleCache::isLoading() const
{
return m_loadingThread.isRunning();
}
QSample* QSampleCache::requestSample(const QUrl& url)
{
//lock and add first to make sure live loadingThread will not be killed during this function call
m_loadingMutex.lock();
m_loadingRefCount++;
m_loadingMutex.unlock();
if (!m_loadingThread.isRunning())
m_loadingThread.start();
#ifdef QT_SAMPLECACHE_DEBUG
qDebug() << "QSampleCache: request sample [" << url << "]";
#endif
QMutexLocker locker(&m_mutex);
QMap<QUrl, QSample*>::iterator it = m_samples.find(url);
QSample* sample;
if (it == m_samples.end()) {
sample = new QSample(url, this);
m_samples.insert(url, sample);
sample->moveToThread(&m_loadingThread);
} else {
sample = *it;
}
sample->addRef();
locker.unlock();
sample->loadIfNecessary();
return sample;
}
void QSampleCache::setCapacity(qint64 capacity)
{
QMutexLocker locker(&m_mutex);
if (m_capacity == capacity)
return;
#ifdef QT_SAMPLECACHE_DEBUG
qDebug() << "QSampleCache: capacity changes from " << m_capacity << "to " << capacity;
#endif
if (m_capacity > 0 && capacity <= 0) { //memory management strategy changed
for (QMap<QUrl, QSample*>::iterator it = m_samples.begin(); it != m_samples.end();) {
QSample* sample = *it;
if (sample->m_ref == 0) {
unloadSample(sample);
it = m_samples.erase(it);
} else
it++;
}
}
m_capacity = capacity;
refresh(0);
}
// Called locked
void QSampleCache::unloadSample(QSample *sample)
{
m_usage -= sample->m_soundData.size();
m_staleSamples.insert(sample);
sample->deleteLater();
}
// Called in both threads
void QSampleCache::refresh(qint64 usageChange)
{
QMutexLocker locker(&m_mutex);
m_usage += usageChange;
if (m_capacity <= 0 || m_usage <= m_capacity)
return;
#ifdef QT_SAMPLECACHE_DEBUG
qint64 recoveredSize = 0;
#endif
//free unused samples to keep usage under capacity limit.
for (QMap<QUrl, QSample*>::iterator it = m_samples.begin(); it != m_samples.end();) {
QSample* sample = *it;
if (sample->m_ref > 0) {
++it;
continue;
}
#ifdef QT_SAMPLECACHE_DEBUG
recoveredSize += sample->m_soundData.size();
#endif
unloadSample(sample);
it = m_samples.erase(it);
if (m_usage <= m_capacity)
return;
}
#ifdef QT_SAMPLECACHE_DEBUG
qDebug() << "QSampleCache: refresh(" << usageChange
<< ") recovered size =" << recoveredSize
<< "new usage =" << m_usage;
#endif
if (m_usage > m_capacity)
qWarning() << "QSampleCache: usage[" << m_usage << " out of limit[" << m_capacity << "]";
}
// Called in both threads
void QSampleCache::removeUnreferencedSample(QSample *sample)
{
QMutexLocker m(&m_mutex);
m_staleSamples.remove(sample);
}
// Called in loader thread (since this lives in that thread)
// Also called from application thread after loader thread dies.
QSample::~QSample()
{
// Remove ourselves from our parent
m_parent->removeUnreferencedSample(this);
QMutexLocker locker(&m_mutex);
#ifdef QT_SAMPLECACHE_DEBUG
qDebug() << "~QSample" << this << ": deleted [" << m_url << "]" << QThread::currentThread();
#endif
cleanup();
}
// Called in application thread
void QSample::loadIfNecessary()
{
QMutexLocker locker(&m_mutex);
if (m_state == QSample::Error || m_state == QSample::Creating) {
m_state = QSample::Loading;
QMetaObject::invokeMethod(this, "load", Qt::QueuedConnection);
} else {
qobject_cast<QSampleCache*>(m_parent)->loadingRelease();
}
}
// Called in both threads
bool QSampleCache::notifyUnreferencedSample(QSample* sample)
{
QMutexLocker locker(&m_mutex);
if (m_capacity > 0)
return false;
m_samples.remove(sample->m_url);
unloadSample(sample);
return true;
}
// Called in application threadd
void QSample::release()
{
QMutexLocker locker(&m_mutex);
#ifdef QT_SAMPLECACHE_DEBUG
qDebug() << "Sample:: release" << this << QThread::currentThread() << m_ref;
#endif
m_ref--;
if (m_ref == 0)
m_parent->notifyUnreferencedSample(this);
}
// Called in dtor and when stream is loaded
// must be called locked.
void QSample::cleanup()
{
if (m_waveDecoder)
m_waveDecoder->deleteLater();
if (m_stream)
m_stream->deleteLater();
m_waveDecoder = 0;
m_stream = 0;
}
// Called in application thread
void QSample::addRef()
{
m_ref++;
}
// Called in loading thread
void QSample::readSample()
{
Q_ASSERT(QThread::currentThread()->objectName() == QLatin1String("QSampleCache::LoadingThread"));
QMutexLocker m(&m_mutex);
#ifdef QT_SAMPLECACHE_DEBUG
qDebug() << "QSample: readSample";
#endif
qint64 read = m_waveDecoder->read(m_soundData.data() + m_sampleReadLength,
qMin(m_waveDecoder->bytesAvailable(),
qint64(m_waveDecoder->size() - m_sampleReadLength)));
if (read > 0)
m_sampleReadLength += read;
if (m_sampleReadLength < m_waveDecoder->size())
return;
Q_ASSERT(m_sampleReadLength == qint64(m_soundData.size()));
onReady();
}
// Called in loading thread
void QSample::decoderReady()
{
Q_ASSERT(QThread::currentThread()->objectName() == QLatin1String("QSampleCache::LoadingThread"));
QMutexLocker m(&m_mutex);
#ifdef QT_SAMPLECACHE_DEBUG
qDebug() << "QSample: decoder ready";
#endif
m_parent->refresh(m_waveDecoder->size());
m_soundData.resize(m_waveDecoder->size());
m_sampleReadLength = 0;
qint64 read = m_waveDecoder->read(m_soundData.data(), m_waveDecoder->size());
if (read > 0)
m_sampleReadLength += read;
if (m_sampleReadLength >= m_waveDecoder->size())
onReady();
}
// Called in all threads
QSample::State QSample::state() const
{
QMutexLocker m(&m_mutex);
return m_state;
}
// Called in loading thread
// Essentially a second ctor, doesn't need locks (?)
void QSample::load()
{
Q_ASSERT(QThread::currentThread()->objectName() == QLatin1String("QSampleCache::LoadingThread"));
#ifdef QT_SAMPLECACHE_DEBUG
qDebug() << "QSample: load [" << m_url << "]";
#endif
m_stream = m_parent->networkAccessManager().get(QNetworkRequest(m_url));
connect(m_stream, SIGNAL(error(QNetworkReply::NetworkError)), SLOT(decoderError()));
m_waveDecoder = new QWaveDecoder(m_stream);
connect(m_waveDecoder, SIGNAL(formatKnown()), SLOT(decoderReady()));
connect(m_waveDecoder, SIGNAL(parsingError()), SLOT(decoderError()));
connect(m_waveDecoder, SIGNAL(readyRead()), SLOT(readSample()));
}
// Called in loading thread
void QSample::decoderError()
{
Q_ASSERT(QThread::currentThread()->objectName() == QLatin1String("QSampleCache::LoadingThread"));
QMutexLocker m(&m_mutex);
#ifdef QT_SAMPLECACHE_DEBUG
qDebug() << "QSample: decoder error";
#endif
cleanup();
m_state = QSample::Error;
qobject_cast<QSampleCache*>(m_parent)->loadingRelease();
emit error();
}
// Called in loading thread from decoder when sample is done. Locked already.
void QSample::onReady()
{
Q_ASSERT(QThread::currentThread()->objectName() == QLatin1String("QSampleCache::LoadingThread"));
#ifdef QT_SAMPLECACHE_DEBUG
qDebug() << "QSample: load ready";
#endif
m_audioFormat = m_waveDecoder->audioFormat();
cleanup();
m_state = QSample::Ready;
qobject_cast<QSampleCache*>(m_parent)->loadingRelease();
emit ready();
}
// Called in application thread, then moved to loader thread
QSample::QSample(const QUrl& url, QSampleCache *parent)
: m_parent(parent)
, m_stream(0)
, m_waveDecoder(0)
, m_url(url)
, m_sampleReadLength(0)
, m_state(Creating)
, m_ref(0)
{
}
QT_END_NAMESPACE
#include "moc_qsamplecache_p.cpp"
<|endoftext|> |
<commit_before>//////////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2004-2020 musikcube team
//
// 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 other 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 "pch.hpp"
#include <musikcore/library/RemoteLibrary.h>
#include <musikcore/config.h>
#include <musikcore/support/Common.h>
#include <musikcore/support/Preferences.h>
#include <musikcore/support/PreferenceKeys.h>
#include <musikcore/library/Indexer.h>
#include <musikcore/library/IQuery.h>
#include <musikcore/library/LibraryFactory.h>
#include <musikcore/library/QueryRegistry.h>
#include <musikcore/runtime/Message.h>
#include <musikcore/debug.h>
#include <nlohmann/json.hpp>
static const std::string TAG = "RemoteLibrary";
using namespace musik::core;
using namespace musik::core::db;
using namespace musik::core::library;
using namespace musik::core::net;
using namespace musik::core::runtime;
#define MESSAGE_QUERY_COMPLETED 5000
#define MESSAGE_RECONNECT_SOCKET 5001
#define MESSAGE_UPDATE_CONNECTION_STATE 5002
class NullIndexer: public musik::core::IIndexer {
public:
virtual ~NullIndexer() override { }
virtual void AddPath(const std::string& path) override { }
virtual void RemovePath(const std::string& path) override { }
virtual void GetPaths(std::vector<std::string>& paths) override { }
virtual void Schedule(SyncType type) override { }
virtual void Stop() override { }
virtual State GetState() override { return StateIdle; }
} kNullIndexer;
class RemoteLibrary::QueryCompletedMessage: public Message {
public:
using QueryContextPtr = RemoteLibrary::QueryContextPtr;
QueryCompletedMessage(IMessageTarget* target, QueryContextPtr context)
: Message(target, MESSAGE_QUERY_COMPLETED, 0, 0) {
this->context = context;
}
virtual ~QueryCompletedMessage() {
}
QueryContextPtr GetContext() { return this->context; }
private:
QueryContextPtr context;
};
ILibraryPtr RemoteLibrary::Create(std::string name, int id) {
ILibraryPtr lib(new RemoteLibrary(name, id));
return lib;
}
RemoteLibrary::RemoteLibrary(std::string name, int id)
: name(name)
, id(id)
, exit(false)
, messageQueue(nullptr)
, wsc(this) {
this->identifier = std::to_string(id);
this->thread = new std::thread(std::bind(&RemoteLibrary::ThreadProc, this));
this->ReloadConnectionFromPreferences();
}
RemoteLibrary::~RemoteLibrary() {
this->Close();
if (this->messageQueue) {
this->messageQueue->Unregister(this);
}
}
int RemoteLibrary::Id() {
return this->id;
}
const std::string& RemoteLibrary::Name() {
return this->name;
}
void RemoteLibrary::Close() {
this->wsc.Disconnect();
std::thread* thread = nullptr;
{
std::unique_lock<std::recursive_mutex> lock(this->queueMutex);
if (this->thread) {
thread = this->thread;
this->thread = nullptr;
this->queryQueue.clear();
this->exit = true;
}
}
if (thread) {
this->queueCondition.notify_all();
this->syncQueryCondition.notify_all();
thread->join();
delete thread;
}
}
bool RemoteLibrary::IsConfigured() {
auto prefs = Preferences::ForComponent(core::prefs::components::Settings);
return prefs->GetBool(core::prefs::keys::RemoteLibraryViewed, false);
}
static inline bool isQueryDone(RemoteLibrary::Query query) {
switch (query->GetStatus()) {
case IQuery::Idle:
case IQuery::Running:
return false;
default:
return true;
}
}
bool RemoteLibrary::IsQueryInFlight(Query query) {
for (auto& kv : this->queriesInFlight) {
if (query == kv.second->query) {
return true;
}
}
return false;
}
int RemoteLibrary::Enqueue(QueryPtr query, unsigned int options, Callback callback) {
if (QueryRegistry::IsLocalOnlyQuery(query->Name())) {
auto defaultLocalLibrary = LibraryFactory::Instance().DefaultLocalLibrary();
return defaultLocalLibrary->Enqueue(query, options, callback);
}
auto serializableQuery = std::dynamic_pointer_cast<ISerializableQuery>(query);
if (serializableQuery) {
auto context = std::make_shared<QueryContext>();
context->query = serializableQuery;
context->callback = callback;
if (options & ILibrary::QuerySynchronous) {
this->RunQuery(context); /* false = do not notify via QueryCompleted */
std::unique_lock<std::recursive_mutex> lock(this->queueMutex);
while (
!this->exit &&
this->IsQueryInFlight(context->query) &&
!isQueryDone(context->query))
{
this->syncQueryCondition.wait(lock);
}
}
else {
std::unique_lock<std::recursive_mutex> lock(this->queueMutex);
if (this->exit) { return -1; }
queryQueue.push_back(context);
queueCondition.notify_all();
}
return query->GetId();
}
return -1;
}
RemoteLibrary::QueryContextPtr RemoteLibrary::GetNextQuery() {
std::unique_lock<std::recursive_mutex> lock(this->queueMutex);
while (!this->queryQueue.size() && !this->exit) {
this->queueCondition.wait(lock);
}
if (this->exit) {
return QueryContextPtr();
}
else {
auto front = queryQueue.front();
queryQueue.pop_front();
return front;
}
}
void RemoteLibrary::ThreadProc() {
while (!this->exit) {
auto query = GetNextQuery();
if (query) {
this->RunQuery(query);
}
}
}
void RemoteLibrary::NotifyQueryCompleted(QueryContextPtr context) {
this->QueryCompleted(context->query.get());
if (context->callback) {
context->callback(context->query);
}
}
void RemoteLibrary::OnQueryCompleted(QueryContextPtr context) {
if (context) {
if (this->messageQueue) {
this->messageQueue->Post(std::make_shared<QueryCompletedMessage>(this, context));
}
else {
this->NotifyQueryCompleted(context);
}
}
}
void RemoteLibrary::OnQueryCompleted(const std::string& messageId, Query query) {
QueryContextPtr context;
{
std::unique_lock<std::recursive_mutex> lock(this->queueMutex);
context = queriesInFlight[messageId];
queriesInFlight.erase(messageId);
}
if (context) {
this->OnQueryCompleted(context);
}
this->syncQueryCondition.notify_all();
}
void RemoteLibrary::RunQuery(QueryContextPtr context) {
#if 0
this->RunQueryOnLoopback(context);
#else
this->RunQueryOnWebSocketClient(context);
#endif
}
void RemoteLibrary::RunQueryOnLoopback(QueryContextPtr context) {
if (context) {
/* do everything via loopback to the local library for testing. we do, however,
go through the motions by serializing the inbound query to a string, then
bouncing through the QueryRegister to create a new instance, run the query
locally, serialize the result, then deserialize it again to emulate the entire
flow. */
auto localLibrary = LibraryFactory::Instance().DefaultLocalLibrary();
localLibrary->SetMessageQueue(*this->messageQueue);
auto localQuery = QueryRegistry::CreateLocalQueryFor(
context->query->Name(), context->query->SerializeQuery(), localLibrary);
if (!localQuery) {
OnQueryCompleted(context);
return;
}
localLibrary->Enqueue(
localQuery,
ILibrary::QuerySynchronous, /* CAL TODO: make async! we have to make TrackList support async lookup first tho. */
[this, context, localQuery](auto result) {
if (localQuery->GetStatus() == IQuery::Finished) {
context->query->DeserializeResult(localQuery->SerializeResult());
}
this->OnQueryCompleted(context);
});
}
}
void RemoteLibrary::RunQueryOnWebSocketClient(QueryContextPtr context) {
if (context->query) {
std::unique_lock<std::recursive_mutex> lock(this->queueMutex);
const std::string messageId = wsc.EnqueueQuery(context->query);
if (messageId.size()) {
queriesInFlight[messageId] = context;
}
}
}
void RemoteLibrary::SetMessageQueue(musik::core::runtime::IMessageQueue& queue) {
if (this->messageQueue && this->messageQueue != &queue) {
this->messageQueue->Unregister(this);
}
this->messageQueue = &queue;
this->messageQueue->Register(this);
}
musik::core::IIndexer* RemoteLibrary::Indexer() {
return &kNullIndexer;
}
/* IMessageTarget */
void RemoteLibrary::ProcessMessage(musik::core::runtime::IMessage &message) {
if (message.Type() == MESSAGE_QUERY_COMPLETED) {
auto context = static_cast<QueryCompletedMessage*>(&message)->GetContext();
this->NotifyQueryCompleted(context);
}
else if (message.Type() == MESSAGE_RECONNECT_SOCKET) {
if (this->wsc.ConnectionState() == Client::State::Disconnected) {
this->ReloadConnectionFromPreferences();
}
}
else if (message.Type() == MESSAGE_UPDATE_CONNECTION_STATE) {
auto updatedState = (ConnectionState)message.UserData1();
this->connectionState = updatedState;
this->ConnectionStateChanged(this->connectionState);
}
}
/* WebSocketClient::Listener */
void RemoteLibrary::OnClientInvalidPassword(Client* client) {
this->messageQueue->Post(Message::Create(this, MESSAGE_UPDATE_CONNECTION_STATE, (int) ConnectionState::AuthenticationFailure));
}
void RemoteLibrary::OnClientStateChanged(Client* client, State newState, State oldState) {
static std::map<State, ConnectionState> kConnectionStateMap = {
{ State::Disconnected, ConnectionState::Disconnected },
{ State::Disconnecting, ConnectionState::Disconnected },
{ State::Connecting, ConnectionState::Connecting },
{ State::Connected, ConnectionState::Connected },
};
if (this->messageQueue) {
const auto reason = this->wsc.LastConnectionError();
bool attemptReconnect =
newState == State::Disconnected &&
reason != WebSocketClient::ConnectionError::InvalidPassword &&
reason != WebSocketClient::ConnectionError::IncompatibleVersion;
if (attemptReconnect) {
this->messageQueue->Remove(this, MESSAGE_RECONNECT_SOCKET);
this->messageQueue->Post(Message::Create(this, MESSAGE_RECONNECT_SOCKET), 2500);
}
this->messageQueue->Post(Message::Create(
this,
MESSAGE_UPDATE_CONNECTION_STATE,
(int) kConnectionStateMap[newState]));
}
}
void RemoteLibrary::OnClientQuerySucceeded(Client* client, const std::string& messageId, Query query) {
this->OnQueryCompleted(messageId, query);
}
void RemoteLibrary::OnClientQueryFailed(Client* client, const std::string& messageId, Query query, Client::QueryError result) {
this->OnQueryCompleted(messageId, query);
}
/* RemoteLibrary::RemoteResourceLocator */
std::string RemoteLibrary::GetTrackUri(musik::core::sdk::ITrack* track, const std::string& defaultUri) {
std::string type = ".mp3";
char buffer[4096];
buffer[0] = 0;
int size = track->Uri(buffer, sizeof(buffer));
if (size) {
std::string originalUri = buffer;
std::string::size_type lastDot = originalUri.find_last_of(".");
if (lastDot != std::string::npos) {
type = originalUri.substr(lastDot).c_str();
}
}
auto prefs = Preferences::ForComponent(core::prefs::components::Settings);
auto host = prefs->GetString(core::prefs::keys::RemoteLibraryHostname, "127.0.0.1");
auto port = (short) prefs->GetInt(core::prefs::keys::RemoteLibraryHttpPort, 7905);
auto password = prefs->GetString(core::prefs::keys::RemoteLibraryPassword, "");
const std::string uri = "http://" + host + ":" + std::to_string(port) + "/audio/id/" + std::to_string(track->GetId());
nlohmann::json path = {
{ "uri", uri },
{ "originalUri", std::string(buffer) },
{ "type", type },
{ "password", password }
};
return "musikcore://remote-track/" + path.dump();
}
/* RemoteLibrary */
const net::WebSocketClient& RemoteLibrary::WebSocketClient() const {
return this->wsc;
}
void RemoteLibrary::ReloadConnectionFromPreferences() {
auto prefs = Preferences::ForComponent(core::prefs::components::Settings);
auto host = prefs->GetString(core::prefs::keys::RemoteLibraryHostname, "127.0.0.1");
auto port = (short) prefs->GetInt(core::prefs::keys::RemoteLibraryWssPort, 7905);
auto password = prefs->GetString(core::prefs::keys::RemoteLibraryPassword, "");
this->wsc.Connect(host, port, password);
}<commit_msg>Removed unnecessary comment.<commit_after>//////////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2004-2020 musikcube team
//
// 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 other 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 "pch.hpp"
#include <musikcore/library/RemoteLibrary.h>
#include <musikcore/config.h>
#include <musikcore/support/Common.h>
#include <musikcore/support/Preferences.h>
#include <musikcore/support/PreferenceKeys.h>
#include <musikcore/library/Indexer.h>
#include <musikcore/library/IQuery.h>
#include <musikcore/library/LibraryFactory.h>
#include <musikcore/library/QueryRegistry.h>
#include <musikcore/runtime/Message.h>
#include <musikcore/debug.h>
#include <nlohmann/json.hpp>
static const std::string TAG = "RemoteLibrary";
using namespace musik::core;
using namespace musik::core::db;
using namespace musik::core::library;
using namespace musik::core::net;
using namespace musik::core::runtime;
#define MESSAGE_QUERY_COMPLETED 5000
#define MESSAGE_RECONNECT_SOCKET 5001
#define MESSAGE_UPDATE_CONNECTION_STATE 5002
class NullIndexer: public musik::core::IIndexer {
public:
virtual ~NullIndexer() override { }
virtual void AddPath(const std::string& path) override { }
virtual void RemovePath(const std::string& path) override { }
virtual void GetPaths(std::vector<std::string>& paths) override { }
virtual void Schedule(SyncType type) override { }
virtual void Stop() override { }
virtual State GetState() override { return StateIdle; }
} kNullIndexer;
class RemoteLibrary::QueryCompletedMessage: public Message {
public:
using QueryContextPtr = RemoteLibrary::QueryContextPtr;
QueryCompletedMessage(IMessageTarget* target, QueryContextPtr context)
: Message(target, MESSAGE_QUERY_COMPLETED, 0, 0) {
this->context = context;
}
virtual ~QueryCompletedMessage() {
}
QueryContextPtr GetContext() { return this->context; }
private:
QueryContextPtr context;
};
ILibraryPtr RemoteLibrary::Create(std::string name, int id) {
ILibraryPtr lib(new RemoteLibrary(name, id));
return lib;
}
RemoteLibrary::RemoteLibrary(std::string name, int id)
: name(name)
, id(id)
, exit(false)
, messageQueue(nullptr)
, wsc(this) {
this->identifier = std::to_string(id);
this->thread = new std::thread(std::bind(&RemoteLibrary::ThreadProc, this));
this->ReloadConnectionFromPreferences();
}
RemoteLibrary::~RemoteLibrary() {
this->Close();
if (this->messageQueue) {
this->messageQueue->Unregister(this);
}
}
int RemoteLibrary::Id() {
return this->id;
}
const std::string& RemoteLibrary::Name() {
return this->name;
}
void RemoteLibrary::Close() {
this->wsc.Disconnect();
std::thread* thread = nullptr;
{
std::unique_lock<std::recursive_mutex> lock(this->queueMutex);
if (this->thread) {
thread = this->thread;
this->thread = nullptr;
this->queryQueue.clear();
this->exit = true;
}
}
if (thread) {
this->queueCondition.notify_all();
this->syncQueryCondition.notify_all();
thread->join();
delete thread;
}
}
bool RemoteLibrary::IsConfigured() {
auto prefs = Preferences::ForComponent(core::prefs::components::Settings);
return prefs->GetBool(core::prefs::keys::RemoteLibraryViewed, false);
}
static inline bool isQueryDone(RemoteLibrary::Query query) {
switch (query->GetStatus()) {
case IQuery::Idle:
case IQuery::Running:
return false;
default:
return true;
}
}
bool RemoteLibrary::IsQueryInFlight(Query query) {
for (auto& kv : this->queriesInFlight) {
if (query == kv.second->query) {
return true;
}
}
return false;
}
int RemoteLibrary::Enqueue(QueryPtr query, unsigned int options, Callback callback) {
if (QueryRegistry::IsLocalOnlyQuery(query->Name())) {
auto defaultLocalLibrary = LibraryFactory::Instance().DefaultLocalLibrary();
return defaultLocalLibrary->Enqueue(query, options, callback);
}
auto serializableQuery = std::dynamic_pointer_cast<ISerializableQuery>(query);
if (serializableQuery) {
auto context = std::make_shared<QueryContext>();
context->query = serializableQuery;
context->callback = callback;
if (options & ILibrary::QuerySynchronous) {
this->RunQuery(context);
std::unique_lock<std::recursive_mutex> lock(this->queueMutex);
while (
!this->exit &&
this->IsQueryInFlight(context->query) &&
!isQueryDone(context->query))
{
this->syncQueryCondition.wait(lock);
}
}
else {
std::unique_lock<std::recursive_mutex> lock(this->queueMutex);
if (this->exit) { return -1; }
queryQueue.push_back(context);
queueCondition.notify_all();
}
return query->GetId();
}
return -1;
}
RemoteLibrary::QueryContextPtr RemoteLibrary::GetNextQuery() {
std::unique_lock<std::recursive_mutex> lock(this->queueMutex);
while (!this->queryQueue.size() && !this->exit) {
this->queueCondition.wait(lock);
}
if (this->exit) {
return QueryContextPtr();
}
else {
auto front = queryQueue.front();
queryQueue.pop_front();
return front;
}
}
void RemoteLibrary::ThreadProc() {
while (!this->exit) {
auto query = GetNextQuery();
if (query) {
this->RunQuery(query);
}
}
}
void RemoteLibrary::NotifyQueryCompleted(QueryContextPtr context) {
this->QueryCompleted(context->query.get());
if (context->callback) {
context->callback(context->query);
}
}
void RemoteLibrary::OnQueryCompleted(QueryContextPtr context) {
if (context) {
if (this->messageQueue) {
this->messageQueue->Post(std::make_shared<QueryCompletedMessage>(this, context));
}
else {
this->NotifyQueryCompleted(context);
}
}
}
void RemoteLibrary::OnQueryCompleted(const std::string& messageId, Query query) {
QueryContextPtr context;
{
std::unique_lock<std::recursive_mutex> lock(this->queueMutex);
context = queriesInFlight[messageId];
queriesInFlight.erase(messageId);
}
if (context) {
this->OnQueryCompleted(context);
}
this->syncQueryCondition.notify_all();
}
void RemoteLibrary::RunQuery(QueryContextPtr context) {
#if 0
this->RunQueryOnLoopback(context);
#else
this->RunQueryOnWebSocketClient(context);
#endif
}
void RemoteLibrary::RunQueryOnLoopback(QueryContextPtr context) {
if (context) {
/* do everything via loopback to the local library for testing. we do, however,
go through the motions by serializing the inbound query to a string, then
bouncing through the QueryRegister to create a new instance, run the query
locally, serialize the result, then deserialize it again to emulate the entire
flow. */
auto localLibrary = LibraryFactory::Instance().DefaultLocalLibrary();
localLibrary->SetMessageQueue(*this->messageQueue);
auto localQuery = QueryRegistry::CreateLocalQueryFor(
context->query->Name(), context->query->SerializeQuery(), localLibrary);
if (!localQuery) {
OnQueryCompleted(context);
return;
}
localLibrary->Enqueue(
localQuery,
ILibrary::QuerySynchronous, /* CAL TODO: make async! we have to make TrackList support async lookup first tho. */
[this, context, localQuery](auto result) {
if (localQuery->GetStatus() == IQuery::Finished) {
context->query->DeserializeResult(localQuery->SerializeResult());
}
this->OnQueryCompleted(context);
});
}
}
void RemoteLibrary::RunQueryOnWebSocketClient(QueryContextPtr context) {
if (context->query) {
std::unique_lock<std::recursive_mutex> lock(this->queueMutex);
const std::string messageId = wsc.EnqueueQuery(context->query);
if (messageId.size()) {
queriesInFlight[messageId] = context;
}
}
}
void RemoteLibrary::SetMessageQueue(musik::core::runtime::IMessageQueue& queue) {
if (this->messageQueue && this->messageQueue != &queue) {
this->messageQueue->Unregister(this);
}
this->messageQueue = &queue;
this->messageQueue->Register(this);
}
musik::core::IIndexer* RemoteLibrary::Indexer() {
return &kNullIndexer;
}
/* IMessageTarget */
void RemoteLibrary::ProcessMessage(musik::core::runtime::IMessage &message) {
if (message.Type() == MESSAGE_QUERY_COMPLETED) {
auto context = static_cast<QueryCompletedMessage*>(&message)->GetContext();
this->NotifyQueryCompleted(context);
}
else if (message.Type() == MESSAGE_RECONNECT_SOCKET) {
if (this->wsc.ConnectionState() == Client::State::Disconnected) {
this->ReloadConnectionFromPreferences();
}
}
else if (message.Type() == MESSAGE_UPDATE_CONNECTION_STATE) {
auto updatedState = (ConnectionState)message.UserData1();
this->connectionState = updatedState;
this->ConnectionStateChanged(this->connectionState);
}
}
/* WebSocketClient::Listener */
void RemoteLibrary::OnClientInvalidPassword(Client* client) {
this->messageQueue->Post(Message::Create(this, MESSAGE_UPDATE_CONNECTION_STATE, (int) ConnectionState::AuthenticationFailure));
}
void RemoteLibrary::OnClientStateChanged(Client* client, State newState, State oldState) {
static std::map<State, ConnectionState> kConnectionStateMap = {
{ State::Disconnected, ConnectionState::Disconnected },
{ State::Disconnecting, ConnectionState::Disconnected },
{ State::Connecting, ConnectionState::Connecting },
{ State::Connected, ConnectionState::Connected },
};
if (this->messageQueue) {
const auto reason = this->wsc.LastConnectionError();
bool attemptReconnect =
newState == State::Disconnected &&
reason != WebSocketClient::ConnectionError::InvalidPassword &&
reason != WebSocketClient::ConnectionError::IncompatibleVersion;
if (attemptReconnect) {
this->messageQueue->Remove(this, MESSAGE_RECONNECT_SOCKET);
this->messageQueue->Post(Message::Create(this, MESSAGE_RECONNECT_SOCKET), 2500);
}
this->messageQueue->Post(Message::Create(
this,
MESSAGE_UPDATE_CONNECTION_STATE,
(int) kConnectionStateMap[newState]));
}
}
void RemoteLibrary::OnClientQuerySucceeded(Client* client, const std::string& messageId, Query query) {
this->OnQueryCompleted(messageId, query);
}
void RemoteLibrary::OnClientQueryFailed(Client* client, const std::string& messageId, Query query, Client::QueryError result) {
this->OnQueryCompleted(messageId, query);
}
/* RemoteLibrary::RemoteResourceLocator */
std::string RemoteLibrary::GetTrackUri(musik::core::sdk::ITrack* track, const std::string& defaultUri) {
std::string type = ".mp3";
char buffer[4096];
buffer[0] = 0;
int size = track->Uri(buffer, sizeof(buffer));
if (size) {
std::string originalUri = buffer;
std::string::size_type lastDot = originalUri.find_last_of(".");
if (lastDot != std::string::npos) {
type = originalUri.substr(lastDot).c_str();
}
}
auto prefs = Preferences::ForComponent(core::prefs::components::Settings);
auto host = prefs->GetString(core::prefs::keys::RemoteLibraryHostname, "127.0.0.1");
auto port = (short) prefs->GetInt(core::prefs::keys::RemoteLibraryHttpPort, 7905);
auto password = prefs->GetString(core::prefs::keys::RemoteLibraryPassword, "");
const std::string uri = "http://" + host + ":" + std::to_string(port) + "/audio/id/" + std::to_string(track->GetId());
nlohmann::json path = {
{ "uri", uri },
{ "originalUri", std::string(buffer) },
{ "type", type },
{ "password", password }
};
return "musikcore://remote-track/" + path.dump();
}
/* RemoteLibrary */
const net::WebSocketClient& RemoteLibrary::WebSocketClient() const {
return this->wsc;
}
void RemoteLibrary::ReloadConnectionFromPreferences() {
auto prefs = Preferences::ForComponent(core::prefs::components::Settings);
auto host = prefs->GetString(core::prefs::keys::RemoteLibraryHostname, "127.0.0.1");
auto port = (short) prefs->GetInt(core::prefs::keys::RemoteLibraryWssPort, 7905);
auto password = prefs->GetString(core::prefs::keys::RemoteLibraryPassword, "");
this->wsc.Connect(host, port, password);
}<|endoftext|> |
<commit_before>#include <catch.hpp>
#ifndef WX_PRECOMP
#include "wx/app.h"
#include "wx/sizer.h"
#include "wx/uiaction.h"
#endif // WX_PRECOMP
#include <iostream>
#include <tuple>
#include "testableframe.h"
#include "OptionsGroup/Field.hpp"
#include "ConfigBase.hpp"
#include "Point.hpp"
using namespace std::string_literals;
SCENARIO( "UI_Point: default values from options and basic accessor methods") {
wxTestableFrame* old = dynamic_cast<wxTestableFrame*>(wxTheApp->GetTopWindow());
old->Destroy();
wxTheApp->SetTopWindow(new wxTestableFrame());
wxUIActionSimulator sim;
wxMilliSleep(500);
GIVEN( "A UI point method and a X,Y coordinate (3.2, 10.2) as the default_value") {
auto simple_option {ConfigOptionDef()};
auto* default_point {new ConfigOptionPoint(Pointf(3.2, 10.2))};
simple_option.default_value = default_point;
auto test_field {Slic3r::GUI::UI_Point(wxTheApp->GetTopWindow(), simple_option)};
THEN( "get_string() returns '3.2;10.2'.") {
REQUIRE(test_field.get_string() == "3.2;10.2"s);
}
THEN( "get_point() yields a Pointf structure with x = 3.2, y = 10.2") {
REQUIRE(test_field.get_point().x == 3.2);
REQUIRE(test_field.get_point().y == 10.2);
}
}
GIVEN( "A UI point method and a tooltip in simple_option") {
auto simple_option {ConfigOptionDef()};
auto* default_point {new ConfigOptionPoint(Pointf(3.2, 10.2))};
simple_option.default_value = default_point;
auto test_field {Slic3r::GUI::UI_Point(wxTheApp->GetTopWindow(), simple_option)};
THEN( "Tooltip for both labels and textctrls matches simple_option") {
REQUIRE(test_field.ctrl_x()->GetToolTipText().ToStdString() == simple_option.tooltip );
REQUIRE(test_field.lbl_x()->GetToolTipText().ToStdString() == simple_option.tooltip );
REQUIRE(test_field.ctrl_y()->GetToolTipText().ToStdString() == simple_option.tooltip );
REQUIRE(test_field.lbl_y()->GetToolTipText().ToStdString() == simple_option.tooltip );
}
THEN( "get_point() yields a Pointf structure with x = 3.2, y = 10.2") {
REQUIRE(test_field.get_point().x == 3.2);
REQUIRE(test_field.get_point().y == 10.2);
}
}
}
SCENARIO( "UI_Point: set_value works with several types of inputs") {
wxTestableFrame* old = dynamic_cast<wxTestableFrame*>(wxTheApp->GetTopWindow());
old->Destroy();
wxTheApp->SetTopWindow(new wxTestableFrame());
wxUIActionSimulator sim;
wxMilliSleep(500);
GIVEN( "A UI point method with no default value.") {
auto simple_option {ConfigOptionDef()};
auto test_field {Slic3r::GUI::UI_Point(wxTheApp->GetTopWindow(), simple_option)};
WHEN( "set_value is called with a Pointf(19.0, 2.1)") {
test_field.set_value(Pointf(19.0, 2.1));
THEN( "get_point() returns a Pointf(19.0, 2.1)") {
REQUIRE(test_field.get_point() == Pointf(19.0, 2.1));
}
THEN( "get_string() returns '19.0;2.1'") {
REQUIRE(test_field.get_string() == "19.0;2.1"s);
}
THEN( "X TextCtrl contains X coordinate") {
REQUIRE(test_field.ctrl_x()->GetValue() == wxString("19.0"s));
}
THEN( "Y TextCtrl contains Y coordinate") {
REQUIRE(test_field.ctrl_y()->GetValue() == wxString("2.1"s));
}
}
WHEN( "set_value is called with a Pointf3(19.0, 2.1, 0.2)") {
test_field.set_value(Pointf3(19.0, 2.1, 0.2));
THEN( "get_point() returns a Pointf(19.0, 2.1)") {
REQUIRE(test_field.get_point() == Pointf(19.0, 2.1));
}
THEN( "get_point() returns a Pointf(19.0, 2.1)") {
REQUIRE(test_field.get_point3() == Pointf3(19.0, 2.1, 0.0));
}
THEN( "get_string() returns '19.0;2.1'") {
REQUIRE(test_field.get_string() == "19.0;2.1"s);
}
THEN( "X TextCtrl contains X coordinate") {
REQUIRE(test_field.ctrl_x()->GetValue() == wxString("19.0"s));
}
THEN( "Y TextCtrl contains Y coordinate") {
REQUIRE(test_field.ctrl_y()->GetValue() == wxString("2.1"s));
}
}
WHEN( "set_value is called with a string of the form '30.9;211.2'") {
test_field.set_value("30.9;211.2"s);
THEN( "get_point() returns a Pointf(30.9, 211.2)") {
REQUIRE(test_field.get_point() == Pointf(30.9, 211.2));
}
THEN( "get_string() returns '30.9;211.2'") {
REQUIRE(test_field.get_string() == "30.9;211.2"s);
}
THEN( "X TextCtrl contains X coordinate") {
REQUIRE(test_field.ctrl_x()->GetValue() == wxString("30.9"s));
}
THEN( "Y TextCtrl contains Y coordinate") {
REQUIRE(test_field.ctrl_y()->GetValue() == wxString("211.2"s));
}
}
WHEN( "set_value is called with a wxString of the form '30.9;211.2'") {
test_field.set_value(wxString("30.9;211.2"s));
THEN( "get_point() returns a Pointf(30.9, 211.2)") {
REQUIRE(test_field.get_point() == Pointf(30.9, 211.2));
}
THEN( "get_string() returns '30.9;211.2'") {
REQUIRE(test_field.get_string() == "30.9;211.2"s);
}
THEN( "X TextCtrl contains X coordinate") {
REQUIRE(test_field.ctrl_x()->GetValue() == wxString("30.9"s));
}
THEN( "Y TextCtrl contains Y coordinate") {
REQUIRE(test_field.ctrl_y()->GetValue() == wxString("211.2"s));
}
}
}
}
SCENARIO( "UI_Point: Event responses") {
wxTestableFrame* old = dynamic_cast<wxTestableFrame*>(wxTheApp->GetTopWindow());
old->Destroy();
wxTheApp->SetTopWindow(new wxTestableFrame());
wxMilliSleep(250);
GIVEN ( "A UI_Point with no default value and a registered on_change method that increments a counter.") {
auto simple_option {ConfigOptionDef()};
auto test_field {Slic3r::GUI::UI_Point(wxTheApp->GetTopWindow(), simple_option)};
auto event_count {0};
auto changefunc {[&event_count] (const std::string& opt_id, std::tuple<std::string, std::string> value) { event_count++; }};
auto killfunc {[&event_count](const std::string& opt_id) { event_count++; }};
test_field.on_change = changefunc;
test_field.on_kill_focus = killfunc;
test_field.disable_change_event = false;
WHEN( "kill focus event is received on X") {
event_count = 0;
auto ev {wxFocusEvent(wxEVT_KILL_FOCUS, test_field.ctrl_x()->GetId())};
ev.SetEventObject(test_field.ctrl_x());
test_field.ctrl_x()->ProcessWindowEvent(ev);
THEN( "on_kill_focus is executed.") {
REQUIRE(event_count == 2);
}
}
WHEN( "kill focus event is received on Y") {
event_count = 0;
auto ev {wxFocusEvent(wxEVT_KILL_FOCUS, test_field.ctrl_y()->GetId())};
ev.SetEventObject(test_field.ctrl_y());
test_field.ctrl_y()->ProcessWindowEvent(ev);
THEN( "on_kill_focus is executed.") {
REQUIRE(event_count == 2);
}
}
WHEN( "enter key pressed event is received on X") {
event_count = 0;
auto ev {wxCommandEvent(wxEVT_TEXT_ENTER, test_field.ctrl_x()->GetId())};
ev.SetEventObject(test_field.ctrl_x());
test_field.ctrl_x()->ProcessWindowEvent(ev);
THEN( "on_change is executed.") {
REQUIRE(event_count == 1);
}
}
WHEN( "enter key pressed event is received on Y") {
event_count = 0;
auto ev {wxCommandEvent(wxEVT_TEXT_ENTER, test_field.ctrl_y()->GetId())};
ev.SetEventObject(test_field.ctrl_y());
test_field.ctrl_y()->ProcessWindowEvent(ev);
THEN( "on_change is executed.") {
REQUIRE(event_count == 1);
}
}
}
GIVEN ( "A UI_Point with no default value and a registered on_change method that increments a counter only when disable_change_event = false.") {
auto simple_option {ConfigOptionDef()};
auto test_field {Slic3r::GUI::UI_Point(wxTheApp->GetTopWindow(), simple_option)};
auto event_count {0};
auto changefunc {[&event_count] (const std::string& opt_id, std::tuple<std::string, std::string> value) { event_count++; }};
auto killfunc {[&event_count](const std::string& opt_id) { event_count += 1; }};
test_field.on_change = changefunc;
test_field.on_kill_focus = killfunc;
test_field.disable_change_event = true;
WHEN( "kill focus event is received on X") {
event_count = 0;
auto ev {wxFocusEvent(wxEVT_KILL_FOCUS, test_field.ctrl_x()->GetId())};
ev.SetEventObject(test_field.ctrl_x());
test_field.ctrl_x()->ProcessWindowEvent(ev);
THEN( "on_kill_focus is executed.") {
REQUIRE(event_count == 1);
}
}
WHEN( "kill focus event is received on Y") {
event_count = 0;
auto ev {wxFocusEvent(wxEVT_KILL_FOCUS, test_field.ctrl_y()->GetId())};
ev.SetEventObject(test_field.ctrl_y());
test_field.ctrl_y()->ProcessWindowEvent(ev);
THEN( "on_kill_focus is executed.") {
REQUIRE(event_count == 1);
}
}
WHEN( "enter key pressed event is received on X") {
event_count = 0;
auto ev {wxCommandEvent(wxEVT_TEXT_ENTER, test_field.ctrl_x()->GetId())};
ev.SetEventObject(test_field.ctrl_x());
test_field.ctrl_x()->ProcessWindowEvent(ev);
THEN( "on_change is not executed.") {
REQUIRE(event_count == 0);
}
}
WHEN( "enter key pressed event is received on Y") {
event_count = 0;
auto ev {wxCommandEvent(wxEVT_TEXT_ENTER, test_field.ctrl_y()->GetId())};
ev.SetEventObject(test_field.ctrl_y());
test_field.ctrl_y()->ProcessWindowEvent(ev);
THEN( "on_change is not executed.") {
REQUIRE(event_count == 0);
}
}
}
}
SCENARIO( "UI_Point: Enable/Disable") {
wxTestableFrame* old = dynamic_cast<wxTestableFrame*>(wxTheApp->GetTopWindow());
old->Destroy();
wxTheApp->SetTopWindow(new wxTestableFrame());
wxMilliSleep(250);
GIVEN ( "A UI_Point with no default value.") {
auto simple_option {ConfigOptionDef()};
auto test_field {Slic3r::GUI::UI_Point(wxTheApp->GetTopWindow(), simple_option)};
WHEN( "disable() is called") {
test_field.disable();
THEN( "IsEnabled == False for X and Y textctrls") {
REQUIRE(test_field.ctrl_x()->IsEnabled() == false);
REQUIRE(test_field.ctrl_y()->IsEnabled() == false);
}
}
WHEN( "enable() is called") {
test_field.enable();
THEN( "IsEnabled == True for X and Y textctrls") {
REQUIRE(test_field.ctrl_x()->IsEnabled() == true);
REQUIRE(test_field.ctrl_y()->IsEnabled() == true);
}
}
WHEN( "toggle() is called with false argument") {
test_field.toggle(false);
THEN( "IsEnabled == False for X and Y textctrls") {
REQUIRE(test_field.ctrl_x()->IsEnabled() == false);
REQUIRE(test_field.ctrl_y()->IsEnabled() == false);
}
}
WHEN( "toggle() is called with true argument") {
test_field.toggle(true);
THEN( "IsEnabled == True for X and Y textctrls") {
REQUIRE(test_field.ctrl_x()->IsEnabled() == true);
REQUIRE(test_field.ctrl_y()->IsEnabled() == true);
}
}
}
}
SCENARIO( "UI_Point: get_sizer()") {
wxTestableFrame* old = dynamic_cast<wxTestableFrame*>(wxTheApp->GetTopWindow());
old->Destroy();
wxTheApp->SetTopWindow(new wxTestableFrame());
wxMilliSleep(250);
GIVEN ( "A UI_Point with no default value.") {
auto simple_option {ConfigOptionDef()};
auto test_field {Slic3r::GUI::UI_Point(wxTheApp->GetTopWindow(), simple_option)};
WHEN( "get_sizer() is called") {
THEN( "get_sizer() returns a wxSizer that has 4 direct children in it that are Windows.") {
REQUIRE(test_field.get_sizer()->GetItemCount() == 4);
auto tmp {test_field.get_sizer()->GetChildren().begin()};
REQUIRE((*tmp)->IsWindow() == true);
tmp++;
REQUIRE((*tmp)->IsWindow() == true);
tmp++;
REQUIRE((*tmp)->IsWindow() == true);
tmp++;
REQUIRE((*tmp)->IsWindow() == true);
}
}
}
}
<commit_msg>Fix a typo in description.<commit_after>#include <catch.hpp>
#ifndef WX_PRECOMP
#include "wx/app.h"
#include "wx/sizer.h"
#include "wx/uiaction.h"
#endif // WX_PRECOMP
#include <iostream>
#include <tuple>
#include "testableframe.h"
#include "OptionsGroup/Field.hpp"
#include "ConfigBase.hpp"
#include "Point.hpp"
using namespace std::string_literals;
SCENARIO( "UI_Point: default values from options and basic accessor methods") {
wxTestableFrame* old = dynamic_cast<wxTestableFrame*>(wxTheApp->GetTopWindow());
old->Destroy();
wxTheApp->SetTopWindow(new wxTestableFrame());
wxUIActionSimulator sim;
wxMilliSleep(500);
GIVEN( "A UI point method and a X,Y coordinate (3.2, 10.2) as the default_value") {
auto simple_option {ConfigOptionDef()};
auto* default_point {new ConfigOptionPoint(Pointf(3.2, 10.2))};
simple_option.default_value = default_point;
auto test_field {Slic3r::GUI::UI_Point(wxTheApp->GetTopWindow(), simple_option)};
THEN( "get_string() returns '3.2;10.2'.") {
REQUIRE(test_field.get_string() == "3.2;10.2"s);
}
THEN( "get_point() yields a Pointf structure with x = 3.2, y = 10.2") {
REQUIRE(test_field.get_point().x == 3.2);
REQUIRE(test_field.get_point().y == 10.2);
}
}
GIVEN( "A UI point method and a tooltip in simple_option") {
auto simple_option {ConfigOptionDef()};
auto* default_point {new ConfigOptionPoint(Pointf(3.2, 10.2))};
simple_option.default_value = default_point;
auto test_field {Slic3r::GUI::UI_Point(wxTheApp->GetTopWindow(), simple_option)};
THEN( "Tooltip for both labels and textctrls matches simple_option") {
REQUIRE(test_field.ctrl_x()->GetToolTipText().ToStdString() == simple_option.tooltip );
REQUIRE(test_field.lbl_x()->GetToolTipText().ToStdString() == simple_option.tooltip );
REQUIRE(test_field.ctrl_y()->GetToolTipText().ToStdString() == simple_option.tooltip );
REQUIRE(test_field.lbl_y()->GetToolTipText().ToStdString() == simple_option.tooltip );
}
THEN( "get_point() yields a Pointf structure with x = 3.2, y = 10.2") {
REQUIRE(test_field.get_point().x == 3.2);
REQUIRE(test_field.get_point().y == 10.2);
}
}
}
SCENARIO( "UI_Point: set_value works with several types of inputs") {
wxTestableFrame* old = dynamic_cast<wxTestableFrame*>(wxTheApp->GetTopWindow());
old->Destroy();
wxTheApp->SetTopWindow(new wxTestableFrame());
wxUIActionSimulator sim;
wxMilliSleep(500);
GIVEN( "A UI point method with no default value.") {
auto simple_option {ConfigOptionDef()};
auto test_field {Slic3r::GUI::UI_Point(wxTheApp->GetTopWindow(), simple_option)};
WHEN( "set_value is called with a Pointf(19.0, 2.1)") {
test_field.set_value(Pointf(19.0, 2.1));
THEN( "get_point() returns a Pointf(19.0, 2.1)") {
REQUIRE(test_field.get_point() == Pointf(19.0, 2.1));
}
THEN( "get_string() returns '19.0;2.1'") {
REQUIRE(test_field.get_string() == "19.0;2.1"s);
}
THEN( "X TextCtrl contains X coordinate") {
REQUIRE(test_field.ctrl_x()->GetValue() == wxString("19.0"s));
}
THEN( "Y TextCtrl contains Y coordinate") {
REQUIRE(test_field.ctrl_y()->GetValue() == wxString("2.1"s));
}
}
WHEN( "set_value is called with a Pointf3(19.0, 2.1, 0.2)") {
test_field.set_value(Pointf3(19.0, 2.1, 0.2));
THEN( "get_point() returns a Pointf(19.0, 2.1)") {
REQUIRE(test_field.get_point() == Pointf(19.0, 2.1));
}
THEN( "get_point3() returns a Pointf3(19.0, 2.1, 0.0)") {
REQUIRE(test_field.get_point3() == Pointf3(19.0, 2.1, 0.0));
}
THEN( "get_string() returns '19.0;2.1'") {
REQUIRE(test_field.get_string() == "19.0;2.1"s);
}
THEN( "X TextCtrl contains X coordinate") {
REQUIRE(test_field.ctrl_x()->GetValue() == wxString("19.0"s));
}
THEN( "Y TextCtrl contains Y coordinate") {
REQUIRE(test_field.ctrl_y()->GetValue() == wxString("2.1"s));
}
}
WHEN( "set_value is called with a string of the form '30.9;211.2'") {
test_field.set_value("30.9;211.2"s);
THEN( "get_point() returns a Pointf(30.9, 211.2)") {
REQUIRE(test_field.get_point() == Pointf(30.9, 211.2));
}
THEN( "get_string() returns '30.9;211.2'") {
REQUIRE(test_field.get_string() == "30.9;211.2"s);
}
THEN( "X TextCtrl contains X coordinate") {
REQUIRE(test_field.ctrl_x()->GetValue() == wxString("30.9"s));
}
THEN( "Y TextCtrl contains Y coordinate") {
REQUIRE(test_field.ctrl_y()->GetValue() == wxString("211.2"s));
}
}
WHEN( "set_value is called with a wxString of the form '30.9;211.2'") {
test_field.set_value(wxString("30.9;211.2"s));
THEN( "get_point() returns a Pointf(30.9, 211.2)") {
REQUIRE(test_field.get_point() == Pointf(30.9, 211.2));
}
THEN( "get_string() returns '30.9;211.2'") {
REQUIRE(test_field.get_string() == "30.9;211.2"s);
}
THEN( "X TextCtrl contains X coordinate") {
REQUIRE(test_field.ctrl_x()->GetValue() == wxString("30.9"s));
}
THEN( "Y TextCtrl contains Y coordinate") {
REQUIRE(test_field.ctrl_y()->GetValue() == wxString("211.2"s));
}
}
}
}
SCENARIO( "UI_Point: Event responses") {
wxTestableFrame* old = dynamic_cast<wxTestableFrame*>(wxTheApp->GetTopWindow());
old->Destroy();
wxTheApp->SetTopWindow(new wxTestableFrame());
wxMilliSleep(250);
GIVEN ( "A UI_Point with no default value and a registered on_change method that increments a counter.") {
auto simple_option {ConfigOptionDef()};
auto test_field {Slic3r::GUI::UI_Point(wxTheApp->GetTopWindow(), simple_option)};
auto event_count {0};
auto changefunc {[&event_count] (const std::string& opt_id, std::tuple<std::string, std::string> value) { event_count++; }};
auto killfunc {[&event_count](const std::string& opt_id) { event_count++; }};
test_field.on_change = changefunc;
test_field.on_kill_focus = killfunc;
test_field.disable_change_event = false;
WHEN( "kill focus event is received on X") {
event_count = 0;
auto ev {wxFocusEvent(wxEVT_KILL_FOCUS, test_field.ctrl_x()->GetId())};
ev.SetEventObject(test_field.ctrl_x());
test_field.ctrl_x()->ProcessWindowEvent(ev);
THEN( "on_kill_focus is executed.") {
REQUIRE(event_count == 2);
}
}
WHEN( "kill focus event is received on Y") {
event_count = 0;
auto ev {wxFocusEvent(wxEVT_KILL_FOCUS, test_field.ctrl_y()->GetId())};
ev.SetEventObject(test_field.ctrl_y());
test_field.ctrl_y()->ProcessWindowEvent(ev);
THEN( "on_kill_focus is executed.") {
REQUIRE(event_count == 2);
}
}
WHEN( "enter key pressed event is received on X") {
event_count = 0;
auto ev {wxCommandEvent(wxEVT_TEXT_ENTER, test_field.ctrl_x()->GetId())};
ev.SetEventObject(test_field.ctrl_x());
test_field.ctrl_x()->ProcessWindowEvent(ev);
THEN( "on_change is executed.") {
REQUIRE(event_count == 1);
}
}
WHEN( "enter key pressed event is received on Y") {
event_count = 0;
auto ev {wxCommandEvent(wxEVT_TEXT_ENTER, test_field.ctrl_y()->GetId())};
ev.SetEventObject(test_field.ctrl_y());
test_field.ctrl_y()->ProcessWindowEvent(ev);
THEN( "on_change is executed.") {
REQUIRE(event_count == 1);
}
}
}
GIVEN ( "A UI_Point with no default value and a registered on_change method that increments a counter only when disable_change_event = false.") {
auto simple_option {ConfigOptionDef()};
auto test_field {Slic3r::GUI::UI_Point(wxTheApp->GetTopWindow(), simple_option)};
auto event_count {0};
auto changefunc {[&event_count] (const std::string& opt_id, std::tuple<std::string, std::string> value) { event_count++; }};
auto killfunc {[&event_count](const std::string& opt_id) { event_count += 1; }};
test_field.on_change = changefunc;
test_field.on_kill_focus = killfunc;
test_field.disable_change_event = true;
WHEN( "kill focus event is received on X") {
event_count = 0;
auto ev {wxFocusEvent(wxEVT_KILL_FOCUS, test_field.ctrl_x()->GetId())};
ev.SetEventObject(test_field.ctrl_x());
test_field.ctrl_x()->ProcessWindowEvent(ev);
THEN( "on_kill_focus is executed.") {
REQUIRE(event_count == 1);
}
}
WHEN( "kill focus event is received on Y") {
event_count = 0;
auto ev {wxFocusEvent(wxEVT_KILL_FOCUS, test_field.ctrl_y()->GetId())};
ev.SetEventObject(test_field.ctrl_y());
test_field.ctrl_y()->ProcessWindowEvent(ev);
THEN( "on_kill_focus is executed.") {
REQUIRE(event_count == 1);
}
}
WHEN( "enter key pressed event is received on X") {
event_count = 0;
auto ev {wxCommandEvent(wxEVT_TEXT_ENTER, test_field.ctrl_x()->GetId())};
ev.SetEventObject(test_field.ctrl_x());
test_field.ctrl_x()->ProcessWindowEvent(ev);
THEN( "on_change is not executed.") {
REQUIRE(event_count == 0);
}
}
WHEN( "enter key pressed event is received on Y") {
event_count = 0;
auto ev {wxCommandEvent(wxEVT_TEXT_ENTER, test_field.ctrl_y()->GetId())};
ev.SetEventObject(test_field.ctrl_y());
test_field.ctrl_y()->ProcessWindowEvent(ev);
THEN( "on_change is not executed.") {
REQUIRE(event_count == 0);
}
}
}
}
SCENARIO( "UI_Point: Enable/Disable") {
wxTestableFrame* old = dynamic_cast<wxTestableFrame*>(wxTheApp->GetTopWindow());
old->Destroy();
wxTheApp->SetTopWindow(new wxTestableFrame());
wxMilliSleep(250);
GIVEN ( "A UI_Point with no default value.") {
auto simple_option {ConfigOptionDef()};
auto test_field {Slic3r::GUI::UI_Point(wxTheApp->GetTopWindow(), simple_option)};
WHEN( "disable() is called") {
test_field.disable();
THEN( "IsEnabled == False for X and Y textctrls") {
REQUIRE(test_field.ctrl_x()->IsEnabled() == false);
REQUIRE(test_field.ctrl_y()->IsEnabled() == false);
}
}
WHEN( "enable() is called") {
test_field.enable();
THEN( "IsEnabled == True for X and Y textctrls") {
REQUIRE(test_field.ctrl_x()->IsEnabled() == true);
REQUIRE(test_field.ctrl_y()->IsEnabled() == true);
}
}
WHEN( "toggle() is called with false argument") {
test_field.toggle(false);
THEN( "IsEnabled == False for X and Y textctrls") {
REQUIRE(test_field.ctrl_x()->IsEnabled() == false);
REQUIRE(test_field.ctrl_y()->IsEnabled() == false);
}
}
WHEN( "toggle() is called with true argument") {
test_field.toggle(true);
THEN( "IsEnabled == True for X and Y textctrls") {
REQUIRE(test_field.ctrl_x()->IsEnabled() == true);
REQUIRE(test_field.ctrl_y()->IsEnabled() == true);
}
}
}
}
SCENARIO( "UI_Point: get_sizer()") {
wxTestableFrame* old = dynamic_cast<wxTestableFrame*>(wxTheApp->GetTopWindow());
old->Destroy();
wxTheApp->SetTopWindow(new wxTestableFrame());
wxMilliSleep(250);
GIVEN ( "A UI_Point with no default value.") {
auto simple_option {ConfigOptionDef()};
auto test_field {Slic3r::GUI::UI_Point(wxTheApp->GetTopWindow(), simple_option)};
WHEN( "get_sizer() is called") {
THEN( "get_sizer() returns a wxSizer that has 4 direct children in it that are Windows.") {
REQUIRE(test_field.get_sizer()->GetItemCount() == 4);
auto tmp {test_field.get_sizer()->GetChildren().begin()};
REQUIRE((*tmp)->IsWindow() == true);
tmp++;
REQUIRE((*tmp)->IsWindow() == true);
tmp++;
REQUIRE((*tmp)->IsWindow() == true);
tmp++;
REQUIRE((*tmp)->IsWindow() == true);
}
}
}
}
<|endoftext|> |
<commit_before><commit_msg>The AutomationMsg_SetCookie IPC should be channeled to the automation cookie store for ChromeFrame. This ensures that the automation client would receive a callback when the cookie is set on the store.<commit_after><|endoftext|> |
<commit_before>/*
* Copyright (c) 2012 The WebRTC project authors. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree. An additional intellectual property rights grant can be found
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
#include "test/testsupport/fileutils.h"
#ifdef WIN32
#include <direct.h>
#define GET_CURRENT_DIR _getcwd
#else
#include <unistd.h>
#define GET_CURRENT_DIR getcwd
#endif
#include <sys/stat.h> // To check for directory existence.
#ifndef S_ISDIR // Not defined in stat.h on Windows.
#define S_ISDIR(mode) (((mode) & S_IFMT) == S_IFDIR)
#endif
#include <cstdio>
#include <cstring>
#include "typedefs.h" // For architecture defines
namespace webrtc {
namespace test {
#ifdef WIN32
static const char* kPathDelimiter = "\\";
#else
static const char* kPathDelimiter = "/";
#endif
// The file we're looking for to identify the project root dir.
static const char* kProjectRootFileName = "DEPS";
static const char* kOutputDirName = "out";
static const char* kFallbackPath = "./";
#ifdef WEBRTC_ANDROID
static const char* kResourcesDirName = "/sdcard/";
#else
static const char* kResourcesDirName = "resources";
#endif
const char* kCannotFindProjectRootDir = "ERROR_CANNOT_FIND_PROJECT_ROOT_DIR";
namespace {
char relative_dir_path[FILENAME_MAX];
bool relative_dir_path_set = false;
}
void SetRelativeExecutablePath(const std::string& path) {
// Trim away the executable name; we only want to store the relative dir path.
std::string temp_path = path.substr(0, path.find_last_of(kPathDelimiter));
strncpy(relative_dir_path, temp_path.c_str(), FILENAME_MAX);
relative_dir_path_set = true;
}
bool FileExists(std::string& file_name) {
struct stat file_info = {0};
return stat(file_name.c_str(), &file_info) == 0;
}
std::string ProjectRootPath() {
std::string path = WorkingDir();
if (path == kFallbackPath) {
return kCannotFindProjectRootDir;
}
if (relative_dir_path_set) {
path = path + kPathDelimiter + relative_dir_path;
}
// Check for our file that verifies the root dir.
int path_delimiter_index = path.find_last_of(kPathDelimiter);
while (path_delimiter_index > -1) {
std::string root_filename = path + kPathDelimiter + kProjectRootFileName;
if (FileExists(root_filename)) {
return path + kPathDelimiter;
}
// Move up one directory in the directory tree.
path = path.substr(0, path_delimiter_index);
path_delimiter_index = path.find_last_of(kPathDelimiter);
}
// Reached the root directory.
fprintf(stderr, "Cannot find project root directory!\n");
return kCannotFindProjectRootDir;
}
#ifdef WEBRTC_ANDROID
std::string OutputPath() {
// We need to touch this variable so it doesn't get flagged as unused.
(void)kOutputDirName;
return "/sdcard/";
}
#else // WEBRTC_ANDROID
std::string OutputPath() {
std::string path = ProjectRootPath();
if (path == kCannotFindProjectRootDir) {
return kFallbackPath;
}
path += kOutputDirName;
if (!CreateDirectory(path)) {
return kFallbackPath;
}
return path + kPathDelimiter;
}
#endif // !WEBRTC_ANDROID
std::string WorkingDir() {
char path_buffer[FILENAME_MAX];
if (!GET_CURRENT_DIR(path_buffer, sizeof(path_buffer))) {
fprintf(stderr, "Cannot get current directory!\n");
return kFallbackPath;
} else {
return std::string(path_buffer);
}
}
bool CreateDirectory(std::string directory_name) {
struct stat path_info = {0};
// Check if the path exists already:
if (stat(directory_name.c_str(), &path_info) == 0) {
if (!S_ISDIR(path_info.st_mode)) {
fprintf(stderr, "Path %s exists but is not a directory! Remove this "
"file and re-run to create the directory.\n",
directory_name.c_str());
return false;
}
} else {
#ifdef WIN32
return _mkdir(directory_name.c_str()) == 0;
#else
return mkdir(directory_name.c_str(), S_IRWXU | S_IRWXG | S_IRWXO) == 0;
#endif
}
return true;
}
std::string ResourcePath(std::string name, std::string extension) {
std::string platform = "win";
#ifdef WEBRTC_LINUX
platform = "linux";
#endif // WEBRTC_LINUX
#ifdef WEBRTC_MAC
platform = "mac";
#endif // WEBRTC_MAC
#ifdef WEBRTC_ARCH_64_BITS
std::string architecture = "64";
#else
std::string architecture = "32";
#endif // WEBRTC_ARCH_64_BITS
#ifdef WEBRTC_ANDROID
std::string resources_path = kResourcesDirName;
#else
std::string resources_path = ProjectRootPath() + kResourcesDirName +
kPathDelimiter;
std::string resource_file = resources_path + name + "_" + platform + "_" +
architecture + "." + extension;
if (FileExists(resource_file)) {
return resource_file;
}
// Try without architecture.
resource_file = resources_path + name + "_" + platform + "." + extension;
if (FileExists(resource_file)) {
return resource_file;
}
// Try without platform.
resource_file = resources_path + name + "_" + architecture + "." + extension;
if (FileExists(resource_file)) {
return resource_file;
}
#endif
// Fall back on name without architecture or platform.
return resources_path + name + "." + extension;
}
size_t GetFileSize(std::string filename) {
FILE* f = fopen(filename.c_str(), "rb");
size_t size = 0;
if (f != NULL) {
if (fseek(f, 0, SEEK_END) == 0) {
size = ftell(f);
}
fclose(f);
}
return size;
}
} // namespace test
} // namespace webrtc
<commit_msg>Consolidate test file path on Android<commit_after>/*
* Copyright (c) 2012 The WebRTC project authors. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree. An additional intellectual property rights grant can be found
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
#include "test/testsupport/fileutils.h"
#ifdef WIN32
#include <direct.h>
#define GET_CURRENT_DIR _getcwd
#else
#include <unistd.h>
#define GET_CURRENT_DIR getcwd
#endif
#include <sys/stat.h> // To check for directory existence.
#ifndef S_ISDIR // Not defined in stat.h on Windows.
#define S_ISDIR(mode) (((mode) & S_IFMT) == S_IFDIR)
#endif
#include <cstdio>
#include <cstring>
#include "typedefs.h" // For architecture defines
namespace webrtc {
namespace test {
#ifdef WIN32
static const char* kPathDelimiter = "\\";
#else
static const char* kPathDelimiter = "/";
#endif
#ifdef WEBRTC_ANDROID
static const char* kRootDirName = "/sdcard/";
static const char* kResourcesDirName = "resources";
#else
// The file we're looking for to identify the project root dir.
static const char* kProjectRootFileName = "DEPS";
static const char* kOutputDirName = "out";
static const char* kFallbackPath = "./";
static const char* kResourcesDirName = "resources";
#endif
const char* kCannotFindProjectRootDir = "ERROR_CANNOT_FIND_PROJECT_ROOT_DIR";
namespace {
char relative_dir_path[FILENAME_MAX];
bool relative_dir_path_set = false;
}
void SetRelativeExecutablePath(const std::string& path) {
// Trim away the executable name; we only want to store the relative dir path.
std::string temp_path = path.substr(0, path.find_last_of(kPathDelimiter));
strncpy(relative_dir_path, temp_path.c_str(), FILENAME_MAX);
relative_dir_path_set = true;
}
bool FileExists(std::string& file_name) {
struct stat file_info = {0};
return stat(file_name.c_str(), &file_info) == 0;
}
#ifdef WEBRTC_ANDROID
std::string ProjectRootPath() {
return kRootDirName;
}
std::string OutputPath() {
return kRootDirName;
}
std::string WorkingDir() {
return kRootDirName;
}
#else // WEBRTC_ANDROID
std::string ProjectRootPath() {
std::string path = WorkingDir();
if (path == kFallbackPath) {
return kCannotFindProjectRootDir;
}
if (relative_dir_path_set) {
path = path + kPathDelimiter + relative_dir_path;
}
// Check for our file that verifies the root dir.
int path_delimiter_index = path.find_last_of(kPathDelimiter);
while (path_delimiter_index > -1) {
std::string root_filename = path + kPathDelimiter + kProjectRootFileName;
if (FileExists(root_filename)) {
return path + kPathDelimiter;
}
// Move up one directory in the directory tree.
path = path.substr(0, path_delimiter_index);
path_delimiter_index = path.find_last_of(kPathDelimiter);
}
// Reached the root directory.
fprintf(stderr, "Cannot find project root directory!\n");
return kCannotFindProjectRootDir;
}
std::string OutputPath() {
std::string path = ProjectRootPath();
if (path == kCannotFindProjectRootDir) {
return kFallbackPath;
}
path += kOutputDirName;
if (!CreateDirectory(path)) {
return kFallbackPath;
}
return path + kPathDelimiter;
}
std::string WorkingDir() {
char path_buffer[FILENAME_MAX];
if (!GET_CURRENT_DIR(path_buffer, sizeof(path_buffer))) {
fprintf(stderr, "Cannot get current directory!\n");
return kFallbackPath;
} else {
return std::string(path_buffer);
}
}
#endif // !WEBRTC_ANDROID
bool CreateDirectory(std::string directory_name) {
struct stat path_info = {0};
// Check if the path exists already:
if (stat(directory_name.c_str(), &path_info) == 0) {
if (!S_ISDIR(path_info.st_mode)) {
fprintf(stderr, "Path %s exists but is not a directory! Remove this "
"file and re-run to create the directory.\n",
directory_name.c_str());
return false;
}
} else {
#ifdef WIN32
return _mkdir(directory_name.c_str()) == 0;
#else
return mkdir(directory_name.c_str(), S_IRWXU | S_IRWXG | S_IRWXO) == 0;
#endif
}
return true;
}
std::string ResourcePath(std::string name, std::string extension) {
std::string platform = "win";
#ifdef WEBRTC_LINUX
platform = "linux";
#endif // WEBRTC_LINUX
#ifdef WEBRTC_MAC
platform = "mac";
#endif // WEBRTC_MAC
#ifdef WEBRTC_ARCH_64_BITS
std::string architecture = "64";
#else
std::string architecture = "32";
#endif // WEBRTC_ARCH_64_BITS
std::string resources_path = ProjectRootPath() + kResourcesDirName +
kPathDelimiter;
std::string resource_file = resources_path + name + "_" + platform + "_" +
architecture + "." + extension;
if (FileExists(resource_file)) {
return resource_file;
}
// Try without architecture.
resource_file = resources_path + name + "_" + platform + "." + extension;
if (FileExists(resource_file)) {
return resource_file;
}
// Try without platform.
resource_file = resources_path + name + "_" + architecture + "." + extension;
if (FileExists(resource_file)) {
return resource_file;
}
// Fall back on name without architecture or platform.
return resources_path + name + "." + extension;
}
size_t GetFileSize(std::string filename) {
FILE* f = fopen(filename.c_str(), "rb");
size_t size = 0;
if (f != NULL) {
if (fseek(f, 0, SEEK_END) == 0) {
size = ftell(f);
}
fclose(f);
}
return size;
}
} // namespace test
} // namespace webrtc
<|endoftext|> |
<commit_before>//*****************************************************************************
// Copyright 2017-2018 Intel Corporation
//
// 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.
//*****************************************************************************
#pragma once
#include <thread>
#include <mkldnn.hpp>
#include "ngraph/runtime/cpu/cpu_runtime_context.hpp"
#define EIGEN_USE_THREADS
#include <unsupported/Eigen/CXX11/Tensor>
#include "tbb/task_arena.h"
namespace ngraph
{
namespace runtime
{
namespace cpu
{
namespace executor
{
extern mkldnn::engine global_cpu_engine;
// CPUExecutor owns the resources for executing a graph.
class CPUExecutor
{
public:
explicit CPUExecutor(int num_thread_pools);
Eigen::ThreadPoolDevice& get_device(int id)
{
return *m_thread_pool_devices[id].get();
}
void execute(CPUKernelFunctor& f,
CPURuntimeContext* ctx,
CPUExecutionContext* ectx,
bool use_tbb = false);
int get_num_thread_pools() { return m_num_thread_pools; }
private:
std::vector<std::unique_ptr<Eigen::ThreadPool>> m_thread_pools;
std::vector<std::unique_ptr<Eigen::ThreadPoolDevice>> m_thread_pool_devices;
std::vector<tbb::task_arena> m_tbb_arenas;
int m_num_thread_pools;
};
extern CPUExecutor& GetCPUExecutor();
}
}
}
}
<commit_msg>Missing header (#1992)<commit_after>//*****************************************************************************
// Copyright 2017-2018 Intel Corporation
//
// 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.
//*****************************************************************************
#pragma once
#include <functional>
#include <thread>
#include <mkldnn.hpp>
#include "ngraph/runtime/cpu/cpu_runtime_context.hpp"
#define EIGEN_USE_THREADS
#include <unsupported/Eigen/CXX11/Tensor>
#include "tbb/task_arena.h"
namespace ngraph
{
namespace runtime
{
namespace cpu
{
namespace executor
{
extern mkldnn::engine global_cpu_engine;
// CPUExecutor owns the resources for executing a graph.
class CPUExecutor
{
public:
explicit CPUExecutor(int num_thread_pools);
Eigen::ThreadPoolDevice& get_device(int id)
{
return *m_thread_pool_devices[id].get();
}
void execute(CPUKernelFunctor& f,
CPURuntimeContext* ctx,
CPUExecutionContext* ectx,
bool use_tbb = false);
int get_num_thread_pools() { return m_num_thread_pools; }
private:
std::vector<std::unique_ptr<Eigen::ThreadPool>> m_thread_pools;
std::vector<std::unique_ptr<Eigen::ThreadPoolDevice>> m_thread_pool_devices;
std::vector<tbb::task_arena> m_tbb_arenas;
int m_num_thread_pools;
};
extern CPUExecutor& GetCPUExecutor();
}
}
}
}
<|endoftext|> |
<commit_before>// This Source Code Form is licensed MPL-2.0: http://mozilla.org/MPL/2.0
#ifndef __RAPICORN_FORMATTER_HH__
#define __RAPICORN_FORMATTER_HH__
#include <rcore/cxxaux.hh>
#include <rcore/aida.hh>
#include <sstream>
namespace Rapicorn {
namespace Lib { // Namespace for implementation internals
// == StringFormatter ==
/** StringFormatter - sprintf() like string formatting for C++.
*
* See format() for supported flags, modifiers and conversions.
* To find source code strings with size modifiers for possible cleanups, use:
* egrep "\"([^\"]|\\\")*%[0-9$]*[-+#0 \'I]*[*0-9$]*[.*0-9$]*[hlLqjzt]+[nSspmCcdiouXxFfGgEeAa]"
*/
class StringFormatter {
typedef long long signed int LLong;
typedef long long unsigned int ULLong;
typedef long double LDouble;
struct FormatArg {
union { LDouble d; double f; signed char i1; short i2; int i4; long i6; LLong i8; void *p; const char *s; };
char kind; // f d i u p s
};
inline void assign (FormatArg &farg, bool arg) { farg.kind = '1'; farg.i1 = arg; }
inline void assign (FormatArg &farg, char arg) { farg.kind = '1'; farg.i1 = arg; }
inline void assign (FormatArg &farg, signed char arg) { farg.kind = '1'; farg.i1 = arg; }
inline void assign (FormatArg &farg, unsigned char arg) { farg.kind = '1'; farg.i1 = arg; }
#if __SIZEOF_WCHAR_T__ == 1
inline void assign (FormatArg &farg, wchar_t arg) { farg.kind = '1'; farg.i1 = arg; }
#endif
inline void assign (FormatArg &farg, short arg) { farg.kind = '2'; farg.i2 = arg; }
inline void assign (FormatArg &farg, unsigned short arg) { farg.kind = '2'; farg.i2 = arg; }
#if __SIZEOF_WCHAR_T__ == 2
inline void assign (FormatArg &farg, wchar_t arg) { farg.kind = '2'; farg.i2 = arg; }
#endif
inline void assign (FormatArg &farg, int arg) { farg.kind = '4'; farg.i4 = arg; }
inline void assign (FormatArg &farg, unsigned int arg) { farg.kind = '4'; farg.i4 = arg; }
#if __SIZEOF_WCHAR_T__ == 4
inline void assign (FormatArg &farg, wchar_t arg) { farg.kind = '4'; farg.i4 = arg; }
#endif
inline void assign (FormatArg &farg, long arg) { farg.kind = '6'; farg.i6 = arg; }
inline void assign (FormatArg &farg, unsigned long arg) { farg.kind = '6'; farg.i6 = arg; }
inline void assign (FormatArg &farg, long long arg) { farg.kind = '8'; farg.i8 = arg; }
inline void assign (FormatArg &farg, unsigned long long arg) { farg.kind = '8'; farg.i8 = arg; }
inline void assign (FormatArg &farg, float arg) { farg.kind = 'f'; farg.f = arg; }
inline void assign (FormatArg &farg, double arg) { farg.kind = 'f'; farg.f = arg; }
inline void assign (FormatArg &farg, long double arg) { farg.kind = 'd'; farg.d = arg; }
inline void assign (FormatArg &farg, char *arg) { farg.kind = 's'; farg.s = arg; }
inline void assign (FormatArg &farg, const char *arg) { farg.kind = 's'; farg.s = arg; }
inline void assign (FormatArg &farg, const std::string &arg) { assign (farg, arg.c_str()); }
inline void assign (FormatArg &farg, void *arg) { farg.kind = 'p'; farg.p = arg; }
template<class T> inline void assign (FormatArg &farg, T *const &arg) { assign (farg, (void*) arg); }
template<class T> typename std::enable_if<std::is_enum<T>::value, void> // eliminated via SFINAE
::type assign (FormatArg &farg, const T &arg) { farg.kind = '8'; farg.i8 = arg; }
template<class T> typename std::enable_if<std::is_class<T>::value, void> // eliminated via SFINAE
::type assign (FormatArg &farg, const T &arg)
{
std::ostringstream os;
os << arg;
temporaries_.push_back (os.str());
assign (farg, temporaries_[temporaries_.size()-1]);
}
const FormatArg& format_arg (size_t nth);
uint32_t arg_as_width (size_t nth);
uint32_t arg_as_precision (size_t nth);
LLong arg_as_longlong (size_t nth);
LDouble arg_as_ldouble (size_t nth);
const char* arg_as_chars (size_t nth);
void* arg_as_ptr (size_t nth);
struct Directive {
char conversion;
uint32_t adjust_left : 1, add_sign : 1, use_width : 1, use_precision : 1;
uint32_t alternate_form : 1, zero_padding : 1, add_space : 1, locale_grouping : 1;
uint32_t field_width, precision, start, end, value_index, width_index, precision_index;
Directive() :
conversion (0), adjust_left (0), add_sign (0), use_width (0), use_precision (0),
alternate_form (0), zero_padding (0), add_space (0), locale_grouping (0),
field_width (0), precision (0), start (0), end (0), value_index (0), width_index (0), precision_index (0)
{}
};
typedef std::function<String (const String&)> ArgTransform;
FormatArg *const fargs_;
const size_t nargs_;
const int locale_context_;
const ArgTransform &arg_transform_;
vector<std::string> temporaries_;
static std::string format_error (const char *err, const char *format, size_t directive);
static const char* parse_directive (const char **stringp, size_t *indexp, Directive *dirp);
std::string locale_format (size_t last, const char *format);
std::string render_format (size_t last, const char *format);
std::string render_directive (const Directive &dir);
template<class A> std::string render_arg (const Directive &dir, const char *modifier, A arg);
template<size_t N> inline std::string
intern_format (const char *format)
{
return locale_format (N, format);
}
template<size_t N, class A, class ...Args> inline std::string
intern_format (const char *format, const A &arg, const Args &...args)
{
assign (fargs_[N], arg);
return intern_format<N+1> (format, args...);
}
template<size_t N> inline constexpr
StringFormatter (const ArgTransform &arg_transform, size_t nargs, FormatArg (&mem)[N], int lc) :
fargs_ (mem), nargs_ (nargs), locale_context_ (lc), arg_transform_ (arg_transform) {}
public:
enum LocaleContext {
POSIX_LOCALE,
CURRENT_LOCALE,
};
/** Format a string according to an sprintf() @a format string with @a arguments.
* Refer to sprintf() for the format string details, this function is designed to
* serve as an sprintf() replacement and mimick its behaviour as close as possible.
* Supported format directive features are:
* - Formatting flags (sign conversion, padding, alignment), i.e. the flags: [-#0+ ']
* - Field width and precision specifications.
* - Positional arguments for field width, precision and value.
* - Length modifiers are tolerated: i.e. any of [hlLjztqZ].
* - The conversion specifiers [spmcCdiouXxFfGgEeAa].
*
* Additionally, arguments can be transformed after conversion by passing a std::string
* conversion function as @a arg_transform. This may e.g. be used for XML character
* escaping of the format argument values. <br/>
* @NOTE Format errors, e.g. missing arguments will produce a warning on stderr and
* return the @a format string unmodified.
* @returns A formatted string.
*/
template<LocaleContext LC = POSIX_LOCALE, class ...Args>
static __attribute__ ((__format__ (printf, 2, 0), noinline)) std::string
format (const ArgTransform &arg_transform, const char *format, const Args &...arguments)
{
constexpr size_t N = sizeof... (Args);
FormatArg mem[N ? N : 1];
StringFormatter formatter (arg_transform, N, mem, LC);
return formatter.intern_format<0> (format, arguments...);
}
};
} // Lib
} // Rapicorn
#endif /* __RAPICORN_FORMATTER_HH__ */
<commit_msg>RCORE: StringFormatter: explicitely cast enum class value arguments to integer<commit_after>// This Source Code Form is licensed MPL-2.0: http://mozilla.org/MPL/2.0
#ifndef __RAPICORN_FORMATTER_HH__
#define __RAPICORN_FORMATTER_HH__
#include <rcore/cxxaux.hh>
#include <rcore/aida.hh>
#include <sstream>
namespace Rapicorn {
namespace Lib { // Namespace for implementation internals
// == StringFormatter ==
/** StringFormatter - sprintf() like string formatting for C++.
*
* See format() for supported flags, modifiers and conversions.
* To find source code strings with size modifiers for possible cleanups, use:
* egrep "\"([^\"]|\\\")*%[0-9$]*[-+#0 \'I]*[*0-9$]*[.*0-9$]*[hlLqjzt]+[nSspmCcdiouXxFfGgEeAa]"
*/
class StringFormatter {
typedef long long signed int LLong;
typedef long long unsigned int ULLong;
typedef long double LDouble;
struct FormatArg {
union { LDouble d; double f; signed char i1; short i2; int i4; long i6; LLong i8; void *p; const char *s; };
char kind; // f d i u p s
};
inline void assign (FormatArg &farg, bool arg) { farg.kind = '1'; farg.i1 = arg; }
inline void assign (FormatArg &farg, char arg) { farg.kind = '1'; farg.i1 = arg; }
inline void assign (FormatArg &farg, signed char arg) { farg.kind = '1'; farg.i1 = arg; }
inline void assign (FormatArg &farg, unsigned char arg) { farg.kind = '1'; farg.i1 = arg; }
#if __SIZEOF_WCHAR_T__ == 1
inline void assign (FormatArg &farg, wchar_t arg) { farg.kind = '1'; farg.i1 = arg; }
#endif
inline void assign (FormatArg &farg, short arg) { farg.kind = '2'; farg.i2 = arg; }
inline void assign (FormatArg &farg, unsigned short arg) { farg.kind = '2'; farg.i2 = arg; }
#if __SIZEOF_WCHAR_T__ == 2
inline void assign (FormatArg &farg, wchar_t arg) { farg.kind = '2'; farg.i2 = arg; }
#endif
inline void assign (FormatArg &farg, int arg) { farg.kind = '4'; farg.i4 = arg; }
inline void assign (FormatArg &farg, unsigned int arg) { farg.kind = '4'; farg.i4 = arg; }
#if __SIZEOF_WCHAR_T__ == 4
inline void assign (FormatArg &farg, wchar_t arg) { farg.kind = '4'; farg.i4 = arg; }
#endif
inline void assign (FormatArg &farg, long arg) { farg.kind = '6'; farg.i6 = arg; }
inline void assign (FormatArg &farg, unsigned long arg) { farg.kind = '6'; farg.i6 = arg; }
inline void assign (FormatArg &farg, long long arg) { farg.kind = '8'; farg.i8 = arg; }
inline void assign (FormatArg &farg, unsigned long long arg) { farg.kind = '8'; farg.i8 = arg; }
inline void assign (FormatArg &farg, float arg) { farg.kind = 'f'; farg.f = arg; }
inline void assign (FormatArg &farg, double arg) { farg.kind = 'f'; farg.f = arg; }
inline void assign (FormatArg &farg, long double arg) { farg.kind = 'd'; farg.d = arg; }
inline void assign (FormatArg &farg, char *arg) { farg.kind = 's'; farg.s = arg; }
inline void assign (FormatArg &farg, const char *arg) { farg.kind = 's'; farg.s = arg; }
inline void assign (FormatArg &farg, const std::string &arg) { assign (farg, arg.c_str()); }
inline void assign (FormatArg &farg, void *arg) { farg.kind = 'p'; farg.p = arg; }
template<class T> inline void assign (FormatArg &farg, T *const &arg) { assign (farg, (void*) arg); }
template<class T> typename std::enable_if<std::is_enum<T>::value, void> // eliminated via SFINAE
::type assign (FormatArg &farg, const T &arg) { farg.kind = '8'; farg.i8 = LLong (arg); }
template<class T> typename std::enable_if<std::is_class<T>::value, void> // eliminated via SFINAE
::type assign (FormatArg &farg, const T &arg)
{
std::ostringstream os;
os << arg;
temporaries_.push_back (os.str());
assign (farg, temporaries_[temporaries_.size()-1]);
}
const FormatArg& format_arg (size_t nth);
uint32_t arg_as_width (size_t nth);
uint32_t arg_as_precision (size_t nth);
LLong arg_as_longlong (size_t nth);
LDouble arg_as_ldouble (size_t nth);
const char* arg_as_chars (size_t nth);
void* arg_as_ptr (size_t nth);
struct Directive {
char conversion;
uint32_t adjust_left : 1, add_sign : 1, use_width : 1, use_precision : 1;
uint32_t alternate_form : 1, zero_padding : 1, add_space : 1, locale_grouping : 1;
uint32_t field_width, precision, start, end, value_index, width_index, precision_index;
Directive() :
conversion (0), adjust_left (0), add_sign (0), use_width (0), use_precision (0),
alternate_form (0), zero_padding (0), add_space (0), locale_grouping (0),
field_width (0), precision (0), start (0), end (0), value_index (0), width_index (0), precision_index (0)
{}
};
typedef std::function<String (const String&)> ArgTransform;
FormatArg *const fargs_;
const size_t nargs_;
const int locale_context_;
const ArgTransform &arg_transform_;
vector<std::string> temporaries_;
static std::string format_error (const char *err, const char *format, size_t directive);
static const char* parse_directive (const char **stringp, size_t *indexp, Directive *dirp);
std::string locale_format (size_t last, const char *format);
std::string render_format (size_t last, const char *format);
std::string render_directive (const Directive &dir);
template<class A> std::string render_arg (const Directive &dir, const char *modifier, A arg);
template<size_t N> inline std::string
intern_format (const char *format)
{
return locale_format (N, format);
}
template<size_t N, class A, class ...Args> inline std::string
intern_format (const char *format, const A &arg, const Args &...args)
{
assign (fargs_[N], arg);
return intern_format<N+1> (format, args...);
}
template<size_t N> inline constexpr
StringFormatter (const ArgTransform &arg_transform, size_t nargs, FormatArg (&mem)[N], int lc) :
fargs_ (mem), nargs_ (nargs), locale_context_ (lc), arg_transform_ (arg_transform) {}
public:
enum LocaleContext {
POSIX_LOCALE,
CURRENT_LOCALE,
};
/** Format a string according to an sprintf() @a format string with @a arguments.
* Refer to sprintf() for the format string details, this function is designed to
* serve as an sprintf() replacement and mimick its behaviour as close as possible.
* Supported format directive features are:
* - Formatting flags (sign conversion, padding, alignment), i.e. the flags: [-#0+ ']
* - Field width and precision specifications.
* - Positional arguments for field width, precision and value.
* - Length modifiers are tolerated: i.e. any of [hlLjztqZ].
* - The conversion specifiers [spmcCdiouXxFfGgEeAa].
*
* Additionally, arguments can be transformed after conversion by passing a std::string
* conversion function as @a arg_transform. This may e.g. be used for XML character
* escaping of the format argument values. <br/>
* @NOTE Format errors, e.g. missing arguments will produce a warning on stderr and
* return the @a format string unmodified.
* @returns A formatted string.
*/
template<LocaleContext LC = POSIX_LOCALE, class ...Args>
static __attribute__ ((__format__ (printf, 2, 0), noinline)) std::string
format (const ArgTransform &arg_transform, const char *format, const Args &...arguments)
{
constexpr size_t N = sizeof... (Args);
FormatArg mem[N ? N : 1];
StringFormatter formatter (arg_transform, N, mem, LC);
return formatter.intern_format<0> (format, arguments...);
}
};
} // Lib
} // Rapicorn
#endif /* __RAPICORN_FORMATTER_HH__ */
<|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 "chrome/browser/prerender/prerender_histograms.h"
#include <string>
#include "base/metrics/field_trial.h"
#include "base/metrics/histogram.h"
#include "base/stringprintf.h"
#include "chrome/browser/autocomplete/network_action_predictor.h"
#include "chrome/browser/prerender/prerender_field_trial.h"
#include "chrome/browser/prerender/prerender_manager.h"
#include "chrome/browser/prerender/prerender_util.h"
namespace prerender {
namespace {
// Time window for which we will record windowed PLT's from the last
// observed link rel=prefetch tag.
const int kWindowDurationSeconds = 30;
std::string ComposeHistogramName(const std::string& prefix_type,
const std::string& name) {
if (prefix_type.empty())
return std::string("Prerender.") + name;
return std::string("Prerender.") + prefix_type + std::string("_") + name;
}
std::string GetHistogramName(Origin origin, uint8 experiment_id,
bool is_wash, const std::string& name) {
if (is_wash)
return ComposeHistogramName("wash", name);
if (origin == ORIGIN_GWS_PRERENDER) {
if (experiment_id == kNoExperiment)
return ComposeHistogramName("gws", name);
return ComposeHistogramName("exp" + std::string(1, experiment_id + '0'),
name);
}
if (experiment_id != kNoExperiment)
return ComposeHistogramName("wash", name);
switch (origin) {
case ORIGIN_OMNIBOX:
return ComposeHistogramName(
StringPrintf("omnibox_%.1f",
NetworkActionPredictor::get_hit_weight()).c_str(),
name);
case ORIGIN_LINK_REL_PRERENDER:
return ComposeHistogramName("web", name);
case ORIGIN_GWS_PRERENDER: // Handled above.
default:
NOTREACHED();
break;
};
// Dummy return value to make the compiler happy.
NOTREACHED();
return ComposeHistogramName("wash", name);
}
bool OriginIsOmnibox(Origin origin) {
return origin == ORIGIN_OMNIBOX;
}
} // namespace
// Helper macros for experiment-based and origin-based histogram reporting.
// All HISTOGRAM arguments must be UMA_HISTOGRAM... macros that contain an
// argument "name" which these macros will eventually substitute for the
// actual name used.
#define PREFIXED_HISTOGRAM(histogram_name, HISTOGRAM) \
PREFIXED_HISTOGRAM_INTERNAL(GetCurrentOrigin(), GetCurrentExperimentId(), \
IsOriginExperimentWash(), HISTOGRAM, \
histogram_name)
#define PREFIXED_HISTOGRAM_ORIGIN_EXPERIMENT(histogram_name, origin, \
experiment, HISTOGRAM) \
PREFIXED_HISTOGRAM_INTERNAL(origin, experiment, false, HISTOGRAM, \
histogram_name)
#define PREFIXED_HISTOGRAM_INTERNAL(origin, experiment, wash, HISTOGRAM, \
histogram_name) { \
{ \
/* Do not rename. HISTOGRAM expects a local variable "name". */ \
std::string name = ComposeHistogramName("", histogram_name); \
HISTOGRAM; \
} \
/* Do not rename. HISTOGRAM expects a local variable "name". */ \
std::string name = GetHistogramName(origin, experiment, wash, \
histogram_name); \
static uint8 recording_experiment = kNoExperiment; \
if (recording_experiment == kNoExperiment && experiment != kNoExperiment) \
recording_experiment = experiment; \
if (wash) { \
HISTOGRAM; \
} else if (experiment != kNoExperiment && \
(origin != ORIGIN_GWS_PRERENDER || \
experiment != recording_experiment)) { \
} else if (origin == ORIGIN_LINK_REL_PRERENDER) { \
HISTOGRAM; \
} else if (origin == ORIGIN_OMNIBOX) { \
HISTOGRAM; \
} else if (experiment != kNoExperiment) { \
HISTOGRAM; \
} else { \
HISTOGRAM; \
} \
}
PrerenderHistograms::PrerenderHistograms()
: last_experiment_id_(kNoExperiment),
last_origin_(ORIGIN_LINK_REL_PRERENDER),
origin_experiment_wash_(false),
seen_any_pageload_(true),
seen_pageload_started_after_prerender_(true) {
}
void PrerenderHistograms::RecordPrerender(Origin origin, const GURL& url) {
// Check if we are doing an experiment.
uint8 experiment = GetQueryStringBasedExperiment(url);
// We need to update last_experiment_id_, last_origin_, and
// origin_experiment_wash_.
if (!WithinWindow()) {
// If we are outside a window, this is a fresh start and we are fine,
// and there is no mix.
origin_experiment_wash_ = false;
} else {
// If we are inside the last window, there is a mish mash of origins
// and experiments if either there was a mish mash before, or the current
// experiment/origin does not match the previous one.
if (experiment != last_experiment_id_ || origin != last_origin_)
origin_experiment_wash_ = true;
}
last_origin_ = origin;
last_experiment_id_ = experiment;
// If we observe multiple tags within the 30 second window, we will still
// reset the window to begin at the most recent occurrence, so that we will
// always be in a window in the 30 seconds from each occurrence.
last_prerender_seen_time_ = GetCurrentTimeTicks();
seen_any_pageload_ = false;
seen_pageload_started_after_prerender_ = false;
}
void PrerenderHistograms::RecordPrerenderStarted(Origin origin) const {
if (OriginIsOmnibox(origin)) {
UMA_HISTOGRAM_COUNTS(
StringPrintf("Prerender.OmniboxPrerenderCount_%.1f%s",
NetworkActionPredictor::get_hit_weight(),
PrerenderManager::GetModeString()).c_str(),
1);
}
}
void PrerenderHistograms::RecordUsedPrerender(Origin origin) const {
if (OriginIsOmnibox(origin)) {
UMA_HISTOGRAM_COUNTS(
StringPrintf("Prerender.OmniboxNavigationsUsedPrerenderCount_%.1f%s",
NetworkActionPredictor::get_hit_weight(),
PrerenderManager::GetModeString()).c_str(),
1);
}
}
base::TimeTicks PrerenderHistograms::GetCurrentTimeTicks() const {
return base::TimeTicks::Now();
}
// Helper macro for histograms.
#define RECORD_PLT(tag, perceived_page_load_time) { \
PREFIXED_HISTOGRAM( \
base::FieldTrial::MakeName(tag, "Prerender"), \
UMA_HISTOGRAM_CUSTOM_TIMES( \
name, \
perceived_page_load_time, \
base::TimeDelta::FromMilliseconds(10), \
base::TimeDelta::FromSeconds(60), \
100)); \
}
// Summary of all histograms Perceived PLT histograms:
// (all prefixed PerceivedPLT)
// PerceivedPLT -- Perceived Pageloadtimes (PPLT) for all pages in the group.
// ...Windowed -- PPLT for pages in the 30s after a prerender is created.
// ...Matched -- A prerendered page that was swapped in. In the NoUse
// and Control group cases, while nothing ever gets swapped in, we do keep
// track of what would be prerendered and would be swapped in -- and those
// cases are what is classified as Match for these groups.
// ...MatchedComplete -- A prerendered page that was swapped in + a few
// that were not swapped in so that the set of pages lines up more closely with
// the control group.
// ...FirstAfterMiss -- First page to finish loading after a prerender, which
// is different from the page that was prerendered.
// ...FirstAfterMissNonOverlapping -- Same as FirstAfterMiss, but only
// triggering for the first page to finish after the prerender that also started
// after the prerender started.
// ...FirstAfterMissBoth -- pages meeting
// FirstAfterMiss AND FirstAfterMissNonOverlapping
// ...FirstAfterMissAnyOnly -- pages meeting
// FirstAfterMiss but NOT FirstAfterMissNonOverlapping
// ..FirstAfterMissNonOverlappingOnly -- pages meeting
// FirstAfterMissNonOverlapping but NOT FirstAfterMiss
void PrerenderHistograms::RecordPerceivedPageLoadTime(
base::TimeDelta perceived_page_load_time, bool was_prerender,
bool was_complete_prerender, const GURL& url) {
if (!IsWebURL(url))
return;
bool within_window = WithinWindow();
bool is_google_url = IsGoogleDomain(url);
RECORD_PLT("PerceivedPLT", perceived_page_load_time);
if (within_window)
RECORD_PLT("PerceivedPLTWindowed", perceived_page_load_time);
if (was_prerender || was_complete_prerender) {
if (was_prerender)
RECORD_PLT("PerceivedPLTMatched", perceived_page_load_time);
if (was_complete_prerender)
RECORD_PLT("PerceivedPLTMatchedComplete", perceived_page_load_time);
seen_any_pageload_ = true;
seen_pageload_started_after_prerender_ = true;
} else if (within_window) {
RECORD_PLT("PerceivedPLTWindowNotMatched", perceived_page_load_time);
if (!is_google_url) {
bool recorded_any = false;
bool recorded_non_overlapping = false;
if (!seen_any_pageload_) {
seen_any_pageload_ = true;
RECORD_PLT("PerceivedPLTFirstAfterMiss", perceived_page_load_time);
recorded_any = true;
}
if (!seen_pageload_started_after_prerender_ &&
perceived_page_load_time <= GetTimeSinceLastPrerender()) {
seen_pageload_started_after_prerender_ = true;
RECORD_PLT("PerceivedPLTFirstAfterMissNonOverlapping",
perceived_page_load_time);
recorded_non_overlapping = true;
}
if (recorded_any || recorded_non_overlapping) {
if (recorded_any && recorded_non_overlapping) {
RECORD_PLT("PerceivedPLTFirstAfterMissBoth",
perceived_page_load_time);
} else if (recorded_any) {
RECORD_PLT("PerceivedPLTFirstAfterMissAnyOnly",
perceived_page_load_time);
} else if (recorded_non_overlapping) {
RECORD_PLT("PerceivedPLTFirstAfterMissNonOverlappingOnly",
perceived_page_load_time);
}
}
}
}
}
void PrerenderHistograms::RecordPageLoadTimeNotSwappedIn(
base::TimeDelta page_load_time, const GURL& url) const {
// If the URL to be prerendered is not a http[s] URL, or is a Google URL,
// do not record.
if (!IsWebURL(url) || IsGoogleDomain(url))
return;
RECORD_PLT("PrerenderNotSwappedInPLT", page_load_time);
}
void PrerenderHistograms::RecordPercentLoadDoneAtSwapin(double fraction)
const {
if (fraction < 0.0 || fraction > 1.0)
return;
int percentage = static_cast<int>(fraction * 100);
if (percentage < 0 || percentage > 100)
return;
PREFIXED_HISTOGRAM("PercentLoadDoneAtSwapin",
HISTOGRAM_PERCENTAGE(name, percentage));
}
base::TimeDelta PrerenderHistograms::GetTimeSinceLastPrerender() const {
return base::TimeTicks::Now() - last_prerender_seen_time_;
}
bool PrerenderHistograms::WithinWindow() const {
if (last_prerender_seen_time_.is_null())
return false;
return GetTimeSinceLastPrerender() <=
base::TimeDelta::FromSeconds(kWindowDurationSeconds);
}
void PrerenderHistograms::RecordTimeUntilUsed(
base::TimeDelta time_until_used, base::TimeDelta max_age) const {
PREFIXED_HISTOGRAM(
"TimeUntilUsed",
UMA_HISTOGRAM_CUSTOM_TIMES(
name,
time_until_used,
base::TimeDelta::FromMilliseconds(10),
max_age,
50));
}
void PrerenderHistograms::RecordPerSessionCount(int count) const {
PREFIXED_HISTOGRAM(
"PrerendersPerSessionCount",
UMA_HISTOGRAM_COUNTS(name, count));
}
void PrerenderHistograms::RecordTimeBetweenPrerenderRequests(
base::TimeDelta time) const {
PREFIXED_HISTOGRAM(
"TimeBetweenPrerenderRequests",
UMA_HISTOGRAM_TIMES(name, time));
}
void PrerenderHistograms::RecordFinalStatus(
Origin origin,
uint8 experiment_id,
PrerenderContents::MatchCompleteStatus mc_status,
FinalStatus final_status) const {
DCHECK(final_status != FINAL_STATUS_MAX);
// There are three cases for MatchCompleteStatus:
// MATCH_COMPLETE_DEFAULT:
// In this case, Match & MatchComplete line up. So we record this in both
// histograms.
// MATCH_COMPLETE_REPLACED: The actual prerender was replaced by a dummy.
// So we only record it in (the actual) FinalStatus, but not MatchComplete.
// MATCH_COMPLETE_REPLACEMENT: This is a pseudo element to emulate what
// the control group would do. Since it won't actually be swapped in,
// it may not go into FinalStatus. Since in the control group it would be
// swapped in though, it must go into MatchComplete.
if (mc_status != PrerenderContents::MATCH_COMPLETE_REPLACEMENT) {
PREFIXED_HISTOGRAM_ORIGIN_EXPERIMENT(
base::FieldTrial::MakeName("FinalStatus", "Prerender"),
origin, experiment_id,
UMA_HISTOGRAM_ENUMERATION(name, final_status, FINAL_STATUS_MAX));
}
if (mc_status != PrerenderContents::MATCH_COMPLETE_REPLACED) {
PREFIXED_HISTOGRAM_ORIGIN_EXPERIMENT(
base::FieldTrial::MakeName("FinalStatusMatchComplete", "Prerender"),
origin, experiment_id,
UMA_HISTOGRAM_ENUMERATION(name, final_status, FINAL_STATUS_MAX));
}
}
uint8 PrerenderHistograms::GetCurrentExperimentId() const {
if (!WithinWindow())
return kNoExperiment;
return last_experiment_id_;
}
Origin PrerenderHistograms::GetCurrentOrigin() const {
if (!WithinWindow())
return ORIGIN_LINK_REL_PRERENDER;
return last_origin_;
}
bool PrerenderHistograms::IsOriginExperimentWash() const {
if (!WithinWindow())
return false;
return origin_experiment_wash_;
}
} // namespace prerender
<commit_msg>For Prerender.PercnetLoadDoneAtSwapin, generate histograms on a per field trial basis. R=mmenke Review URL: https://chromiumcodereview.appspot.com/9731002<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 "chrome/browser/prerender/prerender_histograms.h"
#include <string>
#include "base/metrics/field_trial.h"
#include "base/metrics/histogram.h"
#include "base/stringprintf.h"
#include "chrome/browser/autocomplete/network_action_predictor.h"
#include "chrome/browser/prerender/prerender_field_trial.h"
#include "chrome/browser/prerender/prerender_manager.h"
#include "chrome/browser/prerender/prerender_util.h"
namespace prerender {
namespace {
// Time window for which we will record windowed PLT's from the last
// observed link rel=prefetch tag.
const int kWindowDurationSeconds = 30;
std::string ComposeHistogramName(const std::string& prefix_type,
const std::string& name) {
if (prefix_type.empty())
return std::string("Prerender.") + name;
return std::string("Prerender.") + prefix_type + std::string("_") + name;
}
std::string GetHistogramName(Origin origin, uint8 experiment_id,
bool is_wash, const std::string& name) {
if (is_wash)
return ComposeHistogramName("wash", name);
if (origin == ORIGIN_GWS_PRERENDER) {
if (experiment_id == kNoExperiment)
return ComposeHistogramName("gws", name);
return ComposeHistogramName("exp" + std::string(1, experiment_id + '0'),
name);
}
if (experiment_id != kNoExperiment)
return ComposeHistogramName("wash", name);
switch (origin) {
case ORIGIN_OMNIBOX:
return ComposeHistogramName(
StringPrintf("omnibox_%.1f",
NetworkActionPredictor::get_hit_weight()).c_str(),
name);
case ORIGIN_LINK_REL_PRERENDER:
return ComposeHistogramName("web", name);
case ORIGIN_GWS_PRERENDER: // Handled above.
default:
NOTREACHED();
break;
};
// Dummy return value to make the compiler happy.
NOTREACHED();
return ComposeHistogramName("wash", name);
}
bool OriginIsOmnibox(Origin origin) {
return origin == ORIGIN_OMNIBOX;
}
} // namespace
// Helper macros for experiment-based and origin-based histogram reporting.
// All HISTOGRAM arguments must be UMA_HISTOGRAM... macros that contain an
// argument "name" which these macros will eventually substitute for the
// actual name used.
#define PREFIXED_HISTOGRAM(histogram_name, HISTOGRAM) \
PREFIXED_HISTOGRAM_INTERNAL(GetCurrentOrigin(), GetCurrentExperimentId(), \
IsOriginExperimentWash(), HISTOGRAM, \
histogram_name)
#define PREFIXED_HISTOGRAM_ORIGIN_EXPERIMENT(histogram_name, origin, \
experiment, HISTOGRAM) \
PREFIXED_HISTOGRAM_INTERNAL(origin, experiment, false, HISTOGRAM, \
histogram_name)
#define PREFIXED_HISTOGRAM_INTERNAL(origin, experiment, wash, HISTOGRAM, \
histogram_name) { \
{ \
/* Do not rename. HISTOGRAM expects a local variable "name". */ \
std::string name = ComposeHistogramName("", histogram_name); \
HISTOGRAM; \
} \
/* Do not rename. HISTOGRAM expects a local variable "name". */ \
std::string name = GetHistogramName(origin, experiment, wash, \
histogram_name); \
static uint8 recording_experiment = kNoExperiment; \
if (recording_experiment == kNoExperiment && experiment != kNoExperiment) \
recording_experiment = experiment; \
if (wash) { \
HISTOGRAM; \
} else if (experiment != kNoExperiment && \
(origin != ORIGIN_GWS_PRERENDER || \
experiment != recording_experiment)) { \
} else if (origin == ORIGIN_LINK_REL_PRERENDER) { \
HISTOGRAM; \
} else if (origin == ORIGIN_OMNIBOX) { \
HISTOGRAM; \
} else if (experiment != kNoExperiment) { \
HISTOGRAM; \
} else { \
HISTOGRAM; \
} \
}
PrerenderHistograms::PrerenderHistograms()
: last_experiment_id_(kNoExperiment),
last_origin_(ORIGIN_LINK_REL_PRERENDER),
origin_experiment_wash_(false),
seen_any_pageload_(true),
seen_pageload_started_after_prerender_(true) {
}
void PrerenderHistograms::RecordPrerender(Origin origin, const GURL& url) {
// Check if we are doing an experiment.
uint8 experiment = GetQueryStringBasedExperiment(url);
// We need to update last_experiment_id_, last_origin_, and
// origin_experiment_wash_.
if (!WithinWindow()) {
// If we are outside a window, this is a fresh start and we are fine,
// and there is no mix.
origin_experiment_wash_ = false;
} else {
// If we are inside the last window, there is a mish mash of origins
// and experiments if either there was a mish mash before, or the current
// experiment/origin does not match the previous one.
if (experiment != last_experiment_id_ || origin != last_origin_)
origin_experiment_wash_ = true;
}
last_origin_ = origin;
last_experiment_id_ = experiment;
// If we observe multiple tags within the 30 second window, we will still
// reset the window to begin at the most recent occurrence, so that we will
// always be in a window in the 30 seconds from each occurrence.
last_prerender_seen_time_ = GetCurrentTimeTicks();
seen_any_pageload_ = false;
seen_pageload_started_after_prerender_ = false;
}
void PrerenderHistograms::RecordPrerenderStarted(Origin origin) const {
if (OriginIsOmnibox(origin)) {
UMA_HISTOGRAM_COUNTS(
StringPrintf("Prerender.OmniboxPrerenderCount_%.1f%s",
NetworkActionPredictor::get_hit_weight(),
PrerenderManager::GetModeString()).c_str(),
1);
}
}
void PrerenderHistograms::RecordUsedPrerender(Origin origin) const {
if (OriginIsOmnibox(origin)) {
UMA_HISTOGRAM_COUNTS(
StringPrintf("Prerender.OmniboxNavigationsUsedPrerenderCount_%.1f%s",
NetworkActionPredictor::get_hit_weight(),
PrerenderManager::GetModeString()).c_str(),
1);
}
}
base::TimeTicks PrerenderHistograms::GetCurrentTimeTicks() const {
return base::TimeTicks::Now();
}
// Helper macro for histograms.
#define RECORD_PLT(tag, perceived_page_load_time) { \
PREFIXED_HISTOGRAM( \
base::FieldTrial::MakeName(tag, "Prerender"), \
UMA_HISTOGRAM_CUSTOM_TIMES( \
name, \
perceived_page_load_time, \
base::TimeDelta::FromMilliseconds(10), \
base::TimeDelta::FromSeconds(60), \
100)); \
}
// Summary of all histograms Perceived PLT histograms:
// (all prefixed PerceivedPLT)
// PerceivedPLT -- Perceived Pageloadtimes (PPLT) for all pages in the group.
// ...Windowed -- PPLT for pages in the 30s after a prerender is created.
// ...Matched -- A prerendered page that was swapped in. In the NoUse
// and Control group cases, while nothing ever gets swapped in, we do keep
// track of what would be prerendered and would be swapped in -- and those
// cases are what is classified as Match for these groups.
// ...MatchedComplete -- A prerendered page that was swapped in + a few
// that were not swapped in so that the set of pages lines up more closely with
// the control group.
// ...FirstAfterMiss -- First page to finish loading after a prerender, which
// is different from the page that was prerendered.
// ...FirstAfterMissNonOverlapping -- Same as FirstAfterMiss, but only
// triggering for the first page to finish after the prerender that also started
// after the prerender started.
// ...FirstAfterMissBoth -- pages meeting
// FirstAfterMiss AND FirstAfterMissNonOverlapping
// ...FirstAfterMissAnyOnly -- pages meeting
// FirstAfterMiss but NOT FirstAfterMissNonOverlapping
// ..FirstAfterMissNonOverlappingOnly -- pages meeting
// FirstAfterMissNonOverlapping but NOT FirstAfterMiss
void PrerenderHistograms::RecordPerceivedPageLoadTime(
base::TimeDelta perceived_page_load_time, bool was_prerender,
bool was_complete_prerender, const GURL& url) {
if (!IsWebURL(url))
return;
bool within_window = WithinWindow();
bool is_google_url = IsGoogleDomain(url);
RECORD_PLT("PerceivedPLT", perceived_page_load_time);
if (within_window)
RECORD_PLT("PerceivedPLTWindowed", perceived_page_load_time);
if (was_prerender || was_complete_prerender) {
if (was_prerender)
RECORD_PLT("PerceivedPLTMatched", perceived_page_load_time);
if (was_complete_prerender)
RECORD_PLT("PerceivedPLTMatchedComplete", perceived_page_load_time);
seen_any_pageload_ = true;
seen_pageload_started_after_prerender_ = true;
} else if (within_window) {
RECORD_PLT("PerceivedPLTWindowNotMatched", perceived_page_load_time);
if (!is_google_url) {
bool recorded_any = false;
bool recorded_non_overlapping = false;
if (!seen_any_pageload_) {
seen_any_pageload_ = true;
RECORD_PLT("PerceivedPLTFirstAfterMiss", perceived_page_load_time);
recorded_any = true;
}
if (!seen_pageload_started_after_prerender_ &&
perceived_page_load_time <= GetTimeSinceLastPrerender()) {
seen_pageload_started_after_prerender_ = true;
RECORD_PLT("PerceivedPLTFirstAfterMissNonOverlapping",
perceived_page_load_time);
recorded_non_overlapping = true;
}
if (recorded_any || recorded_non_overlapping) {
if (recorded_any && recorded_non_overlapping) {
RECORD_PLT("PerceivedPLTFirstAfterMissBoth",
perceived_page_load_time);
} else if (recorded_any) {
RECORD_PLT("PerceivedPLTFirstAfterMissAnyOnly",
perceived_page_load_time);
} else if (recorded_non_overlapping) {
RECORD_PLT("PerceivedPLTFirstAfterMissNonOverlappingOnly",
perceived_page_load_time);
}
}
}
}
}
void PrerenderHistograms::RecordPageLoadTimeNotSwappedIn(
base::TimeDelta page_load_time, const GURL& url) const {
// If the URL to be prerendered is not a http[s] URL, or is a Google URL,
// do not record.
if (!IsWebURL(url) || IsGoogleDomain(url))
return;
RECORD_PLT("PrerenderNotSwappedInPLT", page_load_time);
}
void PrerenderHistograms::RecordPercentLoadDoneAtSwapin(double fraction)
const {
if (fraction < 0.0 || fraction > 1.0)
return;
int percentage = static_cast<int>(fraction * 100);
if (percentage < 0 || percentage > 100)
return;
PREFIXED_HISTOGRAM(
base::FieldTrial::MakeName("FinalStatus", "PercentLoadDoneAtSwapin"),
HISTOGRAM_PERCENTAGE(name, percentage));
}
base::TimeDelta PrerenderHistograms::GetTimeSinceLastPrerender() const {
return base::TimeTicks::Now() - last_prerender_seen_time_;
}
bool PrerenderHistograms::WithinWindow() const {
if (last_prerender_seen_time_.is_null())
return false;
return GetTimeSinceLastPrerender() <=
base::TimeDelta::FromSeconds(kWindowDurationSeconds);
}
void PrerenderHistograms::RecordTimeUntilUsed(
base::TimeDelta time_until_used, base::TimeDelta max_age) const {
PREFIXED_HISTOGRAM(
"TimeUntilUsed",
UMA_HISTOGRAM_CUSTOM_TIMES(
name,
time_until_used,
base::TimeDelta::FromMilliseconds(10),
max_age,
50));
}
void PrerenderHistograms::RecordPerSessionCount(int count) const {
PREFIXED_HISTOGRAM(
"PrerendersPerSessionCount",
UMA_HISTOGRAM_COUNTS(name, count));
}
void PrerenderHistograms::RecordTimeBetweenPrerenderRequests(
base::TimeDelta time) const {
PREFIXED_HISTOGRAM(
"TimeBetweenPrerenderRequests",
UMA_HISTOGRAM_TIMES(name, time));
}
void PrerenderHistograms::RecordFinalStatus(
Origin origin,
uint8 experiment_id,
PrerenderContents::MatchCompleteStatus mc_status,
FinalStatus final_status) const {
DCHECK(final_status != FINAL_STATUS_MAX);
// There are three cases for MatchCompleteStatus:
// MATCH_COMPLETE_DEFAULT:
// In this case, Match & MatchComplete line up. So we record this in both
// histograms.
// MATCH_COMPLETE_REPLACED: The actual prerender was replaced by a dummy.
// So we only record it in (the actual) FinalStatus, but not MatchComplete.
// MATCH_COMPLETE_REPLACEMENT: This is a pseudo element to emulate what
// the control group would do. Since it won't actually be swapped in,
// it may not go into FinalStatus. Since in the control group it would be
// swapped in though, it must go into MatchComplete.
if (mc_status != PrerenderContents::MATCH_COMPLETE_REPLACEMENT) {
PREFIXED_HISTOGRAM_ORIGIN_EXPERIMENT(
base::FieldTrial::MakeName("FinalStatus", "Prerender"),
origin, experiment_id,
UMA_HISTOGRAM_ENUMERATION(name, final_status, FINAL_STATUS_MAX));
}
if (mc_status != PrerenderContents::MATCH_COMPLETE_REPLACED) {
PREFIXED_HISTOGRAM_ORIGIN_EXPERIMENT(
base::FieldTrial::MakeName("FinalStatusMatchComplete", "Prerender"),
origin, experiment_id,
UMA_HISTOGRAM_ENUMERATION(name, final_status, FINAL_STATUS_MAX));
}
}
uint8 PrerenderHistograms::GetCurrentExperimentId() const {
if (!WithinWindow())
return kNoExperiment;
return last_experiment_id_;
}
Origin PrerenderHistograms::GetCurrentOrigin() const {
if (!WithinWindow())
return ORIGIN_LINK_REL_PRERENDER;
return last_origin_;
}
bool PrerenderHistograms::IsOriginExperimentWash() const {
if (!WithinWindow())
return false;
return origin_experiment_wash_;
}
} // namespace prerender
<|endoftext|> |
<commit_before>// ******************************************************************************************
// * This project is licensed under the GNU Affero GPL v3. Copyright © 2014 A3Wasteland.com *
// ******************************************************************************************
#define playerMenuDialog 55500
#define playerMenuPlayerSkin 55501
#define playerMenuPlayerGun 55502
#define playerMenuPlayerItems 55503
#define playerMenuPlayerPos 55504
#define playerMenuPlayerList 55505
#define playerMenuSpectateButton 55506
#define playerMenuPlayerObject 55507
#define playerMenuPlayerHealth 55508
#define playerMenuWarnMessage 55509
#define playerMenuPlayerUID 55510
#define playerMenuPlayerBank 55511
class PlayersMenu
{
idd = playerMenuDialog;
movingEnable = false;
enableSimulation = true;
class controlsBackground {
class MainBackground: w_RscPicture
{
idc = -1;
colorText[] = {1, 1, 1, 1};
colorBackground[] = {0,0,0,0};
text = "#(argb,8,8,3)color(0,0,0,0.6)";
x = 0.1875 * safezoneW + safezoneX;
y = 0.15 * safezoneH + safezoneY;
w = 0.60 * safezoneW;
h = 0.661111 * safezoneH;
};
class TopBar: w_RscPicture
{
idc = -1;
colorText[] = {1, 1, 1, 1};
colorBackground[] = {0,0,0,0};
text = "#(argb,8,8,3)color(0.45,0.005,0,1)";
x = 0.1875 * safezoneW + safezoneX;
y = 0.15 * safezoneH + safezoneY;
w = 0.60 * safezoneW;
h = 0.05 * safezoneH;
};
class DialogTitleText: w_RscText
{
idc = -1;
text = "Player Menu";
font = "PuristaMedium";
sizeEx = "( ( ( ((safezoneW / safezoneH) min 1.2) / 1.2) / 25) * 1)";
x = 0.20 * safezoneW + safezoneX;
y = 0.155 * safezoneH + safezoneY;
w = 0.0844792 * safezoneW;
h = 0.0448148 * safezoneH;
};
class PlayerUIDText: w_RscText
{
idc = playerMenuPlayerUID;
text = "UID:";
sizeEx = 0.030;
x = 0.52 * safezoneW + safezoneX;
y = 0.215 * safezoneH + safezoneY;
w = 0.25 * safezoneW;
h = 0.04 * safezoneH;
};
class PlayerObjectText: w_RscText
{
idc = playerMenuPlayerObject;
text = "Slot:";
sizeEx = 0.030;
x = 0.52 * safezoneW + safezoneX;
y = 0.235 * safezoneH + safezoneY;
w = 0.25 * safezoneW;
h = 0.04 * safezoneH;
};
class PlayerSkinText: w_RscText
{
idc = playerMenuPlayerSkin;
text = "Skin:";
sizeEx = 0.030;
x = 0.52 * safezoneW + safezoneX;
y = 0.255 * safezoneH + safezoneY;
w = 0.25 * safezoneW;
h = 0.04 * safezoneH;
};
class PlayerGunText: w_RscText
{
idc = playerMenuPlayerGun;
text = "Money:";
sizeEx = 0.030;
x = 0.52 * safezoneW + safezoneX;
y = 0.275 * safezoneH + safezoneY;
w = 0.25 * safezoneW;
h = 0.04 * safezoneH;
};
class PlayerBankText: w_RscText
{
idc = playerMenuPlayerBank;
text = "Money:";
sizeEx = 0.030;
x = 0.52 * safezoneW + safezoneX;
y = 0.295 * safezoneH + safezoneY;
w = 0.25 * safezoneW;
h = 0.04 * safezoneH;
};
class PlayerItemsText: w_RscText
{
idc = playerMenuPlayerItems;
text = "Items:";
sizeEx = 0.030;
x = 0.52 * safezoneW + safezoneX;
y = 0.315 * safezoneH + safezoneY;
w = 0.40 * safezoneW;
h = 0.04 * safezoneH;
};
class PlayerHealthText: w_RscText
{
idc = playerMenuPlayerHealth;
text = "Health:";
sizeEx = 0.030;
x = 0.52 * safezoneW + safezoneX;
y = 0.335 * safezoneH + safezoneY;
w = 0.25 * safezoneW;
h = 0.04 * safezoneH;
};
class PlayerPosistionText: w_RscText
{
idc = playerMenuPlayerPos;
text = "Position:";
sizeEx = 0.030;
x = 0.52 * safezoneW + safezoneX;
y = 0.355 * safezoneH + safezoneY;
w = 0.25 * safezoneW;
h = 0.04 * safezoneH;
};
};
class controls {
class PlayerEditBox:w_RscEdit
{
idc=playerMenuWarnMessage;
x = 0.60 * safezoneW + safezoneX;
y = 0.745 * safezoneH + safezoneY;
w = 0.175 * safezoneW;
h = 0.045 * safezoneH;
colorDisabled[] = {1,1,1,0.3};
};
class PlayerListBox: w_RscList
{
idc = playerMenuPlayerList;
onLBSelChanged="[2,_this select 1] execVM ""client\systems\adminPanel\importvalues.sqf"";";
x = 0.2 * safezoneW + safezoneX;
y = 0.225 * safezoneH + safezoneY;
w = 0.315 * safezoneW;
h = 0.45 * safezoneH;
};
class SpectateButton: w_RscButton
{
idc = playerMenuSpectateButton;
text = "Spectate";
onButtonClick = "[0] execVM 'client\systems\adminPanel\playerSelect.sqf'";
x = 0.2 * safezoneW + safezoneX;
y = 0.70 * safezoneH + safezoneY;
w = 0.05 * safezoneW;
h = 0.04 * safezoneH;
};
class SlayButton: w_RscButton
{
idc = -1;
text = "Slay";
onButtonClick = "[2] execVM 'client\systems\adminPanel\playerSelect.sqf'";
x = 0.2 * safezoneW + safezoneX;
y = 0.748 * safezoneH + safezoneY;
w = 0.05 * safezoneW;
h = 0.04 * safezoneH;
};
class UnlockTeamSwitchButton: w_RscButton
{
idc = -1;
text = "Unlock Team Switch";
onButtonClick = "[3] execVM 'client\systems\adminPanel\playerSelect.sqf'";
x = 0.255 * safezoneW + safezoneX;
y = 0.70 * safezoneH + safezoneY;
w = 0.11 * safezoneW;
h = 0.04 * safezoneH;
};
class UnlockTeamKillerButton: w_RscButton
{
idc = -1;
text = "Unlock Team Kill";
onButtonClick = "[4] execVM 'client\systems\adminPanel\playerSelect.sqf'";
x = 0.255 * safezoneW + safezoneX;
y = 0.748 * safezoneH + safezoneY;
w = 0.11 * safezoneW;
h = 0.04 * safezoneH;
};
class RemoveAllMoneyButton: w_RscButton
{
idc = -1;
text = "Remove Money";
onButtonClick = "[5] execVM 'client\systems\adminPanel\playerSelect.sqf'";
x = 0.3705 * safezoneW + safezoneX;
y = 0.70 * safezoneH + safezoneY;
w = 0.105 * safezoneW;
h = 0.04 * safezoneH;
};
class RemoveAllWeaponsButton: w_RscButton
{
idc = -1;
text = "Remove All";
onButtonClick = "[6] execVM 'client\systems\adminPanel\playerSelect.sqf'";
x = 0.3705 * safezoneW + safezoneX;
y = 0.748 * safezoneH + safezoneY;
w = 0.105 * safezoneW;
h = 0.04 * safezoneH;
};
class CheckPlayerGearButton: w_RscButton
{
idc = -1;
text = "Hurt";
onButtonClick = "[7] execVM 'client\systems\adminPanel\playerSelect.sqf'";
x = 0.482 * safezoneW + safezoneX;
y = 0.748 * safezoneH + safezoneY;
w = 0.05 * safezoneW;
h = 0.04 * safezoneH;
};
class WarnButton: w_RscButton
{
idc = -1;
text = "Warn";
onButtonClick = "[1] execVM 'client\systems\adminPanel\playerSelect.sqf'";
x = 0.600 * safezoneW + safezoneX;
y = 0.70 * safezoneH + safezoneY;
w = 0.05 * safezoneW;
h = 0.04 * safezoneH;
};
class KickButton: w_RscButton
{
idc = -1;
text = "Kick";
onButtonClick = "[8] execVM 'client\systems\adminPanel\playerSelect.sqf'";
x = 0.675 * safezoneW + safezoneX;
y = 0.70 * safezoneH + safezoneY;
w = 0.05 * safezoneW;
h = 0.04 * safezoneH;
};
};
};
<commit_msg>Moved button<commit_after>// ******************************************************************************************
// * This project is licensed under the GNU Affero GPL v3. Copyright © 2014 A3Wasteland.com *
// ******************************************************************************************
#define playerMenuDialog 55500
#define playerMenuPlayerSkin 55501
#define playerMenuPlayerGun 55502
#define playerMenuPlayerItems 55503
#define playerMenuPlayerPos 55504
#define playerMenuPlayerList 55505
#define playerMenuSpectateButton 55506
#define playerMenuPlayerObject 55507
#define playerMenuPlayerHealth 55508
#define playerMenuWarnMessage 55509
#define playerMenuPlayerUID 55510
#define playerMenuPlayerBank 55511
class PlayersMenu
{
idd = playerMenuDialog;
movingEnable = false;
enableSimulation = true;
class controlsBackground {
class MainBackground: w_RscPicture
{
idc = -1;
colorText[] = {1, 1, 1, 1};
colorBackground[] = {0,0,0,0};
text = "#(argb,8,8,3)color(0,0,0,0.6)";
x = 0.1875 * safezoneW + safezoneX;
y = 0.15 * safezoneH + safezoneY;
w = 0.60 * safezoneW;
h = 0.661111 * safezoneH;
};
class TopBar: w_RscPicture
{
idc = -1;
colorText[] = {1, 1, 1, 1};
colorBackground[] = {0,0,0,0};
text = "#(argb,8,8,3)color(0.45,0.005,0,1)";
x = 0.1875 * safezoneW + safezoneX;
y = 0.15 * safezoneH + safezoneY;
w = 0.60 * safezoneW;
h = 0.05 * safezoneH;
};
class DialogTitleText: w_RscText
{
idc = -1;
text = "Player Menu";
font = "PuristaMedium";
sizeEx = "( ( ( ((safezoneW / safezoneH) min 1.2) / 1.2) / 25) * 1)";
x = 0.20 * safezoneW + safezoneX;
y = 0.155 * safezoneH + safezoneY;
w = 0.0844792 * safezoneW;
h = 0.0448148 * safezoneH;
};
class PlayerUIDText: w_RscText
{
idc = playerMenuPlayerUID;
text = "UID:";
sizeEx = 0.030;
x = 0.52 * safezoneW + safezoneX;
y = 0.215 * safezoneH + safezoneY;
w = 0.25 * safezoneW;
h = 0.04 * safezoneH;
};
class PlayerObjectText: w_RscText
{
idc = playerMenuPlayerObject;
text = "Slot:";
sizeEx = 0.030;
x = 0.52 * safezoneW + safezoneX;
y = 0.235 * safezoneH + safezoneY;
w = 0.25 * safezoneW;
h = 0.04 * safezoneH;
};
class PlayerSkinText: w_RscText
{
idc = playerMenuPlayerSkin;
text = "Skin:";
sizeEx = 0.030;
x = 0.52 * safezoneW + safezoneX;
y = 0.255 * safezoneH + safezoneY;
w = 0.25 * safezoneW;
h = 0.04 * safezoneH;
};
class PlayerGunText: w_RscText
{
idc = playerMenuPlayerGun;
text = "Money:";
sizeEx = 0.030;
x = 0.52 * safezoneW + safezoneX;
y = 0.275 * safezoneH + safezoneY;
w = 0.25 * safezoneW;
h = 0.04 * safezoneH;
};
class PlayerBankText: w_RscText
{
idc = playerMenuPlayerBank;
text = "Money:";
sizeEx = 0.030;
x = 0.52 * safezoneW + safezoneX;
y = 0.295 * safezoneH + safezoneY;
w = 0.25 * safezoneW;
h = 0.04 * safezoneH;
};
class PlayerItemsText: w_RscText
{
idc = playerMenuPlayerItems;
text = "Items:";
sizeEx = 0.030;
x = 0.52 * safezoneW + safezoneX;
y = 0.315 * safezoneH + safezoneY;
w = 0.40 * safezoneW;
h = 0.04 * safezoneH;
};
class PlayerHealthText: w_RscText
{
idc = playerMenuPlayerHealth;
text = "Health:";
sizeEx = 0.030;
x = 0.52 * safezoneW + safezoneX;
y = 0.335 * safezoneH + safezoneY;
w = 0.25 * safezoneW;
h = 0.04 * safezoneH;
};
class PlayerPosistionText: w_RscText
{
idc = playerMenuPlayerPos;
text = "Position:";
sizeEx = 0.030;
x = 0.52 * safezoneW + safezoneX;
y = 0.355 * safezoneH + safezoneY;
w = 0.25 * safezoneW;
h = 0.04 * safezoneH;
};
};
class controls {
class PlayerEditBox:w_RscEdit
{
idc=playerMenuWarnMessage;
x = 0.60 * safezoneW + safezoneX;
y = 0.745 * safezoneH + safezoneY;
w = 0.175 * safezoneW;
h = 0.045 * safezoneH;
colorDisabled[] = {1,1,1,0.3};
};
class PlayerListBox: w_RscList
{
idc = playerMenuPlayerList;
onLBSelChanged="[2,_this select 1] execVM ""client\systems\adminPanel\importvalues.sqf"";";
x = 0.2 * safezoneW + safezoneX;
y = 0.225 * safezoneH + safezoneY;
w = 0.315 * safezoneW;
h = 0.45 * safezoneH;
};
class SpectateButton: w_RscButton
{
idc = playerMenuSpectateButton;
text = "Spectate";
onButtonClick = "[0] execVM 'client\systems\adminPanel\playerSelect.sqf'";
x = 0.2 * safezoneW + safezoneX;
y = 0.70 * safezoneH + safezoneY;
w = 0.05 * safezoneW;
h = 0.04 * safezoneH;
};
class SlayButton: w_RscButton
{
idc = -1;
text = "Slay";
onButtonClick = "[2] execVM 'client\systems\adminPanel\playerSelect.sqf'";
x = 0.2 * safezoneW + safezoneX;
y = 0.748 * safezoneH + safezoneY;
w = 0.05 * safezoneW;
h = 0.04 * safezoneH;
};
class UnlockTeamSwitchButton: w_RscButton
{
idc = -1;
text = "Unlock Team Switch";
onButtonClick = "[3] execVM 'client\systems\adminPanel\playerSelect.sqf'";
x = 0.255 * safezoneW + safezoneX;
y = 0.70 * safezoneH + safezoneY;
w = 0.11 * safezoneW;
h = 0.04 * safezoneH;
};
class UnlockTeamKillerButton: w_RscButton
{
idc = -1;
text = "Unlock Team Kill";
onButtonClick = "[4] execVM 'client\systems\adminPanel\playerSelect.sqf'";
x = 0.255 * safezoneW + safezoneX;
y = 0.748 * safezoneH + safezoneY;
w = 0.11 * safezoneW;
h = 0.04 * safezoneH;
};
class RemoveAllMoneyButton: w_RscButton
{
idc = -1;
text = "Remove Money";
onButtonClick = "[5] execVM 'client\systems\adminPanel\playerSelect.sqf'";
x = 0.3705 * safezoneW + safezoneX;
y = 0.70 * safezoneH + safezoneY;
w = 0.105 * safezoneW;
h = 0.04 * safezoneH;
};
class RemoveAllWeaponsButton: w_RscButton
{
idc = -1;
text = "Remove All";
onButtonClick = "[6] execVM 'client\systems\adminPanel\playerSelect.sqf'";
x = 0.3705 * safezoneW + safezoneX;
y = 0.748 * safezoneH + safezoneY;
w = 0.105 * safezoneW;
h = 0.04 * safezoneH;
};
class CheckPlayerGearButton: w_RscButton
{
idc = -1;
text = "Hurt";
onButtonClick = "[7] execVM 'client\systems\adminPanel\playerSelect.sqf'";
x = 0.482 * safezoneW + safezoneX;
y = 0.748 * safezoneH + safezoneY;
w = 0.05 * safezoneW;
h = 0.04 * safezoneH;
};
class WarnButton: w_RscButton
{
idc = -1;
text = "Warn";
onButtonClick = "[1] execVM 'client\systems\adminPanel\playerSelect.sqf'";
x = 0.600 * safezoneW + safezoneX;
y = 0.70 * safezoneH + safezoneY;
w = 0.05 * safezoneW;
h = 0.04 * safezoneH;
};
class KickButton: w_RscButton
{
idc = -1;
text = "Kick";
onButtonClick = "[8] execVM 'client\systems\adminPanel\playerSelect.sqf'";
x = 0.665 * safezoneW + safezoneX;
y = 0.70 * safezoneH + safezoneY;
w = 0.05 * safezoneW;
h = 0.04 * safezoneH;
};
};
};
<|endoftext|> |
<commit_before>/*
* Copyright (c) 2013 Maciej Cencora <m.cencora@gmail.com>
*
* Permission is hereby granted, free of charge, to any person
* obtaining a copy of this software and associated documentation
* files (the "Software"), to deal in the Software without
* restriction, including without limitation the rights to use,
* copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following
* conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
* OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
* WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
*
*/
#include "refactorplugin.h"
#include <interfaces/contextmenuextension.h>
#include <language/interfaces/editorcontext.h>
#include <QAction>
#include <QString>
#include <KPluginFactory>
#include <KAboutData>
#include <KTextEditor/Document>
#include "CppManip.hpp"
#include "SourceReplacement.hpp"
#include "sourcemodificationsapplier.hpp"
#include "ui/extractfunctiondialog.h"
K_PLUGIN_FACTORY(RefactorPluginFactory, registerPlugin<RefactorPlugin>();)
K_EXPORT_PLUGIN(RefactorPluginFactory(
KAboutData("kdevcpprefactor",
"kdevcpprefactor",
ki18n("C/C++ code refactoring support"),
"0.0.1",
ki18n("C/C++ code refactoring support"),
KAboutData::License_GPL)
.addAuthor(ki18n("Maciej Cencora"), ki18n("Author"), "m.cencora@gmail.com")))
RefactorPlugin::RefactorPlugin(QObject* parent, const QVariantList&)
: IPlugin(RefactorPluginFactory::componentData(), parent)
{}
KDevelop::ContextMenuExtension RefactorPlugin::contextMenuExtension(KDevelop::Context* context)
{
KDevelop::ContextMenuExtension extension;
if ((this->context = dynamic_cast<KDevelop::EditorContext*>(context))) {
QAction* action = new QAction(i18n("Extract function"), this);
// action->setData(QVariant::fromValue(IndexedDeclaration(declaration)));
connect(action, SIGNAL(triggered(bool)), this, SLOT(showExtractFunction()));
extension.addAction(KDevelop::ContextMenuExtension::RefactorGroup, action);
}
return extension;
}
namespace
{
SourceSelection rangeToSourceSelection(const KTextEditor::Range& range)
{
SourceSelection ss;
ss.from.col = range.start().column();
ss.from.row = range.start().line();
ss.to.col = range.end().column();
ss.to.row = range.start().line();
return ss;
}
}
void RefactorPlugin::showExtractFunction()
{
ExtractFunctionDialog *d = new ExtractFunctionDialog();
connect(d, SIGNAL(accepted(QString)), this, SLOT(executeExtractFunction(QString)));
d->exec();
delete d;
}
void RefactorPlugin::executeExtractFunction(const QString& functionName)
{
try
{
KTextEditor::Range range = context->view()->selectionRange();
if (range.isEmpty())
{
range = KTextEditor::Range(context->view()->cursorPosition(),
context->view()->cursorPosition());
}
SourceSelection selection = rangeToSourceSelection(range);
QString fileName = context->url().path();
SourceReplacements reps = extractFunctionInFile(functionName.toAscii().constData(),
selection,
fileName.toLocal8Bit().constData());
SourceModificationsApplier app;
app.apply(context->view()->document(), reps);
context->view()->setSelection(KTextEditor::Range());
}
catch (const std::exception&)
{ }
}
#include "refactorplugin.moc"
<commit_msg>Show information about failed extraction<commit_after>/*
* Copyright (c) 2013 Maciej Cencora <m.cencora@gmail.com>
*
* Permission is hereby granted, free of charge, to any person
* obtaining a copy of this software and associated documentation
* files (the "Software"), to deal in the Software without
* restriction, including without limitation the rights to use,
* copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following
* conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
* OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
* WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
*
*/
#include "refactorplugin.h"
#include <interfaces/contextmenuextension.h>
#include <language/interfaces/editorcontext.h>
#include <QAction>
#include <QString>
#include <KPluginFactory>
#include <KAboutData>
#include <KTextEditor/Document>
#include "CppManip.hpp"
#include "SourceReplacement.hpp"
#include "sourcemodificationsapplier.hpp"
#include "ui/extractfunctiondialog.h"
K_PLUGIN_FACTORY(RefactorPluginFactory, registerPlugin<RefactorPlugin>();)
K_EXPORT_PLUGIN(RefactorPluginFactory(
KAboutData("kdevcpprefactor",
"kdevcpprefactor",
ki18n("C/C++ code refactoring support"),
"0.0.1",
ki18n("C/C++ code refactoring support"),
KAboutData::License_GPL)
.addAuthor(ki18n("Maciej Cencora"), ki18n("Author"), "m.cencora@gmail.com")))
RefactorPlugin::RefactorPlugin(QObject* parent, const QVariantList&)
: IPlugin(RefactorPluginFactory::componentData(), parent)
{}
KDevelop::ContextMenuExtension RefactorPlugin::contextMenuExtension(KDevelop::Context* context)
{
KDevelop::ContextMenuExtension extension;
if ((this->context = dynamic_cast<KDevelop::EditorContext*>(context))) {
QAction* action = new QAction(i18n("Extract function"), this);
// action->setData(QVariant::fromValue(IndexedDeclaration(declaration)));
connect(action, SIGNAL(triggered(bool)), this, SLOT(showExtractFunction()));
extension.addAction(KDevelop::ContextMenuExtension::RefactorGroup, action);
}
return extension;
}
namespace
{
SourceSelection rangeToSourceSelection(const KTextEditor::Range& range)
{
SourceSelection ss;
ss.from.col = range.start().column();
ss.from.row = range.start().line();
ss.to.col = range.end().column();
ss.to.row = range.start().line();
return ss;
}
}
void RefactorPlugin::showExtractFunction()
{
ExtractFunctionDialog *d = new ExtractFunctionDialog();
connect(d, SIGNAL(accepted(QString)), this, SLOT(executeExtractFunction(QString)));
d->exec();
delete d;
}
void RefactorPlugin::executeExtractFunction(const QString& functionName)
{
try
{
KTextEditor::Range range = context->view()->selectionRange();
if (range.isEmpty())
{
range = KTextEditor::Range(context->view()->cursorPosition(),
context->view()->cursorPosition());
}
SourceSelection selection = rangeToSourceSelection(range);
QString fileName = context->url().path();
SourceReplacements reps = extractFunctionInFile(functionName.toAscii().constData(),
selection,
fileName.toLocal8Bit().constData());
SourceModificationsApplier app;
app.apply(context->view()->document(), reps);
context->view()->setSelection(KTextEditor::Range());
}
catch (const std::exception& e)
{
KMessageBox::error(nullptr, e.what(), i18n("Function extraction failed"));
}
}
#include "refactorplugin.moc"
<|endoftext|> |
<commit_before>#pragma once
#include "ReflectionUtility.hpp"
// Remove Lua if the user requests so.
#ifdef REFLECT_NO_LUA
#define REFLECT_LUA_PLUGIN_LIST_ENTRY
#else
#define REFLECT_LUA_PLUGIN_LIST_ENTRY ,Lua::ReflectionPlugin
#endif
// Includes for all plugins: include your custom plugin here.
#include "DefaultPlugin.hpp"
#ifndef REFLECT_NO_LUA
#include "lua/ReflectionPlugin.hpp"
#endif
// List of plugin types: add a backslash to the previous line,
// then write `,MyPluginType` to hook in `MyPluginType`.
#define REFLECT_PLUGIN_LIST \
REFLECT_LUA_PLUGIN_LIST_ENTRY
#include "PluginHelper.hpp"
<commit_msg>Quick compile fix.<commit_after>#pragma once
#include "ReflectionUtility.hpp"
// Remove Lua if the user requests so.
#ifdef REFLECT_NO_LUA
#define REFLECT_LUA_PLUGIN_LIST_ENTRY
#else
#define REFLECT_LUA_PLUGIN_LIST_ENTRY ,Lua::ReflectionPlugin
#endif
// Includes for all plugins: include your custom plugin here.
#include "DefaultPlugin.hpp"
#ifndef REFLECT_NO_LUA
#include "lua/ReflectionPlugin.hpp"
#endif
// List of plugin types: add a backslash to the previous line,
// then write `,MyPluginType` to hook in `MyPluginType`.
#define REFLECT_PLUGIN_LIST reflect::DefaultPlugin \
REFLECT_LUA_PLUGIN_LIST_ENTRY
#include "PluginHelper.hpp"
<|endoftext|> |
<commit_before>/*=====================================================================
QGroundControl Open Source Ground Control Station
(c) 2009, 2010 QGROUNDCONTROL PROJECT <http://www.qgroundcontrol.org>
This file is part of the QGROUNDCONTROL project
QGROUNDCONTROL 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.
QGROUNDCONTROL 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 QGROUNDCONTROL. If not, see <http://www.gnu.org/licenses/>.
======================================================================*/
/**
* @file
* @brief Implementation of CommConfigurationWindow
*
* @author Lorenz Meier <mavteam@student.ethz.ch>
*
*/
#include <QDebug>
#include <QDir>
#include <QFileInfoList>
#include <QBoxLayout>
#include <QWidget>
#include "CommConfigurationWindow.h"
#include "SerialConfigurationWindow.h"
#include "SerialLink.h"
#include "UDPLink.h"
#include "MAVLinkSimulationLink.h"
#ifdef XBEELINK
#include "XbeeLink.h"
#include "XbeeConfigurationWindow.h"
#endif // XBEELINK
#ifdef OPAL_RT
#include "OpalLink.h"
#include "OpalLinkConfigurationWindow.h"
#endif
#include "MAVLinkProtocol.h"
#include "MAVLinkSettingsWidget.h"
#include "QGCUDPLinkConfiguration.h"
#include "LinkManager.h"
#include "MainWindow.h"
CommConfigurationWindow::CommConfigurationWindow(LinkInterface* link, ProtocolInterface* protocol, QWidget *parent) : QDialog(parent)
{
this->link = link;
// Setup the user interface according to link type
ui.setupUi(this);
// Center the window on the screen.
QRect position = frameGeometry();
position.moveCenter(QDesktopWidget().availableGeometry().center());
move(position.topLeft());
// Initialize basic ui state
// Do not allow changes here unless advanced is checked
ui.connectionType->setEnabled(false);
ui.linkType->setEnabled(false);
ui.protocolGroupBox->setVisible(false);
ui.protocolTypeGroupBox->setVisible(false);
// Connect UI element visibility to checkbox
//connect(ui.advancedOptionsCheckBox, SIGNAL(clicked(bool)), ui.connectionType, SLOT(setEnabled(bool)));
//connect(ui.advancedOptionsCheckBox, SIGNAL(clicked(bool)), ui.linkType, SLOT(setEnabled(bool)));
//connect(ui.advancedOptionsCheckBox, SIGNAL(clicked(bool)), ui.protocolGroupBox, SLOT(setVisible(bool)));
ui.advancedOptionsCheckBox->setVisible(false);
//connect(ui.advCheckBox,SIGNAL(clicked(bool)),ui.advancedOptionsCheckBox,SLOT(setChecked(bool)));
connect(ui.advCheckBox,SIGNAL(clicked(bool)),ui.protocolTypeGroupBox,SLOT(setVisible(bool)));
connect(ui.advCheckBox, SIGNAL(clicked(bool)), ui.connectionType, SLOT(setEnabled(bool)));
connect(ui.advCheckBox, SIGNAL(clicked(bool)), ui.linkType, SLOT(setEnabled(bool)));
connect(ui.advCheckBox, SIGNAL(clicked(bool)), ui.protocolGroupBox, SLOT(setVisible(bool)));
// add link types
ui.linkType->addItem(tr("Serial"), QGC_LINK_SERIAL);
ui.linkType->addItem(tr("UDP"), QGC_LINK_UDP);
ui.linkType->addItem(tr("Simulation"), QGC_LINK_SIMULATION);
ui.linkType->addItem(tr("Opal-RT Link"), QGC_LINK_OPAL);
#ifdef XBEELINK
ui.linkType->addItem(tr("Xbee API"),QGC_LINK_XBEE);
#endif // XBEELINK
ui.linkType->setEditable(false);
ui.connectionType->addItem("MAVLink", QGC_PROTOCOL_MAVLINK);
// Create action to open this menu
// Create configuration action for this link
// Connect the current UAS
action = new QAction(QIcon(":/files/images/devices/network-wireless.svg"), "", this);
LinkManager::instance()->add(link);
action->setData(link->getId());
action->setEnabled(true);
action->setVisible(true);
setLinkName(link->getName());
connect(action, SIGNAL(triggered()), this, SLOT(show()));
// Make sure that a change in the link name will be reflected in the UI
connect(link, SIGNAL(nameChanged(QString)), this, SLOT(setLinkName(QString)));
// Setup user actions and link notifications
connect(ui.connectButton, SIGNAL(clicked()), this, SLOT(setConnection()));
connect(ui.closeButton, SIGNAL(clicked()), this->window(), SLOT(close()));
connect(ui.deleteButton, SIGNAL(clicked()), this, SLOT(remove()));
connect(this->link, SIGNAL(connected(bool)), this, SLOT(connectionState(bool)));
// Fill in the current data
if(this->link->isConnected()) ui.connectButton->setChecked(true);
//connect(this->link, SIGNAL(connected(bool)), ui.connectButton, SLOT(setChecked(bool)));
if(this->link->isConnected()) {
ui.connectionStatusLabel->setText(tr("Connected"));
// TODO Deactivate all settings to force user to manually disconnect first
} else {
ui.connectionStatusLabel->setText(tr("Disconnected"));
}
// TODO Move these calls to each link so that dynamic casts vanish
// Open details pane for serial link if necessary
SerialLink* serial = dynamic_cast<SerialLink*>(link);
if(serial != 0) {
QWidget* conf = new SerialConfigurationWindow(serial, this);
ui.linkScrollArea->setWidget(conf);
ui.linkGroupBox->setTitle(tr("Serial Link"));
ui.linkType->setCurrentIndex(0);
}
UDPLink* udp = dynamic_cast<UDPLink*>(link);
if (udp != 0) {
QWidget* conf = new QGCUDPLinkConfiguration(udp, this);
ui.linkScrollArea->setWidget(conf);
ui.linkGroupBox->setTitle(tr("UDP Link"));
ui.linkType->setCurrentIndex(1);
}
MAVLinkSimulationLink* sim = dynamic_cast<MAVLinkSimulationLink*>(link);
if (sim != 0) {
ui.linkType->setCurrentIndex(2);
ui.linkGroupBox->setTitle(tr("MAVLink Simulation Link"));
}
#ifdef OPAL_RT
OpalLink* opal = dynamic_cast<OpalLink*>(link);
if (opal != 0) {
QWidget* conf = new OpalLinkConfigurationWindow(opal, this);
QBoxLayout* layout = new QBoxLayout(QBoxLayout::LeftToRight, ui.linkGroupBox);
layout->addWidget(conf);
ui.linkGroupBox->setLayout(layout);
ui.linkType->setCurrentIndex(3);
ui.linkGroupBox->setTitle(tr("Opal-RT Link"));
}
#endif
#ifdef XBEELINK
XbeeLink* xbee = dynamic_cast<XbeeLink*>(link); // new Konrad
if(xbee != 0)
{
QWidget* conf = new XbeeConfigurationWindow(xbee,this);
ui.linkScrollArea->setWidget(conf);
ui.linkGroupBox->setTitle(tr("Xbee Link"));
ui.linkType->setCurrentIndex(4);
connect(xbee,SIGNAL(tryConnectBegin(bool)),ui.actionConnect,SLOT(setDisabled(bool)));
connect(xbee,SIGNAL(tryConnectEnd(bool)),ui.actionConnect,SLOT(setEnabled(bool)));
}
#endif // XBEELINK
if (serial == 0 && udp == 0 && sim == 0
#ifdef OPAL_RT
&& opal == 0
#endif
#ifdef XBEELINK
&& xbee == 0
#endif // XBEELINK
) {
qDebug() << "Link is NOT a known link, can't open configuration window";
}
#ifdef XBEELINK
connect(ui.linkType,SIGNAL(currentIndexChanged(int)),this,SLOT(setLinkType(int)));
#endif // XBEELINK
// Open details pane for MAVLink if necessary
MAVLinkProtocol* mavlink = dynamic_cast<MAVLinkProtocol*>(protocol);
if (mavlink != 0) {
QWidget* conf = new MAVLinkSettingsWidget(mavlink, this);
ui.protocolScrollArea->setWidget(conf);
ui.protocolGroupBox->setTitle(protocol->getName()+" (Global Settings)");
} else {
qDebug() << "Protocol is NOT MAVLink, can't open configuration window";
}
// Open details for UDP link if necessary
// TODO
// Display the widget
this->window()->setWindowTitle(tr("Settings for ") + this->link->getName());
this->hide();
}
CommConfigurationWindow::~CommConfigurationWindow()
{
}
QAction* CommConfigurationWindow::getAction()
{
return action;
}
void CommConfigurationWindow::setLinkType(int linktype)
{
if(link->isConnected())
{
// close old configuration window
this->window()->close();
}
else
{
// delete old configuration window
this->remove();
}
LinkInterface *tmpLink(NULL);
switch(linktype)
{
#ifdef XBEELINK
case 4:
{
XbeeLink *xbee = new XbeeLink();
tmpLink = xbee;
MainWindow::instance()->addLink(tmpLink);
break;
}
#endif // XBEELINK
case 1:
{
UDPLink *udp = new UDPLink();
tmpLink = udp;
MainWindow::instance()->addLink(tmpLink);
break;
}
#ifdef OPAL_RT
case 3:
{
OpalLink* opal = new OpalLink();
tmpLink = opal;
MainWindow::instance()->addLink(tmpLink);
break;
}
#endif // OPAL_RT
default:
{
}
case 0:
{
SerialLink *serial = new SerialLink();
tmpLink = serial;
MainWindow::instance()->addLink(tmpLink);
break;
}
}
// trigger new window
const int32_t& linkIndex(LinkManager::instance()->getLinks().indexOf(tmpLink));
const int32_t& linkID(LinkManager::instance()->getLinks()[linkIndex]->getId());
QList<QAction*> actions = MainWindow::instance()->listLinkMenuActions();
foreach (QAction* act, actions)
{
if (act->data().toInt() == linkID)
{
act->trigger();
break;
}
}
}
void CommConfigurationWindow::setProtocol(int protocol)
{
qDebug() << "Changing to protocol" << protocol;
}
void CommConfigurationWindow::setConnection()
{
if(!link->isConnected()) {
link->connect();
QGC::SLEEP::msleep(100);
if (link->isConnected())
// Auto-close window on connect
this->window()->close();
} else {
link->disconnect();
}
}
void CommConfigurationWindow::setLinkName(QString name)
{
action->setText(tr("%1 Settings").arg(name));
action->setStatusTip(tr("Adjust setting for link %1").arg(name));
this->window()->setWindowTitle(tr("Settings for %1").arg(name));
}
void CommConfigurationWindow::remove()
{
if(action) delete action; //delete action first since it has a pointer to link
action=NULL;
if(link) {
LinkManager::instance()->removeLink(link); //remove link from LinkManager list
link->disconnect(); //disconnect port, and also calls terminate() to stop the thread
if (link->isRunning()) link->terminate(); // terminate() the serial thread just in case it is still running
link->wait(); // wait() until thread is stoped before deleting
link->deleteLater();
}
link=NULL;
this->window()->close();
this->deleteLater();
}
void CommConfigurationWindow::connectionState(bool connect)
{
ui.connectButton->setChecked(connect);
if(connect) {
ui.connectionStatusLabel->setText(tr("Connected"));
ui.connectButton->setText(tr("Disconnect"));
} else {
ui.connectionStatusLabel->setText(tr("Disconnected"));
ui.connectButton->setText(tr("Connect"));
}
}
<commit_msg>CommConfigurationWindow - don't try to manually center, now that it is a proper QDialog<commit_after>/*=====================================================================
QGroundControl Open Source Ground Control Station
(c) 2009, 2010 QGROUNDCONTROL PROJECT <http://www.qgroundcontrol.org>
This file is part of the QGROUNDCONTROL project
QGROUNDCONTROL 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.
QGROUNDCONTROL 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 QGROUNDCONTROL. If not, see <http://www.gnu.org/licenses/>.
======================================================================*/
/**
* @file
* @brief Implementation of CommConfigurationWindow
*
* @author Lorenz Meier <mavteam@student.ethz.ch>
*
*/
#include <QDebug>
#include <QDir>
#include <QFileInfoList>
#include <QBoxLayout>
#include <QWidget>
#include "CommConfigurationWindow.h"
#include "SerialConfigurationWindow.h"
#include "SerialLink.h"
#include "UDPLink.h"
#include "MAVLinkSimulationLink.h"
#ifdef XBEELINK
#include "XbeeLink.h"
#include "XbeeConfigurationWindow.h"
#endif // XBEELINK
#ifdef OPAL_RT
#include "OpalLink.h"
#include "OpalLinkConfigurationWindow.h"
#endif
#include "MAVLinkProtocol.h"
#include "MAVLinkSettingsWidget.h"
#include "QGCUDPLinkConfiguration.h"
#include "LinkManager.h"
#include "MainWindow.h"
CommConfigurationWindow::CommConfigurationWindow(LinkInterface* link, ProtocolInterface* protocol, QWidget *parent) : QDialog(parent)
{
this->link = link;
// Setup the user interface according to link type
ui.setupUi(this);
// Initialize basic ui state
// Do not allow changes here unless advanced is checked
ui.connectionType->setEnabled(false);
ui.linkType->setEnabled(false);
ui.protocolGroupBox->setVisible(false);
ui.protocolTypeGroupBox->setVisible(false);
// Connect UI element visibility to checkbox
//connect(ui.advancedOptionsCheckBox, SIGNAL(clicked(bool)), ui.connectionType, SLOT(setEnabled(bool)));
//connect(ui.advancedOptionsCheckBox, SIGNAL(clicked(bool)), ui.linkType, SLOT(setEnabled(bool)));
//connect(ui.advancedOptionsCheckBox, SIGNAL(clicked(bool)), ui.protocolGroupBox, SLOT(setVisible(bool)));
ui.advancedOptionsCheckBox->setVisible(false);
//connect(ui.advCheckBox,SIGNAL(clicked(bool)),ui.advancedOptionsCheckBox,SLOT(setChecked(bool)));
connect(ui.advCheckBox,SIGNAL(clicked(bool)),ui.protocolTypeGroupBox,SLOT(setVisible(bool)));
connect(ui.advCheckBox, SIGNAL(clicked(bool)), ui.connectionType, SLOT(setEnabled(bool)));
connect(ui.advCheckBox, SIGNAL(clicked(bool)), ui.linkType, SLOT(setEnabled(bool)));
connect(ui.advCheckBox, SIGNAL(clicked(bool)), ui.protocolGroupBox, SLOT(setVisible(bool)));
// add link types
ui.linkType->addItem(tr("Serial"), QGC_LINK_SERIAL);
ui.linkType->addItem(tr("UDP"), QGC_LINK_UDP);
ui.linkType->addItem(tr("Simulation"), QGC_LINK_SIMULATION);
ui.linkType->addItem(tr("Opal-RT Link"), QGC_LINK_OPAL);
#ifdef XBEELINK
ui.linkType->addItem(tr("Xbee API"),QGC_LINK_XBEE);
#endif // XBEELINK
ui.linkType->setEditable(false);
ui.connectionType->addItem("MAVLink", QGC_PROTOCOL_MAVLINK);
// Create action to open this menu
// Create configuration action for this link
// Connect the current UAS
action = new QAction(QIcon(":/files/images/devices/network-wireless.svg"), "", this);
LinkManager::instance()->add(link);
action->setData(link->getId());
action->setEnabled(true);
action->setVisible(true);
setLinkName(link->getName());
connect(action, SIGNAL(triggered()), this, SLOT(show()));
// Make sure that a change in the link name will be reflected in the UI
connect(link, SIGNAL(nameChanged(QString)), this, SLOT(setLinkName(QString)));
// Setup user actions and link notifications
connect(ui.connectButton, SIGNAL(clicked()), this, SLOT(setConnection()));
connect(ui.closeButton, SIGNAL(clicked()), this->window(), SLOT(close()));
connect(ui.deleteButton, SIGNAL(clicked()), this, SLOT(remove()));
connect(this->link, SIGNAL(connected(bool)), this, SLOT(connectionState(bool)));
// Fill in the current data
if(this->link->isConnected()) ui.connectButton->setChecked(true);
//connect(this->link, SIGNAL(connected(bool)), ui.connectButton, SLOT(setChecked(bool)));
if(this->link->isConnected()) {
ui.connectionStatusLabel->setText(tr("Connected"));
// TODO Deactivate all settings to force user to manually disconnect first
} else {
ui.connectionStatusLabel->setText(tr("Disconnected"));
}
// TODO Move these calls to each link so that dynamic casts vanish
// Open details pane for serial link if necessary
SerialLink* serial = dynamic_cast<SerialLink*>(link);
if(serial != 0) {
QWidget* conf = new SerialConfigurationWindow(serial, this);
ui.linkScrollArea->setWidget(conf);
ui.linkGroupBox->setTitle(tr("Serial Link"));
ui.linkType->setCurrentIndex(0);
}
UDPLink* udp = dynamic_cast<UDPLink*>(link);
if (udp != 0) {
QWidget* conf = new QGCUDPLinkConfiguration(udp, this);
ui.linkScrollArea->setWidget(conf);
ui.linkGroupBox->setTitle(tr("UDP Link"));
ui.linkType->setCurrentIndex(1);
}
MAVLinkSimulationLink* sim = dynamic_cast<MAVLinkSimulationLink*>(link);
if (sim != 0) {
ui.linkType->setCurrentIndex(2);
ui.linkGroupBox->setTitle(tr("MAVLink Simulation Link"));
}
#ifdef OPAL_RT
OpalLink* opal = dynamic_cast<OpalLink*>(link);
if (opal != 0) {
QWidget* conf = new OpalLinkConfigurationWindow(opal, this);
QBoxLayout* layout = new QBoxLayout(QBoxLayout::LeftToRight, ui.linkGroupBox);
layout->addWidget(conf);
ui.linkGroupBox->setLayout(layout);
ui.linkType->setCurrentIndex(3);
ui.linkGroupBox->setTitle(tr("Opal-RT Link"));
}
#endif
#ifdef XBEELINK
XbeeLink* xbee = dynamic_cast<XbeeLink*>(link); // new Konrad
if(xbee != 0)
{
QWidget* conf = new XbeeConfigurationWindow(xbee,this);
ui.linkScrollArea->setWidget(conf);
ui.linkGroupBox->setTitle(tr("Xbee Link"));
ui.linkType->setCurrentIndex(4);
connect(xbee,SIGNAL(tryConnectBegin(bool)),ui.actionConnect,SLOT(setDisabled(bool)));
connect(xbee,SIGNAL(tryConnectEnd(bool)),ui.actionConnect,SLOT(setEnabled(bool)));
}
#endif // XBEELINK
if (serial == 0 && udp == 0 && sim == 0
#ifdef OPAL_RT
&& opal == 0
#endif
#ifdef XBEELINK
&& xbee == 0
#endif // XBEELINK
) {
qDebug() << "Link is NOT a known link, can't open configuration window";
}
#ifdef XBEELINK
connect(ui.linkType,SIGNAL(currentIndexChanged(int)),this,SLOT(setLinkType(int)));
#endif // XBEELINK
// Open details pane for MAVLink if necessary
MAVLinkProtocol* mavlink = dynamic_cast<MAVLinkProtocol*>(protocol);
if (mavlink != 0) {
QWidget* conf = new MAVLinkSettingsWidget(mavlink, this);
ui.protocolScrollArea->setWidget(conf);
ui.protocolGroupBox->setTitle(protocol->getName()+" (Global Settings)");
} else {
qDebug() << "Protocol is NOT MAVLink, can't open configuration window";
}
// Open details for UDP link if necessary
// TODO
// Display the widget
this->window()->setWindowTitle(tr("Settings for ") + this->link->getName());
this->hide();
}
CommConfigurationWindow::~CommConfigurationWindow()
{
}
QAction* CommConfigurationWindow::getAction()
{
return action;
}
void CommConfigurationWindow::setLinkType(int linktype)
{
if(link->isConnected())
{
// close old configuration window
this->window()->close();
}
else
{
// delete old configuration window
this->remove();
}
LinkInterface *tmpLink(NULL);
switch(linktype)
{
#ifdef XBEELINK
case 4:
{
XbeeLink *xbee = new XbeeLink();
tmpLink = xbee;
MainWindow::instance()->addLink(tmpLink);
break;
}
#endif // XBEELINK
case 1:
{
UDPLink *udp = new UDPLink();
tmpLink = udp;
MainWindow::instance()->addLink(tmpLink);
break;
}
#ifdef OPAL_RT
case 3:
{
OpalLink* opal = new OpalLink();
tmpLink = opal;
MainWindow::instance()->addLink(tmpLink);
break;
}
#endif // OPAL_RT
default:
{
}
case 0:
{
SerialLink *serial = new SerialLink();
tmpLink = serial;
MainWindow::instance()->addLink(tmpLink);
break;
}
}
// trigger new window
const int32_t& linkIndex(LinkManager::instance()->getLinks().indexOf(tmpLink));
const int32_t& linkID(LinkManager::instance()->getLinks()[linkIndex]->getId());
QList<QAction*> actions = MainWindow::instance()->listLinkMenuActions();
foreach (QAction* act, actions)
{
if (act->data().toInt() == linkID)
{
act->trigger();
break;
}
}
}
void CommConfigurationWindow::setProtocol(int protocol)
{
qDebug() << "Changing to protocol" << protocol;
}
void CommConfigurationWindow::setConnection()
{
if(!link->isConnected()) {
link->connect();
QGC::SLEEP::msleep(100);
if (link->isConnected())
// Auto-close window on connect
this->window()->close();
} else {
link->disconnect();
}
}
void CommConfigurationWindow::setLinkName(QString name)
{
action->setText(tr("%1 Settings").arg(name));
action->setStatusTip(tr("Adjust setting for link %1").arg(name));
this->window()->setWindowTitle(tr("Settings for %1").arg(name));
}
void CommConfigurationWindow::remove()
{
if(action) delete action; //delete action first since it has a pointer to link
action=NULL;
if(link) {
LinkManager::instance()->removeLink(link); //remove link from LinkManager list
link->disconnect(); //disconnect port, and also calls terminate() to stop the thread
if (link->isRunning()) link->terminate(); // terminate() the serial thread just in case it is still running
link->wait(); // wait() until thread is stoped before deleting
link->deleteLater();
}
link=NULL;
this->window()->close();
this->deleteLater();
}
void CommConfigurationWindow::connectionState(bool connect)
{
ui.connectButton->setChecked(connect);
if(connect) {
ui.connectionStatusLabel->setText(tr("Connected"));
ui.connectButton->setText(tr("Disconnect"));
} else {
ui.connectionStatusLabel->setText(tr("Disconnected"));
ui.connectButton->setText(tr("Connect"));
}
}
<|endoftext|> |
<commit_before>// UVa11809 Floating-Point Numbers
#include <iostream>
#include <cmath>
#include <sstream>
#include <unordered_map>
#include <tuple>
using namespace std;
struct HashPair {
size_t operator()(const pair<double, int>& p) const {
return hash<double>()(p.first) ^ hash<int>()(p.second);
}
};
int main() {
unordered_map<pair<double, int>, pair<int,int>, HashPair> map;
// Build up the mapping table from "a * 2^b" to "c * 10^d"
for (int i = 0; i <= 9; ++i) {
for (int j = 1; j <= 30; ++j) {
double a = 1 - pow(2, -(i + 1)); // max mantissa = 1 - 2^(-i-1)
int b = pow(2, j) - 1; // max exponent = 2^j - 1
// a * 2^b = c * 10^d => log10(a) + b * log10(2) = log10(c) + d
// Let d = floor(log10(a) + b * log10(2)), then c = 10^(x-d)
double x = log10(a) + b * log10(2);
int d = floor(x);
double c = pow(10, x - d);
map[make_pair(c, d)] = make_pair(i, j);
}
}
string s;
while (cin >> s && s != "0e0") {
s[17] = ' '; // Replace 'e' with ' '.
stringstream ss(s);
double p;
int q;
ss >> p >> q;
// Lookup the mapping table from "c * 10^d" to
for (const auto& pv : map) {
pair<double, int> key;
pair<int, int> val;
tie(key, val) = pv;
if (fabs(key.first - p) < 1e-4 && key.second == q) {
cout << val.first << ' ' << val.second << endl;
}
}
}
return 0;
}<commit_msg>add solution<commit_after>// UVa11809 Floating-Point Numbers
#include <iostream>
#include <cmath>
#include <sstream>
#include <unordered_map>
#include <tuple>
using namespace std;
struct HashPair {
size_t operator()(const pair<double, int>& p) const {
return hash<double>()(p.first) ^ hash<int>()(p.second);
}
};
int main() {
unordered_map<pair<double, int>, pair<int,int>, HashPair> map;
// Build up the mapping table from "a * 2^b" to "c * 10^d"
for (int i = 0; i <= 9; ++i) {
for (int j = 1; j <= 30; ++j) {
double a = 1 - pow(2, -(i + 1)); // max mantissa = 1 - 2^(-i-1)
int b = pow(2, j) - 1; // max exponent = 2^j - 1
// a * 2^b = c * 10^d => log10(a) + b * log10(2) = log10(c) + d
// Let d = floor(log10(a) + b * log10(2)), then c = 10^(x-d)
double x = log10(a) + b * log10(2);
int d = floor(x);
double c = pow(10, x - d);
map[make_pair(c, d)] = make_pair(i, j);
}
}
string s;
while (cin >> s && s != "0e0") {
s[17] = ' '; // Replace 'e' with ' '.
stringstream ss(s);
double p;
int q;
ss >> p >> q;
// Lookup the mapping table from "c * 10^d" to
for (const auto& kv : map) {
pair<double, int> key;
pair<int, int> val;
tie(key, val) = kv;
if (fabs(key.first - p) < 1e-4 && key.second == q) {
cout << val.first << ' ' << val.second << endl;
}
}
}
return 0;
}<|endoftext|> |
<commit_before>//Copyright (c) 2017 Ultimaker B.V.
//CuraEngine is released under the terms of the AGPLv3 or higher.
#include "MinimumSpanningTree.h"
namespace cura
{
MinimumSpanningTree::MinimumSpanningTree(const std::vector<Point> vertices) : adjacency_graph(prim(vertices))
{
//Just copy over the fields.
}
MinimumSpanningTree::Edge::Edge(const Point start, const Point end) : start(start), end(end)
{
//Just copy over the fields.
}
int MinimumSpanningTree::Edge::length() const
{
return vSize2(start - end);
}
const std::unordered_map<Point, std::vector<MinimumSpanningTree::Edge>> MinimumSpanningTree::prim(const std::vector<Point>& vertices) const
{
std::unordered_map<Point, std::vector<Edge>> result;
if (vertices.empty())
{
return result; //No vertices, so we can't create edges either.
}
result.reserve(vertices.size());
Point first_point = vertices[0];
result[first_point] = std::vector<MinimumSpanningTree::Edge>(); //Start with one vertex in the tree.
std::unordered_map<Point*, coord_t> smallest_distance; //The shortest distance to the current tree.
smallest_distance.reserve(vertices.size());
std::unordered_map<Point*, Point*> smallest_distance_to; //Which point the shortest distance goes towards.
smallest_distance_to.reserve(vertices.size());
for(Point vertex : vertices)
{
if (vertex == first_point)
{
continue;
}
smallest_distance[&vertex] = vSize2(vertex - first_point);
smallest_distance_to[&vertex] = &first_point;
}
while(result.size() < vertices.size()) //All of the vertices need to be in the tree at the end.
{
//Choose the closest vertex to connect to.
//This search is O(V) right now, which can be made down to O(log(V)). This reduces the overall time complexity from O(V*V) to O(V*log(E)).
//However that requires an implementation of a heap that supports the decreaseKey operation, which is not in the std library.
//TODO: Implement this?
Point* closest_point = nullptr;
coord_t closest_distance = std::numeric_limits<coord_t>::max();
for(std::pair<Point*, coord_t> point_and_distance : smallest_distance)
{
if (point_and_distance.second < closest_distance) //This one's closer!
{
closest_point = point_and_distance.first;
closest_distance = point_and_distance.second;
}
}
//Add this point to the graph and remove it from the candidates.
Point closest_point_local = *closest_point;
if (result.find(closest_point_local) == result.end())
{
result[closest_point_local] = std::vector<Edge>();
}
result[closest_point_local].emplace_back(closest_point_local, *smallest_distance_to[closest_point]);
smallest_distance.erase(closest_point); //Remove it so we don't check for these points again.
smallest_distance_to.erase(closest_point);
//Update the distances of all points that are not in the graph.
for (std::pair<Point*, coord_t> point_and_distance : smallest_distance)
{
coord_t new_distance = vSize2(*closest_point - *point_and_distance.first);
if (new_distance < point_and_distance.second) //New point is closer.
{
smallest_distance[point_and_distance.first] = new_distance;
smallest_distance_to[point_and_distance.first] = closest_point;
}
}
}
return result;
}
std::vector<Point> MinimumSpanningTree::leaves() const
{
std::vector<Point> result;
for (std::pair<Point, std::vector<Edge>> node : adjacency_graph)
{
if (node.second.size() <= 1) //Leaves are nodes that have only one adjacent edge, or just the one node if the tree contains one node.
{
result.push_back(node.first);
}
}
}
}<commit_msg>Add edge to other side as well<commit_after>//Copyright (c) 2017 Ultimaker B.V.
//CuraEngine is released under the terms of the AGPLv3 or higher.
#include "MinimumSpanningTree.h"
namespace cura
{
MinimumSpanningTree::MinimumSpanningTree(const std::vector<Point> vertices) : adjacency_graph(prim(vertices))
{
//Just copy over the fields.
}
MinimumSpanningTree::Edge::Edge(const Point start, const Point end) : start(start), end(end)
{
//Just copy over the fields.
}
int MinimumSpanningTree::Edge::length() const
{
return vSize2(start - end);
}
const std::unordered_map<Point, std::vector<MinimumSpanningTree::Edge>> MinimumSpanningTree::prim(const std::vector<Point>& vertices) const
{
std::unordered_map<Point, std::vector<Edge>> result;
if (vertices.empty())
{
return result; //No vertices, so we can't create edges either.
}
result.reserve(vertices.size());
Point first_point = vertices[0];
result[first_point] = std::vector<MinimumSpanningTree::Edge>(); //Start with one vertex in the tree.
std::unordered_map<Point*, coord_t> smallest_distance; //The shortest distance to the current tree.
smallest_distance.reserve(vertices.size());
std::unordered_map<Point*, Point*> smallest_distance_to; //Which point the shortest distance goes towards.
smallest_distance_to.reserve(vertices.size());
for(Point vertex : vertices)
{
if (vertex == first_point)
{
continue;
}
smallest_distance[&vertex] = vSize2(vertex - first_point);
smallest_distance_to[&vertex] = &first_point;
}
while(result.size() < vertices.size()) //All of the vertices need to be in the tree at the end.
{
//Choose the closest vertex to connect to.
//This search is O(V) right now, which can be made down to O(log(V)). This reduces the overall time complexity from O(V*V) to O(V*log(E)).
//However that requires an implementation of a heap that supports the decreaseKey operation, which is not in the std library.
//TODO: Implement this?
Point* closest_point = nullptr;
coord_t closest_distance = std::numeric_limits<coord_t>::max();
for(std::pair<Point*, coord_t> point_and_distance : smallest_distance)
{
if (point_and_distance.second < closest_distance) //This one's closer!
{
closest_point = point_and_distance.first;
closest_distance = point_and_distance.second;
}
}
//Add this point to the graph and remove it from the candidates.
Point closest_point_local = *closest_point;
Point other_end = *smallest_distance_to[closest_point];
if (result.find(closest_point_local) == result.end())
{
result[closest_point_local] = std::vector<Edge>();
}
result[closest_point_local].emplace_back(closest_point_local, other_end);
if (result.find(other_end) == result.end())
{
result[other_end] = std::vector<Edge>();
}
result[other_end].emplace_back(other_end, closest_point_local);
smallest_distance.erase(closest_point); //Remove it so we don't check for these points again.
smallest_distance_to.erase(closest_point);
//Update the distances of all points that are not in the graph.
for (std::pair<Point*, coord_t> point_and_distance : smallest_distance)
{
coord_t new_distance = vSize2(*closest_point - *point_and_distance.first);
if (new_distance < point_and_distance.second) //New point is closer.
{
smallest_distance[point_and_distance.first] = new_distance;
smallest_distance_to[point_and_distance.first] = closest_point;
}
}
}
return result;
}
std::vector<Point> MinimumSpanningTree::leaves() const
{
std::vector<Point> result;
for (std::pair<Point, std::vector<Edge>> node : adjacency_graph)
{
if (node.second.size() <= 1) //Leaves are nodes that have only one adjacent edge, or just the one node if the tree contains one node.
{
result.push_back(node.first);
}
}
}
}<|endoftext|> |
<commit_before>#include <vector>
#include <boost/filesystem.hpp>
#include <QtMath>
#include <QTime>
#include "fish_annotator/common/species_dialog.h"
#include "fish_annotator/video_annotator/mainwindow.h"
#include "ui_mainwindow.h"
namespace fish_annotator { namespace video_annotator {
namespace fs = boost::filesystem;
MainWindow::MainWindow(QWidget *parent)
: QWidget(parent)
, annotation_(new VideoAnnotation)
, scene_(new QGraphicsScene)
, pixmap_item_(nullptr)
, ui_(new Ui::MainWidget)
, species_controls_(new SpeciesControls)
, video_path_()
, width_(0)
, height_(0)
, last_frame_(nullptr)
, last_position_(0)
, stopped_(true)
, was_stopped_(true)
, rate_(0.0)
, fish_id_(0)
, current_annotations_() {
ui_->setupUi(this);
ui_->videoWindow->setViewport(new QOpenGLWidget);
ui_->videoWindow->setViewportUpdateMode(QGraphicsView::FullViewportUpdate);
#ifdef _WIN32
setWindowIcon(QIcon(":/icons/FishAnnotator.ico"));
#endif
setStyleSheet("QPushButton { background-color: rgb(230, 230, 230);"
"border-style: outset; border-radius: 5px; border-width: 2px; "
"border-color: grey; padding: 6px;}"
"QPushButton:pressed{background-color: rgb(190, 190, 190); "
"border-style: outset; border-radius: 5px;"
"border-width: 2px; border-color: grey; padding: 6px;}");
ui_->sideBarLayout->addWidget(species_controls_.get());
ui_->videoWindow->setScene(scene_.get());
QObject::connect(species_controls_.get(), &SpeciesControls::individualAdded,
this, &MainWindow::addIndividual);
Player *player = new Player();
QThread *thread = new QThread();
QObject::connect(player, &Player::processedImage,
this, &MainWindow::showFrame);
QObject::connect(player, &Player::durationChanged,
this, &MainWindow::handlePlayerDurationChanged);
QObject::connect(player, &Player::playbackRateChanged,
this, &MainWindow::handlePlayerPlaybackRateChanged);
QObject::connect(player, &Player::resolutionChanged,
this, &MainWindow::handlePlayerResolutionChanged);
QObject::connect(player, &Player::stateChanged,
this, &MainWindow::handlePlayerStateChanged);
QObject::connect(player, &Player::mediaLoaded,
this, &MainWindow::handlePlayerMediaLoaded);
QObject::connect(player, &Player::error,
this, &MainWindow::handlePlayerError);
QObject::connect(this, &MainWindow::requestLoadVideo,
player, &Player::loadVideo);
QObject::connect(this, &MainWindow::requestPlay,
player, &Player::play);
QObject::connect(this, &MainWindow::requestStop,
player, &Player::stop);
QObject::connect(this, &MainWindow::requestSpeedUp,
player, &Player::speedUp);
QObject::connect(this, &MainWindow::requestSlowDown,
player, &Player::slowDown);
QObject::connect(this, &MainWindow::requestSetFrame,
player, &Player::setFrame);
QObject::connect(this, &MainWindow::requestNextFrame,
player, &Player::nextFrame);
QObject::connect(this, &MainWindow::requestPrevFrame,
player, &Player::prevFrame);
QObject::connect(thread, &QThread::finished,
player, &Player::deleteLater);
QObject::connect(thread, &QThread::finished,
thread, &QThread::deleteLater);
player->moveToThread(thread);
thread->start();
}
void MainWindow::resizeEvent(QResizeEvent *event) {
ui_->videoWindow->fitInView(scene_->sceneRect(), Qt::KeepAspectRatio);
}
void MainWindow::on_play_clicked() {
if(stopped_ == true) {
emit requestPlay();
ui_->play->setText("Pause");
ui_->reverse->setEnabled(true);
ui_->plusOneFrame->setEnabled(false);
ui_->minusOneFrame->setEnabled(false);
}
else {
emit requestStop();
ui_->play->setText("Play");
ui_->reverse->setEnabled(false);
ui_->plusOneFrame->setEnabled(true);
ui_->minusOneFrame->setEnabled(true);
}
}
void MainWindow::on_faster_clicked() {
emit requestSpeedUp();
}
void MainWindow::on_slower_clicked() {
emit requestSlowDown();
}
void MainWindow::on_plusOneFrame_clicked() {
emit requestNextFrame();
}
void MainWindow::on_minusOneFrame_clicked() {
emit requestPrevFrame();
}
void MainWindow::on_loadVideo_clicked() {
QString file_str = QFileDialog::getOpenFileName(
this,
tr("Open Video"),
QFileInfo(video_path_).dir().canonicalPath(),
tr("Video Files (*.avi *.mpg *.mp4 *.mkv)"));
QFileInfo file(file_str);
if(file.exists() && file.isFile()) {
emit requestLoadVideo(file_str);
}
}
void MainWindow::on_loadAnnotationFile_clicked() {
QString file_str = QFileDialog::getOpenFileName(
this,
tr("Open Annotation File"),
QFileInfo(video_path_).dir().canonicalPath(),
tr("Annotation Files (*.csv)"));
QFileInfo file(file_str);
if(file.exists() && file.isFile()) {
annotation_->read(file_str.toStdString());
drawAnnotations();
}
}
void MainWindow::on_saveAnnotationFile_clicked() {
fs::path vid_path(video_path_.toStdString());
annotation_->write(
vid_path.replace_extension(".csv"),
ui_->tripIDValue->text().toStdString(),
ui_->towIDValue->text().toStdString(),
ui_->reviewerNameValue->text().toStdString(),
ui_->towStatus->isChecked() ? "Open" : "Closed",
rate_);
}
void MainWindow::on_writeImage_clicked() {
}
void MainWindow::on_videoSlider_sliderPressed() {
was_stopped_ = stopped_;
emit requestStop();
}
void MainWindow::on_videoSlider_sliderReleased() {
emit requestSetFrame(ui_->videoSlider->sliderPosition());
if(was_stopped_ == false) emit requestPlay();
}
void MainWindow::on_videoSlider_actionTriggered(int action) {
emit requestSetFrame(ui_->videoSlider->sliderPosition());
}
void MainWindow::on_typeMenu_currentTextChanged(const QString &text) {
auto trk = annotation_->findTrack(fish_id_);
if(trk != nullptr) {
trk->species_ = text.toStdString();
}
}
void MainWindow::on_subTypeMenu_currentTextChanged(const QString &text) {
auto trk = annotation_->findTrack(fish_id_);
if(trk != nullptr) {
trk->subspecies_ = text.toStdString();
}
}
void MainWindow::on_prevFish_clicked() {
auto trk = annotation_->prevTrack(fish_id_);
if(trk != nullptr) {
fish_id_ = trk->id_;
updateStats();
}
}
void MainWindow::on_nextFish_clicked() {
auto trk = annotation_->nextTrack(fish_id_);
if(trk != nullptr) {
fish_id_ = trk->id_;
updateStats();
}
}
void MainWindow::on_removeFish_clicked() {
annotation_->remove(fish_id_);
drawAnnotations();
}
void MainWindow::on_goToFrame_clicked() {
qint64 frame = annotation_->trackFirstFrame(fish_id_);
emit requestSetFrame(frame);
}
void MainWindow::on_goToFishVal_returnPressed() {
fish_id_ = ui_->goToFishVal->text().toInt();
updateStats();
}
void MainWindow::on_addRegion_clicked() {
annotation_->insert(std::make_shared<DetectionAnnotation>(
last_position_,
fish_id_,
Rect(0, 0, 100, 100)));
drawAnnotations();
}
void MainWindow::on_removeRegion_clicked() {
annotation_->remove(last_position_, fish_id_);
drawAnnotations();
}
void MainWindow::on_nextAndCopy_clicked() {
auto det = annotation_->findDetection(last_position_, fish_id_);
if(det != nullptr) {
on_plusOneFrame_clicked();
annotation_->insert(std::make_shared<DetectionAnnotation>(
last_position_,
fish_id_,
det->area_));
drawAnnotations();
}
else {
QMessageBox msgBox;
msgBox.setText("Could not find region to copy!");
msgBox.exec();
}
}
void MainWindow::showFrame(QImage image, qint64 frame) {
last_frame_ = image;
auto pixmap = QPixmap::fromImage(image);
pixmap_item_->setPixmap(pixmap);
ui_->videoWindow->fitInView(scene_->sceneRect(), Qt::KeepAspectRatio);
last_position_ = frame;
drawAnnotations();
ui_->videoSlider->setValue(static_cast<int>(frame));
}
void MainWindow::addIndividual(std::string species, std::string subspecies) {
fish_id_ = annotation_->nextId();
annotation_->insert(std::make_shared<TrackAnnotation>(
fish_id_, species, subspecies));
on_addRegion_clicked();
updateStats();
drawAnnotations();
}
void MainWindow::handlePlayerDurationChanged(qint64 duration) {
ui_->videoSlider->setRange(0, duration);
ui_->videoSlider->setSingleStep(1);
ui_->videoSlider->setPageStep(duration / 20);
}
void MainWindow::handlePlayerPlaybackRateChanged(double rate) {
rate_ = rate;
ui_->currentSpeed->setText(QString("Current Speed: %1 FPS").arg(rate));
}
void MainWindow::handlePlayerResolutionChanged(qint64 width, qint64 height) {
width_ = width;
height_ = height;
}
void MainWindow::handlePlayerStateChanged(bool stopped) {
stopped_ = stopped;
}
void MainWindow::handlePlayerMediaLoaded(QString video_path) {
video_path_ = video_path;
ui_->videoSlider->setEnabled(true);
ui_->play->setEnabled(true);
ui_->faster->setEnabled(true);
ui_->slower->setEnabled(true);
ui_->minusOneFrame->setEnabled(true);
ui_->plusOneFrame->setEnabled(true);
ui_->loadVideo->setEnabled(true);
ui_->loadAnnotationFile->setEnabled(true);
ui_->saveAnnotationFile->setEnabled(true);
ui_->writeImage->setEnabled(true);
ui_->typeLabel->setEnabled(true);
ui_->typeMenu->setEnabled(true);
ui_->subTypeLabel->setEnabled(true);
ui_->subTypeMenu->setEnabled(true);
ui_->prevFish->setEnabled(true);
ui_->nextFish->setEnabled(true);
ui_->removeFish->setEnabled(true);
ui_->goToFrame->setEnabled(true);
ui_->goToFishLabel->setEnabled(true);
ui_->goToFishVal->setEnabled(true);
ui_->addRegion->setEnabled(true);
ui_->removeRegion->setEnabled(true);
ui_->nextAndCopy->setEnabled(true);
ui_->currentSpeed->setText("Current Speed: 100%");
this->setWindowTitle(video_path_);
annotation_->clear();
scene_->clear();
QPixmap pixmap(width_, height_);
pixmap_item_ = scene_->addPixmap(pixmap);
scene_->setSceneRect(0, 0, width_, height_);
ui_->videoWindow->show();
emit requestNextFrame();
}
void MainWindow::handlePlayerError(QString err) {
QMessageBox msgBox;
msgBox.setText(err);
msgBox.exec();
}
void MainWindow::updateStats() {
ui_->fishNumVal->setText(QString::number(fish_id_));
ui_->totalFishVal->setText(QString::number(annotation_->getTotal()));
ui_->frameCountedVal->setText(QString::number(
annotation_->trackFirstFrame(fish_id_)));
}
void MainWindow::drawAnnotations() {
for(auto ann : current_annotations_) {
scene_->removeItem(ann);
}
current_annotations_.clear();
for(auto ann : annotation_->getDetectionAnnotations(last_position_)) {
auto region = new AnnotatedRegion<DetectionAnnotation>(
ann->id_, ann, pixmap_item_->pixmap().toImage().rect());
scene_->addItem(region);
current_annotations_.push_back(region);
}
}
#include "../../include/fish_annotator/video_annotator/moc_mainwindow.cpp"
}} // namespace fish_annotator::video_annotator
<commit_msg>Add error message if no fish have been added before adding a region.<commit_after>#include <vector>
#include <boost/filesystem.hpp>
#include <QtMath>
#include <QTime>
#include "fish_annotator/common/species_dialog.h"
#include "fish_annotator/video_annotator/mainwindow.h"
#include "ui_mainwindow.h"
namespace fish_annotator { namespace video_annotator {
namespace fs = boost::filesystem;
MainWindow::MainWindow(QWidget *parent)
: QWidget(parent)
, annotation_(new VideoAnnotation)
, scene_(new QGraphicsScene)
, pixmap_item_(nullptr)
, ui_(new Ui::MainWidget)
, species_controls_(new SpeciesControls)
, video_path_()
, width_(0)
, height_(0)
, last_frame_(nullptr)
, last_position_(0)
, stopped_(true)
, was_stopped_(true)
, rate_(0.0)
, fish_id_(0)
, current_annotations_() {
ui_->setupUi(this);
ui_->videoWindow->setViewport(new QOpenGLWidget);
ui_->videoWindow->setViewportUpdateMode(QGraphicsView::FullViewportUpdate);
#ifdef _WIN32
setWindowIcon(QIcon(":/icons/FishAnnotator.ico"));
#endif
setStyleSheet("QPushButton { background-color: rgb(230, 230, 230);"
"border-style: outset; border-radius: 5px; border-width: 2px; "
"border-color: grey; padding: 6px;}"
"QPushButton:pressed{background-color: rgb(190, 190, 190); "
"border-style: outset; border-radius: 5px;"
"border-width: 2px; border-color: grey; padding: 6px;}");
ui_->sideBarLayout->addWidget(species_controls_.get());
ui_->videoWindow->setScene(scene_.get());
QObject::connect(species_controls_.get(), &SpeciesControls::individualAdded,
this, &MainWindow::addIndividual);
Player *player = new Player();
QThread *thread = new QThread();
QObject::connect(player, &Player::processedImage,
this, &MainWindow::showFrame);
QObject::connect(player, &Player::durationChanged,
this, &MainWindow::handlePlayerDurationChanged);
QObject::connect(player, &Player::playbackRateChanged,
this, &MainWindow::handlePlayerPlaybackRateChanged);
QObject::connect(player, &Player::resolutionChanged,
this, &MainWindow::handlePlayerResolutionChanged);
QObject::connect(player, &Player::stateChanged,
this, &MainWindow::handlePlayerStateChanged);
QObject::connect(player, &Player::mediaLoaded,
this, &MainWindow::handlePlayerMediaLoaded);
QObject::connect(player, &Player::error,
this, &MainWindow::handlePlayerError);
QObject::connect(this, &MainWindow::requestLoadVideo,
player, &Player::loadVideo);
QObject::connect(this, &MainWindow::requestPlay,
player, &Player::play);
QObject::connect(this, &MainWindow::requestStop,
player, &Player::stop);
QObject::connect(this, &MainWindow::requestSpeedUp,
player, &Player::speedUp);
QObject::connect(this, &MainWindow::requestSlowDown,
player, &Player::slowDown);
QObject::connect(this, &MainWindow::requestSetFrame,
player, &Player::setFrame);
QObject::connect(this, &MainWindow::requestNextFrame,
player, &Player::nextFrame);
QObject::connect(this, &MainWindow::requestPrevFrame,
player, &Player::prevFrame);
QObject::connect(thread, &QThread::finished,
player, &Player::deleteLater);
QObject::connect(thread, &QThread::finished,
thread, &QThread::deleteLater);
player->moveToThread(thread);
thread->start();
}
void MainWindow::resizeEvent(QResizeEvent *event) {
ui_->videoWindow->fitInView(scene_->sceneRect(), Qt::KeepAspectRatio);
}
void MainWindow::on_play_clicked() {
if(stopped_ == true) {
emit requestPlay();
ui_->play->setText("Pause");
ui_->reverse->setEnabled(true);
ui_->plusOneFrame->setEnabled(false);
ui_->minusOneFrame->setEnabled(false);
}
else {
emit requestStop();
ui_->play->setText("Play");
ui_->reverse->setEnabled(false);
ui_->plusOneFrame->setEnabled(true);
ui_->minusOneFrame->setEnabled(true);
}
}
void MainWindow::on_faster_clicked() {
emit requestSpeedUp();
}
void MainWindow::on_slower_clicked() {
emit requestSlowDown();
}
void MainWindow::on_plusOneFrame_clicked() {
emit requestNextFrame();
}
void MainWindow::on_minusOneFrame_clicked() {
emit requestPrevFrame();
}
void MainWindow::on_loadVideo_clicked() {
QString file_str = QFileDialog::getOpenFileName(
this,
tr("Open Video"),
QFileInfo(video_path_).dir().canonicalPath(),
tr("Video Files (*.avi *.mpg *.mp4 *.mkv)"));
QFileInfo file(file_str);
if(file.exists() && file.isFile()) {
emit requestLoadVideo(file_str);
}
}
void MainWindow::on_loadAnnotationFile_clicked() {
QString file_str = QFileDialog::getOpenFileName(
this,
tr("Open Annotation File"),
QFileInfo(video_path_).dir().canonicalPath(),
tr("Annotation Files (*.csv)"));
QFileInfo file(file_str);
if(file.exists() && file.isFile()) {
annotation_->read(file_str.toStdString());
drawAnnotations();
}
}
void MainWindow::on_saveAnnotationFile_clicked() {
fs::path vid_path(video_path_.toStdString());
annotation_->write(
vid_path.replace_extension(".csv"),
ui_->tripIDValue->text().toStdString(),
ui_->towIDValue->text().toStdString(),
ui_->reviewerNameValue->text().toStdString(),
ui_->towStatus->isChecked() ? "Open" : "Closed",
rate_);
}
void MainWindow::on_writeImage_clicked() {
}
void MainWindow::on_videoSlider_sliderPressed() {
was_stopped_ = stopped_;
emit requestStop();
}
void MainWindow::on_videoSlider_sliderReleased() {
emit requestSetFrame(ui_->videoSlider->sliderPosition());
if(was_stopped_ == false) emit requestPlay();
}
void MainWindow::on_videoSlider_actionTriggered(int action) {
emit requestSetFrame(ui_->videoSlider->sliderPosition());
}
void MainWindow::on_typeMenu_currentTextChanged(const QString &text) {
auto trk = annotation_->findTrack(fish_id_);
if(trk != nullptr) {
trk->species_ = text.toStdString();
}
}
void MainWindow::on_subTypeMenu_currentTextChanged(const QString &text) {
auto trk = annotation_->findTrack(fish_id_);
if(trk != nullptr) {
trk->subspecies_ = text.toStdString();
}
}
void MainWindow::on_prevFish_clicked() {
auto trk = annotation_->prevTrack(fish_id_);
if(trk != nullptr) {
fish_id_ = trk->id_;
updateStats();
}
}
void MainWindow::on_nextFish_clicked() {
auto trk = annotation_->nextTrack(fish_id_);
if(trk != nullptr) {
fish_id_ = trk->id_;
updateStats();
}
}
void MainWindow::on_removeFish_clicked() {
annotation_->remove(fish_id_);
drawAnnotations();
}
void MainWindow::on_goToFrame_clicked() {
qint64 frame = annotation_->trackFirstFrame(fish_id_);
emit requestSetFrame(frame);
}
void MainWindow::on_goToFishVal_returnPressed() {
fish_id_ = ui_->goToFishVal->text().toInt();
updateStats();
}
void MainWindow::on_addRegion_clicked() {
if(annotation_->getTotal() < 1) {
handlePlayerError("Please add a fish before adding a region!");
}
else {
annotation_->insert(std::make_shared<DetectionAnnotation>(
last_position_,
fish_id_,
Rect(0, 0, 100, 100)));
drawAnnotations();
}
}
void MainWindow::on_removeRegion_clicked() {
annotation_->remove(last_position_, fish_id_);
drawAnnotations();
}
void MainWindow::on_nextAndCopy_clicked() {
auto det = annotation_->findDetection(last_position_, fish_id_);
if(det != nullptr) {
on_plusOneFrame_clicked();
annotation_->insert(std::make_shared<DetectionAnnotation>(
last_position_,
fish_id_,
det->area_));
drawAnnotations();
}
else {
QMessageBox msgBox;
msgBox.setText("Could not find region to copy!");
msgBox.exec();
}
}
void MainWindow::showFrame(QImage image, qint64 frame) {
last_frame_ = image;
auto pixmap = QPixmap::fromImage(image);
pixmap_item_->setPixmap(pixmap);
ui_->videoWindow->fitInView(scene_->sceneRect(), Qt::KeepAspectRatio);
last_position_ = frame;
drawAnnotations();
ui_->videoSlider->setValue(static_cast<int>(frame));
}
void MainWindow::addIndividual(std::string species, std::string subspecies) {
fish_id_ = annotation_->nextId();
annotation_->insert(std::make_shared<TrackAnnotation>(
fish_id_, species, subspecies));
on_addRegion_clicked();
updateStats();
drawAnnotations();
}
void MainWindow::handlePlayerDurationChanged(qint64 duration) {
ui_->videoSlider->setRange(0, duration);
ui_->videoSlider->setSingleStep(1);
ui_->videoSlider->setPageStep(duration / 20);
}
void MainWindow::handlePlayerPlaybackRateChanged(double rate) {
rate_ = rate;
ui_->currentSpeed->setText(QString("Current Speed: %1 FPS").arg(rate));
}
void MainWindow::handlePlayerResolutionChanged(qint64 width, qint64 height) {
width_ = width;
height_ = height;
}
void MainWindow::handlePlayerStateChanged(bool stopped) {
stopped_ = stopped;
}
void MainWindow::handlePlayerMediaLoaded(QString video_path) {
video_path_ = video_path;
ui_->videoSlider->setEnabled(true);
ui_->play->setEnabled(true);
ui_->faster->setEnabled(true);
ui_->slower->setEnabled(true);
ui_->minusOneFrame->setEnabled(true);
ui_->plusOneFrame->setEnabled(true);
ui_->loadVideo->setEnabled(true);
ui_->loadAnnotationFile->setEnabled(true);
ui_->saveAnnotationFile->setEnabled(true);
ui_->writeImage->setEnabled(true);
ui_->typeLabel->setEnabled(true);
ui_->typeMenu->setEnabled(true);
ui_->subTypeLabel->setEnabled(true);
ui_->subTypeMenu->setEnabled(true);
ui_->prevFish->setEnabled(true);
ui_->nextFish->setEnabled(true);
ui_->removeFish->setEnabled(true);
ui_->goToFrame->setEnabled(true);
ui_->goToFishLabel->setEnabled(true);
ui_->goToFishVal->setEnabled(true);
ui_->addRegion->setEnabled(true);
ui_->removeRegion->setEnabled(true);
ui_->nextAndCopy->setEnabled(true);
ui_->currentSpeed->setText("Current Speed: 100%");
this->setWindowTitle(video_path_);
annotation_->clear();
scene_->clear();
QPixmap pixmap(width_, height_);
pixmap_item_ = scene_->addPixmap(pixmap);
scene_->setSceneRect(0, 0, width_, height_);
ui_->videoWindow->show();
emit requestNextFrame();
}
void MainWindow::handlePlayerError(QString err) {
QMessageBox msgBox;
msgBox.setText(err);
msgBox.exec();
}
void MainWindow::updateStats() {
ui_->fishNumVal->setText(QString::number(fish_id_));
ui_->totalFishVal->setText(QString::number(annotation_->getTotal()));
ui_->frameCountedVal->setText(QString::number(
annotation_->trackFirstFrame(fish_id_)));
}
void MainWindow::drawAnnotations() {
for(auto ann : current_annotations_) {
scene_->removeItem(ann);
}
current_annotations_.clear();
for(auto ann : annotation_->getDetectionAnnotations(last_position_)) {
auto region = new AnnotatedRegion<DetectionAnnotation>(
ann->id_, ann, pixmap_item_->pixmap().toImage().rect());
scene_->addItem(region);
current_annotations_.push_back(region);
}
}
#include "../../include/fish_annotator/video_annotator/moc_mainwindow.cpp"
}} // namespace fish_annotator::video_annotator
<|endoftext|> |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.