text
stringlengths 54
60.6k
|
|---|
<commit_before>#include <iostream>
#include "net/genecis_server.h"
using namespace std ;
int main() {
cout << "server running..." << endl ;
// try{
int port = 45000 ;
genecis_server server( port ) ;
while( true ) {
genecis_server new_sock ;
server.accept( new_sock ) ;
// try{
while( true ) {
string data ;
new_sock >> data ;
data = "How are you doing today?" ;
new_sock << data ;
}
// } catch (int) {}
}
// } catch (int) {}
cout << "server shutdown" << endl ;
}
<commit_msg>Added couts for debugging.<commit_after>#include <iostream>
#include "net/genecis_server.h"
using namespace std ;
int main() {
cout << "server running..." << endl ;
// try{
int port = 45000 ;
genecis_server server( port ) ;
while( true ) {
cout << "waiting for response from client..." << endl ;
genecis_server new_sock ;
server.accept( new_sock ) ;
// try{
while( true ) {
cout << "Client intialized..." << endl ;
string data ;
new_sock >> data ;
data = "How are you doing today?" ;
new_sock << data ;
}
// } catch (int) {}
}
// } catch (int) {}
cout << "server shutdown" << endl ;
}
<|endoftext|>
|
<commit_before>#include <vector>
#include <openssl/sha.h>
#include <openssl/hmac.h>
#include <opkele/util.h>
#include <opkele/exception.h>
#include <opkele/server.h>
#include <opkele/data.h>
namespace opkele {
using namespace std;
void server_t::associate(const params_t& pin,params_t& pout) {
util::dh_t dh;
util::bignum_t c_pub;
unsigned char key_sha1[SHA_DIGEST_LENGTH];
enum {
sess_cleartext,
sess_dh_sha1
} st = sess_cleartext;
if(
pin.has_param("openid.session_type")
&& pin.get_param("openid.session_type")=="DH-SHA1" ) {
/* TODO: fallback to cleartext in case of exceptions here? */
if(!(dh = DH_new()))
throw exception_openssl(OPKELE_CP_ "failed to DH_new()");
c_pub = util::base64_to_bignum(pin.get_param("openid.dh_consumer_public"));
if(pin.has_param("openid.dh_modulus"))
dh->p = util::base64_to_bignum(pin.get_param("openid.dh_modulus"));
else
dh->p = util::dec_to_bignum(data::_default_p);
if(pin.has_param("openid.dh_gen"))
dh->g = util::base64_to_bignum(pin.get_param("openid.dh_gen"));
else
dh->g = util::dec_to_bignum(data::_default_g);
if(!DH_generate_key(dh))
throw exception_openssl(OPKELE_CP_ "failed to DH_generate_key()");
vector<unsigned char> ck(DH_size(dh)+1);
unsigned char *ckptr = &(ck.front())+1;
int cklen = DH_compute_key(&(ck.front()),c_pub,dh);
if(cklen<0)
throw exception_openssl(OPKELE_CP_ "failed to DH_compute_key()");
if(cklen && (*ckptr)&0x80) {
(*(--ckptr)) = 0; ++cklen;
}
SHA1(ckptr,cklen,key_sha1);
st = sess_dh_sha1;
}
assoc_t assoc = alloc_assoc(mode_associate);
time_t now = time(0);
pout.clear();
pout["assoc_type"] = assoc->assoc_type();
pout["assoc_handle"] = assoc->handle();
/* TODO: eventually remove deprecated stuff */
pout["issued"] = util::time_to_w3c(now);
pout["expiry"] = util::time_to_w3c(now+assoc->expires_in());
pout["expires_in"] = util::long_to_string(assoc->expires_in());
secret_t secret = assoc->secret();
switch(st) {
case sess_dh_sha1:
pout["session_type"] = "DH-SHA1";
pout["dh_server_public"] = util::bignum_to_base64(dh->pub_key);
secret.enxor_to_base64(key_sha1,pout["enc_mac_key"]);
break;
default:
secret.to_base64(pout["mac_key"]);
break;
}
}
void server_t::checkid_immediate(const params_t& pin,string& return_to,params_t& pout,extension_t *ext) {
checkid_(mode_checkid_immediate,pin,return_to,pout,ext);
}
void server_t::checkid_setup(const params_t& pin,string& return_to,params_t& pout,extension_t *ext) {
checkid_(mode_checkid_setup,pin,return_to,pout,ext);
}
void server_t::checkid_(mode_t mode,const params_t& pin,string& return_to,params_t& pout,extension_t *ext) {
if(mode!=mode_checkid_immediate && mode!=mode_checkid_setup)
throw bad_input(OPKELE_CP_ "invalid checkid_* mode");
pout.clear();
assoc_t assoc;
try {
assoc = retrieve_assoc(pin.get_param("openid.assoc_handle"));
}catch(failed_lookup& fl) {
// no handle specified or no valid handle found, going dumb
assoc = alloc_assoc(mode_checkid_setup);
if(pin.has_param("openid.assoc_handle"))
pout["invalidate_handle"]=pin.get_param("openid.assoc_handle");
}
string trust_root;
try {
trust_root = pin.get_param("openid.trust_root");
}catch(failed_lookup& fl) { }
string identity = pin.get_param("openid.identity");
return_to = pin.get_param("openid.return_to");
validate(*assoc,pin,identity,trust_root);
pout["mode"] = "id_res";
pout["assoc_handle"] = assoc->handle();
if(pin.has_param("openid.assoc_handle") && assoc->stateless())
pout["invalidate_handle"] = pin.get_param("openid.assoc_handle");
pout["identity"] = identity;
pout["return_to"] = return_to;
/* TODO: eventually remove deprecated stuff */
time_t now = time(0);
pout["issued"] = util::time_to_w3c(now);
pout["valid_to"] = util::time_to_w3c(now+120);
pout["exipres_in"] = "120";
pout["signed"]="mode,identity,return_to";
if(ext) ext->checkid_hook(pin,pout);
pout.sign(assoc->secret(),pout["sig"],pout["signed"]);
}
void server_t::check_authentication(const params_t& pin,params_t& pout) {
vector<unsigned char> sig;
const string& sigenc = pin.get_param("openid.sig");
util::decode_base64(sigenc,sig);
assoc_t assoc;
try {
assoc = retrieve_assoc(pin.get_param("openid.assoc_handle"));
}catch(failed_lookup& fl) {
throw failed_assertion(OPKELE_CP_ "invalid handle or handle not specified");
}
if(!assoc->stateless())
throw stateful_handle(OPKELE_CP_ "will not do check_authentication on a stateful handle");
const string& slist = pin.get_param("openid.signed");
string kv;
string::size_type p =0;
while(true) {
string::size_type co = slist.find(',',p);
string f = (co==string::npos)?slist.substr(p):slist.substr(p,co-p);
kv += f;
kv += ':';
if(f=="mode")
kv += "id_res";
else {
f.insert(0,"openid.");
kv += pin.get_param(f);
}
kv += '\n';
if(co==string::npos)
break;
p = co+1;
}
secret_t secret = assoc->secret();
unsigned int md_len = 0;
unsigned char *md = HMAC(
EVP_sha1(),
&(secret.front()),secret.size(),
(const unsigned char *)kv.data(),kv.length(),
0,&md_len);
pout.clear();
if(sig.size()==md_len && !memcmp(&(sig.front()),md,md_len)) {
pout["is_valid"]="true";
pout["lifetime"]="60"; /* TODO: eventually remove deprecated stuff */
}else{
pout["is_valid"]="false";
pout["lifetime"]="0"; /* TODO: eventually remove deprecated stuff */
}
if(pin.has_param("openid.invalidate_handle")) {
string h = pin.get_param("openid.invalidate_handle");
try {
assoc_t assoc = retrieve_assoc(h);
}catch(invalid_handle& ih) {
pout["invalidate_handle"] = h;
}catch(failed_lookup& fl) { }
}
}
}
<commit_msg>yet another signature bugfix<commit_after>#include <vector>
#include <openssl/sha.h>
#include <openssl/hmac.h>
#include <opkele/util.h>
#include <opkele/exception.h>
#include <opkele/server.h>
#include <opkele/data.h>
namespace opkele {
using namespace std;
void server_t::associate(const params_t& pin,params_t& pout) {
util::dh_t dh;
util::bignum_t c_pub;
unsigned char key_sha1[SHA_DIGEST_LENGTH];
enum {
sess_cleartext,
sess_dh_sha1
} st = sess_cleartext;
if(
pin.has_param("openid.session_type")
&& pin.get_param("openid.session_type")=="DH-SHA1" ) {
/* TODO: fallback to cleartext in case of exceptions here? */
if(!(dh = DH_new()))
throw exception_openssl(OPKELE_CP_ "failed to DH_new()");
c_pub = util::base64_to_bignum(pin.get_param("openid.dh_consumer_public"));
if(pin.has_param("openid.dh_modulus"))
dh->p = util::base64_to_bignum(pin.get_param("openid.dh_modulus"));
else
dh->p = util::dec_to_bignum(data::_default_p);
if(pin.has_param("openid.dh_gen"))
dh->g = util::base64_to_bignum(pin.get_param("openid.dh_gen"));
else
dh->g = util::dec_to_bignum(data::_default_g);
if(!DH_generate_key(dh))
throw exception_openssl(OPKELE_CP_ "failed to DH_generate_key()");
vector<unsigned char> ck(DH_size(dh)+1);
unsigned char *ckptr = &(ck.front())+1;
int cklen = DH_compute_key(ckptr,c_pub,dh);
if(cklen<0)
throw exception_openssl(OPKELE_CP_ "failed to DH_compute_key()");
if(cklen && (*ckptr)&0x80) {
(*(--ckptr)) = 0; ++cklen;
}
SHA1(ckptr,cklen,key_sha1);
st = sess_dh_sha1;
}
assoc_t assoc = alloc_assoc(mode_associate);
time_t now = time(0);
pout.clear();
pout["assoc_type"] = assoc->assoc_type();
pout["assoc_handle"] = assoc->handle();
/* TODO: eventually remove deprecated stuff */
pout["issued"] = util::time_to_w3c(now);
pout["expiry"] = util::time_to_w3c(now+assoc->expires_in());
pout["expires_in"] = util::long_to_string(assoc->expires_in());
secret_t secret = assoc->secret();
switch(st) {
case sess_dh_sha1:
pout["session_type"] = "DH-SHA1";
pout["dh_server_public"] = util::bignum_to_base64(dh->pub_key);
secret.enxor_to_base64(key_sha1,pout["enc_mac_key"]);
break;
default:
secret.to_base64(pout["mac_key"]);
break;
}
}
void server_t::checkid_immediate(const params_t& pin,string& return_to,params_t& pout,extension_t *ext) {
checkid_(mode_checkid_immediate,pin,return_to,pout,ext);
}
void server_t::checkid_setup(const params_t& pin,string& return_to,params_t& pout,extension_t *ext) {
checkid_(mode_checkid_setup,pin,return_to,pout,ext);
}
void server_t::checkid_(mode_t mode,const params_t& pin,string& return_to,params_t& pout,extension_t *ext) {
if(mode!=mode_checkid_immediate && mode!=mode_checkid_setup)
throw bad_input(OPKELE_CP_ "invalid checkid_* mode");
pout.clear();
assoc_t assoc;
try {
assoc = retrieve_assoc(pin.get_param("openid.assoc_handle"));
}catch(failed_lookup& fl) {
// no handle specified or no valid handle found, going dumb
assoc = alloc_assoc(mode_checkid_setup);
if(pin.has_param("openid.assoc_handle"))
pout["invalidate_handle"]=pin.get_param("openid.assoc_handle");
}
string trust_root;
try {
trust_root = pin.get_param("openid.trust_root");
}catch(failed_lookup& fl) { }
string identity = pin.get_param("openid.identity");
return_to = pin.get_param("openid.return_to");
validate(*assoc,pin,identity,trust_root);
pout["mode"] = "id_res";
pout["assoc_handle"] = assoc->handle();
if(pin.has_param("openid.assoc_handle") && assoc->stateless())
pout["invalidate_handle"] = pin.get_param("openid.assoc_handle");
pout["identity"] = identity;
pout["return_to"] = return_to;
/* TODO: eventually remove deprecated stuff */
time_t now = time(0);
pout["issued"] = util::time_to_w3c(now);
pout["valid_to"] = util::time_to_w3c(now+120);
pout["exipres_in"] = "120";
pout["signed"]="mode,identity,return_to";
if(ext) ext->checkid_hook(pin,pout);
pout.sign(assoc->secret(),pout["sig"],pout["signed"]);
}
void server_t::check_authentication(const params_t& pin,params_t& pout) {
vector<unsigned char> sig;
const string& sigenc = pin.get_param("openid.sig");
util::decode_base64(sigenc,sig);
assoc_t assoc;
try {
assoc = retrieve_assoc(pin.get_param("openid.assoc_handle"));
}catch(failed_lookup& fl) {
throw failed_assertion(OPKELE_CP_ "invalid handle or handle not specified");
}
if(!assoc->stateless())
throw stateful_handle(OPKELE_CP_ "will not do check_authentication on a stateful handle");
const string& slist = pin.get_param("openid.signed");
string kv;
string::size_type p =0;
while(true) {
string::size_type co = slist.find(',',p);
string f = (co==string::npos)?slist.substr(p):slist.substr(p,co-p);
kv += f;
kv += ':';
if(f=="mode")
kv += "id_res";
else {
f.insert(0,"openid.");
kv += pin.get_param(f);
}
kv += '\n';
if(co==string::npos)
break;
p = co+1;
}
secret_t secret = assoc->secret();
unsigned int md_len = 0;
unsigned char *md = HMAC(
EVP_sha1(),
&(secret.front()),secret.size(),
(const unsigned char *)kv.data(),kv.length(),
0,&md_len);
pout.clear();
if(sig.size()==md_len && !memcmp(&(sig.front()),md,md_len)) {
pout["is_valid"]="true";
pout["lifetime"]="60"; /* TODO: eventually remove deprecated stuff */
}else{
pout["is_valid"]="false";
pout["lifetime"]="0"; /* TODO: eventually remove deprecated stuff */
}
if(pin.has_param("openid.invalidate_handle")) {
string h = pin.get_param("openid.invalidate_handle");
try {
assoc_t assoc = retrieve_assoc(h);
}catch(invalid_handle& ih) {
pout["invalidate_handle"] = h;
}catch(failed_lookup& fl) { }
}
}
}
<|endoftext|>
|
<commit_before>// Copyright (c) 1999-2012 OPEN CASCADE SAS
//
// The content of this file is subject to the Open CASCADE Technology Public
// License Version 6.5 (the "License"). You may not use the content of this file
// except in compliance with the License. Please obtain a copy of the License
// at http://www.opencascade.org and read it completely before using this file.
//
// The Initial Developer of the Original Code is Open CASCADE S.A.S., having its
// main offices at: 1, place des Freres Montgolfier, 78280 Guyancourt, France.
//
// The Original Code and all software distributed under the License is
// distributed on an "AS IS" basis, without warranty of any kind, and the
// Initial Developer hereby disclaims all such warranties, including without
// limitation, any warranties of merchantability, fitness for a particular
// purpose or non-infringement. Please see the License for the specific terms
// and conditions governing the rights and limitations under the License.
/*============================================================================*/
/*==== Titre: Aspect_Handle.hxx */
/*==== Role : The header file of primitive type "Handle" from packages */
/*==== "Xw" & "WNT" */
/*==== Implementation: This is a primitive type implemented with typedef */
/*============================================================================*/
#ifndef _Aspect_Handle_HeaderFile
#define _Aspect_Handle_HeaderFile
#ifdef WNT
typedef void* HANDLE;
typedef HANDLE Aspect_Handle;
#else
typedef unsigned long Aspect_Handle;
#endif /* WNT */
#if defined(__cplusplus) || defined(c_plusplus)
/*==== Definition de Type ====================================================*/
#include <Standard_Macro.hxx>
class Handle(Standard_Type);
const Handle(Standard_Type)& STANDARD_TYPE(Aspect_Handle);
/*============================================================================*/
#endif
#endif /* _Aspect_Handle_HeaderFile */
<commit_msg>Define OCE_NULL_Aspect_Handle for use in V3d_View.hxx<commit_after>// Copyright (c) 1999-2012 OPEN CASCADE SAS
//
// The content of this file is subject to the Open CASCADE Technology Public
// License Version 6.5 (the "License"). You may not use the content of this file
// except in compliance with the License. Please obtain a copy of the License
// at http://www.opencascade.org and read it completely before using this file.
//
// The Initial Developer of the Original Code is Open CASCADE S.A.S., having its
// main offices at: 1, place des Freres Montgolfier, 78280 Guyancourt, France.
//
// The Original Code and all software distributed under the License is
// distributed on an "AS IS" basis, without warranty of any kind, and the
// Initial Developer hereby disclaims all such warranties, including without
// limitation, any warranties of merchantability, fitness for a particular
// purpose or non-infringement. Please see the License for the specific terms
// and conditions governing the rights and limitations under the License.
/*============================================================================*/
/*==== Titre: Aspect_Handle.hxx */
/*==== Role : The header file of primitive type "Handle" from packages */
/*==== "Xw" & "WNT" */
/*==== Implementation: This is a primitive type implemented with typedef */
/*============================================================================*/
#ifndef _Aspect_Handle_HeaderFile
#define _Aspect_Handle_HeaderFile
#ifdef WNT
typedef void* HANDLE;
typedef HANDLE Aspect_Handle;
#else
typedef unsigned long Aspect_Handle;
#endif /* WNT */
#if defined(__cplusplus) || defined(c_plusplus)
/*==== Definition de Type ====================================================*/
#include <Standard_Macro.hxx>
class Handle(Standard_Type);
const Handle(Standard_Type)& STANDARD_TYPE(Aspect_Handle);
/*============================================================================*/
#endif
#define OCE_NULL_Aspect_Handle ((Aspect_Handle)NULL)
#endif /* _Aspect_Handle_HeaderFile */
<|endoftext|>
|
<commit_before>/*
This file is part of Kontact.
Copyright (c) 2003 Cornelius Schumacher <schumacher@kde.org>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
As a special exception, permission is given to link this program
with any edition of Qt, and distribute the resulting executable,
without including the source code for Qt in the source distribution.
*/
#include "todoplugin.h"
#include "todosummarywidget.h"
#include "korg_uniqueapp.h"
#include "calendarinterface.h"
#include <kontactinterfaces/core.h>
#include <libkdepim/maillistdrag.h>
#include <libkdepim/kdepimprotocols.h>
#include <libkdepim/kvcarddrag.h>
#include <libkdepim/kpimprefs.h>
#include <kcal/calendarlocal.h>
#include <kcal/icaldrag.h>
#include <kaction.h>
#include <kactioncollection.h>
#include <kdebug.h>
#include <kgenericfactory.h>
#include <kiconloader.h>
#include <kmessagebox.h>
#include <kicon.h>
#include <ktemporaryfile.h>
#include <QWidget>
#include <QDropEvent>
#include <QtDBus/QtDBus>
EXPORT_KONTACT_PLUGIN( TodoPlugin, todo )
TodoPlugin::TodoPlugin( Kontact::Core *core, const QVariantList & )
: Kontact::Plugin( core, core, "korganizer" ), mIface( 0 )
{
setComponentData( KontactPluginFactory::componentData() );
KIconLoader::global()->addAppDir( "korganizer" );
KIconLoader::global()->addAppDir( "kdepim" );
KAction *action =
new KAction( KIcon( "task-new" ), i18n( "New To-do..." ), this );
actionCollection()->addAction( "new_todo", action );
action->setShortcut( QKeySequence( Qt::CTRL + Qt::SHIFT + Qt::Key_T ) );
connect( action, SIGNAL(triggered(bool)), SLOT(slotNewTodo()) );
insertNewAction( action );
KAction *syncAction =
new KAction( KIcon( "view-refresh" ), i18n( "Sync To-do List" ), this );
connect( action, SIGNAL(triggered(bool)), SLOT(slotSyncTodos()) );
insertSyncAction( syncAction );
mUniqueAppWatcher = new Kontact::UniqueAppWatcher(
new Kontact::UniqueAppHandlerFactory<KOrganizerUniqueAppHandler>(), this );
}
TodoPlugin::~TodoPlugin()
{
}
Kontact::Summary *TodoPlugin::createSummaryWidget( QWidget *parent )
{
return new TodoSummaryWidget( this, parent );
}
KParts::ReadOnlyPart *TodoPlugin::createPart()
{
KParts::ReadOnlyPart *part = loadPart();
if ( !part ) {
return 0;
}
mIface = new OrgKdeKorganizerCalendarInterface(
"org.kde.korganizer", "/Calendar", QDBusConnection::sessionBus(), this );
return part;
}
void TodoPlugin::select()
{
interface()->showTodoView();
}
QStringList TodoPlugin::invisibleToolbarActions() const
{
QStringList invisible;
invisible += "new_event";
invisible += "new_todo";
invisible += "new_journal";
invisible += "view_day";
invisible += "view_list";
invisible += "view_workweek";
invisible += "view_week";
invisible += "view_nextx";
invisible += "view_month";
invisible += "view_journal";
return invisible;
}
OrgKdeKorganizerCalendarInterface *TodoPlugin::interface()
{
if ( !mIface ) {
part();
}
Q_ASSERT( mIface );
return mIface;
}
void TodoPlugin::slotNewTodo()
{
interface()->openTodoEditor( "" );
}
void TodoPlugin::slotSyncTodos()
{
QDBusMessage message =
QDBusMessage::createMethodCall( "org.kde.kmail", "/Groupware",
"org.kde.kmail.groupware",
"triggerSync" );
message << QString( "Todo" );
QDBusConnection::sessionBus().send( message );
}
bool TodoPlugin::createDBUSInterface( const QString &serviceType )
{
if ( serviceType == "DBUS/Organizer" || serviceType == "DBUS/Calendar" ) {
if ( part() ) {
return true;
}
}
return false;
}
bool TodoPlugin::canDecodeMimeData( const QMimeData *mimeData )
{
return mimeData->hasText() || KPIM::MailList::canDecode( mimeData ) ||
KPIM::KVCardDrag::canDecode( mimeData ) || KCal::ICalDrag::canDecode( mimeData );
}
bool TodoPlugin::isRunningStandalone()
{
return mUniqueAppWatcher->isRunningStandalone();
}
void TodoPlugin::processDropEvent( QDropEvent *event )
{
const QMimeData *md = event->mimeData();
if ( KPIM::KVCardDrag::canDecode( md ) ) {
KABC::Addressee::List contacts;
KPIM::KVCardDrag::fromMimeData( md, contacts );
KABC::Addressee::List::Iterator it;
QStringList attendees;
for ( it = contacts.begin(); it != contacts.end(); ++it ) {
QString email = (*it).fullEmail();
if ( email.isEmpty() ) {
attendees.append( (*it).realName() + "<>" );
} else {
attendees.append( email );
}
}
interface()->openTodoEditor( i18n( "Meeting" ), QString(), QStringList(), attendees );
return;
}
if ( KCal::ICalDrag::canDecode( event->mimeData() ) ) {
KCal::CalendarLocal cal( KPIM::KPimPrefs::timeSpec() );
if ( KCal::ICalDrag::fromMimeData( event->mimeData(), &cal ) ) {
KCal::Journal::List journals = cal.journals();
if ( !journals.isEmpty() ) {
event->accept();
KCal::Journal *j = journals.first();
interface()->openTodoEditor(
i18n( "Note: %1", j->summary() ), j->description(), QStringList() );
return;
}
// else fall through to text decoding
}
}
if ( md->hasText() ) {
QString text = md->text();
interface()->openTodoEditor( text );
return;
}
if ( KPIM::MailList::canDecode( md ) ) {
KPIM::MailList mails = KPIM::MailList::fromMimeData( md );
event->accept();
if ( mails.count() != 1 ) {
KMessageBox::sorry( core(),
i18n( "Drops of multiple mails are not supported." ) );
} else {
KPIM::MailSummary mail = mails.first();
QString txt = i18n( "From: %1\nTo: %2\nSubject: %3", mail.from(), mail.to(), mail.subject() );
QString uri = KDEPIMPROTOCOL_EMAIL +
QString::number( mail.serialNumber() ) + '/' +
mail.messageId();
KTemporaryFile tf;
tf.setAutoRemove( true );
tf.write( event->encodedData( "message/rfc822" ) );
interface()->openTodoEditor(
i18n( "Mail: %1", mail.subject() ),
txt, uri, tf.fileName(), QStringList(), "message/rfc822" );
tf.close();
}
return;
}
KMessageBox::sorry( core(), i18n( "Cannot handle drop events of type '%1'.", event->format() ) );
}
#include "todoplugin.moc"
<commit_msg>Take incidences, no journals. This way we are able to read the drop event, and create the TODO entry.<commit_after>/*
This file is part of Kontact.
Copyright (c) 2003 Cornelius Schumacher <schumacher@kde.org>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
As a special exception, permission is given to link this program
with any edition of Qt, and distribute the resulting executable,
without including the source code for Qt in the source distribution.
*/
#include "todoplugin.h"
#include "todosummarywidget.h"
#include "korg_uniqueapp.h"
#include "calendarinterface.h"
#include <kontactinterfaces/core.h>
#include <libkdepim/maillistdrag.h>
#include <libkdepim/kdepimprotocols.h>
#include <libkdepim/kvcarddrag.h>
#include <libkdepim/kpimprefs.h>
#include <kcal/calendarlocal.h>
#include <kcal/icaldrag.h>
#include <kaction.h>
#include <kactioncollection.h>
#include <kdebug.h>
#include <kgenericfactory.h>
#include <kiconloader.h>
#include <kmessagebox.h>
#include <kicon.h>
#include <ktemporaryfile.h>
#include <QWidget>
#include <QDropEvent>
#include <QtDBus/QtDBus>
EXPORT_KONTACT_PLUGIN( TodoPlugin, todo )
TodoPlugin::TodoPlugin( Kontact::Core *core, const QVariantList & )
: Kontact::Plugin( core, core, "korganizer" ), mIface( 0 )
{
setComponentData( KontactPluginFactory::componentData() );
KIconLoader::global()->addAppDir( "korganizer" );
KIconLoader::global()->addAppDir( "kdepim" );
KAction *action =
new KAction( KIcon( "task-new" ), i18n( "New To-do..." ), this );
actionCollection()->addAction( "new_todo", action );
action->setShortcut( QKeySequence( Qt::CTRL + Qt::SHIFT + Qt::Key_T ) );
connect( action, SIGNAL(triggered(bool)), SLOT(slotNewTodo()) );
insertNewAction( action );
KAction *syncAction =
new KAction( KIcon( "view-refresh" ), i18n( "Sync To-do List" ), this );
connect( action, SIGNAL(triggered(bool)), SLOT(slotSyncTodos()) );
insertSyncAction( syncAction );
mUniqueAppWatcher = new Kontact::UniqueAppWatcher(
new Kontact::UniqueAppHandlerFactory<KOrganizerUniqueAppHandler>(), this );
}
TodoPlugin::~TodoPlugin()
{
}
Kontact::Summary *TodoPlugin::createSummaryWidget( QWidget *parent )
{
return new TodoSummaryWidget( this, parent );
}
KParts::ReadOnlyPart *TodoPlugin::createPart()
{
KParts::ReadOnlyPart *part = loadPart();
if ( !part ) {
return 0;
}
mIface = new OrgKdeKorganizerCalendarInterface(
"org.kde.korganizer", "/Calendar", QDBusConnection::sessionBus(), this );
return part;
}
void TodoPlugin::select()
{
interface()->showTodoView();
}
QStringList TodoPlugin::invisibleToolbarActions() const
{
QStringList invisible;
invisible += "new_event";
invisible += "new_todo";
invisible += "new_journal";
invisible += "view_day";
invisible += "view_list";
invisible += "view_workweek";
invisible += "view_week";
invisible += "view_nextx";
invisible += "view_month";
invisible += "view_journal";
return invisible;
}
OrgKdeKorganizerCalendarInterface *TodoPlugin::interface()
{
if ( !mIface ) {
part();
}
Q_ASSERT( mIface );
return mIface;
}
void TodoPlugin::slotNewTodo()
{
interface()->openTodoEditor( "" );
}
void TodoPlugin::slotSyncTodos()
{
QDBusMessage message =
QDBusMessage::createMethodCall( "org.kde.kmail", "/Groupware",
"org.kde.kmail.groupware",
"triggerSync" );
message << QString( "Todo" );
QDBusConnection::sessionBus().send( message );
}
bool TodoPlugin::createDBUSInterface( const QString &serviceType )
{
if ( serviceType == "DBUS/Organizer" || serviceType == "DBUS/Calendar" ) {
if ( part() ) {
return true;
}
}
return false;
}
bool TodoPlugin::canDecodeMimeData( const QMimeData *mimeData )
{
return mimeData->hasText() || KPIM::MailList::canDecode( mimeData ) ||
KPIM::KVCardDrag::canDecode( mimeData ) || KCal::ICalDrag::canDecode( mimeData );
}
bool TodoPlugin::isRunningStandalone()
{
return mUniqueAppWatcher->isRunningStandalone();
}
void TodoPlugin::processDropEvent( QDropEvent *event )
{
const QMimeData *md = event->mimeData();
if ( KPIM::KVCardDrag::canDecode( md ) ) {
KABC::Addressee::List contacts;
KPIM::KVCardDrag::fromMimeData( md, contacts );
KABC::Addressee::List::Iterator it;
QStringList attendees;
for ( it = contacts.begin(); it != contacts.end(); ++it ) {
QString email = (*it).fullEmail();
if ( email.isEmpty() ) {
attendees.append( (*it).realName() + "<>" );
} else {
attendees.append( email );
}
}
interface()->openTodoEditor( i18n( "Meeting" ), QString(), QStringList(), attendees );
return;
}
if ( KCal::ICalDrag::canDecode( event->mimeData() ) ) {
KCal::CalendarLocal cal( KPIM::KPimPrefs::timeSpec() );
if ( KCal::ICalDrag::fromMimeData( event->mimeData(), &cal ) ) {
KCal::Incidence::List incidences = cal.incidences();
Q_ASSERT(incidences.count());
if ( !incidences.isEmpty() ) {
event->accept();
KCal::Incidence *i = incidences.first();
interface()->openTodoEditor(
i18n( "Note: %1", i->summary() ), i->description(), QStringList() );
return;
}
// else fall through to text decoding
}
}
if ( md->hasText() ) {
QString text = md->text();
interface()->openTodoEditor( text );
return;
}
if ( KPIM::MailList::canDecode( md ) ) {
KPIM::MailList mails = KPIM::MailList::fromMimeData( md );
event->accept();
if ( mails.count() != 1 ) {
KMessageBox::sorry( core(),
i18n( "Drops of multiple mails are not supported." ) );
} else {
KPIM::MailSummary mail = mails.first();
QString txt = i18n( "From: %1\nTo: %2\nSubject: %3", mail.from(), mail.to(), mail.subject() );
QString uri = KDEPIMPROTOCOL_EMAIL +
QString::number( mail.serialNumber() ) + '/' +
mail.messageId();
KTemporaryFile tf;
tf.setAutoRemove( true );
tf.write( event->encodedData( "message/rfc822" ) );
interface()->openTodoEditor(
i18n( "Mail: %1", mail.subject() ),
txt, uri, tf.fileName(), QStringList(), "message/rfc822" );
tf.close();
}
return;
}
KMessageBox::sorry( core(), i18n( "Cannot handle drop events of type '%1'.", event->format() ) );
}
#include "todoplugin.moc"
<|endoftext|>
|
<commit_before>#include <errno.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/un.h>
#include <assert.h>
#include <stdio.h>
#include <sys/mman.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <pthread.h>
#include <portal.h>
#include "sock_fd.h"
#include "sock_utils.h"
static struct portal p_fd = iport;
static int fd[16];
static unsigned char *buffer[16];
static unsigned long buffer_len[16];
static int size_accum[16]={0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
extern "C" {
void init_pareff(){
pthread_t tid;
struct channel* rc;
struct channel* wc;
fprintf(stderr, "BsimDma::init_pareff()\n");
rc = &(p_fd.read);
snprintf(rc->path, sizeof(rc->path), "fd_sock_rc");
wc = &(p_fd.write);
snprintf(wc->path, sizeof(wc->path), "fd_sock_wc");
if(pthread_create(&tid, NULL, init_socket, (void*)rc)){
fprintf(stderr, "error creating init thread\n");
//exit(1);
}
if(pthread_create(&tid, NULL, init_socket, (void*)wc)){
fprintf(stderr, "error creating init thread\n");
//exit(1);
}
}
void write_pareff32(unsigned long pref, unsigned long offset, unsigned int data){
if(buffer_len[pref-1] <= offset)
fprintf(stderr, "write_pareff32(pref=%08lx, offset=%08lx) going off the reservation \n", pref, offset);
*(unsigned int *)&buffer[pref-1][offset] = data;
}
unsigned int read_pareff32(unsigned long pref, unsigned long offset){
if(buffer_len[pref-1] <= offset)
fprintf(stderr, "read_pareff32(pref=%08lx, offset=%08lx) going off the reservation \n", pref, offset);
unsigned int rv = *(unsigned int *)&buffer[pref-1][offset];
//fprintf(stderr, "read_pareff32(pref=%08lx, offset=%08lx)=%08x\n", pref, offset,rv);
return rv;
}
void write_pareff64(unsigned long pref, unsigned long offset, unsigned long long data){
if(buffer_len[pref-1] <= offset)
fprintf(stderr, "write_pareff64(pref=%08lx, offset=%08lx, buffer_len[%ld]=%08lx) going off the reservation \n", pref, offset, pref-1, buffer_len[pref-1]);
*(unsigned long long *)&buffer[pref-1][offset] = data;
//fprintf(stderr, "write_pareff64(pref=%08lx, offset=%08lx, data=%016llx)\n", pref, offset, data);
}
unsigned long long read_pareff64(unsigned long pref, unsigned long offset){
if(buffer_len[pref-1] <= offset)
fprintf(stderr, "read_pareff64(pref=%08lx, offset=%08lx) going off the reservation \n", pref, offset);
unsigned long long rv = *(unsigned long long *)&buffer[pref-1][offset];
//fprintf(stderr, "read_pareff64(pref=%08lx, offset=%08lx)=%016llx\n", pref, offset,rv);
return rv;
}
unsigned long pareff(unsigned long pref, unsigned long size){
//fprintf(stderr, "BsimDma::pareff pref=%ld, size=%08lx size_accum=%08lx\n", pref, size, size_accum[pref-1]);
assert(pref < 16);
size_accum[pref-1] += size;
if(size == 0){
sock_fd_read(p_fd.write.s2, &(fd[pref-1]));
buffer[pref-1] = (unsigned char *)mmap(0, size_accum[pref-1], PROT_WRITE|PROT_WRITE|PROT_EXEC, MAP_SHARED, fd[pref-1], 0);
buffer_len[pref-1] = size_accum[pref-1]/sizeof(unsigned char);
return buffer[pref-1];
} else {
return 0;
}
}
}
<commit_msg>fixing build break. someone must have tweaked the compile flags<commit_after>#include <errno.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/un.h>
#include <assert.h>
#include <stdio.h>
#include <sys/mman.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <pthread.h>
#include <portal.h>
#include "sock_fd.h"
#include "sock_utils.h"
static struct portal p_fd = iport;
static int fd[16];
static unsigned char *buffer[16];
static unsigned long buffer_len[16];
static int size_accum[16]={0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
extern "C" {
void init_pareff(){
pthread_t tid;
struct channel* rc;
struct channel* wc;
fprintf(stderr, "BsimDma::init_pareff()\n");
rc = &(p_fd.read);
snprintf(rc->path, sizeof(rc->path), "fd_sock_rc");
wc = &(p_fd.write);
snprintf(wc->path, sizeof(wc->path), "fd_sock_wc");
if(pthread_create(&tid, NULL, init_socket, (void*)rc)){
fprintf(stderr, "error creating init thread\n");
//exit(1);
}
if(pthread_create(&tid, NULL, init_socket, (void*)wc)){
fprintf(stderr, "error creating init thread\n");
//exit(1);
}
}
void write_pareff32(unsigned long pref, unsigned long offset, unsigned int data){
if(buffer_len[pref-1] <= offset)
fprintf(stderr, "write_pareff32(pref=%08lx, offset=%08lx) going off the reservation \n", pref, offset);
*(unsigned int *)&buffer[pref-1][offset] = data;
}
unsigned int read_pareff32(unsigned long pref, unsigned long offset){
if(buffer_len[pref-1] <= offset)
fprintf(stderr, "read_pareff32(pref=%08lx, offset=%08lx) going off the reservation \n", pref, offset);
unsigned int rv = *(unsigned int *)&buffer[pref-1][offset];
//fprintf(stderr, "read_pareff32(pref=%08lx, offset=%08lx)=%08x\n", pref, offset,rv);
return rv;
}
void write_pareff64(unsigned long pref, unsigned long offset, unsigned long long data){
if(buffer_len[pref-1] <= offset)
fprintf(stderr, "write_pareff64(pref=%08lx, offset=%08lx, buffer_len[%ld]=%08lx) going off the reservation \n", pref, offset, pref-1, buffer_len[pref-1]);
*(unsigned long long *)&buffer[pref-1][offset] = data;
//fprintf(stderr, "write_pareff64(pref=%08lx, offset=%08lx, data=%016llx)\n", pref, offset, data);
}
unsigned long long read_pareff64(unsigned long pref, unsigned long offset){
if(buffer_len[pref-1] <= offset)
fprintf(stderr, "read_pareff64(pref=%08lx, offset=%08lx) going off the reservation \n", pref, offset);
unsigned long long rv = *(unsigned long long *)&buffer[pref-1][offset];
//fprintf(stderr, "read_pareff64(pref=%08lx, offset=%08lx)=%016llx\n", pref, offset,rv);
return rv;
}
unsigned long pareff(unsigned long pref, unsigned long size){
//fprintf(stderr, "BsimDma::pareff pref=%ld, size=%08lx size_accum=%08lx\n", pref, size, size_accum[pref-1]);
assert(pref < 16);
size_accum[pref-1] += size;
if(size == 0){
sock_fd_read(p_fd.write.s2, &(fd[pref-1]));
buffer[pref-1] = (unsigned char *)mmap(0, size_accum[pref-1], PROT_WRITE|PROT_WRITE|PROT_EXEC, MAP_SHARED, fd[pref-1], 0);
buffer_len[pref-1] = size_accum[pref-1]/sizeof(unsigned char);
return (unsigned long)buffer[pref-1];
} else {
return 0;
}
}
}
<|endoftext|>
|
<commit_before>#include "pixelboost/script/luaManager.h"
extern "C"
{
#include "pixelboost/external/lua/lua.h"
#include "pixelboost/external/lua/lauxlib.h"
#include "pixelboost/external/lua/lualib.h"
}
using namespace pixelboost;
LuaManager::LuaManager()
{
_State = luaL_newstate();
luaL_openlibs(_State);
}
LuaManager::~LuaManager()
{
lua_close(_State);
}
void LuaManager::Open(const std::string& filename)
{
if (luaL_loadfile(_State, filename.c_str()) || lua_pcall(_State, 0, 0, 0))
{
printf("Can't open file: %s", lua_tostring(_State, -1));
}
}
<commit_msg>Use provided lua.hpp<commit_after>#include "pixelboost/script/luaManager.h"
#include "pixelboost/external/lua/lua.hpp"
using namespace pixelboost;
LuaManager::LuaManager()
{
_State = luaL_newstate();
luaL_openlibs(_State);
}
LuaManager::~LuaManager()
{
lua_close(_State);
}
void LuaManager::Open(const std::string& filename)
{
if (luaL_loadfile(_State, filename.c_str()) || lua_pcall(_State, 0, 0, 0))
{
printf("Can't open file: %s", lua_tostring(_State, -1));
}
}
<|endoftext|>
|
<commit_before>/*
Graphics File Loader: a test program for csgfxldr library
Copyright (C) 2000 Andrew Zabolotny <bit@eltech.ru>
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.
*/
#define SYSDEF_PATH
#define SYSDEF_GETOPT
#include "sysdef.h"
#include "csgfxldr/csimage.h"
#include "csgfxldr/pngsave.h"
#include <string.h>
char *programversion = "0.0.1";
char *programname;
/*
NOTE: If your Losing Operating System {tm} (R) does not have getopt_long,
please use the one in support/gnu instead. Please don't comment out blocks
of code, dont #ifdef and so on. It is ugly.
*/
static struct option long_options[] =
{
{"help", no_argument, 0, 'h'},
{"display", optional_argument, 0, 'D'},
{"dither", no_argument, 0, 'd'},
{"scale", required_argument, 0, 's'},
{"mipmap", required_argument, 0, 'm'},
{"transp", required_argument, 0, 't'},
{"paletted", no_argument, 0, '8'},
{"truecolor", no_argument, 0, 'c'},
{"verbose", no_argument, 0, 'v'},
{"version", no_argument, 0, 'V'},
{0, no_argument, 0, 0}
};
static struct
{
bool verbose;
bool save;
bool display;
bool dither;
bool paletted;
bool truecolor;
int scaleX, scaleY;
int displayW, displayH;
int mipmap;
bool transp;
} opt =
{
false,
true,
false,
false,
false,
false,
0, 0,
79, 24,
-1,
false
};
// Dont move inside the struct!
static RGBPixel transpcolor;
static int display_help ()
{
printf ("Crystal Space Graphics File Loader test application v%s\n", programversion);
printf ("Copyright (C) 2000 Andrew Zabolotny\n\n");
printf ("Usage: %s {option/s} [image file] [...]\n\n", programname);
printf (" -D --display{=#,#} Display the image in ASCII format :-)\n");
printf (" -d --dither Apply Floyd-Steinberg dithering when reducing to 8 bpp\n");
printf (" -s --scale=#,# Re-scale the image to given size #\n");
printf (" -m --mipmap=# Create mipmap level # (=0,1,2,3) from image\n");
printf (" -t --transp=#,#,# Treat color (R,G,B) as transparent\n");
printf (" -8 --paletted Convert image to 8 bits-per-pixel paletted format\n");
printf (" -c --truecolor Convert image to truecolor format\n");
printf (" -h --help Display this help text\n");
printf (" -v --verbose Comment on what's happening\n");
printf (" -V --version Display program version\n");
return 1;
}
#if 0
// PNM is a very simple format that is handy for quick-and-dirty programs.
// Many image processing programs understands it...
static bool SavePNM (const char *fname, void *image, int w, int h, bool rgb)
{
FILE *f = fopen (fname, "wb");
if (!f)
{
fprintf (stderr, "%s: cannot open output file %s\n", programname, fname);
return false;
}
char header [100];
sprintf (header, "P%c\n%d %d\n%d\n", rgb ? '6' : '5', w, h, 255);
fwrite (header, 1, strlen (header), f);
if (rgb)
for (int i = w * h; i > 0; i--)
{
fwrite (image, 1, 3, f);
image = ((RGBPixel *)image) + 1;
}
else
fwrite (image, 1, w * h, f);
fclose (f);
return true;
}
#endif
static bool process_file (const char *fname)
{
printf ("Loading file %s\n", fname);
FILE *f = fopen (fname, "rb");
if (!f)
{
printf ("%s: cannot open file %s\n", programname, fname);
return false;
}
fseek (f, 0, SEEK_END);
size_t fsize = ftell (f);
fseek (f, 0, SEEK_SET);
if (opt.verbose)
printf ("Reading %ld bytes from file\n", fsize);
UByte *buffer = new UByte [fsize];
if (fread (buffer, 1, fsize, f) < fsize)
{
printf ("%s: unexpected EOF while reading file %s\n", programname, fname);
return false;
}
fclose (f);
int fmt;
if (opt.paletted)
fmt = CS_IMGFMT_PALETTED8;
else if (opt.truecolor)
fmt = CS_IMGFMT_TRUECOLOR;
else
fmt = CS_IMGFMT_ANY;
iImage *ifile = csImageLoader::Load (buffer, fsize, fmt | CS_IMGFMT_ALPHA);
delete [] buffer;
if (!ifile)
{
printf ("%s: failed to recognise image format for %s\n", programname, fname);
return false;
}
if (opt.verbose)
{
printf ("Image size: %d x %d pixels, %d bytes\n", ifile->GetWidth (),
ifile->GetHeight (), ifile->GetSize ());
int fmt = ifile->GetFormat ();
printf ("Image format: %s, alpha channel: %s\n",
(fmt & CS_IMGFMT_MASK) == CS_IMGFMT_NONE ? "none" :
(fmt & CS_IMGFMT_MASK) == CS_IMGFMT_PALETTED8 ? "paletted, 256 colors" :
(fmt & CS_IMGFMT_MASK) == CS_IMGFMT_TRUECOLOR ? "truecolor" : "unknown",
(fmt & CS_IMGFMT_ALPHA) ? "present" : "not present");
}
char suffix [20];
suffix [0] = 0;
if (opt.scaleX > 0 && opt.scaleY > 0)
{
printf ("Rescaling image to %d x %d\n", opt.scaleX, opt.scaleY);
ifile->Rescale (opt.scaleX, opt.scaleY);
sprintf (strchr (suffix, 0), "-s%dx%d", opt.scaleX, opt.scaleY);
}
if (opt.mipmap >= 0)
{
printf ("Creating mipmap level %d from image\n", opt.mipmap);
iImage *ifile2 = ifile->MipMap (opt.mipmap,
opt.transp ? &transpcolor : NULL);
ifile->DecRef ();
ifile = ifile2;
sprintf (strchr (suffix, 0), "-m%d", opt.mipmap);
}
if (opt.save)
{
char outname [MAXPATHLEN + 1];
strcpy (outname, fname);
char *eol = strchr (outname, 0);
while (eol > outname && *eol != '.') eol--;
if (eol == outname) eol = strchr (outname, 0);
strcpy (eol, suffix);
strcat (eol, ".png");
printf ("Saving output file %s\n", outname);
#if 1
if (!csSavePNG (outname, ifile))
return false;
#else
if (!SavePNM (outname, ifile->GetImageData (), ifile->GetWidth (), ifile->GetHeight (),
(ifile->GetFormat () & CS_IMGFMT_MASK) == CS_IMGFMT_TRUECOLOR))
return false;
#endif
}
if (opt.display)
{
static char imgchr [] = " .,;+*oO";
ifile->Rescale (opt.displayW, opt.displayH);
RGBPixel *rgb;
UByte *idx = NULL;
bool truecolor = (ifile->GetFormat () & CS_IMGFMT_MASK) == CS_IMGFMT_TRUECOLOR;
if (truecolor)
rgb = (RGBPixel *)ifile->GetImageData ();
else
{
idx = (UByte *)ifile->GetImageData ();
rgb = ifile->GetPalette ();
}
for (int y = 0; y < opt.displayH; y++)
{
for (int x = 0; x < opt.displayW; x++)
{
RGBPixel &src = truecolor ? *rgb++ : rgb [*idx++];
int gray = int (sqrt (src.red * src.red + src.green * src.green +
src.blue * src.blue) * 8 / 442);
putc (imgchr [gray], stdout);
}
putc ('\n', stdout);
}
}
// Destroy the image object
ifile->DecRef ();
return true;
}
int main (int argc, char **argv)
{
#if defined (__EMX__) // Expand wildcards on OS/2+GCC+EMX
_wildcard (&argc, &argv);
#endif
programname = argv [0];
int c;
while ((c = getopt_long (argc, argv, "8cd::s:m:t:hvV", long_options, NULL)) != EOF)
switch (c)
{
case '?':
// unknown option
return -1;
case '8':
opt.paletted = true;
break;
case 'c':
opt.truecolor = true;
break;
case 'd':
opt.dither = true;
break;
case 'D':
opt.save = false;
opt.display = true;
if (optarg &&
sscanf (optarg, "%d,%d", &opt.displayW, &opt.displayH) != 2)
{
printf ("%s: expecting <width>,<height> after -d\n", programname);
return -1;
}
break;
case 's':
if (sscanf (optarg, "%d,%d", &opt.scaleX, &opt.scaleY) != 2)
{
printf ("%s: expecting <width>,<height> after -s\n", programname);
return -1;
}
break;
case 't':
{
opt.transp = true;
int r,g,b;
if (sscanf (optarg, "%d,%d,%d", &r, &g, &b) != 3)
{
printf ("%s: expecting <R>,<G>,<B> after -t\n", programname);
return -1;
}
transpcolor.red = r > 255 ? 255 : r < 0 ? 0 : r;
transpcolor.green = g > 255 ? 255 : g < 0 ? 0 : g;
transpcolor.blue = b > 255 ? 255 : b < 0 ? 0 : b;
break;
}
case 'm':
if (sscanf (optarg, "%d", &opt.mipmap) != 1)
{
printf ("%s: expecting <mipmap level> which is one of 0,1,2,3 after -m\n", programname);
return -1;
}
if (opt.mipmap < 0 || opt.mipmap > 3)
{
printf ("%s: bad mipmap level (%d): should be one of 0,1,2,3\n", programname, opt.mipmap);
return -1;
}
break;
case 'h':
return display_help ();
case 'v':
opt.verbose = true;
break;
case 'V':
printf ("%s version %s\n\n", programname, programversion);
printf ("This program is distributed in the hope that it will be useful,\n");
printf ("but WITHOUT ANY WARRANTY; without even the implied warranty of\n");
printf ("MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n");
printf ("GNU Library General Public License for more details.\n");
return 0;
} /* endswitch */
if (optind >= argc)
return display_help ();
csImageLoader::SetDithering (opt.dither);
for (; optind < argc; ++optind)
if (!process_file (argv [optind]))
return -1;
return 0;
}
<commit_msg>%ld to %d placeholder change<commit_after>/*
Graphics File Loader: a test program for csgfxldr library
Copyright (C) 2000 Andrew Zabolotny <bit@eltech.ru>
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.
*/
#define SYSDEF_PATH
#define SYSDEF_GETOPT
#include "sysdef.h"
#include "csgfxldr/csimage.h"
#include "csgfxldr/pngsave.h"
#include <string.h>
char *programversion = "0.0.1";
char *programname;
/*
NOTE: If your Losing Operating System {tm} (R) does not have getopt_long,
please use the one in support/gnu instead. Please don't comment out blocks
of code, dont #ifdef and so on. It is ugly.
*/
static struct option long_options[] =
{
{"help", no_argument, 0, 'h'},
{"display", optional_argument, 0, 'D'},
{"dither", no_argument, 0, 'd'},
{"scale", required_argument, 0, 's'},
{"mipmap", required_argument, 0, 'm'},
{"transp", required_argument, 0, 't'},
{"paletted", no_argument, 0, '8'},
{"truecolor", no_argument, 0, 'c'},
{"verbose", no_argument, 0, 'v'},
{"version", no_argument, 0, 'V'},
{0, no_argument, 0, 0}
};
static struct
{
bool verbose;
bool save;
bool display;
bool dither;
bool paletted;
bool truecolor;
int scaleX, scaleY;
int displayW, displayH;
int mipmap;
bool transp;
} opt =
{
false,
true,
false,
false,
false,
false,
0, 0,
79, 24,
-1,
false
};
// Dont move inside the struct!
static RGBPixel transpcolor;
static int display_help ()
{
printf ("Crystal Space Graphics File Loader test application v%s\n", programversion);
printf ("Copyright (C) 2000 Andrew Zabolotny\n\n");
printf ("Usage: %s {option/s} [image file] [...]\n\n", programname);
printf (" -D --display{=#,#} Display the image in ASCII format :-)\n");
printf (" -d --dither Apply Floyd-Steinberg dithering when reducing to 8 bpp\n");
printf (" -s --scale=#,# Re-scale the image to given size #\n");
printf (" -m --mipmap=# Create mipmap level # (=0,1,2,3) from image\n");
printf (" -t --transp=#,#,# Treat color (R,G,B) as transparent\n");
printf (" -8 --paletted Convert image to 8 bits-per-pixel paletted format\n");
printf (" -c --truecolor Convert image to truecolor format\n");
printf (" -h --help Display this help text\n");
printf (" -v --verbose Comment on what's happening\n");
printf (" -V --version Display program version\n");
return 1;
}
#if 0
// PNM is a very simple format that is handy for quick-and-dirty programs.
// Many image processing programs understands it...
static bool SavePNM (const char *fname, void *image, int w, int h, bool rgb)
{
FILE *f = fopen (fname, "wb");
if (!f)
{
fprintf (stderr, "%s: cannot open output file %s\n", programname, fname);
return false;
}
char header [100];
sprintf (header, "P%c\n%d %d\n%d\n", rgb ? '6' : '5', w, h, 255);
fwrite (header, 1, strlen (header), f);
if (rgb)
for (int i = w * h; i > 0; i--)
{
fwrite (image, 1, 3, f);
image = ((RGBPixel *)image) + 1;
}
else
fwrite (image, 1, w * h, f);
fclose (f);
return true;
}
#endif
static bool process_file (const char *fname)
{
printf ("Loading file %s\n", fname);
FILE *f = fopen (fname, "rb");
if (!f)
{
printf ("%s: cannot open file %s\n", programname, fname);
return false;
}
fseek (f, 0, SEEK_END);
size_t fsize = ftell (f);
fseek (f, 0, SEEK_SET);
if (opt.verbose)
printf ("Reading %d bytes from file\n", fsize);
UByte *buffer = new UByte [fsize];
if (fread (buffer, 1, fsize, f) < fsize)
{
printf ("%s: unexpected EOF while reading file %s\n", programname, fname);
return false;
}
fclose (f);
int fmt;
if (opt.paletted)
fmt = CS_IMGFMT_PALETTED8;
else if (opt.truecolor)
fmt = CS_IMGFMT_TRUECOLOR;
else
fmt = CS_IMGFMT_ANY;
iImage *ifile = csImageLoader::Load (buffer, fsize, fmt | CS_IMGFMT_ALPHA);
delete [] buffer;
if (!ifile)
{
printf ("%s: failed to recognise image format for %s\n", programname, fname);
return false;
}
if (opt.verbose)
{
printf ("Image size: %d x %d pixels, %d bytes\n", ifile->GetWidth (),
ifile->GetHeight (), ifile->GetSize ());
int fmt = ifile->GetFormat ();
printf ("Image format: %s, alpha channel: %s\n",
(fmt & CS_IMGFMT_MASK) == CS_IMGFMT_NONE ? "none" :
(fmt & CS_IMGFMT_MASK) == CS_IMGFMT_PALETTED8 ? "paletted, 256 colors" :
(fmt & CS_IMGFMT_MASK) == CS_IMGFMT_TRUECOLOR ? "truecolor" : "unknown",
(fmt & CS_IMGFMT_ALPHA) ? "present" : "not present");
}
char suffix [20];
suffix [0] = 0;
if (opt.scaleX > 0 && opt.scaleY > 0)
{
printf ("Rescaling image to %d x %d\n", opt.scaleX, opt.scaleY);
ifile->Rescale (opt.scaleX, opt.scaleY);
sprintf (strchr (suffix, 0), "-s%dx%d", opt.scaleX, opt.scaleY);
}
if (opt.mipmap >= 0)
{
printf ("Creating mipmap level %d from image\n", opt.mipmap);
iImage *ifile2 = ifile->MipMap (opt.mipmap,
opt.transp ? &transpcolor : NULL);
ifile->DecRef ();
ifile = ifile2;
sprintf (strchr (suffix, 0), "-m%d", opt.mipmap);
}
if (opt.save)
{
char outname [MAXPATHLEN + 1];
strcpy (outname, fname);
char *eol = strchr (outname, 0);
while (eol > outname && *eol != '.') eol--;
if (eol == outname) eol = strchr (outname, 0);
strcpy (eol, suffix);
strcat (eol, ".png");
printf ("Saving output file %s\n", outname);
#if 1
if (!csSavePNG (outname, ifile))
return false;
#else
if (!SavePNM (outname, ifile->GetImageData (), ifile->GetWidth (), ifile->GetHeight (),
(ifile->GetFormat () & CS_IMGFMT_MASK) == CS_IMGFMT_TRUECOLOR))
return false;
#endif
}
if (opt.display)
{
static char imgchr [] = " .,;+*oO";
ifile->Rescale (opt.displayW, opt.displayH);
RGBPixel *rgb;
UByte *idx = NULL;
bool truecolor = (ifile->GetFormat () & CS_IMGFMT_MASK) == CS_IMGFMT_TRUECOLOR;
if (truecolor)
rgb = (RGBPixel *)ifile->GetImageData ();
else
{
idx = (UByte *)ifile->GetImageData ();
rgb = ifile->GetPalette ();
}
for (int y = 0; y < opt.displayH; y++)
{
for (int x = 0; x < opt.displayW; x++)
{
RGBPixel &src = truecolor ? *rgb++ : rgb [*idx++];
int gray = int (sqrt (src.red * src.red + src.green * src.green +
src.blue * src.blue) * 8 / 442);
putc (imgchr [gray], stdout);
}
putc ('\n', stdout);
}
}
// Destroy the image object
ifile->DecRef ();
return true;
}
int main (int argc, char **argv)
{
#if defined (__EMX__) // Expand wildcards on OS/2+GCC+EMX
_wildcard (&argc, &argv);
#endif
programname = argv [0];
int c;
while ((c = getopt_long (argc, argv, "8cd::s:m:t:hvV", long_options, NULL)) != EOF)
switch (c)
{
case '?':
// unknown option
return -1;
case '8':
opt.paletted = true;
break;
case 'c':
opt.truecolor = true;
break;
case 'd':
opt.dither = true;
break;
case 'D':
opt.save = false;
opt.display = true;
if (optarg &&
sscanf (optarg, "%d,%d", &opt.displayW, &opt.displayH) != 2)
{
printf ("%s: expecting <width>,<height> after -d\n", programname);
return -1;
}
break;
case 's':
if (sscanf (optarg, "%d,%d", &opt.scaleX, &opt.scaleY) != 2)
{
printf ("%s: expecting <width>,<height> after -s\n", programname);
return -1;
}
break;
case 't':
{
opt.transp = true;
int r,g,b;
if (sscanf (optarg, "%d,%d,%d", &r, &g, &b) != 3)
{
printf ("%s: expecting <R>,<G>,<B> after -t\n", programname);
return -1;
}
transpcolor.red = r > 255 ? 255 : r < 0 ? 0 : r;
transpcolor.green = g > 255 ? 255 : g < 0 ? 0 : g;
transpcolor.blue = b > 255 ? 255 : b < 0 ? 0 : b;
break;
}
case 'm':
if (sscanf (optarg, "%d", &opt.mipmap) != 1)
{
printf ("%s: expecting <mipmap level> which is one of 0,1,2,3 after -m\n", programname);
return -1;
}
if (opt.mipmap < 0 || opt.mipmap > 3)
{
printf ("%s: bad mipmap level (%d): should be one of 0,1,2,3\n", programname, opt.mipmap);
return -1;
}
break;
case 'h':
return display_help ();
case 'v':
opt.verbose = true;
break;
case 'V':
printf ("%s version %s\n\n", programname, programversion);
printf ("This program is distributed in the hope that it will be useful,\n");
printf ("but WITHOUT ANY WARRANTY; without even the implied warranty of\n");
printf ("MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n");
printf ("GNU Library General Public License for more details.\n");
return 0;
} /* endswitch */
if (optind >= argc)
return display_help ();
csImageLoader::SetDithering (opt.dither);
for (; optind < argc; ++optind)
if (!process_file (argv [optind]))
return -1;
return 0;
}
<|endoftext|>
|
<commit_before>/***************************************************************
*
* Copyright (C) 1990-2007, Condor Team, Computer Sciences Department,
* University of Wisconsin-Madison, WI.
*
* 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 "condor_common.h"
#include "condor_classad.h"
#include "condor_config.h"
#include "condor_qmgr.h"
#include "match_prefix.h"
#include "sig_install.h"
#include "get_daemon_name.h"
#include "condor_attributes.h"
#include "condor_distribution.h"
#include "daemon.h"
#include "dc_schedd.h"
#include "MyString.h"
void
usage(char name[])
{
fprintf(stderr, "Usage: %s [-n schedd-name] [-pool pool-name] { cluster | cluster.proc | owner | -constraint constraint } attribute-name attribute-value ...\n", name);
exit(1);
}
bool
ProtectedAttribute(char attr[])
{
return (strcmp(attr, ATTR_OWNER) == 0) ||
(strcmp(attr, ATTR_CLUSTER_ID) == 0) ||
(strcmp(attr, ATTR_PROC_ID) == 0) ||
(strcmp(attr, ATTR_MY_TYPE) == 0) ||
(strcmp(attr, ATTR_TARGET_TYPE) == 0) ||
(strcmp(attr, ATTR_JOB_STATUS) == 0);
}
int
main(int argc, char *argv[])
{
MyString constraint;
Qmgr_connection *q;
int nextarg = 1, cluster, proc;
bool UseConstraint = false;
MyString schedd_name;
MyString pool_name;
myDistro->Init( argc, argv );
config();
#if !defined(WIN32)
install_sig_handler(SIGPIPE, SIG_IGN );
#endif
if (argc < 2) {
usage(argv[0]);
}
// if it is present, it must be first
if (argv[nextarg][0] == '-' && argv[nextarg][1] == 'n') {
nextarg++;
// use the given name as the schedd name to connect to
if (argc <= nextarg) {
fprintf(stderr, "%s: -n requires another argument\n",
argv[0]);
exit(1);
}
schedd_name = argv[nextarg];
nextarg++;
}
if (argc <= nextarg) {
usage(argv[0]);
}
// if it is present, it must be just after -n flag
if (argv[nextarg][0] == '-' && argv[nextarg][1] == 'p') {
nextarg++;
if (argc <= nextarg) {
fprintf(stderr, "%s: -pool requires another argument\n",
argv[0]);
exit(1);
}
pool_name = argv[nextarg];
nextarg++;
}
DCSchedd schedd(schedd_name.GetCStr(), pool_name.GetCStr());
if ( schedd.locate() == false ) {
if (schedd_name == "") {
fprintf( stderr, "%s: ERROR: Can't find address of local schedd\n",
argv[0] );
exit(1);
}
if (pool_name == "") {
fprintf( stderr, "%s: No such schedd named %s in local pool\n",
argv[0], schedd_name.Value() );
} else {
fprintf( stderr, "%s: No such schedd named %s in "
"pool %s\n",
argv[0], schedd_name.Value(), pool_name.Value() );
}
exit(1);
}
// Open job queue
q = ConnectQ( schedd.addr() );
if( !q ) {
fprintf( stderr, "Failed to connect to queue manager %s\n",
schedd.addr() );
exit(1);
}
if (argc <= nextarg) {
usage(argv[0]);
}
if (match_prefix(argv[nextarg], "-constraint")) {
nextarg++;
if (argc <= nextarg) {
usage(argv[0]);
}
constraint = argv[nextarg];
nextarg++;
UseConstraint = true;
} else if (isdigit(argv[nextarg][0])) {
char *tmp;
cluster = strtol(argv[nextarg], &tmp, 10);
if (cluster <= 0) {
fprintf( stderr, "Invalid cluster # from %s.\n", argv[nextarg]);
exit(1);
}
if (*tmp == '.') {
proc = strtol(tmp + 1, &tmp, 10);
if (cluster <= 0) {
fprintf( stderr, "Invalid proc # from %s.\n", argv[nextarg]);
exit(1);
}
UseConstraint = false;
} else {
constraint.sprintf("(%s == %d)", ATTR_CLUSTER_ID, cluster);
UseConstraint = true;
}
nextarg++;
} else {
constraint.sprintf("(%s == \"%s\")", ATTR_OWNER, argv[nextarg]);
nextarg++;
UseConstraint = true;
}
if (argc <= nextarg) {
usage(argv[0]);
}
for (; nextarg < argc; nextarg += 2) {
if (argc <= nextarg+1) {
usage(argv[0]);
}
if (ProtectedAttribute(argv[nextarg])) {
fprintf(stderr, "Update of attribute \"%s\" is not allowed.\n",
argv[nextarg]);
exit(1);
}
if (UseConstraint) {
if (SetAttributeByConstraint(constraint.Value(), argv[nextarg],
argv[nextarg+1]) < 0) {
fprintf(stderr,
"Failed to set attribute \"%s\" by constraint: %s\n",
argv[nextarg], constraint.Value());
exit(1);
}
} else {
if (SetAttribute(cluster, proc, argv[nextarg],
argv[nextarg+1]) < 0) {
fprintf(stderr,
"Failed to set attribute \"%s\" for job %d.%d.\n",
argv[nextarg], cluster, proc);
exit(1);
}
}
printf("Set attribute \"%s\".\n", argv[nextarg]);
}
if (!DisconnectQ(q)) {
fprintf(stderr,
"Queue transaction failed. No attributes were set.\n");
exit(1);
}
return 0;
}
#include "daemon_core_stubs.h"
<commit_msg>added support for the "-debug" option to condor_qedit.<commit_after>/***************************************************************
*
* Copyright (C) 1990-2007, Condor Team, Computer Sciences Department,
* University of Wisconsin-Madison, WI.
*
* 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 "condor_common.h"
#include "condor_classad.h"
#include "condor_debug.h"
#include "condor_config.h"
#include "condor_qmgr.h"
#include "match_prefix.h"
#include "sig_install.h"
#include "get_daemon_name.h"
#include "condor_attributes.h"
#include "condor_distribution.h"
#include "daemon.h"
#include "dc_schedd.h"
#include "MyString.h"
void
usage(char name[])
{
fprintf(stderr, "Usage: %s [-debug] [-n schedd-name] [-pool pool-name] { cluster | cluster.proc | owner | -constraint constraint } attribute-name attribute-value ...\n", name);
exit(1);
}
bool
ProtectedAttribute(char attr[])
{
return (strcmp(attr, ATTR_OWNER) == 0) ||
(strcmp(attr, ATTR_CLUSTER_ID) == 0) ||
(strcmp(attr, ATTR_PROC_ID) == 0) ||
(strcmp(attr, ATTR_MY_TYPE) == 0) ||
(strcmp(attr, ATTR_TARGET_TYPE) == 0) ||
(strcmp(attr, ATTR_JOB_STATUS) == 0);
}
int
main(int argc, char *argv[])
{
MyString constraint;
Qmgr_connection *q;
int nextarg = 1, cluster, proc;
bool UseConstraint = false;
MyString schedd_name;
MyString pool_name;
myDistro->Init( argc, argv );
config();
#if !defined(WIN32)
install_sig_handler(SIGPIPE, SIG_IGN );
#endif
if (argc < 2) {
usage(argv[0]);
}
// if -debug is present, it must be first. sigh.
if (argv[nextarg][0] == '-' && argv[nextarg][1] == 'd') {
// output dprintf messages to stderror at TOOL_DEBUG level
Termlog = 1;
dprintf_config ("TOOL");
nextarg++;
}
// if it is present, it must be first after debug.
if (argv[nextarg][0] == '-' && argv[nextarg][1] == 'n') {
nextarg++;
// use the given name as the schedd name to connect to
if (argc <= nextarg) {
fprintf(stderr, "%s: -n requires another argument\n",
argv[0]);
exit(1);
}
schedd_name = argv[nextarg];
nextarg++;
}
if (argc <= nextarg) {
usage(argv[0]);
}
// if it is present, it must be just after -n flag
if (argv[nextarg][0] == '-' && argv[nextarg][1] == 'p') {
nextarg++;
if (argc <= nextarg) {
fprintf(stderr, "%s: -pool requires another argument\n",
argv[0]);
exit(1);
}
pool_name = argv[nextarg];
nextarg++;
}
DCSchedd schedd(schedd_name.GetCStr(), pool_name.GetCStr());
if ( schedd.locate() == false ) {
if (schedd_name == "") {
fprintf( stderr, "%s: ERROR: Can't find address of local schedd\n",
argv[0] );
exit(1);
}
if (pool_name == "") {
fprintf( stderr, "%s: No such schedd named %s in local pool\n",
argv[0], schedd_name.Value() );
} else {
fprintf( stderr, "%s: No such schedd named %s in "
"pool %s\n",
argv[0], schedd_name.Value(), pool_name.Value() );
}
exit(1);
}
// Open job queue
q = ConnectQ( schedd.addr() );
if( !q ) {
fprintf( stderr, "Failed to connect to queue manager %s\n",
schedd.addr() );
exit(1);
}
if (argc <= nextarg) {
usage(argv[0]);
}
if (match_prefix(argv[nextarg], "-constraint")) {
nextarg++;
if (argc <= nextarg) {
usage(argv[0]);
}
constraint = argv[nextarg];
nextarg++;
UseConstraint = true;
} else if (isdigit(argv[nextarg][0])) {
char *tmp;
cluster = strtol(argv[nextarg], &tmp, 10);
if (cluster <= 0) {
fprintf( stderr, "Invalid cluster # from %s.\n", argv[nextarg]);
exit(1);
}
if (*tmp == '.') {
proc = strtol(tmp + 1, &tmp, 10);
if (cluster <= 0) {
fprintf( stderr, "Invalid proc # from %s.\n", argv[nextarg]);
exit(1);
}
UseConstraint = false;
} else {
constraint.sprintf("(%s == %d)", ATTR_CLUSTER_ID, cluster);
UseConstraint = true;
}
nextarg++;
} else {
constraint.sprintf("(%s == \"%s\")", ATTR_OWNER, argv[nextarg]);
nextarg++;
UseConstraint = true;
}
if (argc <= nextarg) {
usage(argv[0]);
}
for (; nextarg < argc; nextarg += 2) {
if (argc <= nextarg+1) {
usage(argv[0]);
}
if (ProtectedAttribute(argv[nextarg])) {
fprintf(stderr, "Update of attribute \"%s\" is not allowed.\n",
argv[nextarg]);
exit(1);
}
if (UseConstraint) {
if (SetAttributeByConstraint(constraint.Value(), argv[nextarg],
argv[nextarg+1]) < 0) {
fprintf(stderr,
"Failed to set attribute \"%s\" by constraint: %s\n",
argv[nextarg], constraint.Value());
exit(1);
}
} else {
if (SetAttribute(cluster, proc, argv[nextarg],
argv[nextarg+1]) < 0) {
fprintf(stderr,
"Failed to set attribute \"%s\" for job %d.%d.\n",
argv[nextarg], cluster, proc);
exit(1);
}
}
printf("Set attribute \"%s\".\n", argv[nextarg]);
}
if (!DisconnectQ(q)) {
fprintf(stderr,
"Queue transaction failed. No attributes were set.\n");
exit(1);
}
return 0;
}
#include "daemon_core_stubs.h"
<|endoftext|>
|
<commit_before>/*******************************************************************************
GPU OPTIMIZED MONTE CARLO (GOMC) 2.20
Copyright (C) 2018 GOMC Group
A copy of the GNU General Public License can be found in the COPYRIGHT.txt
along with this program, also can be found at <http://www.gnu.org/licenses/>.
********************************************************************************/
#include "BoxDimensionsNonOrth.h"
#include "BoxDimensions.h"
#include "MoveConst.h" //For cutoff-related fail condition
void BoxDimensionsNonOrth::Init(config_setup::RestartSettings const& restart,
config_setup::Volume const& confVolume,
pdb_setup::Cryst1 const& cryst,
double rc, double rcSq)
{
rCut = rc;
rCutSq = rcSq;
for (uint b = 0; b < BOX_TOTAL; b++) {
if(restart.enable && cryst.hasVolume) {
axis = cryst.axis;
double alpha = cos(cryst.cellAngle[b][0] * M_PI / 180.0);
double beta = cos(cryst.cellAngle[b][1] * M_PI / 180.0);
double gamma = cos(cryst.cellAngle[b][2] * M_PI / 180.0);
if(float(cryst.cellAngle[b][0]) == 90.0)
alpha = 0.0;
if(float(cryst.cellAngle[b][1]) == 90.0)
beta = 0.0;
if(float(cryst.cellAngle[b][2]) == 90.0)
gamma = 0.0;
double cosASq = alpha * alpha;
double cosBSq = beta * beta;
double cosGSq = gamma * gamma;
double temp = (alpha - beta * gamma) / (sqrt(1.0 - cosGSq));
cellBasis[b].Set(0, 1.0, 0.0, 0.0);
cellBasis[b].Set(1, gamma, sqrt(1.0 - cosGSq), 0.0);
cellBasis[b].Set(2, beta, temp, sqrt(1.0 - cosBSq - temp * temp));
cellBasis[b].Scale(0, axis.Get(b).x);
cellBasis[b].Scale(1, axis.Get(b).y);
cellBasis[b].Scale(2, axis.Get(b).z);
} else if(confVolume.hasVolume) {
confVolume.axis[b].CopyRange(cellBasis[b], 0, 0, 3);
} else {
fprintf(stderr,
"Error: Cell Basis not specified in PDB or in.dat files.\n");
exit(EXIT_FAILURE);
}
//Find the length of a, b, c
cellLength.Set(b, cellBasis[b].Length(0), cellBasis[b].Length(1),
cellBasis[b].Length(2));
//Find Cosine Angle of alpha, beta and gamma
cosAngle[b][0] = Dot(cellBasis[b].Get(1), cellBasis[b].Get(2)) /
(cellLength.Get(b).y * cellLength.Get(b).z);
cosAngle[b][1] = Dot(cellBasis[b].Get(0), cellBasis[b].Get(2)) /
(cellLength.Get(b).x * cellLength.Get(b).z);
cosAngle[b][2] = Dot(cellBasis[b].Get(0), cellBasis[b].Get(1)) /
(cellLength.Get(b).x * cellLength.Get(b).y);
//Calculate Cross Product
XYZ axb = Cross(cellBasis[b].Get(0), cellBasis[b].Get(1));
XYZ bxc = Cross(cellBasis[b].Get(1), cellBasis[b].Get(2));
XYZ cxa = Cross(cellBasis[b].Get(2), cellBasis[b].Get(0));
//Calculate volume = A.(B x C)
volume[b] = abs(Dot(cellBasis[b].Get(0), bxc));
volInv[b] = 1.0 / volume[b];
//normalizing unitcell
for(uint i = 0; i < 3; i++) {
cellBasis[b].Set(i, cellBasis[b].Get(i).Normalize());
}
//Calculate the adjoint and determinant
double det = cellBasis[b].AdjointMatrix(cellBasis_Inv[b]);
//Calculate the inverse matrix of cell basis
cellBasis_Inv[b].ScaleRange(0, 3, 1.0 / det);
//Set the axis with unslant cell box
//XYZ unslant = TransformUnSlant(cellLength.Get(b), b);
//axis.Set(b, unslant.x, unslant.y, unslant.z);
axis.Set(b, cellLength[b]);
}
//Set half axis
axis.CopyRange(halfAx, 0, 0, BOX_TOTAL);
halfAx.ScaleRange(0, BOX_TOTAL, 0.5);
for (uint b = 0; b < BOX_TOTAL; b++) {
//check to see if initial box size is cubic or not
cubic[b] = ((axis.x[b] == axis.y[b]) && (axis.y[b] == axis.z[b]));
//check to see if box is orthogonal or not
orthogonal[b] = ((cosAngle[b][0] == 0.0) &&
(cosAngle[b][1] == 0.0) &&
(cosAngle[b][2] == 0.0));
}
constArea = confVolume.cstArea;
}
void BoxDimensionsNonOrth::CalcCellDimensions(const uint b)
{
//normalizing unitcell
for(uint i = 0; i < 3; i++) {
cellBasis[b].Set(i, cellBasis[b].Get(i).Normalize());
}
//Calculate the adjoint and determinant
double det = cellBasis[b].AdjointMatrix(cellBasis_Inv[b]);
//Calculate the inverse matrix of cell basis
cellBasis_Inv[b].ScaleRange(0, 3, 1.0 / det);
}
BoxDimensionsNonOrth& BoxDimensionsNonOrth::operator=(BoxDimensionsNonOrth const& other)
{
for (uint b = 0; b < BOX_TOTAL; ++b) {
other.cellBasis[b].CopyRange(cellBasis[b], 0, 0, 3);
other.cellBasis_Inv[b].CopyRange(cellBasis_Inv[b], 0, 0, 3);
volume[b] = other.volume[b];
volInv[b] = other.volInv[b];
cubic[b] = other.cubic[b];
orthogonal[b] = other.orthogonal[b];
for(uint i = 0; i < 0; i++) {
cosAngle[b][i] = other.cosAngle[b][i];
}
}
other.axis.CopyRange(axis, 0, 0, BOX_TOTAL);
other.halfAx.CopyRange(halfAx, 0, 0, BOX_TOTAL);
other.cellLength.CopyRange(cellLength, 0, 0, BOX_TOTAL);
rCut = other.rCut;
rCutSq = other.rCutSq;
constArea = other.constArea;
return *this;
}
uint BoxDimensionsNonOrth::ShiftVolume(BoxDimensionsNonOrth & newDim,
XYZ & scale, const uint b,
const double delta) const
{
uint rejectState = mv::fail_state::NO_FAIL;
double newVolume = volume[b] + delta;
newDim = *this;
newDim.SetVolume(b, newVolume);
//If move would shrink any box axis to be less than 2 * rcut, then
//automatically reject to prevent errors.
if ((newDim.halfAx.x[b] < rCut || newDim.halfAx.y[b] < rCut ||
newDim.halfAx.z[b] < rCut)) {
std::cout << "WARNING!!! box shrunk below 2*Rcut! Auto-rejecting!"
<< std::endl;
rejectState = mv::fail_state::VOL_TRANS_WOULD_SHRINK_BOX_BELOW_CUTOFF;
}
scale = newDim.axis.Get(b) / axis.Get(b);
return rejectState;
}
uint BoxDimensionsNonOrth::ExchangeVolume(BoxDimensionsNonOrth & newDim,
XYZ * scale,
const double transfer) const
{
uint state = mv::fail_state::NO_FAIL;
double vTot = GetTotVolume();
newDim = *this;
newDim.SetVolume(0, volume[0] + transfer);
newDim.SetVolume(1, vTot - newDim.volume[0]);
//If move would shrink any box axis to be less than 2 * rcut, then
//automatically reject to prevent errors.
for (uint b = 0; b < BOX_TOTAL && state == mv::fail_state::NO_FAIL; b++) {
scale[b] = newDim.axis.Get(b) / axis.Get(b);
if ((newDim.halfAx.x[b] < rCut || newDim.halfAx.y[b] < rCut ||
newDim.halfAx.z[b] < rCut)) {
std::cout << "WARNING!!! box shrunk below 2*Rcut! Auto-rejecting!"
<< std::endl;
state = state && mv::fail_state::VOL_TRANS_WOULD_SHRINK_BOX_BELOW_CUTOFF;
}
}
return state;
}
void BoxDimensionsNonOrth::SetVolume(const uint b, const double vol)
{
if(constArea) {
double ratio = vol / volume[b];
axis.Scale(b, 1.0, 1.0, ratio);
halfAx.Scale(b, 1.0, 1.0, ratio);
cellLength.Scale(b, 1.0, 1.0, ratio);
//Keep a and b same and change c
cellBasis[b].Scale(2, ratio);
} else {
double ratio = pow(vol / volume[b], (1.0 / 3.0));
axis.Scale(b, ratio);
halfAx.Scale(b, ratio);
cellLength.Scale(b, ratio);
for(uint i = 0; i < 0; i++) {
cellBasis[b].Scale(i, ratio);
}
}
volume[b] = vol;
volInv[b] = 1.0 / volume[b];
//Calculate new cell dimension
CalcCellDimensions(b);
}
XYZ BoxDimensionsNonOrth::MinImage(XYZ rawVecRef, const uint b) const
{
XYZ rawVec = TransformUnSlant(rawVecRef, b);
rawVecRef = BoxDimensions:: MinImage(rawVec, b);
rawVecRef = TransformSlant(rawVecRef, b);
return rawVecRef;
}
void BoxDimensionsNonOrth::WrapPBC(double &x, double &y, double &z,
const uint b) const
{
//convert XYZ to unslant
XYZ unwrap(x, y, z);
XYZ unslant = TransformUnSlant(unwrap, b);
BoxDimensions::WrapPBC(unslant.x, axis.x[b]);
BoxDimensions::WrapPBC(unslant.y, axis.y[b]);
BoxDimensions::WrapPBC(unslant.z, axis.z[b]);
//convert XYZ to slant
XYZ slant = TransformSlant(unslant, b);
x = slant.x;
y = slant.y;
z = slant.z;
}
void BoxDimensionsNonOrth::UnwrapPBC(double & x, double & y, double & z,
const uint b, XYZ const& ref) const
{
//convert XYZ to unslant
XYZ wrap(x, y, z);
XYZ unslant = TransformUnSlant(wrap, b);
XYZ unslantRef = TransformUnSlant(ref, b);
BoxDimensions::UnwrapPBC(unslant.x, unslantRef.x, axis.x[b], halfAx.x[b]);
BoxDimensions::UnwrapPBC(unslant.y, unslantRef.y, axis.y[b], halfAx.y[b]);
BoxDimensions::UnwrapPBC(unslant.z, unslantRef.z, axis.z[b], halfAx.z[b]);
XYZ unwrap(x, y, z);
//convert XYZ to slant
XYZ slant = TransformSlant(unslant, b);
x = slant.x;
y = slant.y;
z = slant.z;
}<commit_msg>error fix<commit_after>/*******************************************************************************
GPU OPTIMIZED MONTE CARLO (GOMC) 2.20
Copyright (C) 2018 GOMC Group
A copy of the GNU General Public License can be found in the COPYRIGHT.txt
along with this program, also can be found at <http://www.gnu.org/licenses/>.
********************************************************************************/
#include "BoxDimensionsNonOrth.h"
#include "BoxDimensions.h"
#include "GeomLib.h"
#include "MoveConst.h" //For cutoff-related fail condition
using namespace geom;
void BoxDimensionsNonOrth::Init(config_setup::RestartSettings const& restart,
config_setup::Volume const& confVolume,
pdb_setup::Cryst1 const& cryst,
double rc, double rcSq)
{
rCut = rc;
rCutSq = rcSq;
for (uint b = 0; b < BOX_TOTAL; b++) {
if(restart.enable && cryst.hasVolume) {
axis = cryst.axis;
double alpha = cos(cryst.cellAngle[b][0] * M_PI / 180.0);
double beta = cos(cryst.cellAngle[b][1] * M_PI / 180.0);
double gamma = cos(cryst.cellAngle[b][2] * M_PI / 180.0);
if(float(cryst.cellAngle[b][0]) == 90.0)
alpha = 0.0;
if(float(cryst.cellAngle[b][1]) == 90.0)
beta = 0.0;
if(float(cryst.cellAngle[b][2]) == 90.0)
gamma = 0.0;
double cosASq = alpha * alpha;
double cosBSq = beta * beta;
double cosGSq = gamma * gamma;
double temp = (alpha - beta * gamma) / (sqrt(1.0 - cosGSq));
cellBasis[b].Set(0, 1.0, 0.0, 0.0);
cellBasis[b].Set(1, gamma, sqrt(1.0 - cosGSq), 0.0);
cellBasis[b].Set(2, beta, temp, sqrt(1.0 - cosBSq - temp * temp));
cellBasis[b].Scale(0, axis.Get(b).x);
cellBasis[b].Scale(1, axis.Get(b).y);
cellBasis[b].Scale(2, axis.Get(b).z);
} else if(confVolume.hasVolume) {
confVolume.axis[b].CopyRange(cellBasis[b], 0, 0, 3);
} else {
fprintf(stderr,
"Error: Cell Basis not specified in PDB or in.dat files.\n");
exit(EXIT_FAILURE);
}
//Find the length of a, b, c
cellLength.Set(b, cellBasis[b].Length(0), cellBasis[b].Length(1),
cellBasis[b].Length(2));
//Find Cosine Angle of alpha, beta and gamma
cosAngle[b][0] = Dot(cellBasis[b].Get(1), cellBasis[b].Get(2)) /
(cellLength.Get(b).y * cellLength.Get(b).z);
cosAngle[b][1] = Dot(cellBasis[b].Get(0), cellBasis[b].Get(2)) /
(cellLength.Get(b).x * cellLength.Get(b).z);
cosAngle[b][2] = Dot(cellBasis[b].Get(0), cellBasis[b].Get(1)) /
(cellLength.Get(b).x * cellLength.Get(b).y);
//Calculate Cross Product
XYZ axb = Cross(cellBasis[b].Get(0), cellBasis[b].Get(1));
XYZ bxc = Cross(cellBasis[b].Get(1), cellBasis[b].Get(2));
XYZ cxa = Cross(cellBasis[b].Get(2), cellBasis[b].Get(0));
//Calculate volume = A.(B x C)
volume[b] = abs(Dot(cellBasis[b].Get(0), bxc));
volInv[b] = 1.0 / volume[b];
//normalizing unitcell
for(uint i = 0; i < 3; i++) {
cellBasis[b].Set(i, cellBasis[b].Get(i).Normalize());
}
//Calculate the adjoint and determinant
double det = cellBasis[b].AdjointMatrix(cellBasis_Inv[b]);
//Calculate the inverse matrix of cell basis
cellBasis_Inv[b].ScaleRange(0, 3, 1.0 / det);
//Set the axis with unslant cell box
//XYZ unslant = TransformUnSlant(cellLength.Get(b), b);
//axis.Set(b, unslant.x, unslant.y, unslant.z);
axis.Set(b, cellLength[b]);
}
//Set half axis
axis.CopyRange(halfAx, 0, 0, BOX_TOTAL);
halfAx.ScaleRange(0, BOX_TOTAL, 0.5);
for (uint b = 0; b < BOX_TOTAL; b++) {
//check to see if initial box size is cubic or not
cubic[b] = ((axis.x[b] == axis.y[b]) && (axis.y[b] == axis.z[b]));
//check to see if box is orthogonal or not
orthogonal[b] = ((cosAngle[b][0] == 0.0) &&
(cosAngle[b][1] == 0.0) &&
(cosAngle[b][2] == 0.0));
}
constArea = confVolume.cstArea;
}
void BoxDimensionsNonOrth::CalcCellDimensions(const uint b)
{
//normalizing unitcell
for(uint i = 0; i < 3; i++) {
cellBasis[b].Set(i, cellBasis[b].Get(i).Normalize());
}
//Calculate the adjoint and determinant
double det = cellBasis[b].AdjointMatrix(cellBasis_Inv[b]);
//Calculate the inverse matrix of cell basis
cellBasis_Inv[b].ScaleRange(0, 3, 1.0 / det);
}
BoxDimensionsNonOrth& BoxDimensionsNonOrth::operator=(BoxDimensionsNonOrth const& other)
{
for (uint b = 0; b < BOX_TOTAL; ++b) {
other.cellBasis[b].CopyRange(cellBasis[b], 0, 0, 3);
other.cellBasis_Inv[b].CopyRange(cellBasis_Inv[b], 0, 0, 3);
volume[b] = other.volume[b];
volInv[b] = other.volInv[b];
cubic[b] = other.cubic[b];
orthogonal[b] = other.orthogonal[b];
for(uint i = 0; i < 0; i++) {
cosAngle[b][i] = other.cosAngle[b][i];
}
}
other.axis.CopyRange(axis, 0, 0, BOX_TOTAL);
other.halfAx.CopyRange(halfAx, 0, 0, BOX_TOTAL);
other.cellLength.CopyRange(cellLength, 0, 0, BOX_TOTAL);
rCut = other.rCut;
rCutSq = other.rCutSq;
constArea = other.constArea;
return *this;
}
uint BoxDimensionsNonOrth::ShiftVolume(BoxDimensionsNonOrth & newDim,
XYZ & scale, const uint b,
const double delta) const
{
uint rejectState = mv::fail_state::NO_FAIL;
double newVolume = volume[b] + delta;
newDim = *this;
newDim.SetVolume(b, newVolume);
//If move would shrink any box axis to be less than 2 * rcut, then
//automatically reject to prevent errors.
if ((newDim.halfAx.x[b] < rCut || newDim.halfAx.y[b] < rCut ||
newDim.halfAx.z[b] < rCut)) {
std::cout << "WARNING!!! box shrunk below 2*Rcut! Auto-rejecting!"
<< std::endl;
rejectState = mv::fail_state::VOL_TRANS_WOULD_SHRINK_BOX_BELOW_CUTOFF;
}
scale = newDim.axis.Get(b) / axis.Get(b);
return rejectState;
}
uint BoxDimensionsNonOrth::ExchangeVolume(BoxDimensionsNonOrth & newDim,
XYZ * scale,
const double transfer) const
{
uint state = mv::fail_state::NO_FAIL;
double vTot = GetTotVolume();
newDim = *this;
newDim.SetVolume(0, volume[0] + transfer);
newDim.SetVolume(1, vTot - newDim.volume[0]);
//If move would shrink any box axis to be less than 2 * rcut, then
//automatically reject to prevent errors.
for (uint b = 0; b < BOX_TOTAL && state == mv::fail_state::NO_FAIL; b++) {
scale[b] = newDim.axis.Get(b) / axis.Get(b);
if ((newDim.halfAx.x[b] < rCut || newDim.halfAx.y[b] < rCut ||
newDim.halfAx.z[b] < rCut)) {
std::cout << "WARNING!!! box shrunk below 2*Rcut! Auto-rejecting!"
<< std::endl;
state = state && mv::fail_state::VOL_TRANS_WOULD_SHRINK_BOX_BELOW_CUTOFF;
}
}
return state;
}
void BoxDimensionsNonOrth::SetVolume(const uint b, const double vol)
{
if(constArea) {
double ratio = vol / volume[b];
axis.Scale(b, 1.0, 1.0, ratio);
halfAx.Scale(b, 1.0, 1.0, ratio);
cellLength.Scale(b, 1.0, 1.0, ratio);
//Keep a and b same and change c
cellBasis[b].Scale(2, ratio);
} else {
double ratio = pow(vol / volume[b], (1.0 / 3.0));
axis.Scale(b, ratio);
halfAx.Scale(b, ratio);
cellLength.Scale(b, ratio);
for(uint i = 0; i < 0; i++) {
cellBasis[b].Scale(i, ratio);
}
}
volume[b] = vol;
volInv[b] = 1.0 / volume[b];
//Calculate new cell dimension
CalcCellDimensions(b);
}
XYZ BoxDimensionsNonOrth::MinImage(XYZ rawVecRef, const uint b) const
{
XYZ rawVec = TransformUnSlant(rawVecRef, b);
rawVecRef = BoxDimensions:: MinImage(rawVec, b);
rawVecRef = TransformSlant(rawVecRef, b);
return rawVecRef;
}
void BoxDimensionsNonOrth::WrapPBC(double &x, double &y, double &z,
const uint b) const
{
//convert XYZ to unslant
XYZ unwrap(x, y, z);
XYZ unslant = TransformUnSlant(unwrap, b);
BoxDimensions::WrapPBC(unslant.x, axis.x[b]);
BoxDimensions::WrapPBC(unslant.y, axis.y[b]);
BoxDimensions::WrapPBC(unslant.z, axis.z[b]);
//convert XYZ to slant
XYZ slant = TransformSlant(unslant, b);
x = slant.x;
y = slant.y;
z = slant.z;
}
void BoxDimensionsNonOrth::UnwrapPBC(double & x, double & y, double & z,
const uint b, XYZ const& ref) const
{
//convert XYZ to unslant
XYZ wrap(x, y, z);
XYZ unslant = TransformUnSlant(wrap, b);
XYZ unslantRef = TransformUnSlant(ref, b);
BoxDimensions::UnwrapPBC(unslant.x, unslantRef.x, axis.x[b], halfAx.x[b]);
BoxDimensions::UnwrapPBC(unslant.y, unslantRef.y, axis.y[b], halfAx.y[b]);
BoxDimensions::UnwrapPBC(unslant.z, unslantRef.z, axis.z[b], halfAx.z[b]);
XYZ unwrap(x, y, z);
//convert XYZ to slant
XYZ slant = TransformSlant(unslant, b);
x = slant.x;
y = slant.y;
z = slant.z;
}<|endoftext|>
|
<commit_before>/*************************************************************************
*
* $RCSfile: editable.hxx,v $
*
* $Revision: 1.1 $
*
* last change: $Author: nn $ $Date: 2002-11-20 14:32:18 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#ifndef SC_EDITABLE_HXX
#define SC_EDITABLE_HXX
#ifndef _SOLAR_H
#include <tools/solar.h>
#endif
class ScDocument;
class ScViewFunc;
class ScMarkData;
class ScRange;
class ScEditableTester
{
BOOL bIsEditable;
BOOL bOnlyMatrix;
public:
// no test in ctor
ScEditableTester();
// calls TestBlock
ScEditableTester( ScDocument* pDoc, USHORT nTab,
USHORT nStartCol, USHORT nStartRow, USHORT nEndCol, USHORT nEndRow );
// calls TestSelectedBlock
ScEditableTester( ScDocument* pDoc,
USHORT nStartCol, USHORT nStartRow, USHORT nEndCol, USHORT nEndRow,
const ScMarkData& rMark );
// calls TestRange
ScEditableTester( ScDocument* pDoc, const ScRange& rRange );
// calls TestSelection
ScEditableTester( ScDocument* pDoc, const ScMarkData& rMark );
// calls TestView
ScEditableTester( ScViewFunc* pView );
~ScEditableTester() {}
// Several calls to the Test... methods check if *all* of the ranges
// are editable. For several independent checks, Reset() has to be used.
void TestBlock( ScDocument* pDoc, USHORT nTab,
USHORT nStartCol, USHORT nStartRow, USHORT nEndCol, USHORT nEndRow );
void TestSelectedBlock( ScDocument* pDoc,
USHORT nStartCol, USHORT nStartRow, USHORT nEndCol, USHORT nEndRow,
const ScMarkData& rMark );
void TestRange( ScDocument* pDoc, const ScRange& rRange );
void TestSelection( ScDocument* pDoc, const ScMarkData& rMark );
void TestView( ScViewFunc* pView );
void Reset();
BOOL IsEditable() const { return bIsEditable; }
BOOL IsFormatEditable() const { return bIsEditable || bOnlyMatrix; }
USHORT GetMessageId() const;
};
#endif
<commit_msg>INTEGRATION: CWS rowlimit (1.1.302); FILE MERGED 2004/01/13 20:04:15 er 1.1.302.1: #i1967# SCCOL,SCROW,SCTAB replace USHORT; SCsCOL,SCsROW,SCsTAB replace short<commit_after>/*************************************************************************
*
* $RCSfile: editable.hxx,v $
*
* $Revision: 1.2 $
*
* last change: $Author: obo $ $Date: 2004-06-04 11:33:11 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#ifndef SC_EDITABLE_HXX
#define SC_EDITABLE_HXX
#ifndef SC_ADDRESS_HXX
#include "address.hxx"
#endif
#ifndef _SOLAR_H
#include <tools/solar.h>
#endif
class ScDocument;
class ScViewFunc;
class ScMarkData;
class ScRange;
class ScEditableTester
{
BOOL bIsEditable;
BOOL bOnlyMatrix;
public:
// no test in ctor
ScEditableTester();
// calls TestBlock
ScEditableTester( ScDocument* pDoc, SCTAB nTab,
SCCOL nStartCol, SCROW nStartRow, SCCOL nEndCol, SCROW nEndRow );
// calls TestSelectedBlock
ScEditableTester( ScDocument* pDoc,
SCCOL nStartCol, SCROW nStartRow, SCCOL nEndCol, SCROW nEndRow,
const ScMarkData& rMark );
// calls TestRange
ScEditableTester( ScDocument* pDoc, const ScRange& rRange );
// calls TestSelection
ScEditableTester( ScDocument* pDoc, const ScMarkData& rMark );
// calls TestView
ScEditableTester( ScViewFunc* pView );
~ScEditableTester() {}
// Several calls to the Test... methods check if *all* of the ranges
// are editable. For several independent checks, Reset() has to be used.
void TestBlock( ScDocument* pDoc, SCTAB nTab,
SCCOL nStartCol, SCROW nStartRow, SCCOL nEndCol, SCROW nEndRow );
void TestSelectedBlock( ScDocument* pDoc,
SCCOL nStartCol, SCROW nStartRow, SCCOL nEndCol, SCROW nEndRow,
const ScMarkData& rMark );
void TestRange( ScDocument* pDoc, const ScRange& rRange );
void TestSelection( ScDocument* pDoc, const ScMarkData& rMark );
void TestView( ScViewFunc* pView );
void Reset();
BOOL IsEditable() const { return bIsEditable; }
BOOL IsFormatEditable() const { return bIsEditable || bOnlyMatrix; }
USHORT GetMessageId() const;
};
#endif
<|endoftext|>
|
<commit_before>/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/*
* This file is part of the libetonyek project.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
#include <stdio.h>
#include <string.h>
#include <libwpd-stream/libwpd-stream.h>
#include <libwpd/libwpd.h>
#include <libetonyek/libetonyek.h>
#include "KEYDirectoryStream.h"
class TextPainter : public libetonyek::KEYPresentationInterface
{
public:
TextPainter();
virtual void startDocument(const ::WPXPropertyList &propList);
virtual void endDocument();
virtual void setDocumentMetaData(const ::WPXPropertyList &propList);
virtual void startSlide(const ::WPXPropertyList &propList);
virtual void endSlide();
virtual void startLayer(const ::WPXPropertyList &propList);
virtual void endLayer();
virtual void startEmbeddedGraphics(const ::WPXPropertyList &propList);
virtual void endEmbeddedGraphics();
virtual void startGroup(const ::WPXPropertyList &propList);
virtual void endGroup();
virtual void setStyle(const ::WPXPropertyList &propList, const ::WPXPropertyListVector &gradient);
virtual void drawRectangle(const ::WPXPropertyList &propList);
virtual void drawEllipse(const ::WPXPropertyList &propList);
virtual void drawPolyline(const ::WPXPropertyListVector &vertices);
virtual void drawPolygon(const ::WPXPropertyListVector &vertices);
virtual void drawPath(const ::WPXPropertyListVector &path);
virtual void drawGraphicObject(const ::WPXPropertyList &propList, const ::WPXBinaryData &binaryData);
virtual void drawConnector(const ::WPXPropertyList &propList, const ::WPXPropertyListVector &path);
virtual void startTextObject(const ::WPXPropertyList &propList, const ::WPXPropertyListVector &path);
virtual void endTextObject();
virtual void openParagraph(const ::WPXPropertyList &propList, const ::WPXPropertyListVector &tabStops);
virtual void closeParagraph();
virtual void openSpan(const ::WPXPropertyList &propList);
virtual void closeSpan();
virtual void insertTab();
virtual void insertSpace();
virtual void insertText(const ::WPXString &str);
virtual void insertLineBreak();
virtual void insertField(const WPXString &type, const ::WPXPropertyList &propList);
virtual void openOrderedListLevel(const ::WPXPropertyList &propList);
virtual void openUnorderedListLevel(const ::WPXPropertyList &propList);
virtual void closeOrderedListLevel();
virtual void closeUnorderedListLevel();
virtual void openListElement(const ::WPXPropertyList &propList, const ::WPXPropertyListVector &tabStops);
virtual void closeListElement();
virtual void openTable(const ::WPXPropertyList &propList, const ::WPXPropertyListVector &columns);
virtual void openTableRow(const ::WPXPropertyList &propList);
virtual void closeTableRow();
virtual void openTableCell(const ::WPXPropertyList &propList);
virtual void closeTableCell();
virtual void insertCoveredTableCell(const ::WPXPropertyList &propList);
virtual void closeTable();
virtual void startComment(const ::WPXPropertyList &propList);
virtual void endComment();
virtual void startNotes(const ::WPXPropertyList &propList);
virtual void endNotes();
};
TextPainter::TextPainter()
{
}
void TextPainter::startDocument(const ::WPXPropertyList &)
{
}
void TextPainter::endDocument()
{
}
void TextPainter::setDocumentMetaData(const ::WPXPropertyList &)
{
}
void TextPainter::startSlide(const ::WPXPropertyList &)
{
}
void TextPainter::endSlide()
{
printf("\n");
}
void TextPainter::startLayer(const ::WPXPropertyList &)
{
}
void TextPainter::endLayer()
{
}
void TextPainter::startEmbeddedGraphics(const ::WPXPropertyList &)
{
}
void TextPainter::endEmbeddedGraphics()
{
}
void TextPainter::startGroup(const ::WPXPropertyList &)
{
}
void TextPainter::endGroup()
{
}
void TextPainter::setStyle(const ::WPXPropertyList &, const ::WPXPropertyListVector &)
{
}
void TextPainter::drawRectangle(const ::WPXPropertyList &)
{
}
void TextPainter::drawEllipse(const ::WPXPropertyList &)
{
}
void TextPainter::drawPolyline(const ::WPXPropertyListVector &)
{
}
void TextPainter::drawPolygon(const ::WPXPropertyListVector &)
{
}
void TextPainter::drawPath(const ::WPXPropertyListVector &)
{
}
void TextPainter::drawGraphicObject(const ::WPXPropertyList &, const ::WPXBinaryData &)
{
}
void TextPainter::drawConnector(const ::WPXPropertyList &, const ::WPXPropertyListVector &)
{
}
void TextPainter::startTextObject(const ::WPXPropertyList &, const ::WPXPropertyListVector &)
{
}
void TextPainter::endTextObject()
{
printf("\n");
}
void TextPainter::openParagraph(const ::WPXPropertyList &, const ::WPXPropertyListVector &)
{
}
void TextPainter::closeParagraph()
{
printf("\n");
}
void TextPainter::openSpan(const ::WPXPropertyList &)
{
}
void TextPainter::closeSpan()
{
}
void TextPainter::insertText(const ::WPXString &str)
{
printf(str.cstr());
}
void TextPainter::insertTab()
{
printf("\t");
}
void TextPainter::insertSpace()
{
printf(" ");
}
void TextPainter::insertLineBreak()
{
printf("\n");
}
void TextPainter::insertField(const WPXString &, const ::WPXPropertyList &)
{
}
void TextPainter::openOrderedListLevel(const ::WPXPropertyList &)
{
}
void TextPainter::openUnorderedListLevel(const ::WPXPropertyList &)
{
}
void TextPainter::closeOrderedListLevel()
{
}
void TextPainter::closeUnorderedListLevel()
{
}
void TextPainter::openListElement(const ::WPXPropertyList &propList, const ::WPXPropertyListVector &tabStops)
{
openParagraph(propList, tabStops);
}
void TextPainter::closeListElement()
{
closeParagraph();
}
void TextPainter::openTable(const ::WPXPropertyList &, const ::WPXPropertyListVector &)
{
}
void TextPainter::openTableRow(const ::WPXPropertyList &)
{
}
void TextPainter::closeTableRow()
{
}
void TextPainter::openTableCell(const ::WPXPropertyList &)
{
}
void TextPainter::closeTableCell()
{
}
void TextPainter::insertCoveredTableCell(const ::WPXPropertyList &)
{
}
void TextPainter::closeTable()
{
}
void TextPainter::startComment(const ::WPXPropertyList &)
{
}
void TextPainter::endComment()
{
}
void TextPainter::startNotes(const ::WPXPropertyList &)
{
}
void TextPainter::endNotes()
{
}
namespace
{
int printUsage()
{
printf("Usage: key2text [OPTION] <KeyNote Document> | <KeyNote Directory>\n");
printf("\n");
printf("Options:\n");
printf("--help Shows this help message\n");
return -1;
}
} // anonymous namespace
int main(int argc, char *argv[])
{
if (argc < 2)
return printUsage();
char *file = 0;
for (int i = 1; i < argc; i++)
{
if (!file && strncmp(argv[i], "--", 2))
file = argv[i];
else
return printUsage();
}
if (!file)
return printUsage();
using boost::shared_ptr;
namespace fs = boost::filesystem;
fs::path path(file);
shared_ptr<WPXInputStream> input;
if (is_directory(path))
input.reset(new conv::KEYDirectoryStream(path));
else
input.reset(new WPXFileStream(file));
libetonyek::KEYDocumentType type = libetonyek::KEY_DOCUMENT_TYPE_UNKNOWN;
if (!libetonyek::KEYDocument::isSupported(input.get(), &type))
{
fprintf(stderr, "ERROR: Unsupported file format!\n");
return 1;
}
if (libetonyek::KEY_DOCUMENT_TYPE_APXL_FILE == type)
{
path.remove_filename();
input.reset(new conv::KEYDirectoryStream(path));
}
TextPainter painter;
libetonyek::KEYDocument::parse(input.get(), &painter);
return 0;
}
/* vim:set shiftwidth=2 softtabstop=2 expandtab: */
<commit_msg>WaE: format string is not a string literal<commit_after>/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/*
* This file is part of the libetonyek project.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
#include <stdio.h>
#include <string.h>
#include <libwpd-stream/libwpd-stream.h>
#include <libwpd/libwpd.h>
#include <libetonyek/libetonyek.h>
#include "KEYDirectoryStream.h"
class TextPainter : public libetonyek::KEYPresentationInterface
{
public:
TextPainter();
virtual void startDocument(const ::WPXPropertyList &propList);
virtual void endDocument();
virtual void setDocumentMetaData(const ::WPXPropertyList &propList);
virtual void startSlide(const ::WPXPropertyList &propList);
virtual void endSlide();
virtual void startLayer(const ::WPXPropertyList &propList);
virtual void endLayer();
virtual void startEmbeddedGraphics(const ::WPXPropertyList &propList);
virtual void endEmbeddedGraphics();
virtual void startGroup(const ::WPXPropertyList &propList);
virtual void endGroup();
virtual void setStyle(const ::WPXPropertyList &propList, const ::WPXPropertyListVector &gradient);
virtual void drawRectangle(const ::WPXPropertyList &propList);
virtual void drawEllipse(const ::WPXPropertyList &propList);
virtual void drawPolyline(const ::WPXPropertyListVector &vertices);
virtual void drawPolygon(const ::WPXPropertyListVector &vertices);
virtual void drawPath(const ::WPXPropertyListVector &path);
virtual void drawGraphicObject(const ::WPXPropertyList &propList, const ::WPXBinaryData &binaryData);
virtual void drawConnector(const ::WPXPropertyList &propList, const ::WPXPropertyListVector &path);
virtual void startTextObject(const ::WPXPropertyList &propList, const ::WPXPropertyListVector &path);
virtual void endTextObject();
virtual void openParagraph(const ::WPXPropertyList &propList, const ::WPXPropertyListVector &tabStops);
virtual void closeParagraph();
virtual void openSpan(const ::WPXPropertyList &propList);
virtual void closeSpan();
virtual void insertTab();
virtual void insertSpace();
virtual void insertText(const ::WPXString &str);
virtual void insertLineBreak();
virtual void insertField(const WPXString &type, const ::WPXPropertyList &propList);
virtual void openOrderedListLevel(const ::WPXPropertyList &propList);
virtual void openUnorderedListLevel(const ::WPXPropertyList &propList);
virtual void closeOrderedListLevel();
virtual void closeUnorderedListLevel();
virtual void openListElement(const ::WPXPropertyList &propList, const ::WPXPropertyListVector &tabStops);
virtual void closeListElement();
virtual void openTable(const ::WPXPropertyList &propList, const ::WPXPropertyListVector &columns);
virtual void openTableRow(const ::WPXPropertyList &propList);
virtual void closeTableRow();
virtual void openTableCell(const ::WPXPropertyList &propList);
virtual void closeTableCell();
virtual void insertCoveredTableCell(const ::WPXPropertyList &propList);
virtual void closeTable();
virtual void startComment(const ::WPXPropertyList &propList);
virtual void endComment();
virtual void startNotes(const ::WPXPropertyList &propList);
virtual void endNotes();
};
TextPainter::TextPainter()
{
}
void TextPainter::startDocument(const ::WPXPropertyList &)
{
}
void TextPainter::endDocument()
{
}
void TextPainter::setDocumentMetaData(const ::WPXPropertyList &)
{
}
void TextPainter::startSlide(const ::WPXPropertyList &)
{
}
void TextPainter::endSlide()
{
printf("\n");
}
void TextPainter::startLayer(const ::WPXPropertyList &)
{
}
void TextPainter::endLayer()
{
}
void TextPainter::startEmbeddedGraphics(const ::WPXPropertyList &)
{
}
void TextPainter::endEmbeddedGraphics()
{
}
void TextPainter::startGroup(const ::WPXPropertyList &)
{
}
void TextPainter::endGroup()
{
}
void TextPainter::setStyle(const ::WPXPropertyList &, const ::WPXPropertyListVector &)
{
}
void TextPainter::drawRectangle(const ::WPXPropertyList &)
{
}
void TextPainter::drawEllipse(const ::WPXPropertyList &)
{
}
void TextPainter::drawPolyline(const ::WPXPropertyListVector &)
{
}
void TextPainter::drawPolygon(const ::WPXPropertyListVector &)
{
}
void TextPainter::drawPath(const ::WPXPropertyListVector &)
{
}
void TextPainter::drawGraphicObject(const ::WPXPropertyList &, const ::WPXBinaryData &)
{
}
void TextPainter::drawConnector(const ::WPXPropertyList &, const ::WPXPropertyListVector &)
{
}
void TextPainter::startTextObject(const ::WPXPropertyList &, const ::WPXPropertyListVector &)
{
}
void TextPainter::endTextObject()
{
printf("\n");
}
void TextPainter::openParagraph(const ::WPXPropertyList &, const ::WPXPropertyListVector &)
{
}
void TextPainter::closeParagraph()
{
printf("\n");
}
void TextPainter::openSpan(const ::WPXPropertyList &)
{
}
void TextPainter::closeSpan()
{
}
void TextPainter::insertText(const ::WPXString &str)
{
printf("%s", str.cstr());
}
void TextPainter::insertTab()
{
printf("\t");
}
void TextPainter::insertSpace()
{
printf(" ");
}
void TextPainter::insertLineBreak()
{
printf("\n");
}
void TextPainter::insertField(const WPXString &, const ::WPXPropertyList &)
{
}
void TextPainter::openOrderedListLevel(const ::WPXPropertyList &)
{
}
void TextPainter::openUnorderedListLevel(const ::WPXPropertyList &)
{
}
void TextPainter::closeOrderedListLevel()
{
}
void TextPainter::closeUnorderedListLevel()
{
}
void TextPainter::openListElement(const ::WPXPropertyList &propList, const ::WPXPropertyListVector &tabStops)
{
openParagraph(propList, tabStops);
}
void TextPainter::closeListElement()
{
closeParagraph();
}
void TextPainter::openTable(const ::WPXPropertyList &, const ::WPXPropertyListVector &)
{
}
void TextPainter::openTableRow(const ::WPXPropertyList &)
{
}
void TextPainter::closeTableRow()
{
}
void TextPainter::openTableCell(const ::WPXPropertyList &)
{
}
void TextPainter::closeTableCell()
{
}
void TextPainter::insertCoveredTableCell(const ::WPXPropertyList &)
{
}
void TextPainter::closeTable()
{
}
void TextPainter::startComment(const ::WPXPropertyList &)
{
}
void TextPainter::endComment()
{
}
void TextPainter::startNotes(const ::WPXPropertyList &)
{
}
void TextPainter::endNotes()
{
}
namespace
{
int printUsage()
{
printf("Usage: key2text [OPTION] <KeyNote Document> | <KeyNote Directory>\n");
printf("\n");
printf("Options:\n");
printf("--help Shows this help message\n");
return -1;
}
} // anonymous namespace
int main(int argc, char *argv[])
{
if (argc < 2)
return printUsage();
char *file = 0;
for (int i = 1; i < argc; i++)
{
if (!file && strncmp(argv[i], "--", 2))
file = argv[i];
else
return printUsage();
}
if (!file)
return printUsage();
using boost::shared_ptr;
namespace fs = boost::filesystem;
fs::path path(file);
shared_ptr<WPXInputStream> input;
if (is_directory(path))
input.reset(new conv::KEYDirectoryStream(path));
else
input.reset(new WPXFileStream(file));
libetonyek::KEYDocumentType type = libetonyek::KEY_DOCUMENT_TYPE_UNKNOWN;
if (!libetonyek::KEYDocument::isSupported(input.get(), &type))
{
fprintf(stderr, "ERROR: Unsupported file format!\n");
return 1;
}
if (libetonyek::KEY_DOCUMENT_TYPE_APXL_FILE == type)
{
path.remove_filename();
input.reset(new conv::KEYDirectoryStream(path));
}
TextPainter painter;
libetonyek::KEYDocument::parse(input.get(), &painter);
return 0;
}
/* vim:set shiftwidth=2 softtabstop=2 expandtab: */
<|endoftext|>
|
<commit_before>#include "compiler/rewriter/rules/ruleset.h"
#include "compiler/expression/expr.h"
#include "context/static_context.h"
#include "compiler/rewriter/tools/expr_tools.h"
#include "compiler/rewriter/framework/rule_driver.h"
#include <memory>
using namespace std;
namespace zorba {
class SubstVars : public RewriteRule {
protected:
var_expr *var;
expr *subst;
public:
SubstVars (var_expr *var_, expr *subst_) : var (var_), subst (subst_) {}
expr_t rewritePre(expr *node, RewriterContext& rCtx);
expr_t rewritePost(expr *node, RewriterContext& rCtx);
};
RULE_REWRITE_PRE(SubstVars) {
return (node == var) ? subst : NULL;
}
RULE_REWRITE_POST(SubstVars) {
return NULL;
}
expr_t subst_vars (RewriterContext& rCtx, var_expr *var, expr *subst) {
auto_ptr<Rewriter> rw (new SingletonRuleMajorDriverBase (RuleMajorDriver::rule_ptr_t (new SubstVars (var, subst))));
rw->rewrite (rCtx);
return rCtx.getRoot ();
}
RULE_REWRITE_PRE(EliminateUnusedLetVars)
{
static_context *sctx = rCtx.getStaticContext();
TypeManager *ts = sctx->get_typemanager();
flwor_expr *flwor = dynamic_cast<flwor_expr *>(node);
if (flwor != NULL) {
flwor_expr::clause_list_t::iterator i = flwor->clause_begin();
while(i != flwor->clause_end()) {
flwor_expr::forletref_t ref = *i;
expr *cexpr = ref->get_expr ();
forlet_clause::varref_t vref = ref->get_var();
bool is_let = vref->get_kind() == var_expr::let_var;
int quant_cnt = 2; // cardinality of for clause: 0, 1 or more
if (! is_let) {
xqtref_t ctype = cexpr->return_type (sctx);
if (ts->is_equal (*ctype, *ts->create_empty_type ()))
quant_cnt = 0;
else if (ts->quantifier (*ctype) == TypeConstants::QUANT_ONE)
quant_cnt = 1;
}
if (is_let || quant_cnt < 2) {
if (quant_cnt == 0) return new fo_expr (node->get_loc (), LOOKUP_OPN ("concatenate"));
// otherwise is_let || quant_cnt == 1
forlet_clause::varref_t pvref = ref->get_pos_var ();
if (pvref != NULL)
subst_vars (rCtx, pvref.getp (), new const_expr (node->get_loc (), xqp_integer::parseInt (1)));
int uses = count_variable_uses(flwor, &*vref);
if (uses > 1)
++i;
else {
if (uses == 1) {
if (flwor->forlet_count () == 1 // TODO: if cardinality FLWOR result = 1...
|| cexpr->get_annotation (AnnotationKey::UNFOLDABLE_OP) != TSVAnnotationValue::TRUE_VALUE)
{
i = flwor->remove_forlet_clause (i);
subst_vars (rCtx, vref, cexpr);
}
else ++i;
} else {
i = flwor->remove_forlet_clause(i);
}
}
} else {
++i;
}
}
if (flwor->forlet_count() == 0) {
expr_t where = flwor->get_where();
expr_t result = flwor->get_retval();
if (where != NULL) {
rchandle<if_expr> ite(new if_expr(where->get_loc()));
ite->set_cond_expr(where);
ite->set_then_expr(result);
ite->set_else_expr(new fo_expr(where->get_loc(), LOOKUP_FN("fn", "concatenate", 0)));
result = &*ite;
}
return result;
}
}
return NULL;
}
RULE_REWRITE_POST(EliminateUnusedLetVars)
{
return NULL;
}
}
/* vim:set ts=2 sw=2: */
<commit_msg>FLWOR rewrite: substitute consts<commit_after>#include "compiler/rewriter/rules/ruleset.h"
#include "compiler/expression/expr.h"
#include "context/static_context.h"
#include "compiler/rewriter/tools/expr_tools.h"
#include "compiler/rewriter/framework/rule_driver.h"
#include <memory>
using namespace std;
namespace zorba {
class SubstVars : public RewriteRule {
protected:
var_expr *var;
expr *subst;
public:
SubstVars (var_expr *var_, expr *subst_) : var (var_), subst (subst_) {}
expr_t rewritePre(expr *node, RewriterContext& rCtx);
expr_t rewritePost(expr *node, RewriterContext& rCtx);
};
RULE_REWRITE_PRE(SubstVars) {
return (node == var) ? subst : NULL;
}
RULE_REWRITE_POST(SubstVars) {
return NULL;
}
expr_t subst_vars (RewriterContext& rCtx, var_expr *var, expr *subst) {
auto_ptr<Rewriter> rw (new SingletonRuleMajorDriverBase (RuleMajorDriver::rule_ptr_t (new SubstVars (var, subst))));
rw->rewrite (rCtx);
return rCtx.getRoot ();
}
RULE_REWRITE_PRE(EliminateUnusedLetVars)
{
static_context *sctx = rCtx.getStaticContext();
TypeManager *ts = sctx->get_typemanager();
flwor_expr *flwor = dynamic_cast<flwor_expr *>(node);
if (flwor != NULL) {
flwor_expr::clause_list_t::iterator i = flwor->clause_begin();
while(i != flwor->clause_end()) {
flwor_expr::forletref_t ref = *i;
expr *cexpr = ref->get_expr ();
forlet_clause::varref_t vref = ref->get_var();
bool is_let = vref->get_kind() == var_expr::let_var;
int quant_cnt = 2; // cardinality of for clause: 0, 1 or more
if (! is_let) {
xqtref_t ctype = cexpr->return_type (sctx);
if (ts->is_equal (*ctype, *ts->create_empty_type ()))
quant_cnt = 0;
else if (ts->quantifier (*ctype) == TypeConstants::QUANT_ONE)
quant_cnt = 1;
}
if (is_let || quant_cnt < 2) {
if (quant_cnt == 0) return new fo_expr (node->get_loc (), LOOKUP_OPN ("concatenate"));
// otherwise is_let || quant_cnt == 1
forlet_clause::varref_t pvref = ref->get_pos_var ();
if (pvref != NULL)
subst_vars (rCtx, pvref.getp (), new const_expr (node->get_loc (), xqp_integer::parseInt (1)));
int uses = count_variable_uses(flwor, &*vref);
if (uses > 1) {
if (cexpr->get_expr_kind () == const_expr_kind) {
i = flwor->remove_forlet_clause (i);
subst_vars (rCtx, vref, cexpr);
} else ++i;
} else {
if (uses == 1) {
if (flwor->forlet_count () == 1 // TODO: if cardinality FLWOR result = 1...
|| cexpr->get_annotation (AnnotationKey::UNFOLDABLE_OP) != TSVAnnotationValue::TRUE_VALUE)
{
i = flwor->remove_forlet_clause (i);
subst_vars (rCtx, vref, cexpr);
}
else ++i;
} else {
i = flwor->remove_forlet_clause(i);
}
}
} else {
++i;
}
}
if (flwor->forlet_count() == 0) {
expr_t where = flwor->get_where();
expr_t result = flwor->get_retval();
if (where != NULL) {
rchandle<if_expr> ite(new if_expr(where->get_loc()));
ite->set_cond_expr(where);
ite->set_then_expr(result);
ite->set_else_expr(new fo_expr(where->get_loc(), LOOKUP_FN("fn", "concatenate", 0)));
result = &*ite;
}
return result;
}
}
return NULL;
}
RULE_REWRITE_POST(EliminateUnusedLetVars)
{
return NULL;
}
}
/* vim:set ts=2 sw=2: */
<|endoftext|>
|
<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright 2000, 2010 Oracle and/or its affiliates.
*
* OpenOffice.org - a multi-platform office productivity suite
*
* This file is part of OpenOffice.org.
*
* OpenOffice.org is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* only, as published by the Free Software Foundation.
*
* OpenOffice.org is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License version 3 for more details
* (a copy is included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with OpenOffice.org. If not, see
* <http://www.openoffice.org/license.html>
* for a copy of the LGPLv3 License.
*
************************************************************************/
#include "vbastyle.hxx"
#include <com/sun/star/style/XStyleFamiliesSupplier.hpp>
using namespace ::ooo::vba;
using namespace ::com::sun::star;
static rtl::OUString DISPLAYNAME( RTL_CONSTASCII_USTRINGPARAM("DisplayName") );
uno::Reference< container::XNameAccess >
ScVbaStyle::getStylesNameContainer( const uno::Reference< frame::XModel >& xModel ) throw ( uno::RuntimeException )
{
uno::Reference< style::XStyleFamiliesSupplier > xStyleSupplier( xModel, uno::UNO_QUERY_THROW);
uno::Reference< container::XNameAccess > xStylesAccess( xStyleSupplier->getStyleFamilies()->getByName( rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "CellStyles" ) ) ), uno::UNO_QUERY_THROW );
return xStylesAccess;
}
uno::Reference< beans::XPropertySet >
lcl_getStyleProps( const rtl::OUString& sStyleName, const uno::Reference< frame::XModel >& xModel ) throw ( script::BasicErrorException, uno::RuntimeException )
{
uno::Reference< beans::XPropertySet > xStyleProps( ScVbaStyle::getStylesNameContainer( xModel )->getByName( sStyleName ), uno::UNO_QUERY_THROW );
return xStyleProps;
}
void ScVbaStyle::initialise() throw ( uno::RuntimeException )
{
if (!mxModel.is() )
DebugHelper::exception(SbERR_METHOD_FAILED, rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "XModel Interface could not be retrieved")) );
uno::Reference< lang::XServiceInfo > xServiceInfo( mxPropertySet, uno::UNO_QUERY_THROW );
if ( !xServiceInfo->supportsService( rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "com.sun.star.style.CellStyle" ) ) ) )
{
DebugHelper::exception(SbERR_METHOD_FAILED, rtl::OUString() );
}
mxStyle.set( mxPropertySet, uno::UNO_QUERY_THROW );
uno::Reference< style::XStyleFamiliesSupplier > xStyleSupplier( mxModel, uno::UNO_QUERY_THROW );
mxStyleFamilyNameContainer.set( ScVbaStyle::getStylesNameContainer( mxModel ), uno::UNO_QUERY_THROW );
}
ScVbaStyle::ScVbaStyle( const uno::Reference< ov::XHelperInterface >& xParent, const uno::Reference< uno::XComponentContext > & xContext, const rtl::OUString& sStyleName, const uno::Reference< frame::XModel >& _xModel ) throw ( script::BasicErrorException, uno::RuntimeException ) : ScVbaStyle_BASE( xParent, xContext, lcl_getStyleProps( sStyleName, _xModel ), _xModel, false ), mxModel( _xModel )
{
try
{
initialise();
}
catch (uno::Exception& )
{
DebugHelper::exception(SbERR_METHOD_FAILED, rtl::OUString());
}
}
ScVbaStyle::ScVbaStyle( const uno::Reference< XHelperInterface >& xParent, const uno::Reference< uno::XComponentContext > & xContext, const uno::Reference< beans::XPropertySet >& _xPropertySet, const uno::Reference< frame::XModel >& _xModel ) throw ( script::BasicErrorException, uno::RuntimeException ) : ScVbaStyle_BASE( xParent, xContext, _xPropertySet, _xModel, false ), mxModel( _xModel )
{
try
{
initialise();
}
catch (uno::Exception& )
{
DebugHelper::exception(SbERR_METHOD_FAILED, rtl::OUString());
}
}
::sal_Bool SAL_CALL
ScVbaStyle::BuiltIn() throw (script::BasicErrorException, uno::RuntimeException)
{
return !mxStyle->isUserDefined();
}
void SAL_CALL
ScVbaStyle::setName( const ::rtl::OUString& Name ) throw (script::BasicErrorException, uno::RuntimeException)
{
mxStyle->setName(Name);
}
::rtl::OUString SAL_CALL
ScVbaStyle::getName() throw (script::BasicErrorException, uno::RuntimeException)
{
return mxStyle->getName();
}
void SAL_CALL
ScVbaStyle::setNameLocal( const ::rtl::OUString& NameLocal ) throw (script::BasicErrorException, uno::RuntimeException)
{
try
{
mxPropertySet->setPropertyValue(DISPLAYNAME, uno::makeAny( NameLocal ) );
}
catch (uno::Exception& e)
{
DebugHelper::exception(e);
}
}
::rtl::OUString SAL_CALL
ScVbaStyle::getNameLocal() throw (script::BasicErrorException, uno::RuntimeException)
{
rtl::OUString sName;
try
{
mxPropertySet->getPropertyValue(DISPLAYNAME) >>= sName;
}
catch (uno::Exception &e)
{
DebugHelper::exception(SbERR_METHOD_FAILED, rtl::OUString() );
}
return sName;
}
void SAL_CALL
ScVbaStyle::Delete() throw (script::BasicErrorException, uno::RuntimeException)
{
try
{
mxStyleFamilyNameContainer->removeByName(mxStyle->getName());
}
catch (uno::Exception& )
{
DebugHelper::exception(SbERR_METHOD_FAILED, rtl::OUString());
}
}
void SAL_CALL
ScVbaStyle::setMergeCells( const uno::Any& /*MergeCells*/ ) throw (script::BasicErrorException, uno::RuntimeException)
{
DebugHelper::exception(SbERR_NOT_IMPLEMENTED, rtl::OUString());
}
uno::Any SAL_CALL
ScVbaStyle::getMergeCells( ) throw (script::BasicErrorException, uno::RuntimeException)
{
DebugHelper::exception(SbERR_NOT_IMPLEMENTED, rtl::OUString());
return uno::Any();
}
rtl::OUString&
ScVbaStyle::getServiceImplName()
{
static rtl::OUString sImplName( RTL_CONSTASCII_USTRINGPARAM("ScVbaStyle") );
return sImplName;
}
uno::Sequence< rtl::OUString >
ScVbaStyle::getServiceNames()
{
static uno::Sequence< rtl::OUString > aServiceNames;
if ( aServiceNames.getLength() == 0 )
{
aServiceNames.realloc( 1 );
aServiceNames[ 0 ] = rtl::OUString( RTL_CONSTASCII_USTRINGPARAM("ooo.vba.excel.XStyle" ) );
}
return aServiceNames;
}
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<commit_msg>WaE: unused variables<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright 2000, 2010 Oracle and/or its affiliates.
*
* OpenOffice.org - a multi-platform office productivity suite
*
* This file is part of OpenOffice.org.
*
* OpenOffice.org is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* only, as published by the Free Software Foundation.
*
* OpenOffice.org is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License version 3 for more details
* (a copy is included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with OpenOffice.org. If not, see
* <http://www.openoffice.org/license.html>
* for a copy of the LGPLv3 License.
*
************************************************************************/
#include "vbastyle.hxx"
#include <com/sun/star/style/XStyleFamiliesSupplier.hpp>
using namespace ::ooo::vba;
using namespace ::com::sun::star;
static rtl::OUString DISPLAYNAME( RTL_CONSTASCII_USTRINGPARAM("DisplayName") );
uno::Reference< container::XNameAccess >
ScVbaStyle::getStylesNameContainer( const uno::Reference< frame::XModel >& xModel ) throw ( uno::RuntimeException )
{
uno::Reference< style::XStyleFamiliesSupplier > xStyleSupplier( xModel, uno::UNO_QUERY_THROW);
uno::Reference< container::XNameAccess > xStylesAccess( xStyleSupplier->getStyleFamilies()->getByName( rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "CellStyles" ) ) ), uno::UNO_QUERY_THROW );
return xStylesAccess;
}
uno::Reference< beans::XPropertySet >
lcl_getStyleProps( const rtl::OUString& sStyleName, const uno::Reference< frame::XModel >& xModel ) throw ( script::BasicErrorException, uno::RuntimeException )
{
uno::Reference< beans::XPropertySet > xStyleProps( ScVbaStyle::getStylesNameContainer( xModel )->getByName( sStyleName ), uno::UNO_QUERY_THROW );
return xStyleProps;
}
void ScVbaStyle::initialise() throw ( uno::RuntimeException )
{
if (!mxModel.is() )
DebugHelper::exception(SbERR_METHOD_FAILED, rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "XModel Interface could not be retrieved")) );
uno::Reference< lang::XServiceInfo > xServiceInfo( mxPropertySet, uno::UNO_QUERY_THROW );
if ( !xServiceInfo->supportsService( rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "com.sun.star.style.CellStyle" ) ) ) )
{
DebugHelper::exception(SbERR_METHOD_FAILED, rtl::OUString() );
}
mxStyle.set( mxPropertySet, uno::UNO_QUERY_THROW );
uno::Reference< style::XStyleFamiliesSupplier > xStyleSupplier( mxModel, uno::UNO_QUERY_THROW );
mxStyleFamilyNameContainer.set( ScVbaStyle::getStylesNameContainer( mxModel ), uno::UNO_QUERY_THROW );
}
ScVbaStyle::ScVbaStyle( const uno::Reference< ov::XHelperInterface >& xParent, const uno::Reference< uno::XComponentContext > & xContext, const rtl::OUString& sStyleName, const uno::Reference< frame::XModel >& _xModel ) throw ( script::BasicErrorException, uno::RuntimeException ) : ScVbaStyle_BASE( xParent, xContext, lcl_getStyleProps( sStyleName, _xModel ), _xModel, false ), mxModel( _xModel )
{
try
{
initialise();
}
catch (const uno::Exception& )
{
DebugHelper::exception(SbERR_METHOD_FAILED, rtl::OUString());
}
}
ScVbaStyle::ScVbaStyle( const uno::Reference< XHelperInterface >& xParent, const uno::Reference< uno::XComponentContext > & xContext, const uno::Reference< beans::XPropertySet >& _xPropertySet, const uno::Reference< frame::XModel >& _xModel ) throw ( script::BasicErrorException, uno::RuntimeException ) : ScVbaStyle_BASE( xParent, xContext, _xPropertySet, _xModel, false ), mxModel( _xModel )
{
try
{
initialise();
}
catch (const uno::Exception& )
{
DebugHelper::exception(SbERR_METHOD_FAILED, rtl::OUString());
}
}
::sal_Bool SAL_CALL
ScVbaStyle::BuiltIn() throw (script::BasicErrorException, uno::RuntimeException)
{
return !mxStyle->isUserDefined();
}
void SAL_CALL
ScVbaStyle::setName( const ::rtl::OUString& Name ) throw (script::BasicErrorException, uno::RuntimeException)
{
mxStyle->setName(Name);
}
::rtl::OUString SAL_CALL
ScVbaStyle::getName() throw (script::BasicErrorException, uno::RuntimeException)
{
return mxStyle->getName();
}
void SAL_CALL
ScVbaStyle::setNameLocal( const ::rtl::OUString& NameLocal ) throw (script::BasicErrorException, uno::RuntimeException)
{
try
{
mxPropertySet->setPropertyValue(DISPLAYNAME, uno::makeAny( NameLocal ) );
}
catch (const uno::Exception& e)
{
DebugHelper::exception(e);
}
}
::rtl::OUString SAL_CALL
ScVbaStyle::getNameLocal() throw (script::BasicErrorException, uno::RuntimeException)
{
rtl::OUString sName;
try
{
mxPropertySet->getPropertyValue(DISPLAYNAME) >>= sName;
}
catch (const uno::Exception& )
{
DebugHelper::exception(SbERR_METHOD_FAILED, rtl::OUString() );
}
return sName;
}
void SAL_CALL
ScVbaStyle::Delete() throw (script::BasicErrorException, uno::RuntimeException)
{
try
{
mxStyleFamilyNameContainer->removeByName(mxStyle->getName());
}
catch (const uno::Exception& )
{
DebugHelper::exception(SbERR_METHOD_FAILED, rtl::OUString());
}
}
void SAL_CALL
ScVbaStyle::setMergeCells( const uno::Any& /*MergeCells*/ ) throw (script::BasicErrorException, uno::RuntimeException)
{
DebugHelper::exception(SbERR_NOT_IMPLEMENTED, rtl::OUString());
}
uno::Any SAL_CALL
ScVbaStyle::getMergeCells( ) throw (script::BasicErrorException, uno::RuntimeException)
{
DebugHelper::exception(SbERR_NOT_IMPLEMENTED, rtl::OUString());
return uno::Any();
}
rtl::OUString&
ScVbaStyle::getServiceImplName()
{
static rtl::OUString sImplName( RTL_CONSTASCII_USTRINGPARAM("ScVbaStyle") );
return sImplName;
}
uno::Sequence< rtl::OUString >
ScVbaStyle::getServiceNames()
{
static uno::Sequence< rtl::OUString > aServiceNames;
if ( aServiceNames.getLength() == 0 )
{
aServiceNames.realloc( 1 );
aServiceNames[ 0 ] = rtl::OUString( RTL_CONSTASCII_USTRINGPARAM("ooo.vba.excel.XStyle" ) );
}
return aServiceNames;
}
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<|endoftext|>
|
<commit_before>//
// Copyright (c) 2013-2014 The ANGLE 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.
//
// blocklayout.cpp:
// Implementation for block layout classes and methods.
//
#include "compiler/translator/blocklayoutHLSL.h"
#include "common/mathutil.h"
#include "common/utilities.h"
namespace sh
{
HLSLBlockEncoder::HLSLBlockEncoder(HLSLBlockEncoderStrategy strategy)
: mEncoderStrategy(strategy),
mTransposeMatrices(false)
{
}
void HLSLBlockEncoder::enterAggregateType()
{
nextRegister();
}
void HLSLBlockEncoder::exitAggregateType()
{
}
void HLSLBlockEncoder::getBlockLayoutInfo(GLenum typeIn, unsigned int arraySize, bool isRowMajorMatrix, int *arrayStrideOut, int *matrixStrideOut)
{
GLenum type = (mTransposeMatrices ? gl::TransposeMatrixType(typeIn) : typeIn);
// We assume we are only dealing with 4 byte components (no doubles or half-words currently)
ASSERT(gl::VariableComponentSize(gl::VariableComponentType(type)) == BytesPerComponent);
int matrixStride = 0;
int arrayStride = 0;
// if variables are not to be packed, or we're about to
// pack a matrix or array, skip to the start of the next
// register
if (!isPacked() ||
gl::IsMatrixType(type) ||
arraySize > 0)
{
nextRegister();
}
if (gl::IsMatrixType(type))
{
matrixStride = ComponentsPerRegister;
if (arraySize > 0)
{
const int numRegisters = gl::MatrixRegisterCount(type, isRowMajorMatrix);
arrayStride = ComponentsPerRegister * numRegisters;
}
}
else if (arraySize > 0)
{
arrayStride = ComponentsPerRegister;
}
else if (isPacked())
{
int numComponents = gl::VariableComponentCount(type);
if ((numComponents + (mCurrentOffset % ComponentsPerRegister)) > ComponentsPerRegister)
{
nextRegister();
}
}
*matrixStrideOut = matrixStride;
*arrayStrideOut = arrayStride;
}
void HLSLBlockEncoder::advanceOffset(GLenum typeIn, unsigned int arraySize, bool isRowMajorMatrix, int arrayStride, int matrixStride)
{
GLenum type = (mTransposeMatrices ? gl::TransposeMatrixType(typeIn) : typeIn);
if (arraySize > 0)
{
mCurrentOffset += arrayStride * (arraySize - 1);
}
if (gl::IsMatrixType(type))
{
ASSERT(matrixStride == ComponentsPerRegister);
const int numRegisters = gl::MatrixRegisterCount(type, isRowMajorMatrix);
const int numComponents = gl::MatrixComponentCount(type, isRowMajorMatrix);
mCurrentOffset += ComponentsPerRegister * (numRegisters - 1);
mCurrentOffset += numComponents;
}
else if (isPacked())
{
mCurrentOffset += gl::VariableComponentCount(type);
}
else
{
mCurrentOffset += ComponentsPerRegister;
}
}
void HLSLBlockEncoder::skipRegisters(unsigned int numRegisters)
{
mCurrentOffset += (numRegisters * ComponentsPerRegister);
}
HLSLBlockEncoder::HLSLBlockEncoderStrategy HLSLBlockEncoder::GetStrategyFor(ShShaderOutput outputType)
{
switch (outputType)
{
case SH_HLSL9_OUTPUT: return ENCODE_LOOSE;
case SH_HLSL11_OUTPUT: return ENCODE_PACKED;
default: UNREACHABLE(); return ENCODE_PACKED;
}
}
template <class ShaderVarType>
void HLSLVariableRegisterCount(const ShaderVarType &variable, HLSLBlockEncoder *encoder)
{
if (variable.isStruct())
{
for (size_t arrayElement = 0; arrayElement < variable.elementCount(); arrayElement++)
{
encoder->enterAggregateType();
for (size_t fieldIndex = 0; fieldIndex < variable.fields.size(); fieldIndex++)
{
HLSLVariableRegisterCount(variable.fields[fieldIndex], encoder);
}
encoder->exitAggregateType();
}
}
else
{
// We operate only on varyings and uniforms, which do not have matrix layout qualifiers
encoder->encodeType(variable.type, variable.arraySize, false);
}
}
unsigned int HLSLVariableRegisterCount(const Varying &variable, bool transposeMatrices)
{
HLSLBlockEncoder encoder(HLSLBlockEncoder::ENCODE_PACKED);
encoder.setTransposeMatrices(transposeMatrices);
HLSLVariableRegisterCount(variable, &encoder);
const size_t registerBytes = (encoder.BytesPerComponent * encoder.ComponentsPerRegister);
return static_cast<unsigned int>(rx::roundUp<size_t>(encoder.getBlockSize(), registerBytes) / registerBytes);
}
unsigned int HLSLVariableRegisterCount(const Uniform &variable, ShShaderOutput outputType)
{
HLSLBlockEncoder encoder(HLSLBlockEncoder::GetStrategyFor(outputType));
HLSLVariableRegisterCount(variable, &encoder);
const size_t registerBytes = (encoder.BytesPerComponent * encoder.ComponentsPerRegister);
return static_cast<unsigned int>(rx::roundUp<size_t>(encoder.getBlockSize(), registerBytes) / registerBytes);
}
}
<commit_msg>HLSL: Fix uniform packing for non-square matrices.<commit_after>//
// Copyright (c) 2013-2014 The ANGLE 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.
//
// blocklayout.cpp:
// Implementation for block layout classes and methods.
//
#include "compiler/translator/blocklayoutHLSL.h"
#include "common/mathutil.h"
#include "common/utilities.h"
namespace sh
{
HLSLBlockEncoder::HLSLBlockEncoder(HLSLBlockEncoderStrategy strategy)
: mEncoderStrategy(strategy),
mTransposeMatrices(false)
{
}
void HLSLBlockEncoder::enterAggregateType()
{
nextRegister();
}
void HLSLBlockEncoder::exitAggregateType()
{
}
void HLSLBlockEncoder::getBlockLayoutInfo(GLenum typeIn, unsigned int arraySize, bool isRowMajorMatrix, int *arrayStrideOut, int *matrixStrideOut)
{
GLenum type = (mTransposeMatrices ? gl::TransposeMatrixType(typeIn) : typeIn);
// We assume we are only dealing with 4 byte components (no doubles or half-words currently)
ASSERT(gl::VariableComponentSize(gl::VariableComponentType(type)) == BytesPerComponent);
int matrixStride = 0;
int arrayStride = 0;
// if variables are not to be packed, or we're about to
// pack a matrix or array, skip to the start of the next
// register
if (!isPacked() ||
gl::IsMatrixType(type) ||
arraySize > 0)
{
nextRegister();
}
if (gl::IsMatrixType(type))
{
matrixStride = ComponentsPerRegister;
if (arraySize > 0)
{
const int numRegisters = gl::MatrixRegisterCount(type, isRowMajorMatrix);
arrayStride = ComponentsPerRegister * numRegisters;
}
}
else if (arraySize > 0)
{
arrayStride = ComponentsPerRegister;
}
else if (isPacked())
{
int numComponents = gl::VariableComponentCount(type);
if ((numComponents + (mCurrentOffset % ComponentsPerRegister)) > ComponentsPerRegister)
{
nextRegister();
}
}
*matrixStrideOut = matrixStride;
*arrayStrideOut = arrayStride;
}
void HLSLBlockEncoder::advanceOffset(GLenum typeIn, unsigned int arraySize, bool isRowMajorMatrix, int arrayStride, int matrixStride)
{
GLenum type = (mTransposeMatrices ? gl::TransposeMatrixType(typeIn) : typeIn);
if (arraySize > 0)
{
mCurrentOffset += arrayStride * (arraySize - 1);
}
if (gl::IsMatrixType(type))
{
ASSERT(matrixStride == ComponentsPerRegister);
const int numRegisters = gl::MatrixRegisterCount(type, isRowMajorMatrix);
const int numComponents = gl::MatrixComponentCount(type, isRowMajorMatrix);
mCurrentOffset += ComponentsPerRegister * (numRegisters - 1);
mCurrentOffset += numComponents;
}
else if (isPacked())
{
mCurrentOffset += gl::VariableComponentCount(type);
}
else
{
mCurrentOffset += ComponentsPerRegister;
}
}
void HLSLBlockEncoder::skipRegisters(unsigned int numRegisters)
{
mCurrentOffset += (numRegisters * ComponentsPerRegister);
}
HLSLBlockEncoder::HLSLBlockEncoderStrategy HLSLBlockEncoder::GetStrategyFor(ShShaderOutput outputType)
{
switch (outputType)
{
case SH_HLSL9_OUTPUT: return ENCODE_LOOSE;
case SH_HLSL11_OUTPUT: return ENCODE_PACKED;
default: UNREACHABLE(); return ENCODE_PACKED;
}
}
template <class ShaderVarType>
void HLSLVariableRegisterCount(const ShaderVarType &variable, HLSLBlockEncoder *encoder)
{
if (variable.isStruct())
{
for (size_t arrayElement = 0; arrayElement < variable.elementCount(); arrayElement++)
{
encoder->enterAggregateType();
for (size_t fieldIndex = 0; fieldIndex < variable.fields.size(); fieldIndex++)
{
HLSLVariableRegisterCount(variable.fields[fieldIndex], encoder);
}
encoder->exitAggregateType();
}
}
else
{
// We operate only on varyings and uniforms, which do not have matrix layout qualifiers
encoder->encodeType(variable.type, variable.arraySize, false);
}
}
unsigned int HLSLVariableRegisterCount(const Varying &variable, bool transposeMatrices)
{
HLSLBlockEncoder encoder(HLSLBlockEncoder::ENCODE_PACKED);
encoder.setTransposeMatrices(transposeMatrices);
HLSLVariableRegisterCount(variable, &encoder);
const size_t registerBytes = (encoder.BytesPerComponent * encoder.ComponentsPerRegister);
return static_cast<unsigned int>(rx::roundUp<size_t>(encoder.getBlockSize(), registerBytes) / registerBytes);
}
unsigned int HLSLVariableRegisterCount(const Uniform &variable, ShShaderOutput outputType)
{
HLSLBlockEncoder encoder(HLSLBlockEncoder::GetStrategyFor(outputType));
encoder.setTransposeMatrices(true);
HLSLVariableRegisterCount(variable, &encoder);
const size_t registerBytes = (encoder.BytesPerComponent * encoder.ComponentsPerRegister);
return static_cast<unsigned int>(rx::roundUp<size_t>(encoder.getBlockSize(), registerBytes) / registerBytes);
}
}
<|endoftext|>
|
<commit_before>#include "Common.h"
#include "DarunGrim.h"
#include "LogOperation.h"
LogOperation Logger;
DarunGrim::DarunGrim():
pStorageDB(NULL),
pOneIDAClientManagerTheSource(NULL),
pOneIDAClientManagerTheTarget(NULL),
pDiffMachine(NULL),
pIDAClientManager(NULL)
{
Logger.SetLogOutputType( LogToStdout );
Logger.SetDebugLevel( 0 );
Logger.Log(10, "%s: entry\n", __FUNCTION__ );
pIDAClientManager = new IDAClientManager();
}
DarunGrim::~DarunGrim()
{
Logger.Log(10, "%s: entry\n", __FUNCTION__ );
if( pStorageDB )
{
pStorageDB->CloseDatabase();
delete pStorageDB;
}
if( pDiffMachine )
delete pDiffMachine;
if( pIDAClientManager )
delete pIDAClientManager;
}
void DarunGrim::SetLogParameters( int ParamLogOutputType, int ParamDebugLevel, const char *LogFile )
{
Logger.Log(10, "%s: entry\n", __FUNCTION__ );
Logger.SetLogOutputType( ParamLogOutputType );
if( LogFile )
Logger.SetLogFilename( LogFile );
Logger.SetDebugLevel( ParamDebugLevel );
}
void DarunGrim::SetIDAPath( const char *path )
{
Logger.Log(10, "%s: entry\n", __FUNCTION__ );
if( path )
pIDAClientManager->SetIDAPath( path );
}
bool DarunGrim::GenerateDB(
char *ParamStorageFilename,
char *LogFilename,
char *TheSourceFilename, DWORD StartAddressForSource, DWORD EndAddressForSource,
char *TheTargetFilename, DWORD StartAddressForTarget, DWORD EndAddressForTarget )
{
Logger.Log(10, "%s: entry\n", __FUNCTION__ );
StorageFilename = ParamStorageFilename;
printf("TheSourceFilename=%s\nTheTargetFilename=%s\nStorageFilename=%s\n",
TheSourceFilename,TheTargetFilename,StorageFilename);
pIDAClientManager->SetOutputFilename(StorageFilename);
pIDAClientManager->SetLogFilename(LogFilename);
pIDAClientManager->RunIDAToGenerateDB(TheSourceFilename,StartAddressForSource,EndAddressForSource);
pIDAClientManager->RunIDAToGenerateDB(TheTargetFilename,StartAddressForTarget,EndAddressForTarget);
return OpenDatabase();
}
bool DarunGrim::AcceptIDAClientsFromSocket()
{
Logger.Log(10, "%s: entry\n", __FUNCTION__ );
if( pStorageDB )
{
pIDAClientManager->SetDatabase( pStorageDB );
}
pIDAClientManager->StartIDAListener( DARUNGRIM2_PORT );
pOneIDAClientManagerTheSource=new OneIDAClientManager( pStorageDB );
pOneIDAClientManagerTheTarget=new OneIDAClientManager( pStorageDB );
pIDAClientManager->AcceptIDAClient( pOneIDAClientManagerTheSource, pStorageDB? TRUE:FALSE );
pIDAClientManager->AcceptIDAClient( pOneIDAClientManagerTheTarget, pStorageDB? TRUE:FALSE );
pIDAClientManager->SetMembers( pOneIDAClientManagerTheSource, pOneIDAClientManagerTheTarget, pDiffMachine );
pIDAClientManager->CreateIDACommandProcessorThread();
pIDAClientManager->StopIDAListener();
return TRUE;
}
bool DarunGrim::OpenDatabase()
{
Logger.Log(10, "%s: entry\n", __FUNCTION__ );
if( pStorageDB )
delete pStorageDB;
pStorageDB = new DBWrapper( StorageFilename );
pStorageDB->ExecuteStatement(NULL,NULL,CREATE_ONE_LOCATION_INFO_TABLE_STATEMENT);
pStorageDB->ExecuteStatement(NULL,NULL,CREATE_ONE_LOCATION_INFO_TABLE_START_ADDRESS_INDEX_STATEMENT);
pStorageDB->ExecuteStatement(NULL,NULL,CREATE_ONE_LOCATION_INFO_TABLE_END_ADDRESS_INDEX_STATEMENT);
pStorageDB->ExecuteStatement(NULL,NULL,CREATE_MAP_INFO_TABLE_STATEMENT);
pStorageDB->ExecuteStatement(NULL,NULL,CREATE_MAP_INFO_TABLE_INDEX_STATEMENT);
pStorageDB->ExecuteStatement(NULL,NULL,CREATE_FILE_INFO_TABLE_STATEMENT);
return TRUE;
}
bool DarunGrim::Analyze()
{
Logger.Log(10, "%s: entry\n", __FUNCTION__ );
int TheSourceFileID=1;
int TheTargetFileID=2;
if( pOneIDAClientManagerTheSource && pOneIDAClientManagerTheTarget )
{
pDiffMachine=new DiffMachine( pOneIDAClientManagerTheSource, pOneIDAClientManagerTheTarget );
}
else
{
pDiffMachine=new DiffMachine();
pDiffMachine->Retrieve( *pStorageDB,TRUE,TheSourceFileID,TheTargetFileID);
}
pDiffMachine->Analyze();
pDiffMachine->Save( *pStorageDB );
return TRUE;
}
bool DarunGrim::ShowOnIDA()
{
Logger.Log(10, "%s: entry\n", __FUNCTION__ );
//pDiffMachine->PrintMatchMapInfo();
if( pIDAClientManager )
{
pIDAClientManager->SetMembers(
pOneIDAClientManagerTheSource,
pOneIDAClientManagerTheTarget,
pDiffMachine
);
pIDAClientManager->ShowResultsOnIDA();
pIDAClientManager->IDACommandProcessor();
return TRUE;
}
return FALSE;
}
<commit_msg>Put new sanity check<commit_after>#include "Common.h"
#include "DarunGrim.h"
#include "LogOperation.h"
LogOperation Logger;
DarunGrim::DarunGrim():
pStorageDB(NULL),
pOneIDAClientManagerTheSource(NULL),
pOneIDAClientManagerTheTarget(NULL),
pDiffMachine(NULL),
pIDAClientManager(NULL)
{
Logger.SetLogOutputType( LogToStdout );
Logger.SetDebugLevel( 0 );
Logger.Log(10, "%s: entry\n", __FUNCTION__ );
pIDAClientManager = new IDAClientManager();
}
DarunGrim::~DarunGrim()
{
Logger.Log(10, "%s: entry\n", __FUNCTION__ );
if( pStorageDB )
{
pStorageDB->CloseDatabase();
delete pStorageDB;
}
if( pDiffMachine )
delete pDiffMachine;
if( pIDAClientManager )
delete pIDAClientManager;
}
void DarunGrim::SetLogParameters( int ParamLogOutputType, int ParamDebugLevel, const char *LogFile )
{
Logger.Log(10, "%s: entry\n", __FUNCTION__ );
Logger.SetLogOutputType( ParamLogOutputType );
if( LogFile )
Logger.SetLogFilename( LogFile );
Logger.SetDebugLevel( ParamDebugLevel );
}
void DarunGrim::SetIDAPath( const char *path )
{
Logger.Log(10, "%s: entry\n", __FUNCTION__ );
if( path )
pIDAClientManager->SetIDAPath( path );
}
bool DarunGrim::GenerateDB(
char *ParamStorageFilename,
char *LogFilename,
char *TheSourceFilename, DWORD StartAddressForSource, DWORD EndAddressForSource,
char *TheTargetFilename, DWORD StartAddressForTarget, DWORD EndAddressForTarget )
{
Logger.Log(10, "%s: entry\n", __FUNCTION__ );
StorageFilename = ParamStorageFilename;
printf("TheSourceFilename=%s\nTheTargetFilename=%s\nStorageFilename=%s\n",
TheSourceFilename,TheTargetFilename,StorageFilename);
pIDAClientManager->SetOutputFilename(StorageFilename);
pIDAClientManager->SetLogFilename(LogFilename);
pIDAClientManager->RunIDAToGenerateDB(TheSourceFilename,StartAddressForSource,EndAddressForSource);
pIDAClientManager->RunIDAToGenerateDB(TheTargetFilename,StartAddressForTarget,EndAddressForTarget);
return OpenDatabase();
}
bool DarunGrim::AcceptIDAClientsFromSocket()
{
Logger.Log(10, "%s: entry\n", __FUNCTION__ );
if( pStorageDB )
{
pIDAClientManager->SetDatabase( pStorageDB );
}
pIDAClientManager->StartIDAListener( DARUNGRIM2_PORT );
pOneIDAClientManagerTheSource=new OneIDAClientManager( pStorageDB );
pOneIDAClientManagerTheTarget=new OneIDAClientManager( pStorageDB );
pIDAClientManager->AcceptIDAClient( pOneIDAClientManagerTheSource, pStorageDB? TRUE:FALSE );
pIDAClientManager->AcceptIDAClient( pOneIDAClientManagerTheTarget, pStorageDB? TRUE:FALSE );
pIDAClientManager->SetMembers( pOneIDAClientManagerTheSource, pOneIDAClientManagerTheTarget, pDiffMachine );
pIDAClientManager->CreateIDACommandProcessorThread();
pIDAClientManager->StopIDAListener();
return TRUE;
}
bool DarunGrim::OpenDatabase()
{
Logger.Log(10, "%s: entry\n", __FUNCTION__ );
if( pStorageDB )
delete pStorageDB;
pStorageDB = new DBWrapper( StorageFilename );
pStorageDB->ExecuteStatement(NULL,NULL,CREATE_ONE_LOCATION_INFO_TABLE_STATEMENT);
pStorageDB->ExecuteStatement(NULL,NULL,CREATE_ONE_LOCATION_INFO_TABLE_START_ADDRESS_INDEX_STATEMENT);
pStorageDB->ExecuteStatement(NULL,NULL,CREATE_ONE_LOCATION_INFO_TABLE_END_ADDRESS_INDEX_STATEMENT);
pStorageDB->ExecuteStatement(NULL,NULL,CREATE_MAP_INFO_TABLE_STATEMENT);
pStorageDB->ExecuteStatement(NULL,NULL,CREATE_MAP_INFO_TABLE_INDEX_STATEMENT);
pStorageDB->ExecuteStatement(NULL,NULL,CREATE_FILE_INFO_TABLE_STATEMENT);
return TRUE;
}
bool DarunGrim::Analyze()
{
Logger.Log(10, "%s: entry\n", __FUNCTION__ );
int TheSourceFileID=1;
int TheTargetFileID=2;
if( pOneIDAClientManagerTheSource && pOneIDAClientManagerTheTarget )
{
pDiffMachine = new DiffMachine( pOneIDAClientManagerTheSource, pOneIDAClientManagerTheTarget );
}
else if( pStorageDB )
{
pDiffMachine = new DiffMachine();
pDiffMachine->Retrieve( *pStorageDB,TRUE,TheSourceFileID,TheTargetFileID);
}
if( pDiffMachine )
{
pDiffMachine->Analyze();
pDiffMachine->Save( *pStorageDB );
}
return TRUE;
}
bool DarunGrim::ShowOnIDA()
{
Logger.Log(10, "%s: entry\n", __FUNCTION__ );
//pDiffMachine->PrintMatchMapInfo();
if( pIDAClientManager )
{
pIDAClientManager->SetMembers(
pOneIDAClientManagerTheSource,
pOneIDAClientManagerTheTarget,
pDiffMachine
);
pIDAClientManager->ShowResultsOnIDA();
pIDAClientManager->IDACommandProcessor();
return TRUE;
}
return FALSE;
}
<|endoftext|>
|
<commit_before>#include "Common.h"
#include "DarunGrim.h"
#include "LogOperation.h"
LogOperation Logger;
DarunGrim::DarunGrim():
pStorageDB(NULL),
pOneIDAClientManagerTheSource(NULL),
pOneIDAClientManagerTheTarget(NULL),
pDiffMachine(NULL),
pIDAClientManager(NULL)
{
Logger.SetLogOutputType( LogToStdout );
Logger.SetDebugLevel( 0 );
Logger.Log(10, "%s: entry\n", __FUNCTION__ );
pIDAClientManager = new IDAClientManager();
}
DarunGrim::~DarunGrim()
{
Logger.Log(10, "%s: entry\n", __FUNCTION__ );
if( pStorageDB )
{
pStorageDB->CloseDatabase();
delete pStorageDB;
}
if( pDiffMachine )
delete pDiffMachine;
if( pIDAClientManager )
delete pIDAClientManager;
}
void DarunGrim::SetLogParameters( int ParamLogOutputType, int ParamDebugLevel, const char *LogFile )
{
Logger.Log(10, "%s: entry\n", __FUNCTION__ );
Logger.SetLogOutputType( ParamLogOutputType );
if( LogFile )
Logger.SetLogFilename( LogFile );
Logger.SetDebugLevel( ParamDebugLevel );
}
void DarunGrim::SetIDAPath( const char *path )
{
Logger.Log(10, "%s: entry\n", __FUNCTION__ );
if( path )
pIDAClientManager->SetIDAPath( path );
}
bool DarunGrim::GenerateDB(
char *ParamStorageFilename,
char *LogFilename,
char *TheSourceFilename, DWORD StartAddressForSource, DWORD EndAddressForSource,
char *TheTargetFilename, DWORD StartAddressForTarget, DWORD EndAddressForTarget )
{
Logger.Log(10, "%s: entry\n", __FUNCTION__ );
StorageFilename = ParamStorageFilename;
printf("TheSourceFilename=%s\nTheTargetFilename=%s\nStorageFilename=%s\n",
TheSourceFilename,TheTargetFilename,StorageFilename);
pIDAClientManager->SetOutputFilename(StorageFilename);
pIDAClientManager->SetLogFilename(LogFilename);
pIDAClientManager->RunIDAToGenerateDB(TheSourceFilename,StartAddressForSource,EndAddressForSource);
pIDAClientManager->RunIDAToGenerateDB(TheTargetFilename,StartAddressForTarget,EndAddressForTarget);
return OpenDatabase();
}
bool DarunGrim::AcceptIDAClientsFromSocket()
{
Logger.Log(10, "%s: entry\n", __FUNCTION__ );
if( pStorageDB )
{
pIDAClientManager->SetDatabase( pStorageDB );
}
pIDAClientManager->StartIDAListener( DARUNGRIM2_PORT );
pOneIDAClientManagerTheSource=new OneIDAClientManager( pStorageDB );
pOneIDAClientManagerTheTarget=new OneIDAClientManager( pStorageDB );
pIDAClientManager->AcceptIDAClient( pOneIDAClientManagerTheSource, pStorageDB? TRUE:FALSE );
pIDAClientManager->AcceptIDAClient( pOneIDAClientManagerTheTarget, pStorageDB? TRUE:FALSE );
DiffMachine *pDiffMachine = NULL;
pIDAClientManager->SetMembers( pOneIDAClientManagerTheSource, pOneIDAClientManagerTheTarget, pDiffMachine );
pIDAClientManager->CreateIDACommandProcessorThread();
pIDAClientManager->StopIDAListener();
return TRUE;
}
bool DarunGrim::OpenDatabase()
{
Logger.Log(10, "%s: entry\n", __FUNCTION__ );
if( pStorageDB )
delete pStorageDB;
pStorageDB = new DBWrapper( StorageFilename );
pStorageDB->ExecuteStatement(NULL,NULL,CREATE_ONE_LOCATION_INFO_TABLE_STATEMENT);
pStorageDB->ExecuteStatement(NULL,NULL,CREATE_ONE_LOCATION_INFO_TABLE_START_ADDRESS_INDEX_STATEMENT);
pStorageDB->ExecuteStatement(NULL,NULL,CREATE_ONE_LOCATION_INFO_TABLE_END_ADDRESS_INDEX_STATEMENT);
pStorageDB->ExecuteStatement(NULL,NULL,CREATE_MAP_INFO_TABLE_STATEMENT);
pStorageDB->ExecuteStatement(NULL,NULL,CREATE_MAP_INFO_TABLE_INDEX_STATEMENT);
pStorageDB->ExecuteStatement(NULL,NULL,CREATE_FILE_INFO_TABLE_STATEMENT);
return TRUE;
}
bool DarunGrim::Analyze()
{
Logger.Log(10, "%s: entry\n", __FUNCTION__ );
int TheSourceFileID=1;
int TheTargetFileID=2;
if( pOneIDAClientManagerTheSource && pOneIDAClientManagerTheTarget )
{
pDiffMachine=new DiffMachine( pOneIDAClientManagerTheSource, pOneIDAClientManagerTheTarget );
}
else
{
pDiffMachine=new DiffMachine();
pDiffMachine->Retrieve( *pStorageDB,TRUE,TheSourceFileID,TheTargetFileID);
}
pDiffMachine->Analyze();
pDiffMachine->Save( *pStorageDB );
return TRUE;
}
bool DarunGrim::ShowOnIDA()
{
Logger.Log(10, "%s: entry\n", __FUNCTION__ );
//pDiffMachine->PrintMatchMapInfo();
if( pIDAClientManager )
{
pIDAClientManager->SetMembers(
pOneIDAClientManagerTheSource,
pOneIDAClientManagerTheTarget,
pDiffMachine
);
pIDAClientManager->ShowResultsOnIDA();
pIDAClientManager->IDACommandProcessor();
return TRUE;
}
return FALSE;
}
<commit_msg>Use object pDiffMachine variable in AcceptIDAClientsFromSocket<commit_after>#include "Common.h"
#include "DarunGrim.h"
#include "LogOperation.h"
LogOperation Logger;
DarunGrim::DarunGrim():
pStorageDB(NULL),
pOneIDAClientManagerTheSource(NULL),
pOneIDAClientManagerTheTarget(NULL),
pDiffMachine(NULL),
pIDAClientManager(NULL)
{
Logger.SetLogOutputType( LogToStdout );
Logger.SetDebugLevel( 0 );
Logger.Log(10, "%s: entry\n", __FUNCTION__ );
pIDAClientManager = new IDAClientManager();
}
DarunGrim::~DarunGrim()
{
Logger.Log(10, "%s: entry\n", __FUNCTION__ );
if( pStorageDB )
{
pStorageDB->CloseDatabase();
delete pStorageDB;
}
if( pDiffMachine )
delete pDiffMachine;
if( pIDAClientManager )
delete pIDAClientManager;
}
void DarunGrim::SetLogParameters( int ParamLogOutputType, int ParamDebugLevel, const char *LogFile )
{
Logger.Log(10, "%s: entry\n", __FUNCTION__ );
Logger.SetLogOutputType( ParamLogOutputType );
if( LogFile )
Logger.SetLogFilename( LogFile );
Logger.SetDebugLevel( ParamDebugLevel );
}
void DarunGrim::SetIDAPath( const char *path )
{
Logger.Log(10, "%s: entry\n", __FUNCTION__ );
if( path )
pIDAClientManager->SetIDAPath( path );
}
bool DarunGrim::GenerateDB(
char *ParamStorageFilename,
char *LogFilename,
char *TheSourceFilename, DWORD StartAddressForSource, DWORD EndAddressForSource,
char *TheTargetFilename, DWORD StartAddressForTarget, DWORD EndAddressForTarget )
{
Logger.Log(10, "%s: entry\n", __FUNCTION__ );
StorageFilename = ParamStorageFilename;
printf("TheSourceFilename=%s\nTheTargetFilename=%s\nStorageFilename=%s\n",
TheSourceFilename,TheTargetFilename,StorageFilename);
pIDAClientManager->SetOutputFilename(StorageFilename);
pIDAClientManager->SetLogFilename(LogFilename);
pIDAClientManager->RunIDAToGenerateDB(TheSourceFilename,StartAddressForSource,EndAddressForSource);
pIDAClientManager->RunIDAToGenerateDB(TheTargetFilename,StartAddressForTarget,EndAddressForTarget);
return OpenDatabase();
}
bool DarunGrim::AcceptIDAClientsFromSocket()
{
Logger.Log(10, "%s: entry\n", __FUNCTION__ );
if( pStorageDB )
{
pIDAClientManager->SetDatabase( pStorageDB );
}
pIDAClientManager->StartIDAListener( DARUNGRIM2_PORT );
pOneIDAClientManagerTheSource=new OneIDAClientManager( pStorageDB );
pOneIDAClientManagerTheTarget=new OneIDAClientManager( pStorageDB );
pIDAClientManager->AcceptIDAClient( pOneIDAClientManagerTheSource, pStorageDB? TRUE:FALSE );
pIDAClientManager->AcceptIDAClient( pOneIDAClientManagerTheTarget, pStorageDB? TRUE:FALSE );
pIDAClientManager->SetMembers( pOneIDAClientManagerTheSource, pOneIDAClientManagerTheTarget, pDiffMachine );
pIDAClientManager->CreateIDACommandProcessorThread();
pIDAClientManager->StopIDAListener();
return TRUE;
}
bool DarunGrim::OpenDatabase()
{
Logger.Log(10, "%s: entry\n", __FUNCTION__ );
if( pStorageDB )
delete pStorageDB;
pStorageDB = new DBWrapper( StorageFilename );
pStorageDB->ExecuteStatement(NULL,NULL,CREATE_ONE_LOCATION_INFO_TABLE_STATEMENT);
pStorageDB->ExecuteStatement(NULL,NULL,CREATE_ONE_LOCATION_INFO_TABLE_START_ADDRESS_INDEX_STATEMENT);
pStorageDB->ExecuteStatement(NULL,NULL,CREATE_ONE_LOCATION_INFO_TABLE_END_ADDRESS_INDEX_STATEMENT);
pStorageDB->ExecuteStatement(NULL,NULL,CREATE_MAP_INFO_TABLE_STATEMENT);
pStorageDB->ExecuteStatement(NULL,NULL,CREATE_MAP_INFO_TABLE_INDEX_STATEMENT);
pStorageDB->ExecuteStatement(NULL,NULL,CREATE_FILE_INFO_TABLE_STATEMENT);
return TRUE;
}
bool DarunGrim::Analyze()
{
Logger.Log(10, "%s: entry\n", __FUNCTION__ );
int TheSourceFileID=1;
int TheTargetFileID=2;
if( pOneIDAClientManagerTheSource && pOneIDAClientManagerTheTarget )
{
pDiffMachine=new DiffMachine( pOneIDAClientManagerTheSource, pOneIDAClientManagerTheTarget );
}
else
{
pDiffMachine=new DiffMachine();
pDiffMachine->Retrieve( *pStorageDB,TRUE,TheSourceFileID,TheTargetFileID);
}
pDiffMachine->Analyze();
pDiffMachine->Save( *pStorageDB );
return TRUE;
}
bool DarunGrim::ShowOnIDA()
{
Logger.Log(10, "%s: entry\n", __FUNCTION__ );
//pDiffMachine->PrintMatchMapInfo();
if( pIDAClientManager )
{
pIDAClientManager->SetMembers(
pOneIDAClientManagerTheSource,
pOneIDAClientManagerTheTarget,
pDiffMachine
);
pIDAClientManager->ShowResultsOnIDA();
pIDAClientManager->IDACommandProcessor();
return TRUE;
}
return FALSE;
}
<|endoftext|>
|
<commit_before>#include <stdio.h>
#include <string.h>
#include <sys/select.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <sys/uio.h>
#include <sys/un.h>
#include <unistd.h>
#include <Carbon/Carbon.h>
#include "server.hpp"
#include "server_objc_part.h"
#include "Mutex.hpp"
namespace {
org_pqrs_KeyRemap4MacBook::KeyRemap4MacBook_bridge::GetWorkspaceData::ApplicationType currentApplicationType = org_pqrs_KeyRemap4MacBook::KeyRemap4MacBook_bridge::GetWorkspaceData::UNKNOWN;
Mutex mutex_currentApplicationType;
}
bool
KeyRemap4MacBook_server::Server::initialize(const char* basedirectory)
{
if (! basedirectory) return false;
if (*basedirectory == '\0') return false;
socketpath_ = std::string(basedirectory) + "/KeyRemap4MacBook_server";
return makeSocket();
}
void
KeyRemap4MacBook_server::Server::sendReply(int sock, void* data, size_t size, int error)
{
struct iovec iov[2];
iov[0].iov_base = reinterpret_cast<caddr_t>(&error);
iov[0].iov_len = sizeof(error);
if (size > 0) {
iov[1].iov_base = reinterpret_cast<caddr_t>(data);
iov[1].iov_len = size;
}
struct msghdr msg;
memset(&msg, 0, sizeof(msg));
msg.msg_iov = iov;
if (size > 0) {
msg.msg_iovlen = 2;
} else {
msg.msg_iovlen = 1;
}
sendmsg(sock, &msg, 0);
}
void
KeyRemap4MacBook_server::Server::dispatchOperator(int sock)
{
int operation;
if (read(sock, &operation, sizeof(operation)) < 0) goto error;
switch (operation) {
case org_pqrs_KeyRemap4MacBook::KeyRemap4MacBook_bridge::REQUEST_GET_WORKSPACE_DATA:
{
org_pqrs_KeyRemap4MacBook::KeyRemap4MacBook_bridge::GetWorkspaceData::Reply reply;
org_pqrs_KeyRemap4MacBook::KeyRemap4MacBook_bridge::Error error = do_GetWorkspaceData(reply);
sendReply(sock, &reply, sizeof(reply), error);
break;
}
default:
goto error;
}
return;
error:
sendReply(sock, NULL, 0, org_pqrs_KeyRemap4MacBook::KeyRemap4MacBook_bridge::ERROR);
}
void
KeyRemap4MacBook_server::Server::doLoop(void)
{
if (listenSocket_ == -1) return;
int error = listen(listenSocket_, 128);
if (error) return;
for (;;) {
fd_set readfds;
FD_ZERO(&readfds);
FD_SET(listenSocket_, &readfds);
int nfds = listenSocket_ + 1;
struct timeval timeout;
timeout.tv_sec = 1;
timeout.tv_usec = 0;
if (select(nfds, &readfds, NULL, NULL, &timeout) == -1) {
return;
}
if (FD_ISSET(listenSocket_, &readfds)) {
struct sockaddr_un addr;
socklen_t addrlen;
int s = accept(listenSocket_, reinterpret_cast<struct sockaddr*>(&addr), &addrlen);
if (s < 0) {
return;
}
dispatchOperator(s);
close(s);
}
}
}
// --------------------------------------------------
bool
KeyRemap4MacBook_server::Server::makeSocket(void)
{
listenSocket_ = socket(PF_LOCAL, SOCK_STREAM, 0);
if (listenSocket_ < 0) return false;
struct sockaddr_un listenSocketAddr;
memset(&listenSocketAddr, 0, sizeof(listenSocketAddr));
listenSocketAddr.sun_len = sizeof(listenSocketAddr);
listenSocketAddr.sun_family = AF_UNIX;
snprintf(listenSocketAddr.sun_path, sizeof(listenSocketAddr.sun_path), "%s", socketpath_.c_str());
if (bind(listenSocket_, reinterpret_cast<struct sockaddr*>(&listenSocketAddr), sizeof(listenSocketAddr)) < 0) return false;
return true;
}
// --------------------------------------------------
org_pqrs_KeyRemap4MacBook::KeyRemap4MacBook_bridge::Error
KeyRemap4MacBook_server::Server::do_GetWorkspaceData(org_pqrs_KeyRemap4MacBook::KeyRemap4MacBook_bridge::GetWorkspaceData::Reply& reply)
{
char inputmodeName[128];
autoreleasepool_begin();
getTISPropertyInputModeID(inputmodeName, sizeof(inputmodeName));
autoreleasepool_end();
{
Mutex::ScopedLock lk(mutex_currentApplicationType);
reply.type = currentApplicationType;
}
reply.inputmode = org_pqrs_KeyRemap4MacBook::KeyRemap4MacBook_bridge::GetWorkspaceData::INPUTMODE_ROMAN;
reply.inputmodedetail = org_pqrs_KeyRemap4MacBook::KeyRemap4MacBook_bridge::GetWorkspaceData::INPUTMODE_DETAIL_ROMAN;
// ----------------------------------------------------------------------
// inputmode
// get data from util/DumpInputModeToConsole/dump-from-plist.sh
const char* tis_japanese_hiragana = "com.apple.inputmethod.Japanese.Hiragana";
const char* tis_japanese_katakana = "com.apple.inputmethod.Japanese.Katakana";
const char* tis_japanese = "com.apple.inputmethod.Japanese";
const char* tis_tradchinese = "com.apple.inputmethod.TCIM"; // TradChinese
const char* tis_simpchinese = "com.apple.inputmethod.SCIM"; // SimpChinese
const char* tis_korean = "com.apple.inputmethod.Korean";
if (strcmp(inputmodeName, tis_japanese_hiragana) == 0) {
reply.inputmode = org_pqrs_KeyRemap4MacBook::KeyRemap4MacBook_bridge::GetWorkspaceData::INPUTMODE_JAPANESE;
reply.inputmodedetail = org_pqrs_KeyRemap4MacBook::KeyRemap4MacBook_bridge::GetWorkspaceData::INPUTMODE_DETAIL_JAPANESE_HIRAGANA;
} else if (strcmp(inputmodeName, tis_japanese_katakana) == 0) {
reply.inputmode = org_pqrs_KeyRemap4MacBook::KeyRemap4MacBook_bridge::GetWorkspaceData::INPUTMODE_JAPANESE;
reply.inputmodedetail = org_pqrs_KeyRemap4MacBook::KeyRemap4MacBook_bridge::GetWorkspaceData::INPUTMODE_DETAIL_JAPANESE_KATAKANA;
} else if (strncmp(inputmodeName, tis_japanese, strlen(tis_japanese)) == 0) {
reply.inputmode = org_pqrs_KeyRemap4MacBook::KeyRemap4MacBook_bridge::GetWorkspaceData::INPUTMODE_JAPANESE;
reply.inputmodedetail = org_pqrs_KeyRemap4MacBook::KeyRemap4MacBook_bridge::GetWorkspaceData::INPUTMODE_DETAIL_JAPANESE;
} else if (strncmp(inputmodeName, tis_tradchinese, strlen(tis_tradchinese)) == 0) {
reply.inputmode = org_pqrs_KeyRemap4MacBook::KeyRemap4MacBook_bridge::GetWorkspaceData::INPUTMODE_CHINESE_TRADITIONAL;
reply.inputmodedetail = org_pqrs_KeyRemap4MacBook::KeyRemap4MacBook_bridge::GetWorkspaceData::INPUTMODE_DETAIL_CHINESE_TRADITIONAL;
} else if (strncmp(inputmodeName, tis_simpchinese, strlen(tis_simpchinese)) == 0) {
reply.inputmode = org_pqrs_KeyRemap4MacBook::KeyRemap4MacBook_bridge::GetWorkspaceData::INPUTMODE_CHINESE_SIMPLIFIED;
reply.inputmodedetail = org_pqrs_KeyRemap4MacBook::KeyRemap4MacBook_bridge::GetWorkspaceData::INPUTMODE_DETAIL_CHINESE_SIMPLIFIED;
} else if (strncmp(inputmodeName, tis_korean, strlen(tis_korean)) == 0) {
reply.inputmode = org_pqrs_KeyRemap4MacBook::KeyRemap4MacBook_bridge::GetWorkspaceData::INPUTMODE_KOREAN;
reply.inputmodedetail = org_pqrs_KeyRemap4MacBook::KeyRemap4MacBook_bridge::GetWorkspaceData::INPUTMODE_DETAIL_KOREAN;
}
// ----------------------------------------------------------------------
return org_pqrs_KeyRemap4MacBook::KeyRemap4MacBook_bridge::SUCCESS;
}
void
setCurrentApplicationType(const char* applicationName)
{
Mutex::ScopedLock lk(mutex_currentApplicationType);
// we ignore the program for our investigation.
if (strcmp(applicationName, "org.pqrs.KeyDump") == 0) {
// use previous value. (not set "currentApplicationType")
return;
}
#define SET_CURRENT_APPLICATION_TYPE(type) { \
currentApplicationType = org_pqrs_KeyRemap4MacBook::KeyRemap4MacBook_bridge::GetWorkspaceData::type; \
return; \
}
if (strcmp(applicationName, "org.gnu.Emacs") == 0 ||
strcmp(applicationName, "org.gnu.AquamacsEmacs") == 0) {
SET_CURRENT_APPLICATION_TYPE(EMACS);
}
const char* org_vim = "org.vim.";
if (strncmp(applicationName, org_vim, strlen(org_vim)) == 0) {
SET_CURRENT_APPLICATION_TYPE(VI);
}
if (strcmp(applicationName, "com.apple.Terminal") == 0 ||
strcmp(applicationName, "iTerm") == 0 ||
strcmp(applicationName, "net.sourceforge.iTerm") == 0) {
SET_CURRENT_APPLICATION_TYPE(TERMINAL);
}
if (strcmp(applicationName, "com.vmware.fusion") == 0 ||
strcmp(applicationName, "com.parallels.desktop") == 0 ||
strcmp(applicationName, "org.virtualbox.app.VirtualBoxVM") == 0) {
SET_CURRENT_APPLICATION_TYPE(VIRTUALMACHINE);
}
if (strcmp(applicationName, "com.microsoft.rdc") == 0 ||
strcmp(applicationName, "net.sf.cord") == 0) {
SET_CURRENT_APPLICATION_TYPE(REMOTEDESKTOPCONNECTION);
}
if (strcmp(applicationName, "org.x.X11") == 0 ||
strcmp(applicationName, "com.apple.x11") == 0) {
SET_CURRENT_APPLICATION_TYPE(X11);
}
if (strcmp(applicationName, "com.apple.finder") == 0) {
SET_CURRENT_APPLICATION_TYPE(FINDER);
}
if (strcmp(applicationName, "com.apple.Safari") == 0) {
SET_CURRENT_APPLICATION_TYPE(SAFARI);
}
if (strcmp(applicationName, "org.mozilla.firefox") == 0) {
SET_CURRENT_APPLICATION_TYPE(FIREFOX);
}
if (strcmp(applicationName, "org.mozilla.thunderbird") == 0) {
SET_CURRENT_APPLICATION_TYPE(THUNDERBIRD);
}
if (strcmp(applicationName, "com.apple.iChat") == 0) {
SET_CURRENT_APPLICATION_TYPE(ICHAT);
}
if (strcmp(applicationName, "com.adiumX.adiumX") == 0) {
SET_CURRENT_APPLICATION_TYPE(ADIUMX);
}
if (strcmp(applicationName, "com.skype.skype") == 0) {
SET_CURRENT_APPLICATION_TYPE(SKYPE);
}
if (strcmp(applicationName, "com.apple.mail") == 0) {
SET_CURRENT_APPLICATION_TYPE(MAIL);
}
if (strcmp(applicationName, "com.apple.TextEdit") == 0) {
SET_CURRENT_APPLICATION_TYPE(EDITOR);
}
const char* com_adobe = "com.adobe.";
if (strncmp(applicationName, com_adobe, strlen(com_adobe)) == 0) {
SET_CURRENT_APPLICATION_TYPE(ADOBE);
}
if (strcmp(applicationName, "com.microsoft.Excel") == 0) {
SET_CURRENT_APPLICATION_TYPE(EXCEL);
}
if (strcmp(applicationName, "com.microsoft.Entourage") == 0) {
SET_CURRENT_APPLICATION_TYPE(ENTOURAGE);
}
if (strcmp(applicationName, "org.eclipse.eclipse") == 0) {
SET_CURRENT_APPLICATION_TYPE(ECLIPSE);
}
SET_CURRENT_APPLICATION_TYPE(UNKNOWN);
}
<commit_msg>support VMware Fusion Unity @ server<commit_after>#include <stdio.h>
#include <string.h>
#include <sys/select.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <sys/uio.h>
#include <sys/un.h>
#include <unistd.h>
#include <Carbon/Carbon.h>
#include "server.hpp"
#include "server_objc_part.h"
#include "Mutex.hpp"
namespace {
org_pqrs_KeyRemap4MacBook::KeyRemap4MacBook_bridge::GetWorkspaceData::ApplicationType currentApplicationType = org_pqrs_KeyRemap4MacBook::KeyRemap4MacBook_bridge::GetWorkspaceData::UNKNOWN;
Mutex mutex_currentApplicationType;
}
bool
KeyRemap4MacBook_server::Server::initialize(const char* basedirectory)
{
if (! basedirectory) return false;
if (*basedirectory == '\0') return false;
socketpath_ = std::string(basedirectory) + "/KeyRemap4MacBook_server";
return makeSocket();
}
void
KeyRemap4MacBook_server::Server::sendReply(int sock, void* data, size_t size, int error)
{
struct iovec iov[2];
iov[0].iov_base = reinterpret_cast<caddr_t>(&error);
iov[0].iov_len = sizeof(error);
if (size > 0) {
iov[1].iov_base = reinterpret_cast<caddr_t>(data);
iov[1].iov_len = size;
}
struct msghdr msg;
memset(&msg, 0, sizeof(msg));
msg.msg_iov = iov;
if (size > 0) {
msg.msg_iovlen = 2;
} else {
msg.msg_iovlen = 1;
}
sendmsg(sock, &msg, 0);
}
void
KeyRemap4MacBook_server::Server::dispatchOperator(int sock)
{
int operation;
if (read(sock, &operation, sizeof(operation)) < 0) goto error;
switch (operation) {
case org_pqrs_KeyRemap4MacBook::KeyRemap4MacBook_bridge::REQUEST_GET_WORKSPACE_DATA:
{
org_pqrs_KeyRemap4MacBook::KeyRemap4MacBook_bridge::GetWorkspaceData::Reply reply;
org_pqrs_KeyRemap4MacBook::KeyRemap4MacBook_bridge::Error error = do_GetWorkspaceData(reply);
sendReply(sock, &reply, sizeof(reply), error);
break;
}
default:
goto error;
}
return;
error:
sendReply(sock, NULL, 0, org_pqrs_KeyRemap4MacBook::KeyRemap4MacBook_bridge::ERROR);
}
void
KeyRemap4MacBook_server::Server::doLoop(void)
{
if (listenSocket_ == -1) return;
int error = listen(listenSocket_, 128);
if (error) return;
for (;;) {
fd_set readfds;
FD_ZERO(&readfds);
FD_SET(listenSocket_, &readfds);
int nfds = listenSocket_ + 1;
struct timeval timeout;
timeout.tv_sec = 1;
timeout.tv_usec = 0;
if (select(nfds, &readfds, NULL, NULL, &timeout) == -1) {
return;
}
if (FD_ISSET(listenSocket_, &readfds)) {
struct sockaddr_un addr;
socklen_t addrlen;
int s = accept(listenSocket_, reinterpret_cast<struct sockaddr*>(&addr), &addrlen);
if (s < 0) {
return;
}
dispatchOperator(s);
close(s);
}
}
}
// --------------------------------------------------
bool
KeyRemap4MacBook_server::Server::makeSocket(void)
{
listenSocket_ = socket(PF_LOCAL, SOCK_STREAM, 0);
if (listenSocket_ < 0) return false;
struct sockaddr_un listenSocketAddr;
memset(&listenSocketAddr, 0, sizeof(listenSocketAddr));
listenSocketAddr.sun_len = sizeof(listenSocketAddr);
listenSocketAddr.sun_family = AF_UNIX;
snprintf(listenSocketAddr.sun_path, sizeof(listenSocketAddr.sun_path), "%s", socketpath_.c_str());
if (bind(listenSocket_, reinterpret_cast<struct sockaddr*>(&listenSocketAddr), sizeof(listenSocketAddr)) < 0) return false;
return true;
}
// --------------------------------------------------
org_pqrs_KeyRemap4MacBook::KeyRemap4MacBook_bridge::Error
KeyRemap4MacBook_server::Server::do_GetWorkspaceData(org_pqrs_KeyRemap4MacBook::KeyRemap4MacBook_bridge::GetWorkspaceData::Reply& reply)
{
char inputmodeName[128];
autoreleasepool_begin();
getTISPropertyInputModeID(inputmodeName, sizeof(inputmodeName));
autoreleasepool_end();
{
Mutex::ScopedLock lk(mutex_currentApplicationType);
reply.type = currentApplicationType;
}
reply.inputmode = org_pqrs_KeyRemap4MacBook::KeyRemap4MacBook_bridge::GetWorkspaceData::INPUTMODE_ROMAN;
reply.inputmodedetail = org_pqrs_KeyRemap4MacBook::KeyRemap4MacBook_bridge::GetWorkspaceData::INPUTMODE_DETAIL_ROMAN;
// ----------------------------------------------------------------------
// inputmode
// get data from util/DumpInputModeToConsole/dump-from-plist.sh
const char* tis_japanese_hiragana = "com.apple.inputmethod.Japanese.Hiragana";
const char* tis_japanese_katakana = "com.apple.inputmethod.Japanese.Katakana";
const char* tis_japanese = "com.apple.inputmethod.Japanese";
const char* tis_tradchinese = "com.apple.inputmethod.TCIM"; // TradChinese
const char* tis_simpchinese = "com.apple.inputmethod.SCIM"; // SimpChinese
const char* tis_korean = "com.apple.inputmethod.Korean";
if (strcmp(inputmodeName, tis_japanese_hiragana) == 0) {
reply.inputmode = org_pqrs_KeyRemap4MacBook::KeyRemap4MacBook_bridge::GetWorkspaceData::INPUTMODE_JAPANESE;
reply.inputmodedetail = org_pqrs_KeyRemap4MacBook::KeyRemap4MacBook_bridge::GetWorkspaceData::INPUTMODE_DETAIL_JAPANESE_HIRAGANA;
} else if (strcmp(inputmodeName, tis_japanese_katakana) == 0) {
reply.inputmode = org_pqrs_KeyRemap4MacBook::KeyRemap4MacBook_bridge::GetWorkspaceData::INPUTMODE_JAPANESE;
reply.inputmodedetail = org_pqrs_KeyRemap4MacBook::KeyRemap4MacBook_bridge::GetWorkspaceData::INPUTMODE_DETAIL_JAPANESE_KATAKANA;
} else if (strncmp(inputmodeName, tis_japanese, strlen(tis_japanese)) == 0) {
reply.inputmode = org_pqrs_KeyRemap4MacBook::KeyRemap4MacBook_bridge::GetWorkspaceData::INPUTMODE_JAPANESE;
reply.inputmodedetail = org_pqrs_KeyRemap4MacBook::KeyRemap4MacBook_bridge::GetWorkspaceData::INPUTMODE_DETAIL_JAPANESE;
} else if (strncmp(inputmodeName, tis_tradchinese, strlen(tis_tradchinese)) == 0) {
reply.inputmode = org_pqrs_KeyRemap4MacBook::KeyRemap4MacBook_bridge::GetWorkspaceData::INPUTMODE_CHINESE_TRADITIONAL;
reply.inputmodedetail = org_pqrs_KeyRemap4MacBook::KeyRemap4MacBook_bridge::GetWorkspaceData::INPUTMODE_DETAIL_CHINESE_TRADITIONAL;
} else if (strncmp(inputmodeName, tis_simpchinese, strlen(tis_simpchinese)) == 0) {
reply.inputmode = org_pqrs_KeyRemap4MacBook::KeyRemap4MacBook_bridge::GetWorkspaceData::INPUTMODE_CHINESE_SIMPLIFIED;
reply.inputmodedetail = org_pqrs_KeyRemap4MacBook::KeyRemap4MacBook_bridge::GetWorkspaceData::INPUTMODE_DETAIL_CHINESE_SIMPLIFIED;
} else if (strncmp(inputmodeName, tis_korean, strlen(tis_korean)) == 0) {
reply.inputmode = org_pqrs_KeyRemap4MacBook::KeyRemap4MacBook_bridge::GetWorkspaceData::INPUTMODE_KOREAN;
reply.inputmodedetail = org_pqrs_KeyRemap4MacBook::KeyRemap4MacBook_bridge::GetWorkspaceData::INPUTMODE_DETAIL_KOREAN;
}
// ----------------------------------------------------------------------
return org_pqrs_KeyRemap4MacBook::KeyRemap4MacBook_bridge::SUCCESS;
}
void
setCurrentApplicationType(const char* applicationName)
{
Mutex::ScopedLock lk(mutex_currentApplicationType);
// we ignore the program for our investigation.
if (strcmp(applicationName, "org.pqrs.KeyDump") == 0) {
// use previous value. (not set "currentApplicationType")
return;
}
#define SET_CURRENT_APPLICATION_TYPE(type) { \
currentApplicationType = org_pqrs_KeyRemap4MacBook::KeyRemap4MacBook_bridge::GetWorkspaceData::type; \
return; \
}
if (strcmp(applicationName, "org.gnu.Emacs") == 0 ||
strcmp(applicationName, "org.gnu.AquamacsEmacs") == 0) {
SET_CURRENT_APPLICATION_TYPE(EMACS);
}
const char* org_vim = "org.vim.";
if (strncmp(applicationName, org_vim, strlen(org_vim)) == 0) {
SET_CURRENT_APPLICATION_TYPE(VI);
}
if (strcmp(applicationName, "com.apple.Terminal") == 0 ||
strcmp(applicationName, "iTerm") == 0 ||
strcmp(applicationName, "net.sourceforge.iTerm") == 0) {
SET_CURRENT_APPLICATION_TYPE(TERMINAL);
}
const char* vmware_unity = "com.vmware.proxyApp.";
if (strcmp(applicationName, "com.vmware.fusion") == 0 ||
strncmp(applicationName, vmware_unity, strlen(vmware_unity)) == 0 ||
strcmp(applicationName, "com.parallels.desktop") == 0 ||
strcmp(applicationName, "org.virtualbox.app.VirtualBoxVM") == 0) {
SET_CURRENT_APPLICATION_TYPE(VIRTUALMACHINE);
}
if (strcmp(applicationName, "com.microsoft.rdc") == 0 ||
strcmp(applicationName, "net.sf.cord") == 0) {
SET_CURRENT_APPLICATION_TYPE(REMOTEDESKTOPCONNECTION);
}
if (strcmp(applicationName, "org.x.X11") == 0 ||
strcmp(applicationName, "com.apple.x11") == 0) {
SET_CURRENT_APPLICATION_TYPE(X11);
}
if (strcmp(applicationName, "com.apple.finder") == 0) {
SET_CURRENT_APPLICATION_TYPE(FINDER);
}
if (strcmp(applicationName, "com.apple.Safari") == 0) {
SET_CURRENT_APPLICATION_TYPE(SAFARI);
}
if (strcmp(applicationName, "org.mozilla.firefox") == 0) {
SET_CURRENT_APPLICATION_TYPE(FIREFOX);
}
if (strcmp(applicationName, "org.mozilla.thunderbird") == 0) {
SET_CURRENT_APPLICATION_TYPE(THUNDERBIRD);
}
if (strcmp(applicationName, "com.apple.iChat") == 0) {
SET_CURRENT_APPLICATION_TYPE(ICHAT);
}
if (strcmp(applicationName, "com.adiumX.adiumX") == 0) {
SET_CURRENT_APPLICATION_TYPE(ADIUMX);
}
if (strcmp(applicationName, "com.skype.skype") == 0) {
SET_CURRENT_APPLICATION_TYPE(SKYPE);
}
if (strcmp(applicationName, "com.apple.mail") == 0) {
SET_CURRENT_APPLICATION_TYPE(MAIL);
}
if (strcmp(applicationName, "com.apple.TextEdit") == 0) {
SET_CURRENT_APPLICATION_TYPE(EDITOR);
}
const char* com_adobe = "com.adobe.";
if (strncmp(applicationName, com_adobe, strlen(com_adobe)) == 0) {
SET_CURRENT_APPLICATION_TYPE(ADOBE);
}
if (strcmp(applicationName, "com.microsoft.Excel") == 0) {
SET_CURRENT_APPLICATION_TYPE(EXCEL);
}
if (strcmp(applicationName, "com.microsoft.Entourage") == 0) {
SET_CURRENT_APPLICATION_TYPE(ENTOURAGE);
}
if (strcmp(applicationName, "org.eclipse.eclipse") == 0) {
SET_CURRENT_APPLICATION_TYPE(ECLIPSE);
}
SET_CURRENT_APPLICATION_TYPE(UNKNOWN);
}
<|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 "ppapi/cpp/instance.h"
#include "ppapi/c/dev/ppp_printing_dev.h"
#include "ppapi/c/ppb_instance.h"
#include "ppapi/cpp/dev/scrollbar_dev.h"
#include "ppapi/cpp/dev/widget_dev.h"
#include "ppapi/cpp/graphics_2d.h"
#include "ppapi/cpp/image_data.h"
#include "ppapi/cpp/logging.h"
#include "ppapi/cpp/module.h"
#include "ppapi/cpp/module_impl.h"
#include "ppapi/cpp/point.h"
#include "ppapi/cpp/resource.h"
#include "ppapi/cpp/var.h"
namespace {
DeviceFuncs<PPB_Instance> ppb_instance_f(PPB_INSTANCE_INTERFACE);
} // namespace
namespace pp {
Instance::Instance(PP_Instance instance) : pp_instance_(instance) {
}
Instance::~Instance() {
// Ensure that all per-instance objects have been removed. Generally, these
// objects should have their lifetime scoped to the instance, such as being
// instance members or even implemented by your instance sub-class directly.
//
// If they're not unregistered at this point, they will usually have a
// dangling reference to the instance, which can cause a crash later.
PP_DCHECK(interface_name_to_objects_.empty());
}
bool Instance::Init(uint32_t /*argc*/, const char* /*argn*/[],
const char* /*argv*/[]) {
return true;
}
bool Instance::HandleDocumentLoad(const URLLoader_Dev& /*url_loader*/) {
return false;
}
bool Instance::HandleEvent(const PP_Event& /*event*/) {
return false;
}
Var Instance::GetInstanceObject() {
return Var();
}
void Instance::ViewChanged(const pp::Rect& /*position*/,
const pp::Rect& /*clip*/) {
}
Var Instance::GetSelectedText(bool /* html */) {
return Var();
}
PP_PrintOutputFormat_Dev* Instance::QuerySupportedPrintOutputFormats(
uint32_t* format_count) {
*format_count = 0;
return NULL;
}
int32_t Instance::PrintBegin(const PP_PrintSettings_Dev&) {
return 0;
}
Resource Instance::PrintPages(
const PP_PrintPageNumberRange_Dev* /*page_ranges*/,
uint32_t /*page_range_count*/) {
return Resource();
}
void Instance::PrintEnd() {
}
void Instance::InvalidateWidget(Widget_Dev /* widget */,
const Rect& /* dirty_rect */) {
}
void Instance::ScrollbarValueChanged(Scrollbar_Dev /* scrollbar */,
uint32_t /* value */) {
}
void Instance::Zoom(float /* scale */, bool /* text_only */) {
}
bool Instance::StartFind(const char* /* text */, bool /* case_sensitive */) {
return false;
}
void Instance::SelectFindResult(bool /* forward */) {
}
void Instance::StopFind() {
}
void Instance::Graphics3DContextLost() {
}
Var Instance::GetWindowObject() {
if (!ppb_instance_f)
return Var();
return Var(Var::PassRef(), ppb_instance_f->GetWindowObject(pp_instance()));
}
Var Instance::GetOwnerElementObject() {
if (!ppb_instance_f)
return Var();
return Var(Var::PassRef(),
ppb_instance_f->GetOwnerElementObject(pp_instance()));
}
bool Instance::BindGraphics(const Graphics2D& graphics) {
if (!ppb_instance_f)
return false;
return ppb_instance_f->BindGraphics(pp_instance(), graphics.pp_resource());
}
bool Instance::IsFullFrame() {
if (!ppb_instance_f)
return false;
return ppb_instance_f->IsFullFrame(pp_instance());
}
Var Instance::ExecuteScript(const Var& script, Var* exception) {
if (!ppb_instance_f)
return Var();
return Var(Var::PassRef(),
ppb_instance_f->ExecuteScript(pp_instance(), script.pp_var(),
Var::OutException(exception)));
}
void Instance::AddPerInstanceObject(const std::string& interface_name,
void* object) {
// Ensure we're not trying to register more than one object per interface
// type. Otherwise, we'll get confused in GetPerInstanceObject.
PP_DCHECK(interface_name_to_objects_.find(interface_name) ==
interface_name_to_objects_.end());
interface_name_to_objects_[interface_name] = object;
}
void Instance::RemovePerInstanceObject(const std::string& interface_name,
void* object) {
InterfaceNameToObjectMap::iterator found = interface_name_to_objects_.find(
interface_name);
if (found == interface_name_to_objects_.end()) {
// Attempting to unregister an object that doesn't exist or was already
// unregistered.
PP_DCHECK(false);
return;
}
// Validate that we're removing the object we thing we are.
PP_DCHECK(found->second == object);
interface_name_to_objects_.erase(found);
}
// static
void* Instance::GetPerInstanceObject(PP_Instance instance,
const std::string& interface_name) {
Instance* that = Module::Get()->InstanceForPPInstance(instance);
if (!that)
return NULL;
InterfaceNameToObjectMap::iterator found =
that->interface_name_to_objects_.find(interface_name);
if (found == that->interface_name_to_objects_.end())
return NULL;
return found->second;
}
} // namespace pp
<commit_msg>Fix release mode build.<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 "ppapi/cpp/instance.h"
#include "ppapi/c/dev/ppp_printing_dev.h"
#include "ppapi/c/ppb_instance.h"
#include "ppapi/cpp/dev/scrollbar_dev.h"
#include "ppapi/cpp/dev/widget_dev.h"
#include "ppapi/cpp/graphics_2d.h"
#include "ppapi/cpp/image_data.h"
#include "ppapi/cpp/logging.h"
#include "ppapi/cpp/module.h"
#include "ppapi/cpp/module_impl.h"
#include "ppapi/cpp/point.h"
#include "ppapi/cpp/resource.h"
#include "ppapi/cpp/var.h"
namespace {
DeviceFuncs<PPB_Instance> ppb_instance_f(PPB_INSTANCE_INTERFACE);
} // namespace
namespace pp {
Instance::Instance(PP_Instance instance) : pp_instance_(instance) {
}
Instance::~Instance() {
// Ensure that all per-instance objects have been removed. Generally, these
// objects should have their lifetime scoped to the instance, such as being
// instance members or even implemented by your instance sub-class directly.
//
// If they're not unregistered at this point, they will usually have a
// dangling reference to the instance, which can cause a crash later.
PP_DCHECK(interface_name_to_objects_.empty());
}
bool Instance::Init(uint32_t /*argc*/, const char* /*argn*/[],
const char* /*argv*/[]) {
return true;
}
bool Instance::HandleDocumentLoad(const URLLoader_Dev& /*url_loader*/) {
return false;
}
bool Instance::HandleEvent(const PP_Event& /*event*/) {
return false;
}
Var Instance::GetInstanceObject() {
return Var();
}
void Instance::ViewChanged(const pp::Rect& /*position*/,
const pp::Rect& /*clip*/) {
}
Var Instance::GetSelectedText(bool /* html */) {
return Var();
}
PP_PrintOutputFormat_Dev* Instance::QuerySupportedPrintOutputFormats(
uint32_t* format_count) {
*format_count = 0;
return NULL;
}
int32_t Instance::PrintBegin(const PP_PrintSettings_Dev&) {
return 0;
}
Resource Instance::PrintPages(
const PP_PrintPageNumberRange_Dev* /*page_ranges*/,
uint32_t /*page_range_count*/) {
return Resource();
}
void Instance::PrintEnd() {
}
void Instance::InvalidateWidget(Widget_Dev /* widget */,
const Rect& /* dirty_rect */) {
}
void Instance::ScrollbarValueChanged(Scrollbar_Dev /* scrollbar */,
uint32_t /* value */) {
}
void Instance::Zoom(float /* scale */, bool /* text_only */) {
}
bool Instance::StartFind(const char* /* text */, bool /* case_sensitive */) {
return false;
}
void Instance::SelectFindResult(bool /* forward */) {
}
void Instance::StopFind() {
}
void Instance::Graphics3DContextLost() {
}
Var Instance::GetWindowObject() {
if (!ppb_instance_f)
return Var();
return Var(Var::PassRef(), ppb_instance_f->GetWindowObject(pp_instance()));
}
Var Instance::GetOwnerElementObject() {
if (!ppb_instance_f)
return Var();
return Var(Var::PassRef(),
ppb_instance_f->GetOwnerElementObject(pp_instance()));
}
bool Instance::BindGraphics(const Graphics2D& graphics) {
if (!ppb_instance_f)
return false;
return ppb_instance_f->BindGraphics(pp_instance(), graphics.pp_resource());
}
bool Instance::IsFullFrame() {
if (!ppb_instance_f)
return false;
return ppb_instance_f->IsFullFrame(pp_instance());
}
Var Instance::ExecuteScript(const Var& script, Var* exception) {
if (!ppb_instance_f)
return Var();
return Var(Var::PassRef(),
ppb_instance_f->ExecuteScript(pp_instance(), script.pp_var(),
Var::OutException(exception)));
}
void Instance::AddPerInstanceObject(const std::string& interface_name,
void* object) {
// Ensure we're not trying to register more than one object per interface
// type. Otherwise, we'll get confused in GetPerInstanceObject.
PP_DCHECK(interface_name_to_objects_.find(interface_name) ==
interface_name_to_objects_.end());
interface_name_to_objects_[interface_name] = object;
}
void Instance::RemovePerInstanceObject(const std::string& interface_name,
void* object) {
InterfaceNameToObjectMap::iterator found = interface_name_to_objects_.find(
interface_name);
if (found == interface_name_to_objects_.end()) {
// Attempting to unregister an object that doesn't exist or was already
// unregistered.
PP_DCHECK(false);
return;
}
// Validate that we're removing the object we thing we are.
PP_DCHECK(found->second == object);
(void)object; // Prevent warning in release mode.
interface_name_to_objects_.erase(found);
}
// static
void* Instance::GetPerInstanceObject(PP_Instance instance,
const std::string& interface_name) {
Instance* that = Module::Get()->InstanceForPPInstance(instance);
if (!that)
return NULL;
InterfaceNameToObjectMap::iterator found =
that->interface_name_to_objects_.find(interface_name);
if (found == that->interface_name_to_objects_.end())
return NULL;
return found->second;
}
} // namespace pp
<|endoftext|>
|
<commit_before>#include "cookies.h"
#include "util.h"
namespace cpr {
Cookies::Cookies(const std::initializer_list<std::pair<const std::string, std::string>>& pairs)
: map_{pairs} {}
std::string Cookies::GetEncoded() const {
std::stringstream stream;
for (const auto& item : map_) {
// special case version 1 cookies, which can be distinguished by
// beginning and trailing quotes
if (!item.second.empty() && item.second.front() == '"' && item.second.back() == '"') {
stream << cpr::util::urlEncode(item.first) << "=" << item.second << "; ";
} else {
stream << cpr::util::urlEncode(item.first) << "=" << cpr::util::urlEncode(item.second)
<< "; ";
}
}
return stream.str();
}
std::string& Cookies::operator[](const std::string& key) {
return map_[key];
}
} // namespace cpr
<commit_msg>Minor DRY refactoring for cookie encoding.<commit_after>#include "cookies.h"
#include "util.h"
namespace cpr {
Cookies::Cookies(const std::initializer_list<std::pair<const std::string, std::string>>& pairs)
: map_{pairs} {}
std::string Cookies::GetEncoded() const {
std::stringstream stream;
for (const auto& item : map_) {
stream << cpr::util::urlEncode(item.first) << "=";
// special case version 1 cookies, which can be distinguished by
// beginning and trailing quotes
if (!item.second.empty() && item.second.front() == '"' && item.second.back() == '"') {
stream << item.second;
} else {
stream << cpr::util::urlEncode(item.second);
}
stream << "; ";
}
return stream.str();
}
std::string& Cookies::operator[](const std::string& key) {
return map_[key];
}
} // namespace cpr
<|endoftext|>
|
<commit_before>/*
* FixedContextCategory.cpp
*
* Copyright 2001, LifeLine Networks BV (www.lifeline.nl). All rights reserved.
* Copyright 2001, Bastiaan Bakker. All rights reserved.
*
* See the COPYING file for the terms of usage and distribution.
*/
#include "log4cpp/Portability.hh"
#include "log4cpp/FixedContextCategory.hh"
namespace log4cpp {
FixedContextCategory::FixedContextCategory(const std::string& name,
const std::string& context) :
Category(name, Category::getInstance(name).getParent()),
_delegate(Category::getInstance(name)),
_context(context) {
}
FixedContextCategory::~FixedContextCategory() {
}
void FixedContextCategory::setContext(const std::string& context) {
_context = context;
}
std::string FixedContextCategory::getContext() const {
return _context;
}
Priority::Value FixedContextCategory::getPriority() const throw() {
return Category::getPriority();
}
Priority::Value FixedContextCategory::getChainedPriority() const throw() {
Priority::Value result = getPriority();
if (result == Priority::NOTSET) {
result = _delegate.getChainedPriority();
}
return result;
}
void FixedContextCategory::addAppender(Appender* appender) {
// XXX do nothing for now
}
void FixedContextCategory::addAppender(Appender& appender) {
// XXX do nothing for now
}
Appender* FixedContextCategory::getAppender() const {
return _delegate.getAppender();
}
void FixedContextCategory::removeAllAppenders() {
// XXX do nothing for now
}
bool FixedContextCategory::ownsAppender() const throw() {
return false;
}
bool FixedContextCategory::ownsAppender(Appender* appender) const throw() {
return false;
}
void FixedContextCategory::callAppenders(const LoggingEvent& event)
throw() {
_delegate.callAppenders(event);
}
void FixedContextCategory::setAdditivity(bool additivity) {
// XXX do nothing for now
}
bool FixedContextCategory::getAdditivity() const throw() {
return _delegate.getAdditivity();
}
void FixedContextCategory::_logUnconditionally2(Priority::Value priority,
const std::string& message) throw() {
LoggingEvent event(getName(), message, _context, priority);
callAppenders(event);
}
}
<commit_msg>Added missing getAppender(Appender*).<commit_after>/*
* FixedContextCategory.cpp
*
* Copyright 2001, LifeLine Networks BV (www.lifeline.nl). All rights reserved.
* Copyright 2001, Bastiaan Bakker. All rights reserved.
*
* See the COPYING file for the terms of usage and distribution.
*/
#include "log4cpp/Portability.hh"
#include "log4cpp/FixedContextCategory.hh"
namespace log4cpp {
FixedContextCategory::FixedContextCategory(const std::string& name,
const std::string& context) :
Category(name, Category::getInstance(name).getParent()),
_delegate(Category::getInstance(name)),
_context(context) {
}
FixedContextCategory::~FixedContextCategory() {
}
void FixedContextCategory::setContext(const std::string& context) {
_context = context;
}
std::string FixedContextCategory::getContext() const {
return _context;
}
Priority::Value FixedContextCategory::getPriority() const throw() {
return Category::getPriority();
}
Priority::Value FixedContextCategory::getChainedPriority() const throw() {
Priority::Value result = getPriority();
if (result == Priority::NOTSET) {
result = _delegate.getChainedPriority();
}
return result;
}
void FixedContextCategory::addAppender(Appender* appender) {
// XXX do nothing for now
}
void FixedContextCategory::addAppender(Appender& appender) {
// XXX do nothing for now
}
Appender* FixedContextCategory::getAppender() const {
return _delegate.getAppender();
}
Appender* FixedContextCategory::getAppender(const std::string& name)
const {
return _delegate.getAppender(name);
}
void FixedContextCategory::removeAllAppenders() {
// XXX do nothing for now
}
bool FixedContextCategory::ownsAppender() const throw() {
return false;
}
bool FixedContextCategory::ownsAppender(Appender* appender) const throw() {
return false;
}
void FixedContextCategory::callAppenders(const LoggingEvent& event)
throw() {
_delegate.callAppenders(event);
}
void FixedContextCategory::setAdditivity(bool additivity) {
// XXX do nothing for now
}
bool FixedContextCategory::getAdditivity() const throw() {
return _delegate.getAdditivity();
}
void FixedContextCategory::_logUnconditionally2(Priority::Value priority,
const std::string& message) throw() {
LoggingEvent event(getName(), message, _context, priority);
callAppenders(event);
}
}
<|endoftext|>
|
<commit_before>
#include "../../Internal.h"
#include <Lumino/GUI/GUIManager.h>
#include <Lumino/GUI/ControlTemplate.h>
#include <Lumino/GUI/Controls/ListBox.h>
#include <Lumino/GUI/Controls/StackPanel.h>
namespace Lumino
{
namespace GUI
{
//=============================================================================
// ListBoxItem
//=============================================================================
LN_CORE_OBJECT_TYPE_INFO_IMPL(ListBoxItem);
LN_UI_ELEMENT_SUBCLASS_IMPL(ListBoxItem);
//-----------------------------------------------------------------------------
//
//-----------------------------------------------------------------------------
ListBoxItem::ListBoxItem(GUIManager* manager)
: ContentControl(manager)
{
}
//-----------------------------------------------------------------------------
//
//-----------------------------------------------------------------------------
ListBoxItem::~ListBoxItem()
{
}
//=============================================================================
// ListBoxItemList
//=============================================================================
LN_CORE_OBJECT_TYPE_INFO_IMPL(ListBoxItemList);
//-----------------------------------------------------------------------------
//
//-----------------------------------------------------------------------------
void ListBoxItemList::OnItemAdded(ListBoxItem* item)
{
m_owner->OnListBoxItemAdded(item);
}
//-----------------------------------------------------------------------------
//
//-----------------------------------------------------------------------------
void ListBoxItemList::OnItemRemoved(ListBoxItem* item)
{
m_owner->OnListBoxItemRemoved(item);
}
//=============================================================================
// ListBoxChrome
//=============================================================================
LN_CORE_OBJECT_TYPE_INFO_IMPL(ListBoxChrome);
LN_UI_ELEMENT_SUBCLASS_IMPL(ListBoxChrome);
//-----------------------------------------------------------------------------
//
//-----------------------------------------------------------------------------
ListBoxChrome::ListBoxChrome(GUIManager* manager)
: Decorator(manager)
, m_frameWidth(8)
{
}
//-----------------------------------------------------------------------------
//
//-----------------------------------------------------------------------------
ListBoxChrome::~ListBoxChrome()
{
}
//-----------------------------------------------------------------------------
//
//-----------------------------------------------------------------------------
void ListBoxChrome::OnApplyTemplate(CombinedLocalResource* localResource)
{
m_frameBrush = static_cast<Graphics::TextureBrush*>(localResource->GetItem(_T("ListBoxNormalFrameBrush")));
m_bgBrush = static_cast<Graphics::TextureBrush*>(localResource->GetItem(_T("ListBoxNormalBackgroundBrush")));
}
//-----------------------------------------------------------------------------
//
//-----------------------------------------------------------------------------
void ListBoxChrome::OnRender()
{
Graphics::Painter painter(m_manager->GetGraphicsManager());
painter.SetProjection(Size(640, 480), 0, 1000); // TODO
RectF bgRect = m_finalRect;
RectF rect = m_finalRect;
if (!m_isMouseOver)
{
bgRect.Inflate(-m_frameWidth, -m_frameWidth);
painter.SetBrush(m_bgBrush);
painter.DrawRectangle(bgRect);
}
painter.SetBrush(m_frameBrush);
painter.DrawFrameRectangle(rect, m_frameWidth);
}
//=============================================================================
// ListBox
//=============================================================================
LN_CORE_OBJECT_TYPE_INFO_IMPL(ListBox);
LN_UI_ELEMENT_SUBCLASS_IMPL(ListBox);
//-----------------------------------------------------------------------------
//
//-----------------------------------------------------------------------------
ListBox::ListBox(GUIManager* manager)
: Control(manager)
, m_listBoxItems(LN_NEW ListBoxItemList(this))
{
m_itemsPanel.Attach(LN_NEW StackPanel(manager));
AddVisualChild(m_itemsPanel);
}
//-----------------------------------------------------------------------------
//
//-----------------------------------------------------------------------------
ListBox::~ListBox()
{
}
//-----------------------------------------------------------------------------
//
//-----------------------------------------------------------------------------
void ListBox::InsertItem(int index, UIElement* element)
{
RefPtr<ListBoxItem> item(LN_NEW ListBoxItem(m_manager));
item->SetContent(element);
m_listBoxItems->Insert(index, item);
}
#if 0
//-----------------------------------------------------------------------------
//
//-----------------------------------------------------------------------------
UIElement* ListBox::CheckMouseHoverElement(const PointF& globalPt)
{
if (m_itemsPanel != NULL) { // qvfD
UIElement* e = m_itemsPanel->CheckMouseHoverElement(globalPt);
if (e != NULL) { return e; }
}
return UIElement::CheckMouseHoverElement(globalPt);
}
//-----------------------------------------------------------------------------
//
//-----------------------------------------------------------------------------
void ListBox::ApplyTemplateHierarchy(CombinedLocalResource* parent)
{
Control::ApplyTemplateHierarchy(parent);
if (m_itemsPanel != NULL) {
m_itemsPanel->ApplyTemplateHierarchy(m_combinedLocalResource); // ċAIɍXV
}
}
//-----------------------------------------------------------------------------
//
//-----------------------------------------------------------------------------
void ListBox::MeasureLayout(const SizeF& availableSize)
{
if (m_itemsPanel != NULL) {
m_itemsPanel->MeasureLayout(availableSize); // ɘgƂȂ̂ł̂܂܂̃TCYn
}
Control::MeasureLayout(availableSize);
}
//-----------------------------------------------------------------------------
//
//-----------------------------------------------------------------------------
void ListBox::ArrangeLayout(const RectF& finalRect)
{
if (m_itemsPanel != NULL) {
m_itemsPanel->ArrangeLayout(finalRect); // ɘgƂȂ̂ł̂܂܂̃TCYn
}
Control::ArrangeLayout(finalRect);
}
//-----------------------------------------------------------------------------
//
//-----------------------------------------------------------------------------
bool ListBox::OnEvent(EventType type, EventArgs* args)
{
if (m_itemsPanel != NULL) {
if (m_itemsPanel->OnEvent(type, args)) { return true; }
}
return Control::OnEvent(type, args);
}
//-----------------------------------------------------------------------------
//
//-----------------------------------------------------------------------------
void ListBox::Render()
{
Control::Render();
if (m_itemsPanel != NULL) {
m_itemsPanel->Render();
}
}
#endif
//-----------------------------------------------------------------------------
//
//-----------------------------------------------------------------------------
void ListBox::OnListBoxItemAdded(ListBoxItem* item)
{
m_itemsPanel->GetChildren()->Add(item);
}
//-----------------------------------------------------------------------------
//
//-----------------------------------------------------------------------------
void ListBox::OnListBoxItemRemoved(ListBoxItem* item)
{
LN_THROW(0, NotImplementedException);
//m_itemsPanel->GetChildren()->Remove(item);
}
} // namespace GUI
} // namespace Lumino
<commit_msg>listbox<commit_after>/*
EWPF
ListBox
Border gyєwi
ScrollView
VirtualizeStackPanel
*/
#include "../../Internal.h"
#include <Lumino/GUI/GUIManager.h>
#include <Lumino/GUI/ControlTemplate.h>
#include <Lumino/GUI/Controls/ListBox.h>
#include <Lumino/GUI/Controls/StackPanel.h>
namespace Lumino
{
namespace GUI
{
//=============================================================================
// ListBoxItem
//=============================================================================
LN_CORE_OBJECT_TYPE_INFO_IMPL(ListBoxItem);
LN_UI_ELEMENT_SUBCLASS_IMPL(ListBoxItem);
//-----------------------------------------------------------------------------
//
//-----------------------------------------------------------------------------
ListBoxItem::ListBoxItem(GUIManager* manager)
: ContentControl(manager)
{
}
//-----------------------------------------------------------------------------
//
//-----------------------------------------------------------------------------
ListBoxItem::~ListBoxItem()
{
}
//=============================================================================
// ListBoxItemList
//=============================================================================
LN_CORE_OBJECT_TYPE_INFO_IMPL(ListBoxItemList);
//-----------------------------------------------------------------------------
//
//-----------------------------------------------------------------------------
void ListBoxItemList::OnItemAdded(ListBoxItem* item)
{
m_owner->OnListBoxItemAdded(item);
}
//-----------------------------------------------------------------------------
//
//-----------------------------------------------------------------------------
void ListBoxItemList::OnItemRemoved(ListBoxItem* item)
{
m_owner->OnListBoxItemRemoved(item);
}
//=============================================================================
// ListBoxChrome
//=============================================================================
LN_CORE_OBJECT_TYPE_INFO_IMPL(ListBoxChrome);
LN_UI_ELEMENT_SUBCLASS_IMPL(ListBoxChrome);
//-----------------------------------------------------------------------------
//
//-----------------------------------------------------------------------------
ListBoxChrome::ListBoxChrome(GUIManager* manager)
: Decorator(manager)
, m_frameWidth(8)
{
}
//-----------------------------------------------------------------------------
//
//-----------------------------------------------------------------------------
ListBoxChrome::~ListBoxChrome()
{
}
//-----------------------------------------------------------------------------
//
//-----------------------------------------------------------------------------
void ListBoxChrome::OnApplyTemplate(CombinedLocalResource* localResource)
{
m_frameBrush = static_cast<Graphics::TextureBrush*>(localResource->GetItem(_T("ListBoxNormalFrameBrush")));
m_bgBrush = static_cast<Graphics::TextureBrush*>(localResource->GetItem(_T("ListBoxNormalBackgroundBrush")));
}
//-----------------------------------------------------------------------------
//
//-----------------------------------------------------------------------------
void ListBoxChrome::OnRender()
{
Graphics::Painter painter(m_manager->GetGraphicsManager());
painter.SetProjection(Size(640, 480), 0, 1000); // TODO
RectF bgRect = m_finalRect;
RectF rect = m_finalRect;
if (!m_isMouseOver)
{
bgRect.Inflate(-m_frameWidth, -m_frameWidth);
painter.SetBrush(m_bgBrush);
painter.DrawRectangle(bgRect);
}
painter.SetBrush(m_frameBrush);
painter.DrawFrameRectangle(rect, m_frameWidth);
}
//=============================================================================
// ListBox
//=============================================================================
LN_CORE_OBJECT_TYPE_INFO_IMPL(ListBox);
LN_UI_ELEMENT_SUBCLASS_IMPL(ListBox);
//-----------------------------------------------------------------------------
//
//-----------------------------------------------------------------------------
ListBox::ListBox(GUIManager* manager)
: Control(manager)
, m_listBoxItems(LN_NEW ListBoxItemList(this))
{
m_itemsPanel.Attach(LN_NEW StackPanel(manager));
AddVisualChild(m_itemsPanel);
}
//-----------------------------------------------------------------------------
//
//-----------------------------------------------------------------------------
ListBox::~ListBox()
{
}
//-----------------------------------------------------------------------------
//
//-----------------------------------------------------------------------------
void ListBox::InsertItem(int index, UIElement* element)
{
RefPtr<ListBoxItem> item(LN_NEW ListBoxItem(m_manager));
item->SetContent(element);
m_listBoxItems->Insert(index, item);
}
#if 0
//-----------------------------------------------------------------------------
//
//-----------------------------------------------------------------------------
UIElement* ListBox::CheckMouseHoverElement(const PointF& globalPt)
{
if (m_itemsPanel != NULL) { // qvfD
UIElement* e = m_itemsPanel->CheckMouseHoverElement(globalPt);
if (e != NULL) { return e; }
}
return UIElement::CheckMouseHoverElement(globalPt);
}
//-----------------------------------------------------------------------------
//
//-----------------------------------------------------------------------------
void ListBox::ApplyTemplateHierarchy(CombinedLocalResource* parent)
{
Control::ApplyTemplateHierarchy(parent);
if (m_itemsPanel != NULL) {
m_itemsPanel->ApplyTemplateHierarchy(m_combinedLocalResource); // ċAIɍXV
}
}
//-----------------------------------------------------------------------------
//
//-----------------------------------------------------------------------------
void ListBox::MeasureLayout(const SizeF& availableSize)
{
if (m_itemsPanel != NULL) {
m_itemsPanel->MeasureLayout(availableSize); // ɘgƂȂ̂ł̂܂܂̃TCYn
}
Control::MeasureLayout(availableSize);
}
//-----------------------------------------------------------------------------
//
//-----------------------------------------------------------------------------
void ListBox::ArrangeLayout(const RectF& finalRect)
{
if (m_itemsPanel != NULL) {
m_itemsPanel->ArrangeLayout(finalRect); // ɘgƂȂ̂ł̂܂܂̃TCYn
}
Control::ArrangeLayout(finalRect);
}
//-----------------------------------------------------------------------------
//
//-----------------------------------------------------------------------------
bool ListBox::OnEvent(EventType type, EventArgs* args)
{
if (m_itemsPanel != NULL) {
if (m_itemsPanel->OnEvent(type, args)) { return true; }
}
return Control::OnEvent(type, args);
}
//-----------------------------------------------------------------------------
//
//-----------------------------------------------------------------------------
void ListBox::Render()
{
Control::Render();
if (m_itemsPanel != NULL) {
m_itemsPanel->Render();
}
}
#endif
//-----------------------------------------------------------------------------
//
//-----------------------------------------------------------------------------
void ListBox::OnListBoxItemAdded(ListBoxItem* item)
{
m_itemsPanel->GetChildren()->Add(item);
}
//-----------------------------------------------------------------------------
//
//-----------------------------------------------------------------------------
void ListBox::OnListBoxItemRemoved(ListBoxItem* item)
{
LN_THROW(0, NotImplementedException);
//m_itemsPanel->GetChildren()->Remove(item);
}
} // namespace GUI
} // namespace Lumino
<|endoftext|>
|
<commit_before>//////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2008, Image Engine Design Inc. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
//
// * Neither the name of Image Engine Design nor the names of any
// other contributors to this software may be used to endorse or
// promote products derived from this software without specific prior
// written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
// IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
// LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
// NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
//////////////////////////////////////////////////////////////////////////
#include "IECore/CompoundObject.h"
#include "IECore/MeshPrimitive.h"
#include "IECore/TriangulateOp.h"
#include "IECore/DespatchTypedData.h"
#include "IECore/TriangleAlgo.h"
#include "IECore/Exception.h"
#include "IECore/CompoundParameter.h"
using namespace IECore;
TriangulateOp::TriangulateOp() : MeshPrimitiveOp( staticTypeName(), "A MeshPrimitiveOp to triangulate a mesh" )
{
m_toleranceParameter = new FloatParameter(
"tolerance",
"The floating point tolerance to use for various operations, such as determining planarity of faces",
1.e-6f,
0.0f
);
m_throwExceptionsParameter = new BoolParameter(
"throwExceptions",
"When enabled, exceptions are thrown when invalid geometry is encountered (e.g. non-planar or concave faces).",
true
);
parameters()->addParameter( m_toleranceParameter );
parameters()->addParameter( m_throwExceptionsParameter );
}
TriangulateOp::~TriangulateOp()
{
}
FloatParameterPtr TriangulateOp::toleranceParameter()
{
return m_toleranceParameter;
}
ConstFloatParameterPtr TriangulateOp::toleranceParameter() const
{
return m_toleranceParameter;
}
BoolParameterPtr TriangulateOp::throwExceptionsParameter()
{
return m_throwExceptionsParameter;
}
ConstBoolParameterPtr TriangulateOp::throwExceptionsParameter() const
{
return m_throwExceptionsParameter;
}
/// A functor for use with despatchTypedData, which copies elements from another vector, as specified by an array of indices into that data
struct TriangleDataRemap
{
typedef size_t ReturnType;
TriangleDataRemap( const std::vector<int> &indices ) : m_indices( indices )
{
}
ConstDataPtr m_other;
const std::vector<int> &m_indices;
template<typename T>
size_t operator() ( typename T::Ptr data )
{
assert( data );
typename T::ConstPtr otherData = runTimeCast<const T>( m_other );
assert( otherData );
data->writable().clear();
data->writable().reserve( m_indices.size() );
for ( std::vector<int>::const_iterator it = m_indices.begin(); it != m_indices.end(); ++it )
{
data->writable().push_back( otherData->readable()[ *it ] );
}
assert( data->readable().size() == m_indices.size() );
return data->readable().size();
}
};
void TriangulateOp::modifyTypedPrimitive( MeshPrimitivePtr mesh, ConstCompoundObjectPtr operands )
{
if (! mesh->arePrimitiveVariablesValid() )
{
throw InvalidArgumentException( "Mesh with invalid primitive variables given to TriangulateOp");
}
bool alreadyTriangulated = true;
ConstIntVectorDataPtr verticesPerFace = mesh->verticesPerFace();
IntVectorData::ValueType::const_iterator it = verticesPerFace->readable().begin();
while ( it != verticesPerFace->readable().end() && alreadyTriangulated )
{
if (*it++ != 3)
{
alreadyTriangulated = false;
}
}
if ( alreadyTriangulated )
{
return;
}
const float tolerance = toleranceParameter()->getNumericValue();
bool throwExceptions = boost::static_pointer_cast<const BoolData>(throwExceptionsParameter()->getValue())->readable();
ConstV3fVectorDataPtr p = 0;
PrimitiveVariableMap::const_iterator pvIt = mesh->variables.find("P");
if (pvIt != mesh->variables.end())
{
const DataPtr &verticesData = pvIt->second.data;
assert( verticesData );
if (runTimeCast<V3fVectorData>(verticesData))
{
p = runTimeCast<V3fVectorData>(verticesData);
}
else
{
std::string err = "MeshPrimitive has \"P\" of unsupported type \"";
err += verticesData->typeName();
err += "\" in TriangulateOp";
throw InvalidArgumentException( err );
}
}
else
{
throw InvalidArgumentException("MeshPrimitive has no \"P\" data in TriangulateOp");
}
assert( p );
ConstIntVectorDataPtr vertexIds = mesh->vertexIds();
IntVectorDataPtr newVertexIds = new IntVectorData();
newVertexIds->writable().reserve( vertexIds->readable().size() );
IntVectorDataPtr newVerticesPerFace = new IntVectorData();
newVerticesPerFace->writable().reserve( verticesPerFace->readable().size() );
std::vector<int> faceVaryingIndices;
int faceVertexIdStart = 0;
for ( IntVectorData::ValueType::const_iterator it = verticesPerFace->readable().begin(); it != verticesPerFace->readable().end(); ++it )
{
int numFaceVerts = *it;
if ( numFaceVerts > 3 )
{
/// For the time being, just do a simple triangle fan.
const int i0 = faceVertexIdStart + 0;
const int v0 = vertexIds->readable()[ i0 ];
int i1 = faceVertexIdStart + 1;
int i2 = faceVertexIdStart + 2;
int v1 = vertexIds->readable()[ i1 ];
int v2 = vertexIds->readable()[ i2 ];
const Imath::V3f firstTriangleNormal = triangleNormal( p->readable()[ v0 ], p->readable()[ v1 ], p->readable()[ v2 ] );
if (throwExceptions)
{
/// Convexivity test - for each edge, all other vertices must be on the same "side" of it
for (int i = 0; i < numFaceVerts - 1; i++)
{
const int edgeStartIndex = faceVertexIdStart + i + 0;
const int edgeStart = vertexIds->readable()[ edgeStartIndex ];
const int edgeEndIndex = faceVertexIdStart + i + 1;
const int edgeEnd = vertexIds->readable()[ edgeEndIndex ];
const Imath::V3f edge = p->readable()[ edgeEnd ] - p->readable()[ edgeStart ];
const float edgeLength = edge.length();
if (edgeLength > tolerance)
{
const Imath::V3f edgeDirection = edge / edgeLength;
/// Construct a plane whose normal is perpendicular to both the edge and the polygon's normal
const Imath::V3f planeNormal = edgeDirection.cross( firstTriangleNormal );
const float planeConstant = planeNormal.dot( p->readable()[ edgeStart ] );
int sign = 0;
bool first = true;
for (int j = 0; j < numFaceVerts; j++)
{
const int testVertexIndex = faceVertexIdStart + j;
const int testVertex = vertexIds->readable()[ testVertexIndex ];
if ( testVertex != edgeStart && testVertex != edgeEnd )
{
float signedDistance = planeNormal.dot( p->readable()[ testVertex ] ) - planeConstant;
if ( fabs(signedDistance) > tolerance)
{
int thisSign = 1;
if ( signedDistance < 0.0 )
{
thisSign = -1;
}
if (first)
{
sign = thisSign;
first = false;
}
else if ( thisSign != sign )
{
assert( sign != 0 );
throw InvalidArgumentException("TriangulateOp cannot deal with concave polygons");
}
}
}
}
}
}
}
for (int i = 1; i < numFaceVerts - 1; i++)
{
i1 = faceVertexIdStart + ( (i + 0) % numFaceVerts );
i2 = faceVertexIdStart + ( (i + 1) % numFaceVerts );
v1 = vertexIds->readable()[ i1 ];
v2 = vertexIds->readable()[ i2 ];
if ( throwExceptions && fabs( triangleNormal( p->readable()[ v0 ], p->readable()[ v1 ], p->readable()[ v2 ] ).dot( firstTriangleNormal ) - 1.0 ) > tolerance )
{
throw InvalidArgumentException("TriangulateOp cannot deal with non-planar polygons");
}
/// Create a new triangle
newVerticesPerFace->writable().push_back( 3 );
/// Triangulate the vertices
newVertexIds->writable().push_back( v0 );
newVertexIds->writable().push_back( v1 );
newVertexIds->writable().push_back( v2 );
/// Store the indices required to rebuild the facevarying primvars
faceVaryingIndices.push_back( i0 );
faceVaryingIndices.push_back( i1 );
faceVaryingIndices.push_back( i2 );
}
}
else
{
assert( numFaceVerts == 3 );
int i0 = faceVertexIdStart + 0;
int i1 = faceVertexIdStart + 1;
int i2 = faceVertexIdStart + 2;
newVerticesPerFace->writable().push_back( 3 );
/// Copy across the vertexId data
newVertexIds->writable().push_back( vertexIds->readable()[ i0 ] );
newVertexIds->writable().push_back( vertexIds->readable()[ i1 ] );
newVertexIds->writable().push_back( vertexIds->readable()[ i2 ] );
/// Store the indices required to rebuild the facevarying primvars
faceVaryingIndices.push_back( i0 );
faceVaryingIndices.push_back( i1 );
faceVaryingIndices.push_back( i2 );
}
faceVertexIdStart += numFaceVerts;
}
mesh->setTopology( newVerticesPerFace, newVertexIds );
/// Rebuild all the facevarying primvars, using the list of indices into the old data we created above.
assert( faceVaryingIndices.size() == newVertexIds->readable().size() );
TriangleDataRemap func( faceVaryingIndices );
for ( PrimitiveVariableMap::iterator it = mesh->variables.begin(); it != mesh->variables.end(); ++it )
{
if ( it->second.interpolation == PrimitiveVariable::FaceVarying )
{
assert( it->second.data );
func.m_other = it->second.data;
DataPtr data = it->second.data->copy();
size_t primVarSize = despatchTypedData<TriangleDataRemap, TypeTraits::IsVectorTypedData>( data, func );
assert( primVarSize == faceVaryingIndices.size() );
(void)primVarSize;
it->second.data = data;
}
}
assert( mesh->arePrimitiveVariablesValid() );
}
<commit_msg>Added todo<commit_after>//////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2008, Image Engine Design Inc. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
//
// * Neither the name of Image Engine Design nor the names of any
// other contributors to this software may be used to endorse or
// promote products derived from this software without specific prior
// written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
// IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
// LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
// NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
//////////////////////////////////////////////////////////////////////////
#include "IECore/CompoundObject.h"
#include "IECore/MeshPrimitive.h"
#include "IECore/TriangulateOp.h"
#include "IECore/DespatchTypedData.h"
#include "IECore/TriangleAlgo.h"
#include "IECore/Exception.h"
#include "IECore/CompoundParameter.h"
using namespace IECore;
TriangulateOp::TriangulateOp() : MeshPrimitiveOp( staticTypeName(), "A MeshPrimitiveOp to triangulate a mesh" )
{
m_toleranceParameter = new FloatParameter(
"tolerance",
"The floating point tolerance to use for various operations, such as determining planarity of faces",
1.e-6f,
0.0f
);
m_throwExceptionsParameter = new BoolParameter(
"throwExceptions",
"When enabled, exceptions are thrown when invalid geometry is encountered (e.g. non-planar or concave faces).",
true
);
parameters()->addParameter( m_toleranceParameter );
parameters()->addParameter( m_throwExceptionsParameter );
}
TriangulateOp::~TriangulateOp()
{
}
FloatParameterPtr TriangulateOp::toleranceParameter()
{
return m_toleranceParameter;
}
ConstFloatParameterPtr TriangulateOp::toleranceParameter() const
{
return m_toleranceParameter;
}
BoolParameterPtr TriangulateOp::throwExceptionsParameter()
{
return m_throwExceptionsParameter;
}
ConstBoolParameterPtr TriangulateOp::throwExceptionsParameter() const
{
return m_throwExceptionsParameter;
}
/// A functor for use with despatchTypedData, which copies elements from another vector, as specified by an array of indices into that data
struct TriangleDataRemap
{
typedef size_t ReturnType;
TriangleDataRemap( const std::vector<int> &indices ) : m_indices( indices )
{
}
ConstDataPtr m_other;
const std::vector<int> &m_indices;
template<typename T>
size_t operator() ( typename T::Ptr data )
{
assert( data );
typename T::ConstPtr otherData = runTimeCast<const T>( m_other );
assert( otherData );
data->writable().clear();
data->writable().reserve( m_indices.size() );
for ( std::vector<int>::const_iterator it = m_indices.begin(); it != m_indices.end(); ++it )
{
data->writable().push_back( otherData->readable()[ *it ] );
}
assert( data->readable().size() == m_indices.size() );
return data->readable().size();
}
};
void TriangulateOp::modifyTypedPrimitive( MeshPrimitivePtr mesh, ConstCompoundObjectPtr operands )
{
if (! mesh->arePrimitiveVariablesValid() )
{
throw InvalidArgumentException( "Mesh with invalid primitive variables given to TriangulateOp");
}
bool alreadyTriangulated = true;
ConstIntVectorDataPtr verticesPerFace = mesh->verticesPerFace();
IntVectorData::ValueType::const_iterator it = verticesPerFace->readable().begin();
while ( it != verticesPerFace->readable().end() && alreadyTriangulated )
{
if (*it++ != 3)
{
alreadyTriangulated = false;
}
}
if ( alreadyTriangulated )
{
return;
}
const float tolerance = toleranceParameter()->getNumericValue();
bool throwExceptions = boost::static_pointer_cast<const BoolData>(throwExceptionsParameter()->getValue())->readable();
ConstV3fVectorDataPtr p = 0;
PrimitiveVariableMap::const_iterator pvIt = mesh->variables.find("P");
if (pvIt != mesh->variables.end())
{
const DataPtr &verticesData = pvIt->second.data;
assert( verticesData );
/// \todo Use depatchTypedData
if (runTimeCast<V3fVectorData>(verticesData))
{
p = runTimeCast<V3fVectorData>(verticesData);
}
else
{
std::string err = "MeshPrimitive has \"P\" of unsupported type \"";
err += verticesData->typeName();
err += "\" in TriangulateOp";
throw InvalidArgumentException( err );
}
}
else
{
throw InvalidArgumentException("MeshPrimitive has no \"P\" data in TriangulateOp");
}
assert( p );
ConstIntVectorDataPtr vertexIds = mesh->vertexIds();
IntVectorDataPtr newVertexIds = new IntVectorData();
newVertexIds->writable().reserve( vertexIds->readable().size() );
IntVectorDataPtr newVerticesPerFace = new IntVectorData();
newVerticesPerFace->writable().reserve( verticesPerFace->readable().size() );
std::vector<int> faceVaryingIndices;
int faceVertexIdStart = 0;
for ( IntVectorData::ValueType::const_iterator it = verticesPerFace->readable().begin(); it != verticesPerFace->readable().end(); ++it )
{
int numFaceVerts = *it;
if ( numFaceVerts > 3 )
{
/// For the time being, just do a simple triangle fan.
const int i0 = faceVertexIdStart + 0;
const int v0 = vertexIds->readable()[ i0 ];
int i1 = faceVertexIdStart + 1;
int i2 = faceVertexIdStart + 2;
int v1 = vertexIds->readable()[ i1 ];
int v2 = vertexIds->readable()[ i2 ];
const Imath::V3f firstTriangleNormal = triangleNormal( p->readable()[ v0 ], p->readable()[ v1 ], p->readable()[ v2 ] );
if (throwExceptions)
{
/// Convexivity test - for each edge, all other vertices must be on the same "side" of it
for (int i = 0; i < numFaceVerts - 1; i++)
{
const int edgeStartIndex = faceVertexIdStart + i + 0;
const int edgeStart = vertexIds->readable()[ edgeStartIndex ];
const int edgeEndIndex = faceVertexIdStart + i + 1;
const int edgeEnd = vertexIds->readable()[ edgeEndIndex ];
const Imath::V3f edge = p->readable()[ edgeEnd ] - p->readable()[ edgeStart ];
const float edgeLength = edge.length();
if (edgeLength > tolerance)
{
const Imath::V3f edgeDirection = edge / edgeLength;
/// Construct a plane whose normal is perpendicular to both the edge and the polygon's normal
const Imath::V3f planeNormal = edgeDirection.cross( firstTriangleNormal );
const float planeConstant = planeNormal.dot( p->readable()[ edgeStart ] );
int sign = 0;
bool first = true;
for (int j = 0; j < numFaceVerts; j++)
{
const int testVertexIndex = faceVertexIdStart + j;
const int testVertex = vertexIds->readable()[ testVertexIndex ];
if ( testVertex != edgeStart && testVertex != edgeEnd )
{
float signedDistance = planeNormal.dot( p->readable()[ testVertex ] ) - planeConstant;
if ( fabs(signedDistance) > tolerance)
{
int thisSign = 1;
if ( signedDistance < 0.0 )
{
thisSign = -1;
}
if (first)
{
sign = thisSign;
first = false;
}
else if ( thisSign != sign )
{
assert( sign != 0 );
throw InvalidArgumentException("TriangulateOp cannot deal with concave polygons");
}
}
}
}
}
}
}
for (int i = 1; i < numFaceVerts - 1; i++)
{
i1 = faceVertexIdStart + ( (i + 0) % numFaceVerts );
i2 = faceVertexIdStart + ( (i + 1) % numFaceVerts );
v1 = vertexIds->readable()[ i1 ];
v2 = vertexIds->readable()[ i2 ];
if ( throwExceptions && fabs( triangleNormal( p->readable()[ v0 ], p->readable()[ v1 ], p->readable()[ v2 ] ).dot( firstTriangleNormal ) - 1.0 ) > tolerance )
{
throw InvalidArgumentException("TriangulateOp cannot deal with non-planar polygons");
}
/// Create a new triangle
newVerticesPerFace->writable().push_back( 3 );
/// Triangulate the vertices
newVertexIds->writable().push_back( v0 );
newVertexIds->writable().push_back( v1 );
newVertexIds->writable().push_back( v2 );
/// Store the indices required to rebuild the facevarying primvars
faceVaryingIndices.push_back( i0 );
faceVaryingIndices.push_back( i1 );
faceVaryingIndices.push_back( i2 );
}
}
else
{
assert( numFaceVerts == 3 );
int i0 = faceVertexIdStart + 0;
int i1 = faceVertexIdStart + 1;
int i2 = faceVertexIdStart + 2;
newVerticesPerFace->writable().push_back( 3 );
/// Copy across the vertexId data
newVertexIds->writable().push_back( vertexIds->readable()[ i0 ] );
newVertexIds->writable().push_back( vertexIds->readable()[ i1 ] );
newVertexIds->writable().push_back( vertexIds->readable()[ i2 ] );
/// Store the indices required to rebuild the facevarying primvars
faceVaryingIndices.push_back( i0 );
faceVaryingIndices.push_back( i1 );
faceVaryingIndices.push_back( i2 );
}
faceVertexIdStart += numFaceVerts;
}
mesh->setTopology( newVerticesPerFace, newVertexIds );
/// Rebuild all the facevarying primvars, using the list of indices into the old data we created above.
assert( faceVaryingIndices.size() == newVertexIds->readable().size() );
TriangleDataRemap func( faceVaryingIndices );
for ( PrimitiveVariableMap::iterator it = mesh->variables.begin(); it != mesh->variables.end(); ++it )
{
if ( it->second.interpolation == PrimitiveVariable::FaceVarying )
{
assert( it->second.data );
func.m_other = it->second.data;
DataPtr data = it->second.data->copy();
size_t primVarSize = despatchTypedData<TriangleDataRemap, TypeTraits::IsVectorTypedData>( data, func );
assert( primVarSize == faceVaryingIndices.size() );
(void)primVarSize;
it->second.data = data;
}
}
assert( mesh->arePrimitiveVariablesValid() );
}
<|endoftext|>
|
<commit_before>/*
Parsing.cpp - HTTP request parsing.
Copyright (c) 2015 Ivan Grokhotkov. All rights reserved.
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
Modified 8 May 2015 by Hristo Gochkov (proper post and file upload handling)
*/
#include <Arduino.h>
#include "WiFiServer.h"
#include "WiFiClient.h"
#include "ESP8266WebServer.h"
// #define DEBUG
#define DEBUG_OUTPUT Serial1
bool ESP8266WebServer::_parseRequest(WiFiClient& client) {
// Read the first line of HTTP request
String req = client.readStringUntil('\r');
client.readStringUntil('\n');
// First line of HTTP request looks like "GET /path HTTP/1.1"
// Retrieve the "/path" part by finding the spaces
int addr_start = req.indexOf(' ');
int addr_end = req.indexOf(' ', addr_start + 1);
if (addr_start == -1 || addr_end == -1) {
#ifdef DEBUG
DEBUG_OUTPUT.print("Invalid request: ");
DEBUG_OUTPUT.println(req);
#endif
return false;
}
String methodStr = req.substring(0, addr_start);
String url = req.substring(addr_start + 1, addr_end);
String searchStr = "";
int hasSearch = url.indexOf('?');
if (hasSearch != -1){
searchStr = url.substring(hasSearch + 1);
url = url.substring(0, hasSearch);
}
_currentUri = url;
HTTPMethod method = HTTP_GET;
if (methodStr == "POST") {
method = HTTP_POST;
} else if (methodStr == "DELETE") {
method = HTTP_DELETE;
} else if (methodStr == "PUT") {
method = HTTP_PUT;
} else if (methodStr == "PATCH") {
method = HTTP_PATCH;
}
_currentMethod = method;
#ifdef DEBUG
DEBUG_OUTPUT.print("method: ");
DEBUG_OUTPUT.print(methodStr);
DEBUG_OUTPUT.print(" url: ");
DEBUG_OUTPUT.print(url);
DEBUG_OUTPUT.print(" search: ");
DEBUG_OUTPUT.println(searchStr);
#endif
String formData;
// below is needed only when POST type request
if (method == HTTP_POST || method == HTTP_PUT || method == HTTP_PATCH || method == HTTP_DELETE){
String boundaryStr;
String headerName;
String headerValue;
bool isForm = false;
uint32_t contentLength = 0;
//parse headers
while(1){
req = client.readStringUntil('\r');
client.readStringUntil('\n');
if (req == "") break;//no moar headers
int headerDiv = req.indexOf(':');
if (headerDiv == -1){
break;
}
headerName = req.substring(0, headerDiv);
headerValue = req.substring(headerDiv + 2);
if (headerName == "Content-Type"){
if (headerValue.startsWith("text/plain")){
isForm = false;
} else if (headerValue.startsWith("multipart/form-data")){
boundaryStr = headerValue.substring(headerValue.indexOf('=')+1);
isForm = true;
}
} else if (headerName == "Content-Length"){
contentLength = headerValue.toInt();
}
}
if (!isForm){
if (searchStr != "") searchStr += '&';
String bodyLine = client.readStringUntil('\r');
if(bodyLine.startsWith("{") || bodyLine.startsWith("[") || bodyLine.indexOf('=') == -1){
//plain post json or other data
searchStr += "plain";
}
searchStr += bodyLine;
client.readStringUntil('\n');
}
_parseArguments(searchStr);
if (isForm){
_parseForm(client, boundaryStr, contentLength);
}
} else {
_parseArguments(searchStr);
}
client.flush();
#ifdef DEBUG
DEBUG_OUTPUT.print("Request: ");
DEBUG_OUTPUT.println(url);
DEBUG_OUTPUT.print(" Arguments: ");
DEBUG_OUTPUT.println(searchStr);
#endif
return true;
}
void ESP8266WebServer::_parseArguments(String data) {
#ifdef DEBUG
DEBUG_OUTPUT.print("args: ");
DEBUG_OUTPUT.println(data);
#endif
if (_currentArgs)
delete[] _currentArgs;
_currentArgs = 0;
if (data.length() == 0) {
_currentArgCount = 0;
return;
}
_currentArgCount = 1;
for (int i = 0; i < data.length(); ) {
i = data.indexOf('&', i);
if (i == -1)
break;
++i;
++_currentArgCount;
}
#ifdef DEBUG
DEBUG_OUTPUT.print("args count: ");
DEBUG_OUTPUT.println(_currentArgCount);
#endif
_currentArgs = new RequestArgument[_currentArgCount];
int pos = 0;
int iarg;
for (iarg = 0; iarg < _currentArgCount;) {
int equal_sign_index = data.indexOf('=', pos);
int next_arg_index = data.indexOf('&', pos);
#ifdef DEBUG
DEBUG_OUTPUT.print("pos ");
DEBUG_OUTPUT.print(pos);
DEBUG_OUTPUT.print("=@ ");
DEBUG_OUTPUT.print(equal_sign_index);
DEBUG_OUTPUT.print(" &@ ");
DEBUG_OUTPUT.println(next_arg_index);
#endif
if ((equal_sign_index == -1) || ((equal_sign_index > next_arg_index) && (next_arg_index != -1))) {
#ifdef DEBUG
DEBUG_OUTPUT.print("arg missing value: ");
DEBUG_OUTPUT.println(iarg);
#endif
if (next_arg_index == -1)
break;
pos = next_arg_index + 1;
continue;
}
RequestArgument& arg = _currentArgs[iarg];
arg.key = data.substring(pos, equal_sign_index);
arg.value = data.substring(equal_sign_index + 1, next_arg_index);
#ifdef DEBUG
DEBUG_OUTPUT.print("arg ");
DEBUG_OUTPUT.print(iarg);
DEBUG_OUTPUT.print(" key: ");
DEBUG_OUTPUT.print(arg.key);
DEBUG_OUTPUT.print(" value: ");
DEBUG_OUTPUT.println(arg.value);
#endif
++iarg;
if (next_arg_index == -1)
break;
pos = next_arg_index + 1;
}
_currentArgCount = iarg;
#ifdef DEBUG
DEBUG_OUTPUT.print("args count: ");
DEBUG_OUTPUT.println(_currentArgCount);
#endif
}
void ESP8266WebServer::_uploadWriteByte(uint8_t b){
if (_currentUpload.currentSize == HTTP_UPLOAD_BUFLEN){
if (_fileUploadHandler) _fileUploadHandler();
_currentUpload.totalSize += _currentUpload.currentSize;
_currentUpload.currentSize = 0;
}
_currentUpload.buf[_currentUpload.currentSize++] = b;
}
uint8_t ESP8266WebServer::_uploadReadByte(WiFiClient& client){
int res = client.read();
if(res == -1){
while(!client.available())
yield();
res = client.read();
}
return (uint8_t)res;
}
void ESP8266WebServer::_parseForm(WiFiClient& client, String boundary, uint32_t len){
#ifdef DEBUG
DEBUG_OUTPUT.print("Parse Form: Boundary: ");
DEBUG_OUTPUT.print(boundary);
DEBUG_OUTPUT.print(" Length: ");
DEBUG_OUTPUT.println(len);
#endif
String line;
line = client.readStringUntil('\r');
client.readStringUntil('\n');
//start reading the form
if (line == ("--"+boundary)){
RequestArgument* postArgs = new RequestArgument[32];
int postArgsLen = 0;
while(1){
String argName;
String argValue;
String argType;
String argFilename;
bool argIsFile = false;
line = client.readStringUntil('\r');
client.readStringUntil('\n');
if (line.startsWith("Content-Disposition")){
int nameStart = line.indexOf('=');
if (nameStart != -1){
argName = line.substring(nameStart+2);
nameStart = argName.indexOf('=');
if (nameStart == -1){
argName = argName.substring(0, argName.length() - 1);
} else {
argFilename = argName.substring(nameStart+2, argName.length() - 1);
argName = argName.substring(0, argName.indexOf('"'));
argIsFile = true;
#ifdef DEBUG
DEBUG_OUTPUT.print("PostArg FileName: ");
DEBUG_OUTPUT.println(argFilename);
#endif
//use GET to set the filename if uploading using blob
if (argFilename == "blob" && hasArg("filename")) argFilename = arg("filename");
}
#ifdef DEBUG
DEBUG_OUTPUT.print("PostArg Name: ");
DEBUG_OUTPUT.println(argName);
#endif
argType = "text/plain";
line = client.readStringUntil('\r');
client.readStringUntil('\n');
if (line.startsWith("Content-Type")){
argType = line.substring(line.indexOf(':')+2);
//skip next line
client.readStringUntil('\r');
client.readStringUntil('\n');
}
#ifdef DEBUG
DEBUG_OUTPUT.print("PostArg Type: ");
DEBUG_OUTPUT.println(argType);
#endif
if (!argIsFile){
while(1){
line = client.readStringUntil('\r');
client.readStringUntil('\n');
if (line.startsWith("--"+boundary)) break;
if (argValue.length() > 0) argValue += "\n";
argValue += line;
}
#ifdef DEBUG
DEBUG_OUTPUT.print("PostArg Value: ");
DEBUG_OUTPUT.println(argValue);
DEBUG_OUTPUT.println();
#endif
RequestArgument& arg = postArgs[postArgsLen++];
arg.key = argName;
arg.value = argValue;
if (line == ("--"+boundary+"--")){
#ifdef DEBUG
DEBUG_OUTPUT.println("Done Parsing POST");
#endif
break;
}
} else {
_currentUpload.status = UPLOAD_FILE_START;
_currentUpload.name = argName;
_currentUpload.filename = argFilename;
_currentUpload.type = argType;
_currentUpload.totalSize = 0;
_currentUpload.currentSize = 0;
#ifdef DEBUG
DEBUG_OUTPUT.print("Start File: ");
DEBUG_OUTPUT.print(_currentUpload.filename);
DEBUG_OUTPUT.print(" Type: ");
DEBUG_OUTPUT.println(_currentUpload.type);
#endif
if (_fileUploadHandler) _fileUploadHandler();
_currentUpload.status = UPLOAD_FILE_WRITE;
uint8_t argByte = _uploadReadByte(client);
readfile:
while(argByte != 0x0D){
_uploadWriteByte(argByte);
argByte = _uploadReadByte(client);
}
argByte = _uploadReadByte(client);
if (argByte == 0x0A){
argByte = _uploadReadByte(client);
if ((char)argByte != '-'){
//continue reading the file
_uploadWriteByte(0x0D);
_uploadWriteByte(0x0A);
goto readfile;
} else {
argByte = _uploadReadByte(client);
if ((char)argByte != '-'){
//continue reading the file
_uploadWriteByte(0x0D);
_uploadWriteByte(0x0A);
_uploadWriteByte((uint8_t)('-'));
goto readfile;
}
}
uint8_t endBuf[boundary.length()];
client.readBytes(endBuf, boundary.length());
if (strstr((const char*)endBuf, boundary.c_str()) != NULL){
if (_fileUploadHandler) _fileUploadHandler();
_currentUpload.totalSize += _currentUpload.currentSize;
_currentUpload.status = UPLOAD_FILE_END;
if (_fileUploadHandler) _fileUploadHandler();
#ifdef DEBUG
DEBUG_OUTPUT.print("End File: ");
DEBUG_OUTPUT.print(_currentUpload.filename);
DEBUG_OUTPUT.print(" Type: ");
DEBUG_OUTPUT.print(_currentUpload.type);
DEBUG_OUTPUT.print(" Size: ");
DEBUG_OUTPUT.println(_currentUpload.totalSize);
#endif
line = client.readStringUntil(0x0D);
client.readStringUntil(0x0A);
if (line == "--"){
#ifdef DEBUG
DEBUG_OUTPUT.println("Done Parsing POST");
#endif
break;
}
continue;
} else {
_uploadWriteByte(0x0D);
_uploadWriteByte(0x0A);
_uploadWriteByte((uint8_t)('-'));
_uploadWriteByte((uint8_t)('-'));
uint32_t i = 0;
while(i < boundary.length()){
_uploadWriteByte(endBuf[i++]);
}
argByte = _uploadReadByte(client);
goto readfile;
}
} else {
_uploadWriteByte(0x0D);
goto readfile;
}
break;
}
}
}
}
int iarg;
int totalArgs = ((32 - postArgsLen) < _currentArgCount)?(32 - postArgsLen):_currentArgCount;
for (iarg = 0; iarg < totalArgs; iarg++){
RequestArgument& arg = postArgs[postArgsLen++];
arg.key = _currentArgs[iarg].key;
arg.value = _currentArgs[iarg].value;
}
if (_currentArgs) delete[] _currentArgs;
_currentArgs = new RequestArgument[postArgsLen];
for (iarg = 0; iarg < postArgsLen; iarg++){
RequestArgument& arg = _currentArgs[iarg];
arg.key = postArgs[iarg].key;
arg.value = postArgs[iarg].value;
}
_currentArgCount = iarg;
if (postArgs) delete[] postArgs;
}
}
<commit_msg>missingg the equal sign<commit_after>/*
Parsing.cpp - HTTP request parsing.
Copyright (c) 2015 Ivan Grokhotkov. All rights reserved.
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
Modified 8 May 2015 by Hristo Gochkov (proper post and file upload handling)
*/
#include <Arduino.h>
#include "WiFiServer.h"
#include "WiFiClient.h"
#include "ESP8266WebServer.h"
// #define DEBUG
#define DEBUG_OUTPUT Serial1
bool ESP8266WebServer::_parseRequest(WiFiClient& client) {
// Read the first line of HTTP request
String req = client.readStringUntil('\r');
client.readStringUntil('\n');
// First line of HTTP request looks like "GET /path HTTP/1.1"
// Retrieve the "/path" part by finding the spaces
int addr_start = req.indexOf(' ');
int addr_end = req.indexOf(' ', addr_start + 1);
if (addr_start == -1 || addr_end == -1) {
#ifdef DEBUG
DEBUG_OUTPUT.print("Invalid request: ");
DEBUG_OUTPUT.println(req);
#endif
return false;
}
String methodStr = req.substring(0, addr_start);
String url = req.substring(addr_start + 1, addr_end);
String searchStr = "";
int hasSearch = url.indexOf('?');
if (hasSearch != -1){
searchStr = url.substring(hasSearch + 1);
url = url.substring(0, hasSearch);
}
_currentUri = url;
HTTPMethod method = HTTP_GET;
if (methodStr == "POST") {
method = HTTP_POST;
} else if (methodStr == "DELETE") {
method = HTTP_DELETE;
} else if (methodStr == "PUT") {
method = HTTP_PUT;
} else if (methodStr == "PATCH") {
method = HTTP_PATCH;
}
_currentMethod = method;
#ifdef DEBUG
DEBUG_OUTPUT.print("method: ");
DEBUG_OUTPUT.print(methodStr);
DEBUG_OUTPUT.print(" url: ");
DEBUG_OUTPUT.print(url);
DEBUG_OUTPUT.print(" search: ");
DEBUG_OUTPUT.println(searchStr);
#endif
String formData;
// below is needed only when POST type request
if (method == HTTP_POST || method == HTTP_PUT || method == HTTP_PATCH || method == HTTP_DELETE){
String boundaryStr;
String headerName;
String headerValue;
bool isForm = false;
uint32_t contentLength = 0;
//parse headers
while(1){
req = client.readStringUntil('\r');
client.readStringUntil('\n');
if (req == "") break;//no moar headers
int headerDiv = req.indexOf(':');
if (headerDiv == -1){
break;
}
headerName = req.substring(0, headerDiv);
headerValue = req.substring(headerDiv + 2);
if (headerName == "Content-Type"){
if (headerValue.startsWith("text/plain")){
isForm = false;
} else if (headerValue.startsWith("multipart/form-data")){
boundaryStr = headerValue.substring(headerValue.indexOf('=')+1);
isForm = true;
}
} else if (headerName == "Content-Length"){
contentLength = headerValue.toInt();
}
}
if (!isForm){
if (searchStr != "") searchStr += '&';
String bodyLine = client.readStringUntil('\r');
if(bodyLine.startsWith("{") || bodyLine.startsWith("[") || bodyLine.indexOf('=') == -1){
//plain post json or other data
searchStr += "plain=";
}
searchStr += bodyLine;
client.readStringUntil('\n');
}
_parseArguments(searchStr);
if (isForm){
_parseForm(client, boundaryStr, contentLength);
}
} else {
_parseArguments(searchStr);
}
client.flush();
#ifdef DEBUG
DEBUG_OUTPUT.print("Request: ");
DEBUG_OUTPUT.println(url);
DEBUG_OUTPUT.print(" Arguments: ");
DEBUG_OUTPUT.println(searchStr);
#endif
return true;
}
void ESP8266WebServer::_parseArguments(String data) {
#ifdef DEBUG
DEBUG_OUTPUT.print("args: ");
DEBUG_OUTPUT.println(data);
#endif
if (_currentArgs)
delete[] _currentArgs;
_currentArgs = 0;
if (data.length() == 0) {
_currentArgCount = 0;
return;
}
_currentArgCount = 1;
for (int i = 0; i < data.length(); ) {
i = data.indexOf('&', i);
if (i == -1)
break;
++i;
++_currentArgCount;
}
#ifdef DEBUG
DEBUG_OUTPUT.print("args count: ");
DEBUG_OUTPUT.println(_currentArgCount);
#endif
_currentArgs = new RequestArgument[_currentArgCount];
int pos = 0;
int iarg;
for (iarg = 0; iarg < _currentArgCount;) {
int equal_sign_index = data.indexOf('=', pos);
int next_arg_index = data.indexOf('&', pos);
#ifdef DEBUG
DEBUG_OUTPUT.print("pos ");
DEBUG_OUTPUT.print(pos);
DEBUG_OUTPUT.print("=@ ");
DEBUG_OUTPUT.print(equal_sign_index);
DEBUG_OUTPUT.print(" &@ ");
DEBUG_OUTPUT.println(next_arg_index);
#endif
if ((equal_sign_index == -1) || ((equal_sign_index > next_arg_index) && (next_arg_index != -1))) {
#ifdef DEBUG
DEBUG_OUTPUT.print("arg missing value: ");
DEBUG_OUTPUT.println(iarg);
#endif
if (next_arg_index == -1)
break;
pos = next_arg_index + 1;
continue;
}
RequestArgument& arg = _currentArgs[iarg];
arg.key = data.substring(pos, equal_sign_index);
arg.value = data.substring(equal_sign_index + 1, next_arg_index);
#ifdef DEBUG
DEBUG_OUTPUT.print("arg ");
DEBUG_OUTPUT.print(iarg);
DEBUG_OUTPUT.print(" key: ");
DEBUG_OUTPUT.print(arg.key);
DEBUG_OUTPUT.print(" value: ");
DEBUG_OUTPUT.println(arg.value);
#endif
++iarg;
if (next_arg_index == -1)
break;
pos = next_arg_index + 1;
}
_currentArgCount = iarg;
#ifdef DEBUG
DEBUG_OUTPUT.print("args count: ");
DEBUG_OUTPUT.println(_currentArgCount);
#endif
}
void ESP8266WebServer::_uploadWriteByte(uint8_t b){
if (_currentUpload.currentSize == HTTP_UPLOAD_BUFLEN){
if (_fileUploadHandler) _fileUploadHandler();
_currentUpload.totalSize += _currentUpload.currentSize;
_currentUpload.currentSize = 0;
}
_currentUpload.buf[_currentUpload.currentSize++] = b;
}
uint8_t ESP8266WebServer::_uploadReadByte(WiFiClient& client){
int res = client.read();
if(res == -1){
while(!client.available())
yield();
res = client.read();
}
return (uint8_t)res;
}
void ESP8266WebServer::_parseForm(WiFiClient& client, String boundary, uint32_t len){
#ifdef DEBUG
DEBUG_OUTPUT.print("Parse Form: Boundary: ");
DEBUG_OUTPUT.print(boundary);
DEBUG_OUTPUT.print(" Length: ");
DEBUG_OUTPUT.println(len);
#endif
String line;
line = client.readStringUntil('\r');
client.readStringUntil('\n');
//start reading the form
if (line == ("--"+boundary)){
RequestArgument* postArgs = new RequestArgument[32];
int postArgsLen = 0;
while(1){
String argName;
String argValue;
String argType;
String argFilename;
bool argIsFile = false;
line = client.readStringUntil('\r');
client.readStringUntil('\n');
if (line.startsWith("Content-Disposition")){
int nameStart = line.indexOf('=');
if (nameStart != -1){
argName = line.substring(nameStart+2);
nameStart = argName.indexOf('=');
if (nameStart == -1){
argName = argName.substring(0, argName.length() - 1);
} else {
argFilename = argName.substring(nameStart+2, argName.length() - 1);
argName = argName.substring(0, argName.indexOf('"'));
argIsFile = true;
#ifdef DEBUG
DEBUG_OUTPUT.print("PostArg FileName: ");
DEBUG_OUTPUT.println(argFilename);
#endif
//use GET to set the filename if uploading using blob
if (argFilename == "blob" && hasArg("filename")) argFilename = arg("filename");
}
#ifdef DEBUG
DEBUG_OUTPUT.print("PostArg Name: ");
DEBUG_OUTPUT.println(argName);
#endif
argType = "text/plain";
line = client.readStringUntil('\r');
client.readStringUntil('\n');
if (line.startsWith("Content-Type")){
argType = line.substring(line.indexOf(':')+2);
//skip next line
client.readStringUntil('\r');
client.readStringUntil('\n');
}
#ifdef DEBUG
DEBUG_OUTPUT.print("PostArg Type: ");
DEBUG_OUTPUT.println(argType);
#endif
if (!argIsFile){
while(1){
line = client.readStringUntil('\r');
client.readStringUntil('\n');
if (line.startsWith("--"+boundary)) break;
if (argValue.length() > 0) argValue += "\n";
argValue += line;
}
#ifdef DEBUG
DEBUG_OUTPUT.print("PostArg Value: ");
DEBUG_OUTPUT.println(argValue);
DEBUG_OUTPUT.println();
#endif
RequestArgument& arg = postArgs[postArgsLen++];
arg.key = argName;
arg.value = argValue;
if (line == ("--"+boundary+"--")){
#ifdef DEBUG
DEBUG_OUTPUT.println("Done Parsing POST");
#endif
break;
}
} else {
_currentUpload.status = UPLOAD_FILE_START;
_currentUpload.name = argName;
_currentUpload.filename = argFilename;
_currentUpload.type = argType;
_currentUpload.totalSize = 0;
_currentUpload.currentSize = 0;
#ifdef DEBUG
DEBUG_OUTPUT.print("Start File: ");
DEBUG_OUTPUT.print(_currentUpload.filename);
DEBUG_OUTPUT.print(" Type: ");
DEBUG_OUTPUT.println(_currentUpload.type);
#endif
if (_fileUploadHandler) _fileUploadHandler();
_currentUpload.status = UPLOAD_FILE_WRITE;
uint8_t argByte = _uploadReadByte(client);
readfile:
while(argByte != 0x0D){
_uploadWriteByte(argByte);
argByte = _uploadReadByte(client);
}
argByte = _uploadReadByte(client);
if (argByte == 0x0A){
argByte = _uploadReadByte(client);
if ((char)argByte != '-'){
//continue reading the file
_uploadWriteByte(0x0D);
_uploadWriteByte(0x0A);
goto readfile;
} else {
argByte = _uploadReadByte(client);
if ((char)argByte != '-'){
//continue reading the file
_uploadWriteByte(0x0D);
_uploadWriteByte(0x0A);
_uploadWriteByte((uint8_t)('-'));
goto readfile;
}
}
uint8_t endBuf[boundary.length()];
client.readBytes(endBuf, boundary.length());
if (strstr((const char*)endBuf, boundary.c_str()) != NULL){
if (_fileUploadHandler) _fileUploadHandler();
_currentUpload.totalSize += _currentUpload.currentSize;
_currentUpload.status = UPLOAD_FILE_END;
if (_fileUploadHandler) _fileUploadHandler();
#ifdef DEBUG
DEBUG_OUTPUT.print("End File: ");
DEBUG_OUTPUT.print(_currentUpload.filename);
DEBUG_OUTPUT.print(" Type: ");
DEBUG_OUTPUT.print(_currentUpload.type);
DEBUG_OUTPUT.print(" Size: ");
DEBUG_OUTPUT.println(_currentUpload.totalSize);
#endif
line = client.readStringUntil(0x0D);
client.readStringUntil(0x0A);
if (line == "--"){
#ifdef DEBUG
DEBUG_OUTPUT.println("Done Parsing POST");
#endif
break;
}
continue;
} else {
_uploadWriteByte(0x0D);
_uploadWriteByte(0x0A);
_uploadWriteByte((uint8_t)('-'));
_uploadWriteByte((uint8_t)('-'));
uint32_t i = 0;
while(i < boundary.length()){
_uploadWriteByte(endBuf[i++]);
}
argByte = _uploadReadByte(client);
goto readfile;
}
} else {
_uploadWriteByte(0x0D);
goto readfile;
}
break;
}
}
}
}
int iarg;
int totalArgs = ((32 - postArgsLen) < _currentArgCount)?(32 - postArgsLen):_currentArgCount;
for (iarg = 0; iarg < totalArgs; iarg++){
RequestArgument& arg = postArgs[postArgsLen++];
arg.key = _currentArgs[iarg].key;
arg.value = _currentArgs[iarg].value;
}
if (_currentArgs) delete[] _currentArgs;
_currentArgs = new RequestArgument[postArgsLen];
for (iarg = 0; iarg < postArgsLen; iarg++){
RequestArgument& arg = _currentArgs[iarg];
arg.key = postArgs[iarg].key;
arg.value = postArgs[iarg].value;
}
_currentArgCount = iarg;
if (postArgs) delete[] postArgs;
}
}
<|endoftext|>
|
<commit_before>
// the syntax for messages is:
// wd 'mb type buttons title message'
//
// type specifies the icon and default behaviour:
// info (default OK button)
// warn (default OK button)
// critical (default OK button)
// query (requires two or three buttons)
//
// if one button, there is no result,
// otherwise the result is the button name (ok, cancel, ...)
//
// buttons are from the set:
// mb_ok
// mb_cancel
// mb_yes
// mb_no
// mb_save
// mb_discard
#include <QApplication>
#include <QColorDialog>
#include <QFileDialog>
#include <QFontDialog>
#include <QMessageBox>
#include "wd.h"
#include "cmd.h"
QString mbcolor();
QString mbdir();
QString mbfont();
QString mbinfo(QString);
QString mbmsg();
QString mbopen();
QString mbsave();
QString type;
QStringList arg;
QMessageBox::StandardButton getdefaultbutton();
QMessageBox::StandardButton getonebutton();
QMessageBox::StandardButtons getotherbuttons();
QString getname(int);
// ---------------------------------------------------------------------
QString mb(string p)
{
arg=qsplit(p);
if (arg.size()<2) return "";
type=arg.first();
arg.removeFirst();
if (type=="color")
return mbcolor();
if (type=="dir")
return mbdir();
if (type=="font")
return mbfont();
if (type=="open")
return mbopen();
if (type=="save")
return mbsave();
if (type=="info"||type=="query"||type=="warn"||type=="critical")
return mbmsg();
return mbinfo("invalid mb type: " + type);
}
// ---------------------------------------------------------------------
QString mbmsg()
{
int r;
QString t,m;
QMessageBox::StandardButton button1=getdefaultbutton();
QMessageBox::StandardButtons buttons=getotherbuttons();
if (arg.size()==1) {
t="Message Box";
m=arg.at(0);
} else if (arg.size()==2) {
t=arg.at(0);
m=arg.at(1);
} else {
return mbinfo ("Need title and message: "+arg.join(" "));
}
if (button1==-1) {
button1=QMessageBox::Ok;
if (type=="query")
buttons=QMessageBox::Cancel;
}
buttons|=button1;
if (type=="query") {
r=QMessageBox::question(QApplication::focusWidget(),t,m,buttons,button1);
return getname(r);
}
if (type=="critical")
QMessageBox::critical(QApplication::focusWidget(),t,m,buttons,button1);
else if (type=="info")
QMessageBox::information(QApplication::focusWidget(),t,m,buttons,button1);
else if (type=="warn")
QMessageBox::warning(QApplication::focusWidget(),t,m,buttons,button1);
return "";
}
// ---------------------------------------------------------------------
QString mbcolor()
{
QColor c;
int r,g,b;
if (arg.size()==3) {
r=arg.at(0).toInt();
g=arg.at(1).toInt();
b=arg.at(2).toInt();
c=QColor(r,g,b);
} else
c=Qt::white;
c=QColorDialog::getColor(c,QApplication::focusWidget());
if (!c.isValid()) return "";
return s2q(i2s(c.red()) + " " + i2s(c.green()) + " " + i2s(c.blue()));
}
// ---------------------------------------------------------------------
QString mbdir()
{
QString title,dir;
if (arg.size()!=2)
return mbinfo("dir needs title and directory");
title=arg.at(0);
dir=arg.at(1);
return QFileDialog::getExistingDirectory(
QApplication::focusWidget(),title,dir);
}
// ---------------------------------------------------------------------
QString mbfont()
{
bool ok;
QFont font, def;
QString s;
if (arg.size())
def.setFamily(arg.at(0));
if (arg.size()>1)
def.setPointSize(arg.at(1).toInt());
for (int i=2; i<arg.size(); i++) {
s=arg.at(i);
if (s=="bold")
def.setBold(true);
if (s=="italic")
def.setItalic(true);
if (s=="strikeout")
def.setStrikeOut(true);
if (s=="underline")
def.setUnderline(true);
}
font=QFontDialog::getFont(&ok,def,QApplication::focusWidget());
if (!ok) return "";
QString r;
r="\"" + font.family() + "\" " + QString::number(font.pointSize());
if (font.bold()) r+=" bold";
if (font.italic()) r+=" italic";
if (font.strikeOut()) r+=" strikeout";
if (font.underline()) r+=" underline";
return r;
}
// ---------------------------------------------------------------------
QString mbopen()
{
QString title,dir,filter;
if (arg.size()<2)
return mbinfo("open needs title, directory, [filters]");
title=arg.at(0);
dir=arg.at(1);
if (arg.size()==3)
filter=arg.at(2);
return QFileDialog::getOpenFileName(
QApplication::focusWidget(),title,dir,filter);
}
// ---------------------------------------------------------------------
QString mbsave()
{
QString title,dir,filter;
if (arg.size()<2)
return mbinfo("save needs title, directory, [filters]");
title=arg.at(0);
dir=arg.at(1);
if (arg.size()==3)
filter=arg.at(2);
return QFileDialog::getSaveFileName(
QApplication::focusWidget(),title,dir,filter);
}
// ---------------------------------------------------------------------
QString getname(int b)
{
if (b==QMessageBox::Ok)
return "ok";
if (b==QMessageBox::Cancel)
return "cancel";
if (b==QMessageBox::Yes)
return "yes";
if (b==QMessageBox::No)
return "no";
if (b==QMessageBox::Save)
return "save";
if (b==QMessageBox::Discard)
return "discard";
return "unknown button";
}
// ---------------------------------------------------------------------
QMessageBox::StandardButton getonebutton()
{
if (arg.isEmpty()) return QMessageBox::NoButton;
QString s=arg.first();
if (s=="mb_ok")
return QMessageBox::Ok;
if (s=="mb_cancel")
return QMessageBox::Cancel;
if (s=="mb_yes")
return QMessageBox::Yes;
if (s=="mb_no")
return QMessageBox::No;
if (s=="mb_save")
return QMessageBox::Save;
if (s=="mb_discard")
return QMessageBox::Discard;
return QMessageBox::NoButton;
}
// ---------------------------------------------------------------------
QMessageBox::StandardButton getdefaultbutton()
{
QMessageBox::StandardButton r=getonebutton();
if (r!=QMessageBox::NoButton)
arg.removeFirst();
return r;
}
// ---------------------------------------------------------------------
QMessageBox::StandardButtons getotherbuttons()
{
QMessageBox::StandardButtons r=QMessageBox::NoButton;
QMessageBox::StandardButton b;
while (arg.size()) {
b=getonebutton();
if (b==QMessageBox::NoButton)
return r;
r|=b;
arg.removeFirst();
}
return r;
}
// ---------------------------------------------------------------------
QString mbinfo(QString s)
{
info("Message Box",s);
return "";
}
<commit_msg>mbfont without inital fontspec<commit_after>
// the syntax for messages is:
// wd 'mb type buttons title message'
//
// type specifies the icon and default behaviour:
// info (default OK button)
// warn (default OK button)
// critical (default OK button)
// query (requires two or three buttons)
//
// if one button, there is no result,
// otherwise the result is the button name (ok, cancel, ...)
//
// buttons are from the set:
// mb_ok
// mb_cancel
// mb_yes
// mb_no
// mb_save
// mb_discard
#include <QApplication>
#include <QColorDialog>
#include <QFileDialog>
#include <QFontDialog>
#include <QMessageBox>
#include "wd.h"
#include "cmd.h"
QString mbcolor();
QString mbdir();
QString mbfont();
QString mbinfo(QString);
QString mbmsg();
QString mbopen();
QString mbsave();
QString type;
QStringList arg;
QMessageBox::StandardButton getdefaultbutton();
QMessageBox::StandardButton getonebutton();
QMessageBox::StandardButtons getotherbuttons();
QString getname(int);
// ---------------------------------------------------------------------
QString mb(string p)
{
arg=qsplit(p);
if (arg.size()<1) return mbinfo("missing mb type");
type=arg.first();
arg.removeFirst();
if (type=="color")
return mbcolor();
if (type=="dir")
return mbdir();
if (type=="font")
return mbfont();
if (type=="open")
return mbopen();
if (type=="save")
return mbsave();
if (type=="info"||type=="query"||type=="warn"||type=="critical")
return mbmsg();
return mbinfo("invalid mb type: " + type);
}
// ---------------------------------------------------------------------
QString mbmsg()
{
int r;
QString t,m;
QMessageBox::StandardButton button1=getdefaultbutton();
QMessageBox::StandardButtons buttons=getotherbuttons();
if (arg.size()==1) {
t="Message Box";
m=arg.at(0);
} else if (arg.size()==2) {
t=arg.at(0);
m=arg.at(1);
} else {
return mbinfo ("Need title and message: "+arg.join(" "));
}
if (button1==-1) {
button1=QMessageBox::Ok;
if (type=="query")
buttons=QMessageBox::Cancel;
}
buttons|=button1;
if (type=="query") {
r=QMessageBox::question(QApplication::focusWidget(),t,m,buttons,button1);
return getname(r);
}
if (type=="critical")
QMessageBox::critical(QApplication::focusWidget(),t,m,buttons,button1);
else if (type=="info")
QMessageBox::information(QApplication::focusWidget(),t,m,buttons,button1);
else if (type=="warn")
QMessageBox::warning(QApplication::focusWidget(),t,m,buttons,button1);
return "";
}
// ---------------------------------------------------------------------
QString mbcolor()
{
QColor c;
int r,g,b;
if (arg.size()==3) {
r=arg.at(0).toInt();
g=arg.at(1).toInt();
b=arg.at(2).toInt();
c=QColor(r,g,b);
} else
c=Qt::white;
c=QColorDialog::getColor(c,QApplication::focusWidget());
if (!c.isValid()) return "";
return s2q(i2s(c.red()) + " " + i2s(c.green()) + " " + i2s(c.blue()));
}
// ---------------------------------------------------------------------
QString mbdir()
{
QString title,dir;
if (arg.size()!=2)
return mbinfo("dir needs title and directory");
title=arg.at(0);
dir=arg.at(1);
return QFileDialog::getExistingDirectory(
QApplication::focusWidget(),title,dir);
}
// ---------------------------------------------------------------------
QString mbfont()
{
bool ok;
QFont font, def;
QString s;
def.setStrikeOut(false);
def.setUnderline(false);
if (arg.size())
def.setFamily(arg.at(0));
if (arg.size()>1)
def.setPointSize(arg.at(1).toInt());
for (int i=2; i<arg.size(); i++) {
s=arg.at(i);
if (s=="bold")
def.setBold(true);
if (s=="italic")
def.setItalic(true);
if (s=="strikeout")
def.setStrikeOut(true);
if (s=="underline")
def.setUnderline(true);
}
font=QFontDialog::getFont(&ok,def,QApplication::focusWidget());
if (!ok) return "";
QString r;
r="\"" + font.family() + "\" " + QString::number(font.pointSize());
if (font.bold()) r+=" bold";
if (font.italic()) r+=" italic";
if (font.strikeOut()) r+=" strikeout";
if (font.underline()) r+=" underline";
return r;
}
// ---------------------------------------------------------------------
QString mbopen()
{
QString title,dir,filter;
if (arg.size()<2)
return mbinfo("open needs title, directory, [filters]");
title=arg.at(0);
dir=arg.at(1);
if (arg.size()==3)
filter=arg.at(2);
return QFileDialog::getOpenFileName(
QApplication::focusWidget(),title,dir,filter);
}
// ---------------------------------------------------------------------
QString mbsave()
{
QString title,dir,filter;
if (arg.size()<2)
return mbinfo("save needs title, directory, [filters]");
title=arg.at(0);
dir=arg.at(1);
if (arg.size()==3)
filter=arg.at(2);
return QFileDialog::getSaveFileName(
QApplication::focusWidget(),title,dir,filter);
}
// ---------------------------------------------------------------------
QString getname(int b)
{
if (b==QMessageBox::Ok)
return "ok";
if (b==QMessageBox::Cancel)
return "cancel";
if (b==QMessageBox::Yes)
return "yes";
if (b==QMessageBox::No)
return "no";
if (b==QMessageBox::Save)
return "save";
if (b==QMessageBox::Discard)
return "discard";
return "unknown button";
}
// ---------------------------------------------------------------------
QMessageBox::StandardButton getonebutton()
{
if (arg.isEmpty()) return QMessageBox::NoButton;
QString s=arg.first();
if (s=="mb_ok")
return QMessageBox::Ok;
if (s=="mb_cancel")
return QMessageBox::Cancel;
if (s=="mb_yes")
return QMessageBox::Yes;
if (s=="mb_no")
return QMessageBox::No;
if (s=="mb_save")
return QMessageBox::Save;
if (s=="mb_discard")
return QMessageBox::Discard;
return QMessageBox::NoButton;
}
// ---------------------------------------------------------------------
QMessageBox::StandardButton getdefaultbutton()
{
QMessageBox::StandardButton r=getonebutton();
if (r!=QMessageBox::NoButton)
arg.removeFirst();
return r;
}
// ---------------------------------------------------------------------
QMessageBox::StandardButtons getotherbuttons()
{
QMessageBox::StandardButtons r=QMessageBox::NoButton;
QMessageBox::StandardButton b;
while (arg.size()) {
b=getonebutton();
if (b==QMessageBox::NoButton)
return r;
r|=b;
arg.removeFirst();
}
return r;
}
// ---------------------------------------------------------------------
QString mbinfo(QString s)
{
info("Message Box",s);
return "";
}
<|endoftext|>
|
<commit_before>/***************************************************************************
* Copyright (c) 2020 sliptonic <shopinthewoods@gmail.com> *
* *
* This file is part of the FreeCAD CAx development system. *
* *
* This library is free software; you can redistribute it and/or *
* modify it under the terms of the GNU Library General Public *
* License as published by the Free Software Foundation; either *
* version 2 of the License, or (at your option) any later version. *
* *
* This library is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU Library General Public License for more details. *
* *
* You should have received a copy of the GNU Library General Public *
* License along with this library; see the file COPYING.LIB. If not, *
* write to the Free Software Foundation, Inc., 59 Temple Place, *
* Suite 330, Boston, MA 02111-1307, USA *
* *
***************************************************************************/
#include "PreCompiled.h"
#ifndef _PreComp_
# include <Standard_math.hxx>
# include <cinttypes>
# include <iomanip>
# include <boost/algorithm/string.hpp>
# include <boost/lexical_cast.hpp>
#endif
#include <Base/Vector3D.h>
#include <Base/Writer.h>
#include <Base/Reader.h>
#include <Base/Exception.h>
#include "Voronoi.h"
using namespace Base;
using namespace Path;
TYPESYSTEM_SOURCE(Path::Voronoi , Base::BaseClass)
// Helpers
// Voronoi::diagram_type
Voronoi::diagram_type::diagram_type()
:scale(1000)
{
}
double Voronoi::diagram_type::getScale() const {
return scale;
}
void Voronoi::diagram_type::setScale(double s) {
scale = s;
}
Base::Vector3d Voronoi::diagram_type::scaledVector(double x, double y, double z) const {
return Base::Vector3d(x / scale, y / scale, z);
}
Base::Vector3d Voronoi::diagram_type::scaledVector(const point_type &p, double z) const {
return scaledVector(p.x(), p.y(), z);
}
Base::Vector3d Voronoi::diagram_type::scaledVector(const vertex_type &v, double z) const {
return scaledVector(v.x(), v.y(), z);
}
int Voronoi::diagram_type::index(const Voronoi::diagram_type::cell_type *cell) const {
auto it = cell_index.find(intptr_t(cell));
if (it == cell_index.end()) {
return Voronoi::InvalidIndex;
}
return it->second;
}
int Voronoi::diagram_type::index(const Voronoi::diagram_type::edge_type *edge) const {
auto it = edge_index.find(intptr_t(edge));
if (it == edge_index.end()) {
return Voronoi::InvalidIndex;
}
return it->second;
}
int Voronoi::diagram_type::index(const Voronoi::diagram_type::vertex_type *vertex) const {
auto it = vertex_index.find(intptr_t(vertex));
if (it == vertex_index.end()) {
return Voronoi::InvalidIndex;
}
return it->second;
}
void Voronoi::diagram_type::reIndex() {
int idx = 0;
cell_index.clear();
edge_index.clear();
vertex_index.clear();
idx = 0;
for (auto it = cells().begin(); it != cells().end(); ++it, ++idx) {
cell_index[intptr_t(&(*it))] = idx;
}
idx = 0;
for (auto it = edges().begin(); it != edges().end(); ++it, ++idx) {
edge_index[intptr_t(&(*it))] = idx;
}
idx = 0;
for (auto it = vertices().begin(); it != vertices().end(); ++it, ++idx) {
vertex_index[intptr_t(&(*it))] = idx;
}
}
Voronoi::point_type Voronoi::diagram_type::retrievePoint(const Voronoi::diagram_type::cell_type *cell) const {
Voronoi::diagram_type::cell_type::source_index_type index = cell->source_index();
Voronoi::diagram_type::cell_type::source_category_type category = cell->source_category();
if (category == boost::polygon::SOURCE_CATEGORY_SINGLE_POINT) {
return points[index];
}
index -= points.size();
if (category == boost::polygon::SOURCE_CATEGORY_SEGMENT_START_POINT) {
return low(segments[index]);
} else {
return high(segments[index]);
}
}
Voronoi::segment_type Voronoi::diagram_type::retrieveSegment(const Voronoi::diagram_type::cell_type *cell) const {
Voronoi::diagram_type::cell_type::source_index_type index = cell->source_index() - points.size();
return segments[index];
}
// Voronoi
Voronoi::Voronoi()
:vd(new diagram_type)
{
}
Voronoi::~Voronoi()
{
}
void Voronoi::addPoint(const Voronoi::point_type &p) {
Voronoi::point_type pi;
pi.x(p.x() * vd->getScale());
pi.y(p.y() * vd->getScale());
vd->points.push_back(pi);
}
void Voronoi::addSegment(const Voronoi::segment_type &s) {
Voronoi::point_type pil, pih;
pil.x(low(s).x() * vd->getScale());
pil.y(low(s).y() * vd->getScale());
pih.x(high(s).x() * vd->getScale());
pih.y(high(s).y() * vd->getScale());
vd->segments.push_back(segment_type(pil, pih));
}
long Voronoi::numPoints() const {
return vd->points.size();
}
long Voronoi::numSegments() const {
return vd->segments.size();
}
long Voronoi::numCells() const {
return vd->num_cells();
}
long Voronoi::numEdges() const {
return vd->num_edges();
}
long Voronoi::numVertices() const {
return vd->num_vertices();
}
void Voronoi::construct()
{
vd->clear();
construct_voronoi(vd->points.begin(), vd->points.end(), vd->segments.begin(), vd->segments.end(), (voronoi_diagram_type*)vd);
vd->reIndex();
}
void Voronoi::colorExterior(const Voronoi::diagram_type::edge_type *edge, std::size_t colorValue) {
if (edge->color()) {
// end recursion
return;
}
edge->color(colorValue);
edge->twin()->color(colorValue);
auto v = edge->vertex1();
if (v == NULL || !edge->is_primary()) {
return;
}
v->color(colorValue);
auto e = v->incident_edge();
do {
colorExterior(e, colorValue);
e = e->rot_next();
} while (e != v->incident_edge());
}
void Voronoi::colorExterior(Voronoi::color_type color) {
for (diagram_type::const_edge_iterator it = vd->edges().begin(); it != vd->edges().end(); ++it) {
if (it->is_infinite()) {
colorExterior(&(*it), color);
}
}
}
void Voronoi::colorTwins(Voronoi::color_type color) {
for (diagram_type::const_edge_iterator it = vd->edges().begin(); it != vd->edges().end(); ++it) {
if (!it->color()) {
auto twin = it->twin();
if (!twin->color()) {
twin->color(color);
}
}
}
}
double Voronoi::diagram_type::angleOfSegment(int i, Voronoi::diagram_type::angle_map_t *angle) const {
Voronoi::diagram_type::angle_map_t::const_iterator a = angle ? angle->find(i) : Voronoi::diagram_type::angle_map_t::const_iterator();
if (!angle || a == angle->end()) {
Voronoi::point_type p0 = low(segments[i]);
Voronoi::point_type p1 = high(segments[i]);
double ang = 0;
if (p0.x() == p1.x()) {
if ((p0.y() > 0 && p1.y() > 0) || (p0.y() > 0 && p1.y() > 0)) {
ang = M_PI_2;
} else {
ang = -M_PI_2;
}
} else {
ang = atan((p0.y() - p1.y()) / (p0.x() - p1.x()));
}
if (angle) {
angle->insert(angle_map_t::value_type(i, ang));
}
return ang;
}
return a->second;
}
static bool pointsMatch(const Voronoi::point_type &p0, const Voronoi::point_type &p1) {
return long(p0.x()) == long(p1.x()) && long(p0.y()) == long(p1.y());
}
bool Voronoi::diagram_type::segmentsAreConnected(int i, int j) const {
return
pointsMatch(low(segments[i]), low(segments[j]))
|| pointsMatch(low(segments[i]), high(segments[j]))
|| pointsMatch(high(segments[i]), low(segments[j]))
|| pointsMatch(high(segments[i]), high(segments[j]));
}
void Voronoi::colorColinear(Voronoi::color_type color, double degree) {
double rad = degree * M_PI / 180;
Voronoi::diagram_type::angle_map_t angle;
int psize = vd->points.size();
for (diagram_type::const_edge_iterator it = vd->edges().begin(); it != vd->edges().end(); ++it) {
int i0 = it->cell()->source_index() - psize;
int i1 = it->twin()->cell()->source_index() - psize;
if (it->color() == 0
&& it->cell()->contains_segment()
&& it->twin()->cell()->contains_segment()
&& vd->segmentsAreConnected(i0, i1)) {
double a0 = vd->angleOfSegment(i0, &angle);
double a1 = vd->angleOfSegment(i1, &angle);
double a = a0 - a1;
if (a > M_PI_2) {
a -= M_PI;
} else if (a < -M_PI_2) {
a += M_PI;
}
if (fabs(a) < rad) {
it->color(color);
it->twin()->color(color);
}
}
}
}
void Voronoi::resetColor(Voronoi::color_type color) {
for (auto it = vd->cells().begin(); it != vd->cells().end(); ++it) {
if (color == 0 || it->color() == color) {
it->color(0);
}
}
for (auto it = vd->edges().begin(); it != vd->edges().end(); ++it) {
if (it->color() == color) {
it->color(0);
}
}
for (auto it = vd->vertices().begin(); it != vd->vertices().end(); ++it) {
if (it->color() == color) {
it->color(0);
}
}
}
<commit_msg>Fixed angle detection<commit_after>/***************************************************************************
* Copyright (c) 2020 sliptonic <shopinthewoods@gmail.com> *
* *
* This file is part of the FreeCAD CAx development system. *
* *
* This library is free software; you can redistribute it and/or *
* modify it under the terms of the GNU Library General Public *
* License as published by the Free Software Foundation; either *
* version 2 of the License, or (at your option) any later version. *
* *
* This library is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU Library General Public License for more details. *
* *
* You should have received a copy of the GNU Library General Public *
* License along with this library; see the file COPYING.LIB. If not, *
* write to the Free Software Foundation, Inc., 59 Temple Place, *
* Suite 330, Boston, MA 02111-1307, USA *
* *
***************************************************************************/
#include "PreCompiled.h"
#ifndef _PreComp_
# include <Standard_math.hxx>
# include <cinttypes>
# include <iomanip>
# include <boost/algorithm/string.hpp>
# include <boost/lexical_cast.hpp>
#endif
#include <Base/Vector3D.h>
#include <Base/Writer.h>
#include <Base/Reader.h>
#include <Base/Exception.h>
#include "Voronoi.h"
using namespace Base;
using namespace Path;
TYPESYSTEM_SOURCE(Path::Voronoi , Base::BaseClass)
// Helpers
// Voronoi::diagram_type
Voronoi::diagram_type::diagram_type()
:scale(1000)
{
}
double Voronoi::diagram_type::getScale() const {
return scale;
}
void Voronoi::diagram_type::setScale(double s) {
scale = s;
}
Base::Vector3d Voronoi::diagram_type::scaledVector(double x, double y, double z) const {
return Base::Vector3d(x / scale, y / scale, z);
}
Base::Vector3d Voronoi::diagram_type::scaledVector(const point_type &p, double z) const {
return scaledVector(p.x(), p.y(), z);
}
Base::Vector3d Voronoi::diagram_type::scaledVector(const vertex_type &v, double z) const {
return scaledVector(v.x(), v.y(), z);
}
int Voronoi::diagram_type::index(const Voronoi::diagram_type::cell_type *cell) const {
auto it = cell_index.find(intptr_t(cell));
if (it == cell_index.end()) {
return Voronoi::InvalidIndex;
}
return it->second;
}
int Voronoi::diagram_type::index(const Voronoi::diagram_type::edge_type *edge) const {
auto it = edge_index.find(intptr_t(edge));
if (it == edge_index.end()) {
return Voronoi::InvalidIndex;
}
return it->second;
}
int Voronoi::diagram_type::index(const Voronoi::diagram_type::vertex_type *vertex) const {
auto it = vertex_index.find(intptr_t(vertex));
if (it == vertex_index.end()) {
return Voronoi::InvalidIndex;
}
return it->second;
}
void Voronoi::diagram_type::reIndex() {
int idx = 0;
cell_index.clear();
edge_index.clear();
vertex_index.clear();
idx = 0;
for (auto it = cells().begin(); it != cells().end(); ++it, ++idx) {
cell_index[intptr_t(&(*it))] = idx;
}
idx = 0;
for (auto it = edges().begin(); it != edges().end(); ++it, ++idx) {
edge_index[intptr_t(&(*it))] = idx;
}
idx = 0;
for (auto it = vertices().begin(); it != vertices().end(); ++it, ++idx) {
vertex_index[intptr_t(&(*it))] = idx;
}
}
Voronoi::point_type Voronoi::diagram_type::retrievePoint(const Voronoi::diagram_type::cell_type *cell) const {
Voronoi::diagram_type::cell_type::source_index_type index = cell->source_index();
Voronoi::diagram_type::cell_type::source_category_type category = cell->source_category();
if (category == boost::polygon::SOURCE_CATEGORY_SINGLE_POINT) {
return points[index];
}
index -= points.size();
if (category == boost::polygon::SOURCE_CATEGORY_SEGMENT_START_POINT) {
return low(segments[index]);
} else {
return high(segments[index]);
}
}
Voronoi::segment_type Voronoi::diagram_type::retrieveSegment(const Voronoi::diagram_type::cell_type *cell) const {
Voronoi::diagram_type::cell_type::source_index_type index = cell->source_index() - points.size();
return segments[index];
}
// Voronoi
Voronoi::Voronoi()
:vd(new diagram_type)
{
}
Voronoi::~Voronoi()
{
}
void Voronoi::addPoint(const Voronoi::point_type &p) {
Voronoi::point_type pi;
pi.x(p.x() * vd->getScale());
pi.y(p.y() * vd->getScale());
vd->points.push_back(pi);
}
void Voronoi::addSegment(const Voronoi::segment_type &s) {
Voronoi::point_type pil, pih;
pil.x(low(s).x() * vd->getScale());
pil.y(low(s).y() * vd->getScale());
pih.x(high(s).x() * vd->getScale());
pih.y(high(s).y() * vd->getScale());
vd->segments.push_back(segment_type(pil, pih));
}
long Voronoi::numPoints() const {
return vd->points.size();
}
long Voronoi::numSegments() const {
return vd->segments.size();
}
long Voronoi::numCells() const {
return vd->num_cells();
}
long Voronoi::numEdges() const {
return vd->num_edges();
}
long Voronoi::numVertices() const {
return vd->num_vertices();
}
void Voronoi::construct()
{
vd->clear();
construct_voronoi(vd->points.begin(), vd->points.end(), vd->segments.begin(), vd->segments.end(), (voronoi_diagram_type*)vd);
vd->reIndex();
}
void Voronoi::colorExterior(const Voronoi::diagram_type::edge_type *edge, std::size_t colorValue) {
if (edge->color()) {
// end recursion
return;
}
edge->color(colorValue);
edge->twin()->color(colorValue);
auto v = edge->vertex1();
if (v == NULL || !edge->is_primary()) {
return;
}
v->color(colorValue);
auto e = v->incident_edge();
do {
colorExterior(e, colorValue);
e = e->rot_next();
} while (e != v->incident_edge());
}
void Voronoi::colorExterior(Voronoi::color_type color) {
for (diagram_type::const_edge_iterator it = vd->edges().begin(); it != vd->edges().end(); ++it) {
if (it->is_infinite()) {
colorExterior(&(*it), color);
}
}
}
void Voronoi::colorTwins(Voronoi::color_type color) {
for (diagram_type::const_edge_iterator it = vd->edges().begin(); it != vd->edges().end(); ++it) {
if (!it->color()) {
auto twin = it->twin();
if (!twin->color()) {
twin->color(color);
}
}
}
}
double Voronoi::diagram_type::angleOfSegment(int i, Voronoi::diagram_type::angle_map_t *angle) const {
Voronoi::diagram_type::angle_map_t::const_iterator a = angle ? angle->find(i) : Voronoi::diagram_type::angle_map_t::const_iterator();
if (!angle || a == angle->end()) {
Voronoi::point_type p0 = low(segments[i]);
Voronoi::point_type p1 = high(segments[i]);
double ang = 0;
if (p0.x() == p1.x()) {
if (p0.y() < p1.y()) {
ang = M_PI_2;
} else {
ang = -M_PI_2;
}
} else {
ang = atan((p0.y() - p1.y()) / (p0.x() - p1.x()));
}
if (angle) {
angle->insert(angle_map_t::value_type(i, ang));
}
return ang;
}
return a->second;
}
static bool pointsMatch(const Voronoi::point_type &p0, const Voronoi::point_type &p1) {
return long(p0.x()) == long(p1.x()) && long(p0.y()) == long(p1.y());
}
bool Voronoi::diagram_type::segmentsAreConnected(int i, int j) const {
return
pointsMatch(low(segments[i]), low(segments[j]))
|| pointsMatch(low(segments[i]), high(segments[j]))
|| pointsMatch(high(segments[i]), low(segments[j]))
|| pointsMatch(high(segments[i]), high(segments[j]));
}
void Voronoi::colorColinear(Voronoi::color_type color, double degree) {
double rad = degree * M_PI / 180;
Voronoi::diagram_type::angle_map_t angle;
int psize = vd->points.size();
for (diagram_type::const_edge_iterator it = vd->edges().begin(); it != vd->edges().end(); ++it) {
int i0 = it->cell()->source_index() - psize;
int i1 = it->twin()->cell()->source_index() - psize;
if (it->color() == 0
&& it->cell()->contains_segment()
&& it->twin()->cell()->contains_segment()
&& vd->segmentsAreConnected(i0, i1)) {
double a0 = vd->angleOfSegment(i0, &angle);
double a1 = vd->angleOfSegment(i1, &angle);
double a = a0 - a1;
if (a > M_PI_2) {
a -= M_PI;
} else if (a < -M_PI_2) {
a += M_PI;
}
if (fabs(a) < rad) {
it->color(color);
it->twin()->color(color);
}
}
}
}
void Voronoi::resetColor(Voronoi::color_type color) {
for (auto it = vd->cells().begin(); it != vd->cells().end(); ++it) {
if (color == 0 || it->color() == color) {
it->color(0);
}
}
for (auto it = vd->edges().begin(); it != vd->edges().end(); ++it) {
if (it->color() == color) {
it->color(0);
}
}
for (auto it = vd->vertices().begin(); it != vd->vertices().end(); ++it) {
if (it->color() == color) {
it->color(0);
}
}
}
<|endoftext|>
|
<commit_before>// Copyright (c) 2020 by Robert Bosch GmbH. 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 "iceoryx_posh/internal/popo/building_blocks/chunk_distributor.hpp"
#include "iceoryx_posh/internal/popo/building_blocks/chunk_receiver.hpp"
#include "iceoryx_posh/internal/popo/building_blocks/chunk_sender.hpp"
#include "iceoryx_posh/internal/popo/building_blocks/locking_policy.hpp"
#include "iceoryx_posh/internal/popo/ports/base_port.hpp"
#include "iceoryx_posh/mepoo/mepoo_config.hpp"
#include "iceoryx_utils/cxx/generic_raii.hpp"
#include "test.hpp"
#include <chrono>
#include <stdlib.h>
#include <thread>
using namespace ::testing;
using namespace iox::popo;
using namespace iox::cxx;
using namespace iox::mepoo;
using namespace iox::posix;
using ::testing::Return;
struct DummySample
{
uint64_t m_dummy{42};
};
static constexpr uint32_t NUM_CHUNKS_IN_POOL = 3 * iox::MAX_SUBSCRIBER_QUEUE_CAPACITY;
static constexpr uint32_t SMALL_CHUNK = 128;
static constexpr uint32_t CHUNK_META_INFO_SIZE = 256;
static constexpr size_t MEMORY_SIZE = NUM_CHUNKS_IN_POOL * (SMALL_CHUNK + CHUNK_META_INFO_SIZE);
alignas(64) static uint8_t g_memory[MEMORY_SIZE];
static constexpr uint32_t ITERATIONS = 10000;
static constexpr uint32_t MAX_NUMBER_QUEUES = 128;
struct ChunkDistributorConfig
{
static constexpr uint32_t MAX_QUEUES = MAX_NUMBER_QUEUES;
static constexpr uint64_t MAX_HISTORY_CAPACITY = iox::MAX_PUBLISHER_HISTORY;
};
struct ChunkQueueConfig
{
static constexpr uint64_t MAX_QUEUE_CAPACITY = iox::MAX_SUBSCRIBER_QUEUE_CAPACITY;
};
using ChunkQueueData_t = ChunkQueueData<ChunkQueueConfig, ThreadSafePolicy>;
using ChunkDistributorData_t =
ChunkDistributorData<ChunkDistributorConfig, ThreadSafePolicy, ChunkQueuePusher<ChunkQueueData_t>>;
using ChunkDistributor_t = ChunkDistributor<ChunkDistributorData_t>;
using ChunkQueuePopper_t = ChunkQueuePopper<ChunkQueueData_t>;
using ChunkSenderData_t =
ChunkSenderData<iox::MAX_CHUNKS_ALLOCATED_PER_PUBLISHER_SIMULTANEOUSLY, ChunkDistributorData_t>;
using ChunkReceiverData_t = ChunkReceiverData<iox::MAX_CHUNKS_HELD_PER_SUBSCRIBER_SIMULTANEOUSLY, ChunkQueueData_t>;
class ChunkBuildingBlocks_IntegrationTest : public Test
{
public:
ChunkBuildingBlocks_IntegrationTest()
{
m_mempoolConfig.addMemPool({SMALL_CHUNK, NUM_CHUNKS_IN_POOL});
m_memoryManager.configureMemoryManager(m_mempoolConfig, &m_memoryAllocator, &m_memoryAllocator);
}
virtual ~ChunkBuildingBlocks_IntegrationTest()
{
/// @note One chunk is on hold due to the fact that chunkSender and chunkDistributor hold last chunk
EXPECT_THAT(m_memoryManager.getMemPoolInfo(0).m_usedChunks, Eq(1));
}
void SetUp()
{
m_chunkSender.tryAddQueue(&m_chunkQueueData);
m_chunkDistributor.tryAddQueue(&m_chunkReceiverData);
}
void TearDown(){};
void publish()
{
for (size_t i = 0; i < ITERATIONS; i++)
{
m_chunkSender.tryAllocate(sizeof(DummySample), iox::UniquePortId())
.and_then([&](auto chunkHeader) {
auto sample = chunkHeader->payload();
new (sample) DummySample();
static_cast<DummySample*>(sample)->m_dummy = i;
m_chunkSender.send(chunkHeader);
m_sendCounter++;
})
.or_else([](AllocationError) {
// Errors shall never occur
FAIL();
});
/// Add some jitter to make thread breathe
std::this_thread::sleep_for(std::chrono::nanoseconds(rand() % 100));
}
// Signal the next threads we're done
m_publisherRun = false;
}
void forward()
{
uint64_t forwardCounter{0};
bool finished{false};
// this is to prevent a race condition on thread shutdown; there must be two consecutive empty pops after the
// publish thread finished
bool newChunkReceivedInLastIteration{true};
while (!finished)
{
ASSERT_FALSE(m_popper.hasOverflown());
m_popper.tryPop()
.and_then([&](auto& chunk) {
auto dummySample = *reinterpret_cast<DummySample*>(chunk.getPayload());
// Check if monotonically increasing
EXPECT_THAT(dummySample.m_dummy, Eq(forwardCounter));
m_chunkDistributor.deliverToAllStoredQueues(chunk);
forwardCounter++;
newChunkReceivedInLastIteration = true;
})
.or_else([&] {
if (!m_publisherRun.load(std::memory_order_relaxed))
{
if (newChunkReceivedInLastIteration)
{
newChunkReceivedInLastIteration = false;
}
else
{
finished = true;
}
}
});
}
// Signal the next threads we're done
m_forwarderRun = false;
}
void subscribe()
{
bool finished{false};
// this is to prevent a race condition on thread shutdown; there must be two consecutive empty pops after the
// forward thread finished
bool newChunkReceivedInLastIteration{true};
while (!finished)
{
ASSERT_FALSE(m_chunkReceiver.hasOverflown());
m_chunkReceiver.tryGet()
.and_then([&](iox::cxx::optional<const iox::mepoo::ChunkHeader*>& maybeChunkHeader) {
if (maybeChunkHeader.has_value())
{
auto chunkHeader = maybeChunkHeader.value();
auto dummySample = *reinterpret_cast<DummySample*>(chunkHeader->payload());
// Check if monotonically increasing
EXPECT_THAT(dummySample.m_dummy, Eq(m_receiveCounter));
m_receiveCounter++;
m_chunkReceiver.release(chunkHeader);
newChunkReceivedInLastIteration = true;
}
else if (!m_forwarderRun.load(std::memory_order_relaxed))
{
if (newChunkReceivedInLastIteration)
{
newChunkReceivedInLastIteration = false;
}
else
{
finished = true;
}
}
})
.or_else([](ChunkReceiveError) {
// Errors shall never occur
FAIL();
});
}
}
iox::cxx::GenericRAII m_uniqueRouDiId{[] { iox::popo::internal::setUniqueRouDiId(0); },
[] { iox::popo::internal::unsetUniqueRouDiId(); }};
uint64_t m_sendCounter{0};
uint64_t m_receiveCounter{0};
std::atomic<bool> m_publisherRun{true};
std::atomic<bool> m_forwarderRun{true};
// Memory objects
Allocator m_memoryAllocator{g_memory, MEMORY_SIZE};
MePooConfig m_mempoolConfig;
MemoryManager m_memoryManager;
// Objects used by publishing thread
ChunkSenderData_t m_chunkSenderData{&m_memoryManager};
ChunkSender<ChunkSenderData_t> m_chunkSender{&m_chunkSenderData};
// Objects used by forwarding thread
ChunkDistributorData_t m_chunkDistributorData;
ChunkDistributor_t m_chunkDistributor{&m_chunkDistributorData};
ChunkQueueData_t m_chunkQueueData{
iox::cxx::VariantQueueTypes::FiFo_SingleProducerSingleConsumer}; // SoFi intentionally not used
ChunkQueuePopper_t m_popper{&m_chunkQueueData};
// Objects used by subscribing thread
ChunkReceiverData_t m_chunkReceiverData{
iox::cxx::VariantQueueTypes::FiFo_SingleProducerSingleConsumer}; // SoFi intentionally not used
ChunkReceiver<ChunkReceiverData_t> m_chunkReceiver{&m_chunkReceiverData};
};
TEST_F(ChunkBuildingBlocks_IntegrationTest, TwoHopsThreeThreadsNoSoFi)
{
std::thread subscribingThread(&ChunkBuildingBlocks_IntegrationTest::subscribe, this);
std::thread forwardingThread(&ChunkBuildingBlocks_IntegrationTest::forward, this);
std::thread publishingThread(&ChunkBuildingBlocks_IntegrationTest::publish, this);
if (publishingThread.joinable())
{
publishingThread.join();
}
if (forwardingThread.joinable())
{
forwardingThread.join();
}
if (subscribingThread.joinable())
{
subscribingThread.join();
}
EXPECT_EQ(m_sendCounter, m_receiveCounter);
}
<commit_msg>iox-#408 another try to make ChunkBuildingBlocks_IntegrationTest more robust<commit_after>// Copyright (c) 2020 by Robert Bosch GmbH. 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 "iceoryx_posh/internal/popo/building_blocks/chunk_distributor.hpp"
#include "iceoryx_posh/internal/popo/building_blocks/chunk_receiver.hpp"
#include "iceoryx_posh/internal/popo/building_blocks/chunk_sender.hpp"
#include "iceoryx_posh/internal/popo/building_blocks/locking_policy.hpp"
#include "iceoryx_posh/internal/popo/ports/base_port.hpp"
#include "iceoryx_posh/mepoo/mepoo_config.hpp"
#include "iceoryx_utils/cxx/generic_raii.hpp"
#include "test.hpp"
#include <chrono>
#include <stdlib.h>
#include <thread>
using namespace ::testing;
using namespace iox::popo;
using namespace iox::cxx;
using namespace iox::mepoo;
using namespace iox::posix;
using ::testing::Return;
struct DummySample
{
uint64_t m_dummy{42};
};
static constexpr uint32_t NUM_CHUNKS_IN_POOL = 9 * iox::MAX_SUBSCRIBER_QUEUE_CAPACITY;
static constexpr uint32_t SMALL_CHUNK = 128;
static constexpr uint32_t CHUNK_META_INFO_SIZE = 256;
static constexpr size_t MEMORY_SIZE = NUM_CHUNKS_IN_POOL * (SMALL_CHUNK + CHUNK_META_INFO_SIZE);
alignas(64) static uint8_t g_memory[MEMORY_SIZE];
static constexpr uint32_t ITERATIONS = 10000;
static constexpr uint32_t MAX_NUMBER_QUEUES = 128;
struct ChunkDistributorConfig
{
static constexpr uint32_t MAX_QUEUES = MAX_NUMBER_QUEUES;
static constexpr uint64_t MAX_HISTORY_CAPACITY = iox::MAX_PUBLISHER_HISTORY;
};
struct ChunkQueueConfig
{
static constexpr uint64_t MAX_QUEUE_CAPACITY = NUM_CHUNKS_IN_POOL / 3;
};
using ChunkQueueData_t = ChunkQueueData<ChunkQueueConfig, ThreadSafePolicy>;
using ChunkDistributorData_t =
ChunkDistributorData<ChunkDistributorConfig, ThreadSafePolicy, ChunkQueuePusher<ChunkQueueData_t>>;
using ChunkDistributor_t = ChunkDistributor<ChunkDistributorData_t>;
using ChunkQueuePopper_t = ChunkQueuePopper<ChunkQueueData_t>;
using ChunkSenderData_t =
ChunkSenderData<iox::MAX_CHUNKS_ALLOCATED_PER_PUBLISHER_SIMULTANEOUSLY, ChunkDistributorData_t>;
using ChunkReceiverData_t = ChunkReceiverData<iox::MAX_CHUNKS_HELD_PER_SUBSCRIBER_SIMULTANEOUSLY, ChunkQueueData_t>;
class ChunkBuildingBlocks_IntegrationTest : public Test
{
public:
ChunkBuildingBlocks_IntegrationTest()
{
m_mempoolConfig.addMemPool({SMALL_CHUNK, NUM_CHUNKS_IN_POOL});
m_memoryManager.configureMemoryManager(m_mempoolConfig, &m_memoryAllocator, &m_memoryAllocator);
}
virtual ~ChunkBuildingBlocks_IntegrationTest()
{
/// @note One chunk is on hold due to the fact that chunkSender and chunkDistributor hold last chunk
EXPECT_THAT(m_memoryManager.getMemPoolInfo(0).m_usedChunks, Eq(1));
}
void SetUp()
{
m_chunkSender.tryAddQueue(&m_chunkQueueData);
m_chunkDistributor.tryAddQueue(&m_chunkReceiverData);
}
void TearDown(){};
void publish()
{
for (size_t i = 0; i < ITERATIONS; i++)
{
m_chunkSender.tryAllocate(sizeof(DummySample), iox::UniquePortId())
.and_then([&](auto chunkHeader) {
auto sample = chunkHeader->payload();
new (sample) DummySample();
static_cast<DummySample*>(sample)->m_dummy = i;
m_chunkSender.send(chunkHeader);
m_sendCounter++;
})
.or_else([](AllocationError) {
// Errors shall never occur
FAIL();
});
/// Add some jitter to make thread breathe
std::this_thread::sleep_for(std::chrono::nanoseconds(rand() % 100));
}
// Signal the next threads we're done
m_publisherRun = false;
}
void forward()
{
uint64_t forwardCounter{0};
bool finished{false};
// this is to prevent a race condition on thread shutdown; there must be two consecutive empty pops after the
// publish thread finished
bool newChunkReceivedInLastIteration{true};
while (!finished)
{
ASSERT_FALSE(m_popper.hasOverflown());
m_popper.tryPop()
.and_then([&](auto& chunk) {
auto dummySample = *reinterpret_cast<DummySample*>(chunk.getPayload());
// Check if monotonically increasing
EXPECT_THAT(dummySample.m_dummy, Eq(forwardCounter));
m_chunkDistributor.deliverToAllStoredQueues(chunk);
forwardCounter++;
newChunkReceivedInLastIteration = true;
})
.or_else([&] {
if (!m_publisherRun.load(std::memory_order_relaxed))
{
if (newChunkReceivedInLastIteration)
{
newChunkReceivedInLastIteration = false;
}
else
{
finished = true;
}
}
});
}
// Signal the next threads we're done
m_forwarderRun = false;
}
void subscribe()
{
bool finished{false};
// this is to prevent a race condition on thread shutdown; there must be two consecutive empty pops after the
// forward thread finished
bool newChunkReceivedInLastIteration{true};
while (!finished)
{
ASSERT_FALSE(m_chunkReceiver.hasOverflown());
m_chunkReceiver.tryGet()
.and_then([&](iox::cxx::optional<const iox::mepoo::ChunkHeader*>& maybeChunkHeader) {
if (maybeChunkHeader.has_value())
{
auto chunkHeader = maybeChunkHeader.value();
auto dummySample = *reinterpret_cast<DummySample*>(chunkHeader->payload());
// Check if monotonically increasing
EXPECT_THAT(dummySample.m_dummy, Eq(m_receiveCounter));
m_receiveCounter++;
m_chunkReceiver.release(chunkHeader);
newChunkReceivedInLastIteration = true;
}
else if (!m_forwarderRun.load(std::memory_order_relaxed))
{
if (newChunkReceivedInLastIteration)
{
newChunkReceivedInLastIteration = false;
}
else
{
finished = true;
}
}
})
.or_else([](ChunkReceiveError) {
// Errors shall never occur
FAIL();
});
}
}
iox::cxx::GenericRAII m_uniqueRouDiId{[] { iox::popo::internal::setUniqueRouDiId(0); },
[] { iox::popo::internal::unsetUniqueRouDiId(); }};
uint64_t m_sendCounter{0};
uint64_t m_receiveCounter{0};
std::atomic<bool> m_publisherRun{true};
std::atomic<bool> m_forwarderRun{true};
// Memory objects
Allocator m_memoryAllocator{g_memory, MEMORY_SIZE};
MePooConfig m_mempoolConfig;
MemoryManager m_memoryManager;
// Objects used by publishing thread
ChunkSenderData_t m_chunkSenderData{&m_memoryManager};
ChunkSender<ChunkSenderData_t> m_chunkSender{&m_chunkSenderData};
// Objects used by forwarding thread
ChunkDistributorData_t m_chunkDistributorData;
ChunkDistributor_t m_chunkDistributor{&m_chunkDistributorData};
ChunkQueueData_t m_chunkQueueData{
iox::cxx::VariantQueueTypes::FiFo_SingleProducerSingleConsumer}; // SoFi intentionally not used
ChunkQueuePopper_t m_popper{&m_chunkQueueData};
// Objects used by subscribing thread
ChunkReceiverData_t m_chunkReceiverData{
iox::cxx::VariantQueueTypes::FiFo_SingleProducerSingleConsumer}; // SoFi intentionally not used
ChunkReceiver<ChunkReceiverData_t> m_chunkReceiver{&m_chunkReceiverData};
};
TEST_F(ChunkBuildingBlocks_IntegrationTest, TwoHopsThreeThreadsNoSoFi)
{
std::thread subscribingThread(&ChunkBuildingBlocks_IntegrationTest::subscribe, this);
std::thread forwardingThread(&ChunkBuildingBlocks_IntegrationTest::forward, this);
std::thread publishingThread(&ChunkBuildingBlocks_IntegrationTest::publish, this);
if (publishingThread.joinable())
{
publishingThread.join();
}
if (forwardingThread.joinable())
{
forwardingThread.join();
}
if (subscribingThread.joinable())
{
subscribingThread.join();
}
EXPECT_EQ(m_sendCounter, m_receiveCounter);
}
<|endoftext|>
|
<commit_before>// Copyright 2014 Open Source Robotics Foundation, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#ifndef ROSIDL_TYPESUPPORT_INTROSPECTION_CPP__MESSAGE_INTROSPECTION_HPP_
#define ROSIDL_TYPESUPPORT_INTROSPECTION_CPP__MESSAGE_INTROSPECTION_HPP_
#include <cstddef>
#include <cstdint>
#include "rosidl_generator_c/message_type_support.h"
#include "rosidl_typesupport_introspection_cpp/visibility_control.h"
namespace rosidl_typesupport_introspection_cpp
{
struct ROSIDL_TYPESUPPORT_INTROSPECTION_CPP_PUBLIC MessageMembers;
typedef struct ROSIDL_TYPESUPPORT_INTROSPECTION_CPP_PUBLIC MessageMember
{
const char * name_;
uint8_t type_id_;
size_t string_upper_bound_;
const rosidl_message_type_support_t * members_;
bool is_array_;
size_t array_size_;
bool is_upper_bound_;
unsigned long offset_;
const void * default_value_;
size_t (* size_function)(const void *);
const void * (*get_const_function)(const void *, size_t index);
void * (*get_function)(void *, size_t index);
void (* resize_function)(void *, size_t size);
} MessageMember;
typedef struct ROSIDL_TYPESUPPORT_INTROSPECTION_CPP_PUBLIC MessageMembers
{
const char * package_name_;
const char * message_name_;
unsigned long member_count_;
const MessageMember * members_;
} MessageMembers;
} // namespace rosidl_typesupport_introspection_cpp
#endif // ROSIDL_TYPESUPPORT_INTROSPECTION_CPP__MESSAGE_INTROSPECTION_HPP_
<commit_msg>Replace unsigned long with uint32_t<commit_after>// Copyright 2014 Open Source Robotics Foundation, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#ifndef ROSIDL_TYPESUPPORT_INTROSPECTION_CPP__MESSAGE_INTROSPECTION_HPP_
#define ROSIDL_TYPESUPPORT_INTROSPECTION_CPP__MESSAGE_INTROSPECTION_HPP_
#include <cstddef>
#include <cstdint>
#include "rosidl_generator_c/message_type_support.h"
#include "rosidl_typesupport_introspection_cpp/visibility_control.h"
namespace rosidl_typesupport_introspection_cpp
{
struct ROSIDL_TYPESUPPORT_INTROSPECTION_CPP_PUBLIC MessageMembers;
typedef struct ROSIDL_TYPESUPPORT_INTROSPECTION_CPP_PUBLIC MessageMember
{
const char * name_;
uint8_t type_id_;
size_t string_upper_bound_;
const rosidl_message_type_support_t * members_;
bool is_array_;
size_t array_size_;
bool is_upper_bound_;
uint32_t offset_;
const void * default_value_;
size_t (* size_function)(const void *);
const void * (*get_const_function)(const void *, size_t index);
void * (*get_function)(void *, size_t index);
void (* resize_function)(void *, size_t size);
} MessageMember;
typedef struct ROSIDL_TYPESUPPORT_INTROSPECTION_CPP_PUBLIC MessageMembers
{
const char * package_name_;
const char * message_name_;
uint32_t member_count_;
const MessageMember * members_;
} MessageMembers;
} // namespace rosidl_typesupport_introspection_cpp
#endif // ROSIDL_TYPESUPPORT_INTROSPECTION_CPP__MESSAGE_INTROSPECTION_HPP_
<|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 "base/message_pump_libevent.h"
#include <errno.h>
#include <fcntl.h>
#include "base/logging.h"
#include "base/scoped_nsautorelease_pool.h"
#include "base/time.h"
#include "third_party/libevent/event.h"
namespace base {
// Return 0 on success
// Too small a function to bother putting in a library?
static int SetNonBlocking(int fd) {
int flags = fcntl(fd, F_GETFL, 0);
if (flags == -1)
flags = 0;
return fcntl(fd, F_SETFL, flags | O_NONBLOCK);
}
MessagePumpLibevent::FileDescriptorWatcher::FileDescriptorWatcher()
: is_persistent_(false),
event_(NULL) {
}
MessagePumpLibevent::FileDescriptorWatcher::~FileDescriptorWatcher() {
if (event_.get()) {
StopWatchingFileDescriptor();
}
}
void MessagePumpLibevent::FileDescriptorWatcher::Init(event *e,
bool is_persistent) {
DCHECK(e);
DCHECK(event_.get() == NULL);
is_persistent_ = is_persistent;
event_.reset(e);
}
event *MessagePumpLibevent::FileDescriptorWatcher::ReleaseEvent() {
return event_.release();
}
bool MessagePumpLibevent::FileDescriptorWatcher::StopWatchingFileDescriptor() {
if (event_.get() == NULL) {
return true;
}
// event_del() is a no-op of the event isn't active.
return (event_del(event_.get()) == 0);
}
// Called if a byte is received on the wakeup pipe.
void MessagePumpLibevent::OnWakeup(int socket, short flags, void* context) {
base::MessagePumpLibevent* that =
static_cast<base::MessagePumpLibevent*>(context);
DCHECK(that->wakeup_pipe_out_ == socket);
// Remove and discard the wakeup byte.
char buf;
int nread = read(socket, &buf, 1);
DCHECK(nread == 1);
// Tell libevent to break out of inner loop.
event_base_loopbreak(that->event_base_);
}
MessagePumpLibevent::MessagePumpLibevent()
: keep_running_(true),
in_run_(false),
event_base_(event_base_new()),
wakeup_pipe_in_(-1),
wakeup_pipe_out_(-1) {
if (!Init())
NOTREACHED();
}
bool MessagePumpLibevent::Init() {
int fds[2];
if (pipe(fds)) {
DLOG(ERROR) << "pipe() failed, errno: " << errno;
return false;
}
if (SetNonBlocking(fds[0])) {
DLOG(ERROR) << "SetNonBlocking for pipe fd[0] failed, errno: " << errno;
return false;
}
if (SetNonBlocking(fds[1])) {
DLOG(ERROR) << "SetNonBlocking for pipe fd[1] failed, errno: " << errno;
return false;
}
wakeup_pipe_out_ = fds[0];
wakeup_pipe_in_ = fds[1];
wakeup_event_ = new event;
event_set(wakeup_event_, wakeup_pipe_out_, EV_READ | EV_PERSIST,
OnWakeup, this);
event_base_set(event_base_, wakeup_event_);
if (event_add(wakeup_event_, 0))
return false;
return true;
}
MessagePumpLibevent::~MessagePumpLibevent() {
DCHECK(wakeup_event_);
DCHECK(event_base_);
event_del(wakeup_event_);
delete wakeup_event_;
event_base_free(event_base_);
}
bool MessagePumpLibevent::WatchFileDescriptor(int fd,
bool persistent,
Mode mode,
FileDescriptorWatcher *controller,
Watcher *delegate) {
DCHECK(fd > 0);
DCHECK(controller);
DCHECK(delegate);
DCHECK(mode == WATCH_READ || mode == WATCH_WRITE || mode == WATCH_READ_WRITE);
int event_mask = persistent ? EV_PERSIST : 0;
if ((mode & WATCH_READ) != 0) {
event_mask |= EV_READ;
}
if ((mode & WATCH_WRITE) != 0) {
event_mask |= EV_WRITE;
}
// |should_delete_event| is true if we're modifying an event that's currently
// active in |controller|.
// If we're modifying an existing event and there's an error then we need to
// tell libevent to clean it up via event_delete() before returning.
bool should_delete_event = true;
scoped_ptr<event> evt(controller->ReleaseEvent());
if (evt.get() == NULL) {
should_delete_event = false;
// Ownership is transferred to the controller.
evt.reset(new event);
}
// Set current interest mask and message pump for this event.
event_set(evt.get(), fd, event_mask, OnLibeventNotification,
delegate);
// Tell libevent which message pump this socket will belong to when we add it.
if (event_base_set(event_base_, evt.get()) != 0) {
if (should_delete_event) {
event_del(evt.get());
}
return false;
}
// Add this socket to the list of monitored sockets.
if (event_add(evt.get(), NULL) != 0) {
if (should_delete_event) {
event_del(evt.get());
}
return false;
}
// Transfer ownership of e to controller.
controller->Init(evt.release(), persistent);
return true;
}
void MessagePumpLibevent::OnLibeventNotification(int fd, short flags,
void* context) {
Watcher* watcher = static_cast<Watcher*>(context);
if (flags & EV_WRITE) {
watcher->OnFileCanWriteWithoutBlocking(fd);
}
if (flags & EV_READ) {
watcher->OnFileCanReadWithoutBlocking(fd);
}
}
// Reentrant!
void MessagePumpLibevent::Run(Delegate* delegate) {
DCHECK(keep_running_) << "Quit must have been called outside of Run!";
bool old_in_run = in_run_;
in_run_ = true;
for (;;) {
ScopedNSAutoreleasePool autorelease_pool;
bool did_work = delegate->DoWork();
if (!keep_running_)
break;
did_work |= delegate->DoDelayedWork(&delayed_work_time_);
if (!keep_running_)
break;
if (did_work)
continue;
did_work = delegate->DoIdleWork();
if (!keep_running_)
break;
if (did_work)
continue;
// EVLOOP_ONCE tells libevent to only block once,
// but to service all pending events when it wakes up.
if (delayed_work_time_.is_null()) {
event_base_loop(event_base_, EVLOOP_ONCE);
} else {
TimeDelta delay = delayed_work_time_ - Time::Now();
if (delay > TimeDelta()) {
struct timeval poll_tv;
poll_tv.tv_sec = delay.InSeconds();
poll_tv.tv_usec = delay.InMicroseconds() % Time::kMicrosecondsPerSecond;
event_base_loopexit(event_base_, &poll_tv);
event_base_loop(event_base_, EVLOOP_ONCE);
} else {
// It looks like delayed_work_time_ indicates a time in the past, so we
// need to call DoDelayedWork now.
delayed_work_time_ = Time();
}
}
}
keep_running_ = true;
in_run_ = old_in_run;
}
void MessagePumpLibevent::Quit() {
DCHECK(in_run_);
// Tell both libevent and Run that they should break out of their loops.
keep_running_ = false;
ScheduleWork();
}
void MessagePumpLibevent::ScheduleWork() {
// Tell libevent (in a threadsafe way) that it should break out of its loop.
char buf = 0;
int nwrite = write(wakeup_pipe_in_, &buf, 1);
DCHECK(nwrite == 1);
}
void MessagePumpLibevent::ScheduleDelayedWork(const Time& delayed_work_time) {
// We know that we can't be blocked on Wait right now since this method can
// only be called on the same thread as Run, so we only need to update our
// record of how long to sleep when we do sleep.
delayed_work_time_ = delayed_work_time;
}
} // namespace base
<commit_msg>The dtor wasn't actually cleaning up the fds from the pipe, so close them down during shutdown. (this w/ the zombies was what caused the bots to run out of fds) Review URL: http://codereview.chromium.org/20006<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 "base/message_pump_libevent.h"
#include <errno.h>
#include <fcntl.h>
#include "base/logging.h"
#include "base/scoped_nsautorelease_pool.h"
#include "base/time.h"
#include "third_party/libevent/event.h"
namespace base {
// Return 0 on success
// Too small a function to bother putting in a library?
static int SetNonBlocking(int fd) {
int flags = fcntl(fd, F_GETFL, 0);
if (flags == -1)
flags = 0;
return fcntl(fd, F_SETFL, flags | O_NONBLOCK);
}
MessagePumpLibevent::FileDescriptorWatcher::FileDescriptorWatcher()
: is_persistent_(false),
event_(NULL) {
}
MessagePumpLibevent::FileDescriptorWatcher::~FileDescriptorWatcher() {
if (event_.get()) {
StopWatchingFileDescriptor();
}
}
void MessagePumpLibevent::FileDescriptorWatcher::Init(event *e,
bool is_persistent) {
DCHECK(e);
DCHECK(event_.get() == NULL);
is_persistent_ = is_persistent;
event_.reset(e);
}
event *MessagePumpLibevent::FileDescriptorWatcher::ReleaseEvent() {
return event_.release();
}
bool MessagePumpLibevent::FileDescriptorWatcher::StopWatchingFileDescriptor() {
if (event_.get() == NULL) {
return true;
}
// event_del() is a no-op of the event isn't active.
return (event_del(event_.get()) == 0);
}
// Called if a byte is received on the wakeup pipe.
void MessagePumpLibevent::OnWakeup(int socket, short flags, void* context) {
base::MessagePumpLibevent* that =
static_cast<base::MessagePumpLibevent*>(context);
DCHECK(that->wakeup_pipe_out_ == socket);
// Remove and discard the wakeup byte.
char buf;
int nread = read(socket, &buf, 1);
DCHECK(nread == 1);
// Tell libevent to break out of inner loop.
event_base_loopbreak(that->event_base_);
}
MessagePumpLibevent::MessagePumpLibevent()
: keep_running_(true),
in_run_(false),
event_base_(event_base_new()),
wakeup_pipe_in_(-1),
wakeup_pipe_out_(-1) {
if (!Init())
NOTREACHED();
}
bool MessagePumpLibevent::Init() {
int fds[2];
if (pipe(fds)) {
DLOG(ERROR) << "pipe() failed, errno: " << errno;
return false;
}
if (SetNonBlocking(fds[0])) {
DLOG(ERROR) << "SetNonBlocking for pipe fd[0] failed, errno: " << errno;
return false;
}
if (SetNonBlocking(fds[1])) {
DLOG(ERROR) << "SetNonBlocking for pipe fd[1] failed, errno: " << errno;
return false;
}
wakeup_pipe_out_ = fds[0];
wakeup_pipe_in_ = fds[1];
wakeup_event_ = new event;
event_set(wakeup_event_, wakeup_pipe_out_, EV_READ | EV_PERSIST,
OnWakeup, this);
event_base_set(event_base_, wakeup_event_);
if (event_add(wakeup_event_, 0))
return false;
return true;
}
MessagePumpLibevent::~MessagePumpLibevent() {
DCHECK(wakeup_event_);
DCHECK(event_base_);
event_del(wakeup_event_);
delete wakeup_event_;
if (wakeup_pipe_in_ >= 0)
close(wakeup_pipe_in_);
if (wakeup_pipe_out_ >= 0)
close(wakeup_pipe_out_);
event_base_free(event_base_);
}
bool MessagePumpLibevent::WatchFileDescriptor(int fd,
bool persistent,
Mode mode,
FileDescriptorWatcher *controller,
Watcher *delegate) {
DCHECK(fd > 0);
DCHECK(controller);
DCHECK(delegate);
DCHECK(mode == WATCH_READ || mode == WATCH_WRITE || mode == WATCH_READ_WRITE);
int event_mask = persistent ? EV_PERSIST : 0;
if ((mode & WATCH_READ) != 0) {
event_mask |= EV_READ;
}
if ((mode & WATCH_WRITE) != 0) {
event_mask |= EV_WRITE;
}
// |should_delete_event| is true if we're modifying an event that's currently
// active in |controller|.
// If we're modifying an existing event and there's an error then we need to
// tell libevent to clean it up via event_delete() before returning.
bool should_delete_event = true;
scoped_ptr<event> evt(controller->ReleaseEvent());
if (evt.get() == NULL) {
should_delete_event = false;
// Ownership is transferred to the controller.
evt.reset(new event);
}
// Set current interest mask and message pump for this event.
event_set(evt.get(), fd, event_mask, OnLibeventNotification,
delegate);
// Tell libevent which message pump this socket will belong to when we add it.
if (event_base_set(event_base_, evt.get()) != 0) {
if (should_delete_event) {
event_del(evt.get());
}
return false;
}
// Add this socket to the list of monitored sockets.
if (event_add(evt.get(), NULL) != 0) {
if (should_delete_event) {
event_del(evt.get());
}
return false;
}
// Transfer ownership of e to controller.
controller->Init(evt.release(), persistent);
return true;
}
void MessagePumpLibevent::OnLibeventNotification(int fd, short flags,
void* context) {
Watcher* watcher = static_cast<Watcher*>(context);
if (flags & EV_WRITE) {
watcher->OnFileCanWriteWithoutBlocking(fd);
}
if (flags & EV_READ) {
watcher->OnFileCanReadWithoutBlocking(fd);
}
}
// Reentrant!
void MessagePumpLibevent::Run(Delegate* delegate) {
DCHECK(keep_running_) << "Quit must have been called outside of Run!";
bool old_in_run = in_run_;
in_run_ = true;
for (;;) {
ScopedNSAutoreleasePool autorelease_pool;
bool did_work = delegate->DoWork();
if (!keep_running_)
break;
did_work |= delegate->DoDelayedWork(&delayed_work_time_);
if (!keep_running_)
break;
if (did_work)
continue;
did_work = delegate->DoIdleWork();
if (!keep_running_)
break;
if (did_work)
continue;
// EVLOOP_ONCE tells libevent to only block once,
// but to service all pending events when it wakes up.
if (delayed_work_time_.is_null()) {
event_base_loop(event_base_, EVLOOP_ONCE);
} else {
TimeDelta delay = delayed_work_time_ - Time::Now();
if (delay > TimeDelta()) {
struct timeval poll_tv;
poll_tv.tv_sec = delay.InSeconds();
poll_tv.tv_usec = delay.InMicroseconds() % Time::kMicrosecondsPerSecond;
event_base_loopexit(event_base_, &poll_tv);
event_base_loop(event_base_, EVLOOP_ONCE);
} else {
// It looks like delayed_work_time_ indicates a time in the past, so we
// need to call DoDelayedWork now.
delayed_work_time_ = Time();
}
}
}
keep_running_ = true;
in_run_ = old_in_run;
}
void MessagePumpLibevent::Quit() {
DCHECK(in_run_);
// Tell both libevent and Run that they should break out of their loops.
keep_running_ = false;
ScheduleWork();
}
void MessagePumpLibevent::ScheduleWork() {
// Tell libevent (in a threadsafe way) that it should break out of its loop.
char buf = 0;
int nwrite = write(wakeup_pipe_in_, &buf, 1);
DCHECK(nwrite == 1);
}
void MessagePumpLibevent::ScheduleDelayedWork(const Time& delayed_work_time) {
// We know that we can't be blocked on Wait right now since this method can
// only be called on the same thread as Run, so we only need to update our
// record of how long to sleep when we do sleep.
delayed_work_time_ = delayed_work_time;
}
} // namespace base
<|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/path_service.h"
#include "base/basictypes.h"
#include "base/file_util.h"
#include "base/file_path.h"
#if defined(OS_WIN)
#include "base/win/windows_version.h"
#endif
#include "testing/gtest/include/gtest/gtest.h"
#include "testing/gtest/include/gtest/gtest-spi.h"
#include "testing/platform_test.h"
namespace {
// Returns true if PathService::Get returns true and sets the path parameter
// to non-empty for the given PathService::DirType enumeration value.
bool ReturnsValidPath(int dir_type) {
FilePath path;
bool result = PathService::Get(dir_type, &path);
return result && !path.value().empty() && file_util::PathExists(path);
}
#if defined(OS_WIN)
// Function to test DIR_LOCAL_APP_DATA_LOW on Windows XP. Make sure it fails.
bool ReturnsInvalidPath(int dir_type) {
FilePath path;
bool result = PathService::Get(base::DIR_LOCAL_APP_DATA_LOW, &path);
return !result && path.empty();
}
#endif
} // namespace
// On the Mac this winds up using some autoreleased objects, so we need to
// be a PlatformTest.
typedef PlatformTest PathServiceTest;
// Test that all PathService::Get calls return a value and a true result
// in the development environment. (This test was created because a few
// later changes to Get broke the semantics of the function and yielded the
// correct value while returning false.)
TEST_F(PathServiceTest, Get) {
for (int key = base::DIR_CURRENT; key < base::PATH_END; ++key) {
EXPECT_PRED1(ReturnsValidPath, key);
}
#if defined(OS_WIN)
for (int key = base::PATH_WIN_START + 1; key < base::PATH_WIN_END; ++key) {
if (key == base::DIR_LOCAL_APP_DATA_LOW &&
base::win::GetVersion() < base::win::VERSION_VISTA) {
// DIR_LOCAL_APP_DATA_LOW is not supported prior Vista and is expected to
// fail.
EXPECT_TRUE(ReturnsInvalidPath(key)) << key;
} else {
EXPECT_TRUE(ReturnsValidPath(key)) << key;
}
}
#elif defined(OS_MACOSX)
for (int key = base::PATH_MAC_START + 1; key < base::PATH_MAC_END; ++key) {
EXPECT_PRED1(ReturnsValidPath, key);
}
#endif
}
<commit_msg>If chromium has not been started yet, the cache path will not exist.<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/path_service.h"
#include "base/basictypes.h"
#include "base/file_util.h"
#include "base/file_path.h"
#if defined(OS_WIN)
#include "base/win/windows_version.h"
#endif
#include "testing/gtest/include/gtest/gtest.h"
#include "testing/gtest/include/gtest/gtest-spi.h"
#include "testing/platform_test.h"
namespace {
// Returns true if PathService::Get returns true and sets the path parameter
// to non-empty for the given PathService::DirType enumeration value.
bool ReturnsValidPath(int dir_type) {
FilePath path;
bool result = PathService::Get(dir_type, &path);
#if defined(OS_POSIX)
// If chromium has never been started on this account, the cache path will not
// exist.
if (dir_type == base::DIR_USER_CACHE)
return result && !path.value().empty();
#endif
return result && !path.value().empty() && file_util::PathExists(path);
}
#if defined(OS_WIN)
// Function to test DIR_LOCAL_APP_DATA_LOW on Windows XP. Make sure it fails.
bool ReturnsInvalidPath(int dir_type) {
FilePath path;
bool result = PathService::Get(base::DIR_LOCAL_APP_DATA_LOW, &path);
return !result && path.empty();
}
#endif
} // namespace
// On the Mac this winds up using some autoreleased objects, so we need to
// be a PlatformTest.
typedef PlatformTest PathServiceTest;
// Test that all PathService::Get calls return a value and a true result
// in the development environment. (This test was created because a few
// later changes to Get broke the semantics of the function and yielded the
// correct value while returning false.)
TEST_F(PathServiceTest, Get) {
for (int key = base::DIR_CURRENT; key < base::PATH_END; ++key) {
EXPECT_PRED1(ReturnsValidPath, key);
}
#if defined(OS_WIN)
for (int key = base::PATH_WIN_START + 1; key < base::PATH_WIN_END; ++key) {
if (key == base::DIR_LOCAL_APP_DATA_LOW &&
base::win::GetVersion() < base::win::VERSION_VISTA) {
// DIR_LOCAL_APP_DATA_LOW is not supported prior Vista and is expected to
// fail.
EXPECT_TRUE(ReturnsInvalidPath(key)) << key;
} else {
EXPECT_TRUE(ReturnsValidPath(key)) << key;
}
}
#elif defined(OS_MACOSX)
for (int key = base::PATH_MAC_START + 1; key < base::PATH_MAC_END; ++key) {
EXPECT_PRED1(ReturnsValidPath, key);
}
#endif
}
<|endoftext|>
|
<commit_before>// @(#)root/base:$Name: $:$Id: TVirtualProofMgr.cxx,v 1.7 2006/06/02 15:14:35 rdm Exp $
// Author: G. Ganis, Nov 2005
/*************************************************************************
* Copyright (C) 1995-2005, Rene Brun and Fons Rademakers. *
* All rights reserved. *
* *
* For the licensing terms see $ROOTSYS/LICENSE. *
* For the list of contributors see $ROOTSYS/README/CREDITS. *
*************************************************************************/
//////////////////////////////////////////////////////////////////////////
// //
// TVirtualProofMgr //
// //
// Abstract interface to the manager for PROOF sessions. //
// The PROOF manager interacts with the PROOF server coordinator to //
// create or destroy a PROOF session, attach to or detach from //
// existing one, and to monitor any client activity on the cluster. //
// At most one manager instance per server is allowed. //
// //
//////////////////////////////////////////////////////////////////////////
#ifdef HAVE_CONFIG
#include "config.h"
#endif
#include "TError.h"
#include "TInetAddress.h"
#include "TList.h"
#include "TROOT.h"
#include "TSystem.h"
#include "TVirtualMutex.h"
#include "TVirtualProof.h"
#include "TVirtualProofMgr.h"
ClassImp(TVirtualProofMgr)
// Sub-list of TROOT::fProofs with managers
TList TVirtualProofMgr::fgListOfManagers;
TVirtualProofMgr_t TVirtualProofMgr::fgTProofMgrHook[2] = { 0, 0 };
//______________________________________________________________________________
TVirtualProofMgr::TVirtualProofMgr(const char *url, Int_t, const char *)
: TNamed("",""), fRemoteProtocol(-1),
fServType(kXProofd), fSessions(0)
{
// Constructor
// AVoid problems with empty URLs
fUrl = (!url || strlen(url) <= 0) ? TUrl("proof://localhost") : TUrl(url);
}
//______________________________________________________________________________
TVirtualProofMgr::~TVirtualProofMgr()
{
// Destroy a TVirtualProofMgr instance
SafeDelete(fSessions);
fgListOfManagers.Remove(this);
gROOT->GetListOfProofs()->Remove(this);
}
//______________________________________________________________________________
void TVirtualProofMgr::ShowWorkers()
{
// Show available workers
AbstractMethod("ShowWorkers");
}
//______________________________________________________________________________
TVirtualProofDesc *TVirtualProofMgr::GetProofDesc(Int_t id)
{
// Get TVirtualProof instance corresponding to 'id'.
if (id > 0) {
TVirtualProofDesc *d = 0;
// Retrieve an updated list
QuerySessions("");
if (fSessions) {
TIter nxd(fSessions);
while ((d = (TVirtualProofDesc *)nxd())) {
if (d->MatchId(id))
return d;
}
}
}
return 0;
}
//______________________________________________________________________________
void TVirtualProofMgr::ShutdownSession(TVirtualProof *p)
{
// Discard PROOF session 'p'
if (p) {
TVirtualProofDesc *d = 0;
if (fSessions) {
TIter nxd(fSessions);
while ((d = (TVirtualProofDesc *)nxd())) {
if (p == d->GetProof()) {
fSessions->Remove(d);
delete d;
break;
}
}
}
}
}
//______________________________________________________________________________
TVirtualProof *TVirtualProofMgr::CreateSession(const char *cfg,
const char *cfgdir, Int_t loglevel)
{
// Create a new remote session (master and associated workers).
// Create
if (IsProofd())
fUrl.SetOptions("std");
TProof_t proofhook = TVirtualProof::GetTProofHook();
if (!proofhook) {
// Load the library containing TProof ...
#ifdef ROOTLIBDIR
TString prooflib = TString(ROOTLIBDIR) + "/libProof";
#else
#ifndef WIN32
TString prooflib = TString(gRootDir) + "/lib/libProof";
#else
TString prooflib = TString(gRootDir) + "/bin/libProof";
#endif
#endif
char *p = 0;
if ((p = gSystem->DynamicPathName(prooflib, kTRUE))) {
delete[] p;
if (gSystem->Load(prooflib) == -1)
Error("CreateSession", "can't load %s", prooflib.Data());
proofhook = TVirtualProof::GetTProofHook();
} else
Error("CreateSession", "can't locate %s", prooflib.Data());
}
if (!proofhook) {
Error("CreateSession", "hook for TVirtualProof could not be loaded");
return 0;
}
// Create the instance
TVirtualProof *p =
(TVirtualProof*) (*proofhook)(fUrl.GetUrl(), cfg, cfgdir, loglevel, 0);
if (p && p->IsValid()) {
// Set reference manager
p->SetManager(this);
// Save record about this session
Int_t ns = 1;
if (fSessions) {
// To avoid ambiguities in case of removal of some elements
if (fSessions->Last())
ns = ((TVirtualProofDesc *)(fSessions->Last()))->GetLocalId() + 1;
} else {
// Create the list
fSessions = new TList;
}
// Create the description class
Int_t st = (p->IsIdle()) ? TVirtualProofDesc::kIdle : TVirtualProofDesc::kRunning ;
TVirtualProofDesc *d =
new TVirtualProofDesc(p->GetName(), p->GetTitle(), p->GetUrl(),
ns, p->GetSessionID(), st, p);
fSessions->Add(d);
} else {
// Session creation failed
Error("CreateSession", "creating PROOF session");
SafeDelete(p);
}
// We are done
return p;
}
//______________________________________________________________________________
Bool_t TVirtualProofMgr::MatchUrl(const char *url)
{
// Checks if 'url' refers to the same 'user@host:port' entity as the URL
// in memory
TUrl u(url);
// Correct URL protocol
if (!strcmp(u.GetProtocol(), TUrl("a").GetProtocol()))
u.SetProtocol("proof");
// Correct port
if (u.GetPort() == TUrl("a").GetPort()) {
Int_t port = gSystem->GetServiceByName("rootd");
if (port < 0)
port = 1094;
u.SetPort(port);
}
// Now we can check
if (!strcmp(u.GetHostFQDN(), fUrl.GetHostFQDN()))
if (u.GetPort() == fUrl.GetPort())
if (strlen(u.GetUser()) <= 0 || !strcmp(u.GetUser(),fUrl.GetUser()))
return kTRUE;
// Match failed
return kFALSE;
}
//________________________________________________________________________
TList *TVirtualProofMgr::GetListOfManagers()
{
// Extract pointers to PROOF managers from TROOT::fProofs.
// Update the list with new entries
if (gROOT->GetListOfProofs()) {
TIter nxp(gROOT->GetListOfProofs());
TVirtualProofMgr *p = 0;
while ((p = dynamic_cast<TVirtualProofMgr *> (nxp())))
if (!fgListOfManagers.FindObject(p))
fgListOfManagers.Add(p);
}
// Get rid of invalid entries and notify
if (fgListOfManagers.GetSize() > 0) {
TIter nxp(&fgListOfManagers);
TObject *o = 0;
Int_t nm = 0;
while ((o = nxp())) {
if (!(gROOT->GetListOfProofs()->FindObject(o))) {
fgListOfManagers.Remove(o);
} else {
TVirtualProofMgr *p = (TVirtualProofMgr *)o;
Printf("// #%d: \"%s\" (%s)", ++nm, p->GetName(), p->GetTitle());
}
}
} else {
if (gDebug > 0)
Printf("No managers found");
}
// We are done
return &fgListOfManagers;
}
//______________________________________________________________________________
TVirtualProofMgr *TVirtualProofMgr::Create(const char *url, Int_t loglevel,
const char *alias, Bool_t xpd)
{
// Static method returning the appropriate TProofMgr object using
// the plugin manager.
TVirtualProofMgr *m= 0;
// Make sure we do not have already a manager for this URL
TList *lm = TVirtualProofMgr::GetListOfManagers();
if (lm) {
TIter nxm(lm);
while ((m = (TVirtualProofMgr *)nxm()))
if (m->MatchUrl(url))
if (m->IsValid()) {
return m;
} else {
fgListOfManagers.Remove(m);
SafeDelete(m);
break;
}
}
m = 0;
Bool_t trystd = kTRUE;
// If required, we assume first that the remote server is based on XrdProofd
if (xpd) {
TVirtualProofMgr_t cm = TVirtualProofMgr::GetProofMgrHook("xpd");
if (cm) {
m = (TVirtualProofMgr *) (*cm)(url, loglevel, alias);
// Update trystd flag
trystd = (m && !(m->IsValid()) && m->IsProofd()) ? kTRUE : kFALSE;
}
}
// If the first attempt failed, we instantiate an old interface
if (trystd) {
SafeDelete(m);
TVirtualProofMgr_t cm = TVirtualProofMgr::GetProofMgrHook("std");
if (cm)
m = (TVirtualProofMgr *) (*cm)(url, loglevel, alias);
}
// Record the new manager, if any
if (m) {
fgListOfManagers.Add(m);
if (m->IsValid() && !(m->IsProofd())) {
R__LOCKGUARD2(gROOTMutex);
gROOT->GetListOfProofs()->Add(m);
gROOT->GetListOfSockets()->Add(m);
}
}
// We are done
return m;
}
//________________________________________________________________________
TVirtualProofMgr_t TVirtualProofMgr::GetProofMgrHook(const char *type)
{
// Get the specified constructor hook.
// We do this without the plugin manager because it blocks the
// CINT mutex breaking the parallel startup.
static const char *libs[] = { "/libProof", "/libProofx" };
// Find index (default: classic)
Int_t idx = (type && !strncmp(type,"xpd",3)) ? 1 : 0;
if (!fgTProofMgrHook[idx]) {
// Load the appropriate library ...
#ifdef ROOTLIBDIR
TString prooflib = TString(ROOTLIBDIR);
#else
#ifndef WIN32
TString prooflib = TString(gRootDir) + "/lib";
#else
TString prooflib = TString(gRootDir) + "/bin";
#endif
#endif
prooflib += libs[idx];
char *p = 0;
if ((p = gSystem->DynamicPathName(prooflib, kTRUE))) {
delete[] p;
if (gSystem->Load(prooflib) == -1)
::Error("TVirtualProofMgr::GetProofMgrCtor",
"can't load %s", prooflib.Data());
} else
::Error("TVirtualProofMgr::GetProofMgrCtor",
"can't locate %s", prooflib.Data());
}
// Done
return fgTProofMgrHook[idx];
}
//_____________________________________________________________________________
void TVirtualProofMgr::SetTProofMgrHook(TVirtualProofMgr_t pmh, const char *t)
{
// Set hook to TProofMgr ctor
// Find index (default: classic)
Int_t idx = (t && !strncmp(t,"xpd",3)) ? 1 : 0;
fgTProofMgrHook[idx] = pmh;
}
ClassImp(TVirtualProofDesc)
//________________________________________________________________________
void TVirtualProofDesc::Print(Option_t *) const
{
// Dump the content to the screen.
const char *st[] = { "unknown", "idle", "processsing", "shutting down"};
Printf("// # %d", fLocalId);
Printf("// alias: %s, url: \"%s\"", GetTitle(), GetUrl());
Printf("// tag: %s", GetName());
Printf("// status: %s, attached: %s (remote ID: %d)",
st[fStatus+1], (fProof ? "YES" : "NO"), fRemoteId);
}
<commit_msg>Fix coding convention violation<commit_after>// @(#)root/base:$Name: $:$Id: TVirtualProofMgr.cxx,v 1.8 2006/06/21 16:18:26 rdm Exp $
// Author: G. Ganis, Nov 2005
/*************************************************************************
* Copyright (C) 1995-2005, Rene Brun and Fons Rademakers. *
* All rights reserved. *
* *
* For the licensing terms see $ROOTSYS/LICENSE. *
* For the list of contributors see $ROOTSYS/README/CREDITS. *
*************************************************************************/
//////////////////////////////////////////////////////////////////////////
// //
// TVirtualProofMgr //
// //
// Abstract interface to the manager for PROOF sessions. //
// The PROOF manager interacts with the PROOF server coordinator to //
// create or destroy a PROOF session, attach to or detach from //
// existing one, and to monitor any client activity on the cluster. //
// At most one manager instance per server is allowed. //
// //
//////////////////////////////////////////////////////////////////////////
#ifdef HAVE_CONFIG
#include "config.h"
#endif
#include "TError.h"
#include "TInetAddress.h"
#include "TList.h"
#include "TROOT.h"
#include "TSystem.h"
#include "TVirtualMutex.h"
#include "TVirtualProof.h"
#include "TVirtualProofMgr.h"
ClassImp(TVirtualProofMgr)
// Sub-list of TROOT::fProofs with managers
TList TVirtualProofMgr::fgListOfManagers;
TVirtualProofMgr_t TVirtualProofMgr::fgTProofMgrHook[2] = { 0, 0 };
//______________________________________________________________________________
TVirtualProofMgr::TVirtualProofMgr(const char *url, Int_t, const char *)
: TNamed("",""), fRemoteProtocol(-1),
fServType(kXProofd), fSessions(0)
{
// Constructor
// AVoid problems with empty URLs
fUrl = (!url || strlen(url) <= 0) ? TUrl("proof://localhost") : TUrl(url);
}
//______________________________________________________________________________
TVirtualProofMgr::~TVirtualProofMgr()
{
// Destroy a TVirtualProofMgr instance
SafeDelete(fSessions);
fgListOfManagers.Remove(this);
gROOT->GetListOfProofs()->Remove(this);
}
//______________________________________________________________________________
void TVirtualProofMgr::ShowWorkers()
{
// Show available workers
AbstractMethod("ShowWorkers");
}
//______________________________________________________________________________
TVirtualProofDesc *TVirtualProofMgr::GetProofDesc(Int_t id)
{
// Get TVirtualProof instance corresponding to 'id'.
if (id > 0) {
TVirtualProofDesc *d = 0;
// Retrieve an updated list
QuerySessions("");
if (fSessions) {
TIter nxd(fSessions);
while ((d = (TVirtualProofDesc *)nxd())) {
if (d->MatchId(id))
return d;
}
}
}
return 0;
}
//______________________________________________________________________________
void TVirtualProofMgr::ShutdownSession(TVirtualProof *p)
{
// Discard PROOF session 'p'
if (p) {
TVirtualProofDesc *d = 0;
if (fSessions) {
TIter nxd(fSessions);
while ((d = (TVirtualProofDesc *)nxd())) {
if (p == d->GetProof()) {
fSessions->Remove(d);
delete d;
break;
}
}
}
}
}
//______________________________________________________________________________
TVirtualProof *TVirtualProofMgr::CreateSession(const char *cfg,
const char *cfgdir, Int_t loglevel)
{
// Create a new remote session (master and associated workers).
// Create
if (IsProofd())
fUrl.SetOptions("std");
TProof_t proofhook = TVirtualProof::GetTProofHook();
if (!proofhook) {
// Load the library containing TProof ...
#ifdef ROOTLIBDIR
TString prooflib = TString(ROOTLIBDIR) + "/libProof";
#else
#ifndef WIN32
TString prooflib = TString(gRootDir) + "/lib/libProof";
#else
TString prooflib = TString(gRootDir) + "/bin/libProof";
#endif
#endif
char *p = 0;
if ((p = gSystem->DynamicPathName(prooflib, kTRUE))) {
delete[] p;
if (gSystem->Load(prooflib) == -1)
Error("CreateSession", "can't load %s", prooflib.Data());
proofhook = TVirtualProof::GetTProofHook();
} else
Error("CreateSession", "can't locate %s", prooflib.Data());
}
if (!proofhook) {
Error("CreateSession", "hook for TVirtualProof could not be loaded");
return 0;
}
// Create the instance
TVirtualProof *p =
(TVirtualProof*) (*proofhook)(fUrl.GetUrl(), cfg, cfgdir, loglevel, 0);
if (p && p->IsValid()) {
// Set reference manager
p->SetManager(this);
// Save record about this session
Int_t ns = 1;
if (fSessions) {
// To avoid ambiguities in case of removal of some elements
if (fSessions->Last())
ns = ((TVirtualProofDesc *)(fSessions->Last()))->GetLocalId() + 1;
} else {
// Create the list
fSessions = new TList;
}
// Create the description class
Int_t st = (p->IsIdle()) ? TVirtualProofDesc::kIdle : TVirtualProofDesc::kRunning ;
TVirtualProofDesc *d =
new TVirtualProofDesc(p->GetName(), p->GetTitle(), p->GetUrl(),
ns, p->GetSessionID(), st, p);
fSessions->Add(d);
} else {
// Session creation failed
Error("CreateSession", "creating PROOF session");
SafeDelete(p);
}
// We are done
return p;
}
//______________________________________________________________________________
Bool_t TVirtualProofMgr::MatchUrl(const char *url)
{
// Checks if 'url' refers to the same 'user@host:port' entity as the URL
// in memory
TUrl u(url);
// Correct URL protocol
if (!strcmp(u.GetProtocol(), TUrl("a").GetProtocol()))
u.SetProtocol("proof");
// Correct port
if (u.GetPort() == TUrl("a").GetPort()) {
Int_t port = gSystem->GetServiceByName("rootd");
if (port < 0)
port = 1094;
u.SetPort(port);
}
// Now we can check
if (!strcmp(u.GetHostFQDN(), fUrl.GetHostFQDN()))
if (u.GetPort() == fUrl.GetPort())
if (strlen(u.GetUser()) <= 0 || !strcmp(u.GetUser(),fUrl.GetUser()))
return kTRUE;
// Match failed
return kFALSE;
}
//________________________________________________________________________
TList *TVirtualProofMgr::GetListOfManagers()
{
// Extract pointers to PROOF managers from TROOT::fProofs.
// Update the list with new entries
if (gROOT->GetListOfProofs()) {
TIter nxp(gROOT->GetListOfProofs());
TVirtualProofMgr *p = 0;
while ((p = dynamic_cast<TVirtualProofMgr *> (nxp())))
if (!fgListOfManagers.FindObject(p))
fgListOfManagers.Add(p);
}
// Get rid of invalid entries and notify
if (fgListOfManagers.GetSize() > 0) {
TIter nxp(&fgListOfManagers);
TObject *o = 0;
Int_t nm = 0;
while ((o = nxp())) {
if (!(gROOT->GetListOfProofs()->FindObject(o))) {
fgListOfManagers.Remove(o);
} else {
TVirtualProofMgr *p = (TVirtualProofMgr *)o;
Printf("// #%d: \"%s\" (%s)", ++nm, p->GetName(), p->GetTitle());
}
}
} else {
if (gDebug > 0)
Printf("No managers found");
}
// We are done
return &fgListOfManagers;
}
//______________________________________________________________________________
TVirtualProofMgr *TVirtualProofMgr::Create(const char *url, Int_t loglevel,
const char *alias, Bool_t xpd)
{
// Static method returning the appropriate TProofMgr object using
// the plugin manager.
TVirtualProofMgr *m= 0;
// Make sure we do not have already a manager for this URL
TList *lm = TVirtualProofMgr::GetListOfManagers();
if (lm) {
TIter nxm(lm);
while ((m = (TVirtualProofMgr *)nxm()))
if (m->MatchUrl(url))
if (m->IsValid()) {
return m;
} else {
fgListOfManagers.Remove(m);
SafeDelete(m);
break;
}
}
m = 0;
Bool_t trystd = kTRUE;
// If required, we assume first that the remote server is based on XrdProofd
if (xpd) {
TVirtualProofMgr_t cm = TVirtualProofMgr::GetProofMgrHook("xpd");
if (cm) {
m = (TVirtualProofMgr *) (*cm)(url, loglevel, alias);
// Update trystd flag
trystd = (m && !(m->IsValid()) && m->IsProofd()) ? kTRUE : kFALSE;
}
}
// If the first attempt failed, we instantiate an old interface
if (trystd) {
SafeDelete(m);
TVirtualProofMgr_t cm = TVirtualProofMgr::GetProofMgrHook("std");
if (cm)
m = (TVirtualProofMgr *) (*cm)(url, loglevel, alias);
}
// Record the new manager, if any
if (m) {
fgListOfManagers.Add(m);
if (m->IsValid() && !(m->IsProofd())) {
R__LOCKGUARD2(gROOTMutex);
gROOT->GetListOfProofs()->Add(m);
gROOT->GetListOfSockets()->Add(m);
}
}
// We are done
return m;
}
//________________________________________________________________________
TVirtualProofMgr_t TVirtualProofMgr::GetProofMgrHook(const char *type)
{
// Get the specified constructor hook.
// We do this without the plugin manager because it blocks the
// CINT mutex breaking the parallel startup.
static const char *libs[] = { "/libProof", "/libProofx" };
// Find index (default: classic)
Int_t idx = (type && !strncmp(type,"xpd",3)) ? 1 : 0;
if (!fgTProofMgrHook[idx]) {
// Load the appropriate library ...
#ifdef ROOTLIBDIR
TString prooflib = TString(ROOTLIBDIR);
#else
#ifndef WIN32
TString prooflib = TString(gRootDir) + "/lib";
#else
TString prooflib = TString(gRootDir) + "/bin";
#endif
#endif
prooflib += libs[idx];
char *p = 0;
if ((p = gSystem->DynamicPathName(prooflib, kTRUE))) {
delete[] p;
if (gSystem->Load(prooflib) == -1)
::Error("TVirtualProofMgr::GetProofMgrCtor",
"can't load %s", prooflib.Data());
} else
::Error("TVirtualProofMgr::GetProofMgrCtor",
"can't locate %s", prooflib.Data());
}
// Done
return fgTProofMgrHook[idx];
}
//_____________________________________________________________________________
void TVirtualProofMgr::SetTProofMgrHook(TVirtualProofMgr_t pmh, const char *t)
{
// Set hook to TProofMgr ctor
// Find index (default: classic)
Int_t idx = (t && !strncmp(t,"xpd",3)) ? 1 : 0;
fgTProofMgrHook[idx] = pmh;
}
ClassImp(TVirtualProofDesc)
//________________________________________________________________________
void TVirtualProofDesc::Print(Option_t *) const
{
// Dump the content to the screen.
const char *st[] = { "unknown", "idle", "processsing", "shutting down"};
Printf("// # %d", fLocalId);
Printf("// alias: %s, url: \"%s\"", GetTitle(), GetUrl());
Printf("// tag: %s", GetName());
Printf("// status: %s, attached: %s (remote ID: %d)",st[fStatus+1], (fProof ? "YES" : "NO"), fRemoteId);
}
<|endoftext|>
|
<commit_before>////////////////////////////////////////////////////////////////////////////////
/// @brief client connection
///
/// @file
///
/// DISCLAIMER
///
/// Copyright 2004-2013 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 triAGENS GmbH, Cologne, Germany
///
/// @author Jan Steemann
/// @author Copyright 2012-2013, triAGENS GmbH, Cologne, Germany
////////////////////////////////////////////////////////////////////////////////
#include "ClientConnection.h"
#ifdef TRI_HAVE_LINUX_SOCKETS
#include <netinet/in.h>
#include <netinet/tcp.h>
#include <netdb.h>
#include <sys/socket.h>
#endif
#ifdef TRI_HAVE_WINSOCK2_H
#include <WinSock2.h>
#include <WS2tcpip.h>
#endif
#include <sys/types.h>
using namespace triagens::basics;
using namespace triagens::httpclient;
using namespace triagens::rest;
using namespace std;
// -----------------------------------------------------------------------------
// --SECTION-- constructors / destructors
// -----------------------------------------------------------------------------
////////////////////////////////////////////////////////////////////////////////
/// @addtogroup httpclient
/// @{
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
/// @brief creates a new client connection
////////////////////////////////////////////////////////////////////////////////
ClientConnection::ClientConnection (Endpoint* endpoint,
double requestTimeout,
double connectTimeout,
size_t connectRetries) :
GeneralClientConnection(endpoint, requestTimeout, connectTimeout, connectRetries) {
}
////////////////////////////////////////////////////////////////////////////////
/// @brief destroys a client connection
////////////////////////////////////////////////////////////////////////////////
ClientConnection::~ClientConnection () {
disconnect();
}
////////////////////////////////////////////////////////////////////////////////
/// @}
////////////////////////////////////////////////////////////////////////////////
// -----------------------------------------------------------------------------
// --SECTION-- private methods
// -----------------------------------------------------------------------------
////////////////////////////////////////////////////////////////////////////////
/// @addtogroup httpclient
/// @{
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
/// @brief check whether the socket is still alive
////////////////////////////////////////////////////////////////////////////////
bool ClientConnection::checkSocket () {
int so_error = -1;
socklen_t len = sizeof so_error;
assert(TRI_isvalidsocket(_socket));
int res = TRI_getsockopt(_socket, SOL_SOCKET, SO_ERROR, (void*)(&so_error), &len);
if (res != TRI_ERROR_NO_ERROR) {
TRI_set_errno(errno);
_isConnected = false;
return false;
}
if (so_error == 0) {
return true;
}
TRI_set_errno(so_error);
_isConnected = false;
return false;
}
////////////////////////////////////////////////////////////////////////////////
/// @}
////////////////////////////////////////////////////////////////////////////////
// -----------------------------------------------------------------------------
// --SECTION-- protected virtual methods
// -----------------------------------------------------------------------------
////////////////////////////////////////////////////////////////////////////////
/// @addtogroup httpclient
/// @{
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
/// @brief connect
////////////////////////////////////////////////////////////////////////////////
bool ClientConnection::connectSocket () {
assert(_endpoint != 0);
if (_endpoint->isConnected()) {
_endpoint->disconnect();
}
_socket = _endpoint->connect(_connectTimeout, _requestTimeout);
if (!TRI_isvalidsocket(_socket)) {
return false;
}
if (checkSocket()) {
return _endpoint->isConnected();
}
return false;
}
////////////////////////////////////////////////////////////////////////////////
/// @brief disconnect
////////////////////////////////////////////////////////////////////////////////
void ClientConnection::disconnectSocket () {
if (_endpoint) {
_endpoint->disconnect();
}
TRI_invalidatesocket(&_socket);
}
////////////////////////////////////////////////////////////////////////////////
/// @brief prepare connection for read/write I/O
////////////////////////////////////////////////////////////////////////////////
bool ClientConnection::prepare (const double timeout, const bool isWrite) const {
struct timeval tv;
fd_set fdset;
assert(TRI_isvalidsocket(_socket));
tv.tv_sec = (long) timeout;
tv.tv_usec = ((long) (timeout * 1000000.0)) % 1000000;
FD_ZERO(&fdset);
FD_SET(TRI_get_fd_or_handle_of_socket(_socket), &fdset);
fd_set* readFds = NULL;
fd_set* writeFds = NULL;
if (isWrite) {
writeFds = &fdset;
}
else {
readFds = &fdset;
}
int sockn = (int) (TRI_get_fd_or_handle_of_socket(_socket) + 1);
int res = select(sockn, readFds, writeFds, NULL, &tv);
if (res > 0) {
return true;
}
if (res == 0) {
if (isWrite) {
TRI_set_errno(TRI_SIMPLE_CLIENT_COULD_NOT_WRITE);
}
else {
TRI_set_errno(TRI_SIMPLE_CLIENT_COULD_NOT_READ);
}
}
return false;
}
////////////////////////////////////////////////////////////////////////////////
/// @brief write data to the connection
////////////////////////////////////////////////////////////////////////////////
bool ClientConnection::writeClientConnection (void* buffer, size_t length, size_t* bytesWritten) {
if (! checkSocket()) {
return false;
}
#if defined(__APPLE__)
// MSG_NOSIGNAL not supported on apple platform
int status = TRI_send(_socket, buffer, length, 0);
#elif defined(_WIN32)
// MSG_NOSIGNAL not supported on windows platform
int status = TRI_send(_socket, buffer, length, 0);
#else
int status = TRI_send(_socket, buffer, length, MSG_NOSIGNAL);
#endif
if (status < 0) {
TRI_set_errno(errno);
return false;
}
*bytesWritten = (size_t) status;
return true;
}
////////////////////////////////////////////////////////////////////////////////
/// @brief read data from the connection
////////////////////////////////////////////////////////////////////////////////
bool ClientConnection::readClientConnection (StringBuffer& stringBuffer) {
if (! checkSocket()) {
return false;
}
assert(TRI_isvalidsocket(_socket));
do {
// reserve some memory for reading
if (stringBuffer.reserve(READBUFFER_SIZE) == TRI_ERROR_OUT_OF_MEMORY) {
// out of memory
TRI_set_errno(TRI_ERROR_OUT_OF_MEMORY);
return false;
}
int lenRead = TRI_READ_SOCKET(_socket, stringBuffer.end(), READBUFFER_SIZE - 1, 0);
if (lenRead == -1) {
// error occurred
return false;
}
if (lenRead == 0) {
// nothing more to read
_isConnected = false;
break;
}
stringBuffer.increaseLength(lenRead);
}
while (readable());
return true;
}
////////////////////////////////////////////////////////////////////////////////
/// @brief return whether the connection is readable
////////////////////////////////////////////////////////////////////////////////
bool ClientConnection::readable () {
if (prepare(0.0, false)) {
return checkSocket();
}
return false;
}
////////////////////////////////////////////////////////////////////////////////
/// @}
////////////////////////////////////////////////////////////////////////////////
<commit_msg>Fix a deadlock situation in the SimpleHttpClient if the server dies.<commit_after>////////////////////////////////////////////////////////////////////////////////
/// @brief client connection
///
/// @file
///
/// DISCLAIMER
///
/// Copyright 2004-2013 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 triAGENS GmbH, Cologne, Germany
///
/// @author Jan Steemann
/// @author Copyright 2012-2013, triAGENS GmbH, Cologne, Germany
////////////////////////////////////////////////////////////////////////////////
#include "ClientConnection.h"
#ifdef TRI_HAVE_LINUX_SOCKETS
#include <netinet/in.h>
#include <netinet/tcp.h>
#include <netdb.h>
#include <sys/socket.h>
#endif
#ifdef TRI_HAVE_WINSOCK2_H
#include <WinSock2.h>
#include <WS2tcpip.h>
#endif
#include <sys/types.h>
using namespace triagens::basics;
using namespace triagens::httpclient;
using namespace triagens::rest;
using namespace std;
// -----------------------------------------------------------------------------
// --SECTION-- constructors / destructors
// -----------------------------------------------------------------------------
////////////////////////////////////////////////////////////////////////////////
/// @addtogroup httpclient
/// @{
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
/// @brief creates a new client connection
////////////////////////////////////////////////////////////////////////////////
ClientConnection::ClientConnection (Endpoint* endpoint,
double requestTimeout,
double connectTimeout,
size_t connectRetries) :
GeneralClientConnection(endpoint, requestTimeout, connectTimeout, connectRetries) {
}
////////////////////////////////////////////////////////////////////////////////
/// @brief destroys a client connection
////////////////////////////////////////////////////////////////////////////////
ClientConnection::~ClientConnection () {
disconnect();
}
////////////////////////////////////////////////////////////////////////////////
/// @}
////////////////////////////////////////////////////////////////////////////////
// -----------------------------------------------------------------------------
// --SECTION-- private methods
// -----------------------------------------------------------------------------
////////////////////////////////////////////////////////////////////////////////
/// @addtogroup httpclient
/// @{
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
/// @brief check whether the socket is still alive
////////////////////////////////////////////////////////////////////////////////
bool ClientConnection::checkSocket () {
int so_error = -1;
socklen_t len = sizeof so_error;
assert(TRI_isvalidsocket(_socket));
int res = TRI_getsockopt(_socket, SOL_SOCKET, SO_ERROR, (void*)(&so_error), &len);
if (res != TRI_ERROR_NO_ERROR) {
TRI_set_errno(errno);
_isConnected = false;
return false;
}
if (so_error == 0) {
return true;
}
TRI_set_errno(so_error);
_isConnected = false;
return false;
}
////////////////////////////////////////////////////////////////////////////////
/// @}
////////////////////////////////////////////////////////////////////////////////
// -----------------------------------------------------------------------------
// --SECTION-- protected virtual methods
// -----------------------------------------------------------------------------
////////////////////////////////////////////////////////////////////////////////
/// @addtogroup httpclient
/// @{
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
/// @brief connect
////////////////////////////////////////////////////////////////////////////////
bool ClientConnection::connectSocket () {
assert(_endpoint != 0);
if (_endpoint->isConnected()) {
_endpoint->disconnect();
}
_socket = _endpoint->connect(_connectTimeout, _requestTimeout);
if (!TRI_isvalidsocket(_socket)) {
return false;
}
if (checkSocket()) {
return _endpoint->isConnected();
}
return false;
}
////////////////////////////////////////////////////////////////////////////////
/// @brief disconnect
////////////////////////////////////////////////////////////////////////////////
void ClientConnection::disconnectSocket () {
if (_endpoint) {
_endpoint->disconnect();
}
TRI_invalidatesocket(&_socket);
}
////////////////////////////////////////////////////////////////////////////////
/// @brief prepare connection for read/write I/O
////////////////////////////////////////////////////////////////////////////////
bool ClientConnection::prepare (const double timeout, const bool isWrite) const {
struct timeval tv;
fd_set fdset;
assert(TRI_isvalidsocket(_socket));
tv.tv_sec = (long) timeout;
tv.tv_usec = ((long) (timeout * 1000000.0)) % 1000000;
FD_ZERO(&fdset);
FD_SET(TRI_get_fd_or_handle_of_socket(_socket), &fdset);
fd_set* readFds = NULL;
fd_set* writeFds = NULL;
if (isWrite) {
writeFds = &fdset;
}
else {
readFds = &fdset;
}
int sockn = (int) (TRI_get_fd_or_handle_of_socket(_socket) + 1);
int res = select(sockn, readFds, writeFds, NULL, &tv);
if (res > 0) {
return true;
}
if (res == 0) {
if (isWrite) {
TRI_set_errno(TRI_SIMPLE_CLIENT_COULD_NOT_WRITE);
}
else {
TRI_set_errno(TRI_SIMPLE_CLIENT_COULD_NOT_READ);
}
}
return false;
}
////////////////////////////////////////////////////////////////////////////////
/// @brief write data to the connection
////////////////////////////////////////////////////////////////////////////////
bool ClientConnection::writeClientConnection (void* buffer, size_t length, size_t* bytesWritten) {
if (! checkSocket()) {
return false;
}
#if defined(__APPLE__)
// MSG_NOSIGNAL not supported on apple platform
int status = TRI_send(_socket, buffer, length, 0);
#elif defined(_WIN32)
// MSG_NOSIGNAL not supported on windows platform
int status = TRI_send(_socket, buffer, length, 0);
#else
int status = TRI_send(_socket, buffer, length, MSG_NOSIGNAL);
#endif
if (status < 0) {
TRI_set_errno(errno);
return false;
}
*bytesWritten = (size_t) status;
return true;
}
////////////////////////////////////////////////////////////////////////////////
/// @brief read data from the connection
////////////////////////////////////////////////////////////////////////////////
bool ClientConnection::readClientConnection (StringBuffer& stringBuffer) {
if (! checkSocket()) {
return false;
}
assert(TRI_isvalidsocket(_socket));
do {
// reserve some memory for reading
if (stringBuffer.reserve(READBUFFER_SIZE) == TRI_ERROR_OUT_OF_MEMORY) {
// out of memory
TRI_set_errno(TRI_ERROR_OUT_OF_MEMORY);
return false;
}
int lenRead = TRI_READ_SOCKET(_socket, stringBuffer.end(), READBUFFER_SIZE - 1, 0);
if (lenRead == -1) {
// error occurred
return false;
}
if (lenRead == 0) {
// nothing more to read
// since we come from a call to select which indicated that there
// is something to read and we are reading from a socket, this is
// an error condition. Therefore we return false
_isConnected = false;
return false;
}
stringBuffer.increaseLength(lenRead);
}
while (readable());
return true;
}
////////////////////////////////////////////////////////////////////////////////
/// @brief return whether the connection is readable
////////////////////////////////////////////////////////////////////////////////
bool ClientConnection::readable () {
if (prepare(0.0, false)) {
return checkSocket();
}
return false;
}
////////////////////////////////////////////////////////////////////////////////
/// @}
////////////////////////////////////////////////////////////////////////////////
<|endoftext|>
|
<commit_before>/***********************************************************************
cpool.cpp - Implements the ConnectionPool class.
Copyright (c) 2007 by Educational Technology Resources, Inc. and
(c) 2007 by Jonathan Wakely. Others may also hold copyrights on
code in this file. See the CREDITS file in the top directory of
the distribution for details.
This file is part of MySQL++.
MySQL++ is free software; you can redistribute it and/or modify it
under the terms of the GNU Lesser General Public License as published
by the Free Software Foundation; either version 2.1 of the License, or
(at your option) any later version.
MySQL++ is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
License for more details.
You should have received a copy of the GNU Lesser General Public
License along with MySQL++; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301
USA
***********************************************************************/
#include "cpool.h"
#include "connection.h"
#include <algorithm>
#include <functional>
namespace mysqlpp {
/// \brief Functor to test whether a given ConnectionInfo object is
/// "too old".
///
/// This is a template only because ConnectionInfo is private. Making
/// it a template means the private type is only used at the point of
/// instantiation, where it is accessible.
template <typename ConnInfoT>
class TooOld : std::unary_function<ConnInfoT, bool>
{
public:
TooOld(unsigned int tmax) :
min_age_(time(0) - tmax)
{
}
bool operator()(const ConnInfoT& conn_info) const
{
return !conn_info.in_use && conn_info.last_used <= min_age_;
}
private:
time_t min_age_;
};
//// clear /////////////////////////////////////////////////////////////
// Destroy all connections in the pool and drain pool.
void
ConnectionPool::clear()
{
ScopedLock lock(mutex_); // ensure we're not interfered with
for (PoolIt it = pool_.begin(); it != pool_.end(); ++it) {
destroy(it->conn);
}
pool_.clear();
}
//// find_mru //////////////////////////////////////////////////////////
// Find most recently used available connection. Uses operator< for
// ConnectionInfo to order pool with MRU connection last. Returns 0 if
// there are no connections not in use.
Connection*
ConnectionPool::find_mru()
{
PoolIt mru = std::max_element(pool_.begin(), pool_.end());
if (mru != pool_.end() && !mru->in_use) {
mru->in_use = true;
return mru->conn;
}
else {
return 0;
}
}
//// grab //////////////////////////////////////////////////////////////
Connection*
ConnectionPool::grab()
{
ScopedLock lock(mutex_); // ensure we're not interfered with
remove_old_connections();
if (Connection* mru = find_mru()) {
return mru;
}
else {
// No free connections, so create and return a new one.
pool_.push_back(ConnectionInfo(create()));
return pool_.back().conn;
}
}
//// release ///////////////////////////////////////////////////////////
void
ConnectionPool::release(const Connection* pc)
{
ScopedLock lock(mutex_); // ensure we're not interfered with
for (PoolIt it = pool_.begin(); it != pool_.end(); ++it) {
if (it->conn == pc) {
it->in_use = false;
it->last_used = time(0);
break;
}
}
}
//// remove_old_connections ////////////////////////////////////////////
// Remove connections that were last used too long ago.
void
ConnectionPool::remove_old_connections()
{
PoolIt it = pool_.begin(), doomed;
TooOld<ConnectionInfo> too_old(max_idle_time());
while ((it = std::find_if(it, pool_.end(), too_old)) != pool_.end()) {
doomed = it++;
destroy(doomed->conn);
pool_.erase(doomed);
}
}
} // end namespace mysqlpp
<commit_msg>Small improvement, reverting a change I made to Jonathan's cpool work to make it more paranoid, which isn't actually an improvement.<commit_after>/***********************************************************************
cpool.cpp - Implements the ConnectionPool class.
Copyright (c) 2007 by Educational Technology Resources, Inc. and
(c) 2007 by Jonathan Wakely. Others may also hold copyrights on
code in this file. See the CREDITS file in the top directory of
the distribution for details.
This file is part of MySQL++.
MySQL++ is free software; you can redistribute it and/or modify it
under the terms of the GNU Lesser General Public License as published
by the Free Software Foundation; either version 2.1 of the License, or
(at your option) any later version.
MySQL++ is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
License for more details.
You should have received a copy of the GNU Lesser General Public
License along with MySQL++; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301
USA
***********************************************************************/
#include "cpool.h"
#include "connection.h"
#include <algorithm>
#include <functional>
namespace mysqlpp {
/// \brief Functor to test whether a given ConnectionInfo object is
/// "too old".
///
/// This is a template only because ConnectionInfo is private. Making
/// it a template means the private type is only used at the point of
/// instantiation, where it is accessible.
template <typename ConnInfoT>
class TooOld : std::unary_function<ConnInfoT, bool>
{
public:
TooOld(unsigned int tmax) :
min_age_(time(0) - tmax)
{
}
bool operator()(const ConnInfoT& conn_info) const
{
return !conn_info.in_use && conn_info.last_used <= min_age_;
}
private:
time_t min_age_;
};
//// clear /////////////////////////////////////////////////////////////
// Destroy all connections in the pool and drain pool.
void
ConnectionPool::clear()
{
ScopedLock lock(mutex_); // ensure we're not interfered with
for (PoolIt it = pool_.begin(); it != pool_.end(); ++it) {
destroy(it->conn);
}
pool_.clear();
}
//// find_mru //////////////////////////////////////////////////////////
// Find most recently used available connection. Uses operator< for
// ConnectionInfo to order pool with MRU connection last. Returns 0 if
// there are no connections not in use.
Connection*
ConnectionPool::find_mru()
{
PoolIt mru = std::max_element(pool_.begin(), pool_.end());
if (mru != pool_.end() && !mru->in_use) {
mru->in_use = true;
return mru->conn;
}
else {
return 0;
}
}
//// grab //////////////////////////////////////////////////////////////
Connection*
ConnectionPool::grab()
{
ScopedLock lock(mutex_); // ensure we're not interfered with
remove_old_connections();
if (Connection* mru = find_mru()) {
return mru;
}
else {
// No free connections, so create and return a new one.
pool_.push_back(ConnectionInfo(create()));
return pool_.back().conn;
}
}
//// release ///////////////////////////////////////////////////////////
void
ConnectionPool::release(const Connection* pc)
{
ScopedLock lock(mutex_); // ensure we're not interfered with
for (PoolIt it = pool_.begin(); it != pool_.end(); ++it) {
if (it->conn == pc) {
it->in_use = false;
it->last_used = time(0);
break;
}
}
}
//// remove_old_connections ////////////////////////////////////////////
// Remove connections that were last used too long ago.
void
ConnectionPool::remove_old_connections()
{
TooOld<ConnectionInfo> too_old(max_idle_time());
PoolIt it = pool_.begin();
while ((it = std::find_if(it, pool_.end(), too_old)) != pool_.end()) {
destroy(it->conn);
pool_.erase(it++);
}
}
} // end namespace mysqlpp
<|endoftext|>
|
<commit_before>/**
* A class which describes the properties of a MySQL database connection.
*
* @date Jul 21, 2013
* @author Joeri HERMANS
* @version 0.1
*
* Copyright 2013 Joeri HERMANS
*
* 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.
*/
// BEGIN Includes. ///////////////////////////////////////////////////
// System dependencies.
#include <assert.h>
#include <stdio.h>
#include <syslog.h>
// Application dependencies.
#include <ias/database/interface/database_connection.h>
#include <ias/database/mysql/mysql_connection.h>
#include <ias/database/mysql/mysql_statement.h>
#include <ias/database/mysql/mysql_driver.h>
// END Includes. /////////////////////////////////////////////////////
inline void MySqlConnection::initialize( void ) {
// Initialize the members of the class.
mConnection = mysql_init( nullptr );
}
MySqlConnection::MySqlConnection( const std::string & username,
const std::string & password,
const std::string & schema,
const std::string & host )
: DatabaseConnection(username,password,schema,host) {
// Nothing to do here.
initialize();
}
MySqlConnection::~MySqlConnection( void ) {
mysql_close( mConnection );
mysql_library_end();
}
bool MySqlConnection::isConnected( void ) const
{
return ( mConnection != nullptr );
}
bool MySqlConnection::connect( void ) {
bool connected;
my_bool argument;
// Enable automatic reconnection by default.
argument = 1;
// Enable the automatic reconnect option.
mysql_options(mConnection,MYSQL_OPT_RECONNECT,&argument);
// Try to connect to the MySQL server.
connected = ( mysql_real_connect(mConnection,
getHost().c_str(),
getUsername().c_str(),
getPassword().c_str(),
getSchema().c_str(),
3306,nullptr,0) != nullptr );
return ( connected );
}
DatabaseStatement * MySqlConnection::createStatement( const std::string & sql ) {
DatabaseStatement * statement;
// Checking the precondition.
assert( sql.length() > 0 );
// Check if the connection with the server is still active.
if( mysql_ping(mConnection) == 0 )
// Allocate a new mysql statement.
statement = new MySqlStatement(this,sql);
else
// No statement should be allocated.
statement = nullptr;
return ( statement );
}
DatabasePreparedStatement * MySqlConnection::prepareStatement(
const std::string & sql ) {
// Checking the precondition.
assert( sql.length() > 0 );
// TODO Implement.
return ( nullptr );
}
void * MySqlConnection::getLink( void )
{
return ( static_cast<void *>(mConnection) );
}
<commit_msg>Test possible bug.<commit_after>/**
* A class which describes the properties of a MySQL database connection.
*
* @date Jul 21, 2013
* @author Joeri HERMANS
* @version 0.1
*
* Copyright 2013 Joeri HERMANS
*
* 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.
*/
// BEGIN Includes. ///////////////////////////////////////////////////
// System dependencies.
#include <assert.h>
#include <stdio.h>
#include <syslog.h>
// Application dependencies.
#include <ias/database/interface/database_connection.h>
#include <ias/database/mysql/mysql_connection.h>
#include <ias/database/mysql/mysql_statement.h>
#include <ias/database/mysql/mysql_driver.h>
// END Includes. /////////////////////////////////////////////////////
inline void MySqlConnection::initialize( void ) {
// Initialize the members of the class.
mConnection = mysql_init( nullptr );
}
MySqlConnection::MySqlConnection( const std::string & username,
const std::string & password,
const std::string & schema,
const std::string & host )
: DatabaseConnection(username,password,schema,host) {
// Nothing to do here.
initialize();
}
MySqlConnection::~MySqlConnection( void ) {
mysql_close( mConnection );
mysql_library_end();
}
bool MySqlConnection::isConnected( void ) const
{
return ( mConnection != nullptr );
}
bool MySqlConnection::connect( void ) {
bool connected;
my_bool argument;
// Enable automatic reconnection by default.
argument = 1;
// Enable the automatic reconnect option.
mysql_options(mConnection,MYSQL_OPT_RECONNECT,&argument);
// Try to connect to the MySQL server.
connected = ( mysql_real_connect(mConnection,
getHost().c_str(),
getUsername().c_str(),
getPassword().c_str(),
getSchema().c_str(),
3306,nullptr,0) != nullptr );
return ( connected );
}
DatabaseStatement * MySqlConnection::createStatement( const std::string & sql ) {
DatabaseStatement * statement;
// Checking the precondition.
assert( sql.length() > 0 );
// // Check if the connection with the server is still active.
// if( mysql_ping(mConnection) == 0 )
// Allocate a new mysql statement.
statement = new MySqlStatement(this,sql);
// else
// No statement should be allocated.
// statement = nullptr;
return ( statement );
}
DatabasePreparedStatement * MySqlConnection::prepareStatement(
const std::string & sql ) {
// Checking the precondition.
assert( sql.length() > 0 );
// TODO Implement.
return ( nullptr );
}
void * MySqlConnection::getLink( void )
{
return ( static_cast<void *>(mConnection) );
}
<|endoftext|>
|
<commit_before>//===- FunctionResolution.cpp - Resolve declarations to implementations ---===//
//
// The LLVM Compiler Infrastructure
//
// This file was developed by the LLVM research group and is distributed under
// the University of Illinois Open Source License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// Loop over the functions that are in the module and look for functions that
// have the same name. More often than not, there will be things like:
//
// declare void %foo(...)
// void %foo(int, int) { ... }
//
// because of the way things are declared in C. If this is the case, patch
// things up.
//
//===----------------------------------------------------------------------===//
#include "llvm/Transforms/IPO.h"
#include "llvm/Module.h"
#include "llvm/DerivedTypes.h"
#include "llvm/Pass.h"
#include "llvm/iOther.h"
#include "llvm/Constants.h"
#include "llvm/Target/TargetData.h"
#include "llvm/Assembly/Writer.h"
#include "Support/Statistic.h"
#include <algorithm>
namespace llvm {
namespace {
Statistic<>NumResolved("funcresolve", "Number of varargs functions resolved");
Statistic<> NumGlobals("funcresolve", "Number of global variables resolved");
struct FunctionResolvingPass : public Pass {
virtual void getAnalysisUsage(AnalysisUsage &AU) const {
AU.addRequired<TargetData>();
}
bool run(Module &M);
};
RegisterOpt<FunctionResolvingPass> X("funcresolve", "Resolve Functions");
}
Pass *createFunctionResolvingPass() {
return new FunctionResolvingPass();
}
static bool ResolveFunctions(Module &M, std::vector<GlobalValue*> &Globals,
Function *Concrete) {
bool Changed = false;
for (unsigned i = 0; i != Globals.size(); ++i)
if (Globals[i] != Concrete) {
Function *Old = cast<Function>(Globals[i]);
const FunctionType *OldMT = Old->getFunctionType();
const FunctionType *ConcreteMT = Concrete->getFunctionType();
if (OldMT->getParamTypes().size() > ConcreteMT->getParamTypes().size() &&
!ConcreteMT->isVarArg())
if (!Old->use_empty()) {
std::cerr << "WARNING: Linking function '" << Old->getName()
<< "' is causing arguments to be dropped.\n";
std::cerr << "WARNING: Prototype: ";
WriteAsOperand(std::cerr, Old);
std::cerr << " resolved to ";
WriteAsOperand(std::cerr, Concrete);
std::cerr << "\n";
}
// Check to make sure that if there are specified types, that they
// match...
//
unsigned NumArguments = std::min(OldMT->getParamTypes().size(),
ConcreteMT->getParamTypes().size());
if (!Old->use_empty() && !Concrete->use_empty())
for (unsigned i = 0; i < NumArguments; ++i)
if (OldMT->getParamTypes()[i] != ConcreteMT->getParamTypes()[i])
if (OldMT->getParamTypes()[i]->getPrimitiveID() !=
ConcreteMT->getParamTypes()[i]->getPrimitiveID()) {
std::cerr << "WARNING: Function [" << Old->getName()
<< "]: Parameter types conflict for: '" << OldMT
<< "' and '" << ConcreteMT << "'\n";
return Changed;
}
// Attempt to convert all of the uses of the old function to the concrete
// form of the function. If there is a use of the fn that we don't
// understand here we punt to avoid making a bad transformation.
//
// At this point, we know that the return values are the same for our two
// functions and that the Old function has no varargs fns specified. In
// otherwords it's just <retty> (...)
//
if (!Old->use_empty()) { // Avoid making the CPR unless we really need it
Value *Replacement = Concrete;
if (Concrete->getType() != Old->getType())
Replacement = ConstantExpr::getCast(ConstantPointerRef::get(Concrete),
Old->getType());
NumResolved += Old->use_size();
Old->replaceAllUsesWith(Replacement);
}
// Since there are no uses of Old anymore, remove it from the module.
M.getFunctionList().erase(Old);
}
return Changed;
}
static bool ResolveGlobalVariables(Module &M,
std::vector<GlobalValue*> &Globals,
GlobalVariable *Concrete) {
bool Changed = false;
Constant *CCPR = ConstantPointerRef::get(Concrete);
for (unsigned i = 0; i != Globals.size(); ++i)
if (Globals[i] != Concrete) {
Constant *Cast = ConstantExpr::getCast(CCPR, Globals[i]->getType());
Globals[i]->replaceAllUsesWith(Cast);
// Since there are no uses of Old anymore, remove it from the module.
M.getGlobalList().erase(cast<GlobalVariable>(Globals[i]));
++NumGlobals;
Changed = true;
}
return Changed;
}
static bool ProcessGlobalsWithSameName(Module &M, TargetData &TD,
std::vector<GlobalValue*> &Globals) {
assert(!Globals.empty() && "Globals list shouldn't be empty here!");
bool isFunction = isa<Function>(Globals[0]); // Is this group all functions?
GlobalValue *Concrete = 0; // The most concrete implementation to resolve to
for (unsigned i = 0; i != Globals.size(); ) {
if (isa<Function>(Globals[i]) != isFunction) {
std::cerr << "WARNING: Found function and global variable with the "
<< "same name: '" << Globals[i]->getName() << "'.\n";
return false; // Don't know how to handle this, bail out!
}
if (isFunction) {
// For functions, we look to merge functions definitions of "int (...)"
// to 'int (int)' or 'int ()' or whatever else is not completely generic.
//
Function *F = cast<Function>(Globals[i]);
if (!F->isExternal()) {
if (Concrete && !Concrete->isExternal())
return false; // Found two different functions types. Can't choose!
Concrete = Globals[i];
} else if (Concrete) {
if (Concrete->isExternal()) // If we have multiple external symbols...x
if (F->getFunctionType()->getNumParams() >
cast<Function>(Concrete)->getFunctionType()->getNumParams())
Concrete = F; // We are more concrete than "Concrete"!
} else {
Concrete = F;
}
} else {
GlobalVariable *GV = cast<GlobalVariable>(Globals[i]);
if (!GV->isExternal()) {
if (Concrete) {
std::cerr << "WARNING: Two global variables with external linkage"
<< " exist with the same name: '" << GV->getName()
<< "'!\n";
return false;
}
Concrete = GV;
}
}
++i;
}
if (Globals.size() > 1) { // Found a multiply defined global...
// If there are no external declarations, and there is at most one
// externally visible instance of the global, then there is nothing to do.
//
bool HasExternal = false;
unsigned NumInstancesWithExternalLinkage = 0;
for (unsigned i = 0, e = Globals.size(); i != e; ++i) {
if (Globals[i]->isExternal())
HasExternal = true;
else if (!Globals[i]->hasInternalLinkage())
NumInstancesWithExternalLinkage++;
}
if (!HasExternal && NumInstancesWithExternalLinkage <= 1)
return false; // Nothing to do? Must have multiple internal definitions.
// There are a couple of special cases we don't want to print the warning
// for, check them now.
bool DontPrintWarning = false;
if (Concrete && Globals.size() == 2) {
GlobalValue *Other = Globals[Globals[0] == Concrete];
// If the non-concrete global is a function which takes (...) arguments,
// and the return values match, do not warn.
if (Function *ConcreteF = dyn_cast<Function>(Concrete))
if (Function *OtherF = dyn_cast<Function>(Other))
if (ConcreteF->getReturnType() == OtherF->getReturnType() &&
OtherF->getFunctionType()->isVarArg() &&
OtherF->getFunctionType()->getParamTypes().empty())
DontPrintWarning = true;
// Otherwise, if the non-concrete global is a global array variable with a
// size of 0, and the concrete global is an array with a real size, don't
// warn. This occurs due to declaring 'extern int A[];'.
if (GlobalVariable *ConcreteGV = dyn_cast<GlobalVariable>(Concrete))
if (GlobalVariable *OtherGV = dyn_cast<GlobalVariable>(Other))
if (const ArrayType *OtherAT =
dyn_cast<ArrayType>(OtherGV->getType()->getElementType()))
if (const ArrayType *ConcreteAT =
dyn_cast<ArrayType>(ConcreteGV->getType()->getElementType()))
if (OtherAT->getElementType() == ConcreteAT->getElementType() &&
OtherAT->getNumElements() == 0)
DontPrintWarning = true;
}
if (!DontPrintWarning) {
std::cerr << "WARNING: Found global types that are not compatible:\n";
for (unsigned i = 0; i < Globals.size(); ++i) {
std::cerr << "\t" << *Globals[i]->getType() << " %"
<< Globals[i]->getName() << "\n";
}
}
if (!Concrete)
Concrete = Globals[0];
else if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Concrete)) {
// Handle special case hack to change globals if it will make their types
// happier in the long run. The situation we do this is intentionally
// extremely limited.
if (GV->use_empty() && GV->hasInitializer() &&
GV->getInitializer()->isNullValue()) {
// Check to see if there is another (external) global with the same size
// and a non-empty use-list. If so, we will make IT be the real
// implementation.
unsigned TS = TD.getTypeSize(Concrete->getType()->getElementType());
for (unsigned i = 0, e = Globals.size(); i != e; ++i)
if (Globals[i] != Concrete && !Globals[i]->use_empty() &&
isa<GlobalVariable>(Globals[i]) &&
TD.getTypeSize(Globals[i]->getType()->getElementType()) == TS) {
// At this point we want to replace Concrete with Globals[i]. Make
// concrete external, and Globals[i] have an initializer.
GlobalVariable *NGV = cast<GlobalVariable>(Globals[i]);
const Type *ElTy = NGV->getType()->getElementType();
NGV->setInitializer(Constant::getNullValue(ElTy));
cast<GlobalVariable>(Concrete)->setInitializer(0);
Concrete = NGV;
break;
}
}
}
if (isFunction)
return ResolveFunctions(M, Globals, cast<Function>(Concrete));
else
return ResolveGlobalVariables(M, Globals,
cast<GlobalVariable>(Concrete));
}
return false;
}
bool FunctionResolvingPass::run(Module &M) {
std::map<std::string, std::vector<GlobalValue*> > Globals;
// Loop over the globals, adding them to the Globals map. We use a two pass
// algorithm here to avoid problems with iterators getting invalidated if we
// did a one pass scheme.
//
bool Changed = false;
for (Module::iterator I = M.begin(), E = M.end(); I != E; ) {
Function *F = I++;
if (F->use_empty() && F->isExternal()) {
M.getFunctionList().erase(F);
Changed = true;
} else if (!F->hasInternalLinkage() && !F->getName().empty())
Globals[F->getName()].push_back(F);
}
for (Module::giterator I = M.gbegin(), E = M.gend(); I != E; ) {
GlobalVariable *GV = I++;
if (GV->use_empty() && GV->isExternal()) {
M.getGlobalList().erase(GV);
Changed = true;
} else if (!GV->hasInternalLinkage() && !GV->getName().empty())
Globals[GV->getName()].push_back(GV);
}
TargetData &TD = getAnalysis<TargetData>();
// Now we have a list of all functions with a particular name. If there is
// more than one entry in a list, merge the functions together.
//
for (std::map<std::string, std::vector<GlobalValue*> >::iterator
I = Globals.begin(), E = Globals.end(); I != E; ++I)
Changed |= ProcessGlobalsWithSameName(M, TD, I->second);
// Now loop over all of the globals, checking to see if any are trivially
// dead. If so, remove them now.
for (Module::iterator I = M.begin(), E = M.end(); I != E; )
if (I->isExternal() && I->use_empty()) {
Function *F = I;
++I;
M.getFunctionList().erase(F);
++NumResolved;
Changed = true;
} else {
++I;
}
for (Module::giterator I = M.gbegin(), E = M.gend(); I != E; )
if (I->isExternal() && I->use_empty()) {
GlobalVariable *GV = I;
++I;
M.getGlobalList().erase(GV);
++NumGlobals;
Changed = true;
} else {
++I;
}
return Changed;
}
} // End llvm namespace
<commit_msg>When spewing out warnings during function resolution, do not vomit out pages and pages of non-symbolic types.<commit_after>//===- FunctionResolution.cpp - Resolve declarations to implementations ---===//
//
// The LLVM Compiler Infrastructure
//
// This file was developed by the LLVM research group and is distributed under
// the University of Illinois Open Source License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// Loop over the functions that are in the module and look for functions that
// have the same name. More often than not, there will be things like:
//
// declare void %foo(...)
// void %foo(int, int) { ... }
//
// because of the way things are declared in C. If this is the case, patch
// things up.
//
//===----------------------------------------------------------------------===//
#include "llvm/Transforms/IPO.h"
#include "llvm/Module.h"
#include "llvm/DerivedTypes.h"
#include "llvm/Pass.h"
#include "llvm/iOther.h"
#include "llvm/Constants.h"
#include "llvm/Target/TargetData.h"
#include "llvm/Assembly/Writer.h"
#include "Support/Statistic.h"
#include <algorithm>
namespace llvm {
namespace {
Statistic<>NumResolved("funcresolve", "Number of varargs functions resolved");
Statistic<> NumGlobals("funcresolve", "Number of global variables resolved");
struct FunctionResolvingPass : public Pass {
virtual void getAnalysisUsage(AnalysisUsage &AU) const {
AU.addRequired<TargetData>();
}
bool run(Module &M);
};
RegisterOpt<FunctionResolvingPass> X("funcresolve", "Resolve Functions");
}
Pass *createFunctionResolvingPass() {
return new FunctionResolvingPass();
}
static bool ResolveFunctions(Module &M, std::vector<GlobalValue*> &Globals,
Function *Concrete) {
bool Changed = false;
for (unsigned i = 0; i != Globals.size(); ++i)
if (Globals[i] != Concrete) {
Function *Old = cast<Function>(Globals[i]);
const FunctionType *OldMT = Old->getFunctionType();
const FunctionType *ConcreteMT = Concrete->getFunctionType();
if (OldMT->getParamTypes().size() > ConcreteMT->getParamTypes().size() &&
!ConcreteMT->isVarArg())
if (!Old->use_empty()) {
std::cerr << "WARNING: Linking function '" << Old->getName()
<< "' is causing arguments to be dropped.\n";
std::cerr << "WARNING: Prototype: ";
WriteAsOperand(std::cerr, Old);
std::cerr << " resolved to ";
WriteAsOperand(std::cerr, Concrete);
std::cerr << "\n";
}
// Check to make sure that if there are specified types, that they
// match...
//
unsigned NumArguments = std::min(OldMT->getParamTypes().size(),
ConcreteMT->getParamTypes().size());
if (!Old->use_empty() && !Concrete->use_empty())
for (unsigned i = 0; i < NumArguments; ++i)
if (OldMT->getParamTypes()[i] != ConcreteMT->getParamTypes()[i])
if (OldMT->getParamTypes()[i]->getPrimitiveID() !=
ConcreteMT->getParamTypes()[i]->getPrimitiveID()) {
std::cerr << "WARNING: Function [" << Old->getName()
<< "]: Parameter types conflict for: '";
WriteTypeSymbolic(std::cerr, OldMT, &M);
std::cerr << "' and '";
WriteTypeSymbolic(std::cerr, ConcreteMT, &M);
std::cerr << "'\n";
return Changed;
}
// Attempt to convert all of the uses of the old function to the concrete
// form of the function. If there is a use of the fn that we don't
// understand here we punt to avoid making a bad transformation.
//
// At this point, we know that the return values are the same for our two
// functions and that the Old function has no varargs fns specified. In
// otherwords it's just <retty> (...)
//
if (!Old->use_empty()) { // Avoid making the CPR unless we really need it
Value *Replacement = Concrete;
if (Concrete->getType() != Old->getType())
Replacement = ConstantExpr::getCast(ConstantPointerRef::get(Concrete),
Old->getType());
NumResolved += Old->use_size();
Old->replaceAllUsesWith(Replacement);
}
// Since there are no uses of Old anymore, remove it from the module.
M.getFunctionList().erase(Old);
}
return Changed;
}
static bool ResolveGlobalVariables(Module &M,
std::vector<GlobalValue*> &Globals,
GlobalVariable *Concrete) {
bool Changed = false;
Constant *CCPR = ConstantPointerRef::get(Concrete);
for (unsigned i = 0; i != Globals.size(); ++i)
if (Globals[i] != Concrete) {
Constant *Cast = ConstantExpr::getCast(CCPR, Globals[i]->getType());
Globals[i]->replaceAllUsesWith(Cast);
// Since there are no uses of Old anymore, remove it from the module.
M.getGlobalList().erase(cast<GlobalVariable>(Globals[i]));
++NumGlobals;
Changed = true;
}
return Changed;
}
static bool ProcessGlobalsWithSameName(Module &M, TargetData &TD,
std::vector<GlobalValue*> &Globals) {
assert(!Globals.empty() && "Globals list shouldn't be empty here!");
bool isFunction = isa<Function>(Globals[0]); // Is this group all functions?
GlobalValue *Concrete = 0; // The most concrete implementation to resolve to
for (unsigned i = 0; i != Globals.size(); ) {
if (isa<Function>(Globals[i]) != isFunction) {
std::cerr << "WARNING: Found function and global variable with the "
<< "same name: '" << Globals[i]->getName() << "'.\n";
return false; // Don't know how to handle this, bail out!
}
if (isFunction) {
// For functions, we look to merge functions definitions of "int (...)"
// to 'int (int)' or 'int ()' or whatever else is not completely generic.
//
Function *F = cast<Function>(Globals[i]);
if (!F->isExternal()) {
if (Concrete && !Concrete->isExternal())
return false; // Found two different functions types. Can't choose!
Concrete = Globals[i];
} else if (Concrete) {
if (Concrete->isExternal()) // If we have multiple external symbols...x
if (F->getFunctionType()->getNumParams() >
cast<Function>(Concrete)->getFunctionType()->getNumParams())
Concrete = F; // We are more concrete than "Concrete"!
} else {
Concrete = F;
}
} else {
GlobalVariable *GV = cast<GlobalVariable>(Globals[i]);
if (!GV->isExternal()) {
if (Concrete) {
std::cerr << "WARNING: Two global variables with external linkage"
<< " exist with the same name: '" << GV->getName()
<< "'!\n";
return false;
}
Concrete = GV;
}
}
++i;
}
if (Globals.size() > 1) { // Found a multiply defined global...
// If there are no external declarations, and there is at most one
// externally visible instance of the global, then there is nothing to do.
//
bool HasExternal = false;
unsigned NumInstancesWithExternalLinkage = 0;
for (unsigned i = 0, e = Globals.size(); i != e; ++i) {
if (Globals[i]->isExternal())
HasExternal = true;
else if (!Globals[i]->hasInternalLinkage())
NumInstancesWithExternalLinkage++;
}
if (!HasExternal && NumInstancesWithExternalLinkage <= 1)
return false; // Nothing to do? Must have multiple internal definitions.
// There are a couple of special cases we don't want to print the warning
// for, check them now.
bool DontPrintWarning = false;
if (Concrete && Globals.size() == 2) {
GlobalValue *Other = Globals[Globals[0] == Concrete];
// If the non-concrete global is a function which takes (...) arguments,
// and the return values match, do not warn.
if (Function *ConcreteF = dyn_cast<Function>(Concrete))
if (Function *OtherF = dyn_cast<Function>(Other))
if (ConcreteF->getReturnType() == OtherF->getReturnType() &&
OtherF->getFunctionType()->isVarArg() &&
OtherF->getFunctionType()->getParamTypes().empty())
DontPrintWarning = true;
// Otherwise, if the non-concrete global is a global array variable with a
// size of 0, and the concrete global is an array with a real size, don't
// warn. This occurs due to declaring 'extern int A[];'.
if (GlobalVariable *ConcreteGV = dyn_cast<GlobalVariable>(Concrete))
if (GlobalVariable *OtherGV = dyn_cast<GlobalVariable>(Other))
if (const ArrayType *OtherAT =
dyn_cast<ArrayType>(OtherGV->getType()->getElementType()))
if (const ArrayType *ConcreteAT =
dyn_cast<ArrayType>(ConcreteGV->getType()->getElementType()))
if (OtherAT->getElementType() == ConcreteAT->getElementType() &&
OtherAT->getNumElements() == 0)
DontPrintWarning = true;
}
if (!DontPrintWarning) {
std::cerr << "WARNING: Found global types that are not compatible:\n";
for (unsigned i = 0; i < Globals.size(); ++i) {
std::cerr << "\t";
WriteTypeSymbolic(std::cerr, Globals[i]->getType(), &M);
std::cerr << " %" << Globals[i]->getName() << "\n";
}
}
if (!Concrete)
Concrete = Globals[0];
else if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Concrete)) {
// Handle special case hack to change globals if it will make their types
// happier in the long run. The situation we do this is intentionally
// extremely limited.
if (GV->use_empty() && GV->hasInitializer() &&
GV->getInitializer()->isNullValue()) {
// Check to see if there is another (external) global with the same size
// and a non-empty use-list. If so, we will make IT be the real
// implementation.
unsigned TS = TD.getTypeSize(Concrete->getType()->getElementType());
for (unsigned i = 0, e = Globals.size(); i != e; ++i)
if (Globals[i] != Concrete && !Globals[i]->use_empty() &&
isa<GlobalVariable>(Globals[i]) &&
TD.getTypeSize(Globals[i]->getType()->getElementType()) == TS) {
// At this point we want to replace Concrete with Globals[i]. Make
// concrete external, and Globals[i] have an initializer.
GlobalVariable *NGV = cast<GlobalVariable>(Globals[i]);
const Type *ElTy = NGV->getType()->getElementType();
NGV->setInitializer(Constant::getNullValue(ElTy));
cast<GlobalVariable>(Concrete)->setInitializer(0);
Concrete = NGV;
break;
}
}
}
if (isFunction)
return ResolveFunctions(M, Globals, cast<Function>(Concrete));
else
return ResolveGlobalVariables(M, Globals,
cast<GlobalVariable>(Concrete));
}
return false;
}
bool FunctionResolvingPass::run(Module &M) {
std::map<std::string, std::vector<GlobalValue*> > Globals;
// Loop over the globals, adding them to the Globals map. We use a two pass
// algorithm here to avoid problems with iterators getting invalidated if we
// did a one pass scheme.
//
bool Changed = false;
for (Module::iterator I = M.begin(), E = M.end(); I != E; ) {
Function *F = I++;
if (F->use_empty() && F->isExternal()) {
M.getFunctionList().erase(F);
Changed = true;
} else if (!F->hasInternalLinkage() && !F->getName().empty())
Globals[F->getName()].push_back(F);
}
for (Module::giterator I = M.gbegin(), E = M.gend(); I != E; ) {
GlobalVariable *GV = I++;
if (GV->use_empty() && GV->isExternal()) {
M.getGlobalList().erase(GV);
Changed = true;
} else if (!GV->hasInternalLinkage() && !GV->getName().empty())
Globals[GV->getName()].push_back(GV);
}
TargetData &TD = getAnalysis<TargetData>();
// Now we have a list of all functions with a particular name. If there is
// more than one entry in a list, merge the functions together.
//
for (std::map<std::string, std::vector<GlobalValue*> >::iterator
I = Globals.begin(), E = Globals.end(); I != E; ++I)
Changed |= ProcessGlobalsWithSameName(M, TD, I->second);
// Now loop over all of the globals, checking to see if any are trivially
// dead. If so, remove them now.
for (Module::iterator I = M.begin(), E = M.end(); I != E; )
if (I->isExternal() && I->use_empty()) {
Function *F = I;
++I;
M.getFunctionList().erase(F);
++NumResolved;
Changed = true;
} else {
++I;
}
for (Module::giterator I = M.gbegin(), E = M.gend(); I != E; )
if (I->isExternal() && I->use_empty()) {
GlobalVariable *GV = I;
++I;
M.getGlobalList().erase(GV);
++NumGlobals;
Changed = true;
} else {
++I;
}
return Changed;
}
} // End llvm namespace
<|endoftext|>
|
<commit_before>//* This file is part of the MOOSE framework
//* https://www.mooseframework.org
//*
//* All rights reserved, see COPYRIGHT for full restrictions
//* https://github.com/idaholab/moose/blob/master/COPYRIGHT
//*
//* Licensed under LGPL 2.1, please see LICENSE for details
//* https://www.gnu.org/licenses/lgpl-2.1.html
#include "PINSFVMomentumFrictionCorrection.h"
#include "INSFVRhieChowInterpolator.h"
#include "NS.h"
#include "SystemBase.h"
registerMooseObject("NavierStokesApp", PINSFVMomentumFrictionCorrection);
InputParameters
PINSFVMomentumFrictionCorrection::validParams()
{
auto params = INSFVFluxKernel::validParams();
params.addClassDescription(
"Computes the diffusion kernel to avoid pressure-driven oscillations.");
params.addParam<MooseFunctorName>("Darcy_name", "Name of the Darcy coefficients property.");
params.addParam<MooseFunctorName>("Forchheimer_name",
"Name of the Forchheimer coefficients property.");
params.addParam<MooseFunctorName>(NS::porosity, NS::porosity, "The porosity");
params.addRequiredParam<MooseFunctorName>(NS::density, "The density.");
params.addRangeCheckedParam<Real>("consistent_scaling",
1,
"consistent_scaling >= 0",
"Smoothing scaling parameter to control "
"collocated mesh oscillations");
return params;
}
PINSFVMomentumFrictionCorrection::PINSFVMomentumFrictionCorrection(const InputParameters & params)
: INSFVFluxKernel(params),
_cL(isParamValid("Darcy_name") ? &getFunctor<ADRealVectorValue>("Darcy_name") : nullptr),
_cQ(isParamValid("Forchheimer_name") ? &getFunctor<ADRealVectorValue>("Forchheimer_name")
: nullptr),
_use_Darcy_friction_model(isParamValid("Darcy_name")),
_use_Forchheimer_friction_model(isParamValid("Forchheimer_name")),
_eps(getFunctor<ADReal>(NS::porosity)),
_rho(getFunctor<ADReal>(NS::density)),
_consistent_scaling(getParam<Real>("consistent_scaling"))
{
if (!_use_Darcy_friction_model && !_use_Forchheimer_friction_model)
mooseError("At least one friction model needs to be specified.");
#ifndef MOOSE_GLOBAL_AD_INDEXING
mooseError("PINSFV is not supported by local AD indexing. In order to use PINSFV, please run "
"the configure script in the root MOOSE directory with the configure option "
"'--with-ad-indexing-type=global'");
#endif
}
void
PINSFVMomentumFrictionCorrection::gatherRCData(const FaceInfo & fi)
{
if (skipForBoundary(fi))
return;
_face_info = &fi;
_normal = fi.normal();
_face_type = fi.faceType(_var.name());
#ifdef MOOSE_GLOBAL_AD_INDEXING
using namespace Moose::FV;
const auto elem_face = elemFromFace();
const auto neighbor_face = neighborFromFace();
ADReal friction_term_elem = 0;
ADReal friction_term_neighbor = 0;
if (_use_Darcy_friction_model)
{
friction_term_elem += (*_cL)(elem_face)(_index)*_rho(elem_face) / _eps(elem_face);
friction_term_neighbor +=
(*_cL)(neighbor_face)(_index)*_rho(neighbor_face) / _eps(neighbor_face);
}
if (_use_Forchheimer_friction_model)
{
friction_term_elem += (*_cQ)(elem_face)(_index)*_rho(elem_face) / _eps(elem_face);
friction_term_neighbor +=
(*_cQ)(neighbor_face)(_index)*_rho(neighbor_face) / _eps(neighbor_face);
}
Point _face_centroid = _face_info->faceCentroid();
Point _elem_centroid = _face_info->elemCentroid();
Point _neighbor_centroid = _face_info->neighborCentroid();
Real geometric_factor = _consistent_scaling * (_neighbor_centroid - _face_centroid).norm() *
(_elem_centroid - _face_centroid).norm();
// Compute the diffusion driven by the velocity gradient
// Interpolate viscosity divided by porosity on the face
ADReal diff_face;
interpolate(Moose::FV::InterpMethod::Average,
diff_face,
friction_term_elem * geometric_factor,
friction_term_neighbor * geometric_factor,
*_face_info,
true);
// Compute face superficial velocity gradient
auto dudn =
_var.gradient(Moose::FV::makeCDFace(*_face_info, faceArgSubdomains())) * _face_info->normal();
if (_face_type == FaceInfo::VarFaceNeighbors::ELEM ||
_face_type == FaceInfo::VarFaceNeighbors::BOTH)
{
const auto dof_number = _face_info->elem().dof_number(_sys.number(), _var.number(), 0);
// A gradient is a linear combination of degrees of freedom so it's safe to straight-up index
// into the derivatives vector at the dof we care about
ADReal ae = dudn.derivatives()[dof_number];
ae *= -diff_face;
_rc_uo.addToA(&fi.elem(), _index, ae * (fi.faceArea() * fi.faceCoord()));
}
if (_face_type == FaceInfo::VarFaceNeighbors::NEIGHBOR ||
_face_type == FaceInfo::VarFaceNeighbors::BOTH)
{
const auto dof_number = _face_info->neighbor().dof_number(_sys.number(), _var.number(), 0);
ADReal an = dudn.derivatives()[dof_number];
an *= diff_face;
_rc_uo.addToA(fi.neighborPtr(), _index, an * (fi.faceArea() * fi.faceCoord()));
}
const auto strong_resid = -diff_face * dudn;
processResidual(strong_resid * (fi.faceArea() * fi.faceCoord()));
#endif
}
<commit_msg>Resolve old Guillaume conversation about doc string<commit_after>//* This file is part of the MOOSE framework
//* https://www.mooseframework.org
//*
//* All rights reserved, see COPYRIGHT for full restrictions
//* https://github.com/idaholab/moose/blob/master/COPYRIGHT
//*
//* Licensed under LGPL 2.1, please see LICENSE for details
//* https://www.gnu.org/licenses/lgpl-2.1.html
#include "PINSFVMomentumFrictionCorrection.h"
#include "INSFVRhieChowInterpolator.h"
#include "NS.h"
#include "SystemBase.h"
registerMooseObject("NavierStokesApp", PINSFVMomentumFrictionCorrection);
InputParameters
PINSFVMomentumFrictionCorrection::validParams()
{
auto params = INSFVFluxKernel::validParams();
params.addClassDescription(
"Computes a correction term to avoid oscillations from average pressure interpolation in "
"regions of high changes in friction coefficients.");
params.addParam<MooseFunctorName>("Darcy_name", "Name of the Darcy coefficients property.");
params.addParam<MooseFunctorName>("Forchheimer_name",
"Name of the Forchheimer coefficients property.");
params.addParam<MooseFunctorName>(NS::porosity, NS::porosity, "The porosity");
params.addRequiredParam<MooseFunctorName>(NS::density, "The density.");
params.addRangeCheckedParam<Real>("consistent_scaling",
1,
"consistent_scaling >= 0",
"Smoothing scaling parameter to control "
"collocated mesh oscillations");
return params;
}
PINSFVMomentumFrictionCorrection::PINSFVMomentumFrictionCorrection(const InputParameters & params)
: INSFVFluxKernel(params),
_cL(isParamValid("Darcy_name") ? &getFunctor<ADRealVectorValue>("Darcy_name") : nullptr),
_cQ(isParamValid("Forchheimer_name") ? &getFunctor<ADRealVectorValue>("Forchheimer_name")
: nullptr),
_use_Darcy_friction_model(isParamValid("Darcy_name")),
_use_Forchheimer_friction_model(isParamValid("Forchheimer_name")),
_eps(getFunctor<ADReal>(NS::porosity)),
_rho(getFunctor<ADReal>(NS::density)),
_consistent_scaling(getParam<Real>("consistent_scaling"))
{
if (!_use_Darcy_friction_model && !_use_Forchheimer_friction_model)
mooseError("At least one friction model needs to be specified.");
#ifndef MOOSE_GLOBAL_AD_INDEXING
mooseError("PINSFV is not supported by local AD indexing. In order to use PINSFV, please run "
"the configure script in the root MOOSE directory with the configure option "
"'--with-ad-indexing-type=global'");
#endif
}
void
PINSFVMomentumFrictionCorrection::gatherRCData(const FaceInfo & fi)
{
if (skipForBoundary(fi))
return;
_face_info = &fi;
_normal = fi.normal();
_face_type = fi.faceType(_var.name());
#ifdef MOOSE_GLOBAL_AD_INDEXING
using namespace Moose::FV;
const auto elem_face = elemFromFace();
const auto neighbor_face = neighborFromFace();
ADReal friction_term_elem = 0;
ADReal friction_term_neighbor = 0;
if (_use_Darcy_friction_model)
{
friction_term_elem += (*_cL)(elem_face)(_index)*_rho(elem_face) / _eps(elem_face);
friction_term_neighbor +=
(*_cL)(neighbor_face)(_index)*_rho(neighbor_face) / _eps(neighbor_face);
}
if (_use_Forchheimer_friction_model)
{
friction_term_elem += (*_cQ)(elem_face)(_index)*_rho(elem_face) / _eps(elem_face);
friction_term_neighbor +=
(*_cQ)(neighbor_face)(_index)*_rho(neighbor_face) / _eps(neighbor_face);
}
Point _face_centroid = _face_info->faceCentroid();
Point _elem_centroid = _face_info->elemCentroid();
Point _neighbor_centroid = _face_info->neighborCentroid();
Real geometric_factor = _consistent_scaling * (_neighbor_centroid - _face_centroid).norm() *
(_elem_centroid - _face_centroid).norm();
// Compute the diffusion driven by the velocity gradient
// Interpolate viscosity divided by porosity on the face
ADReal diff_face;
interpolate(Moose::FV::InterpMethod::Average,
diff_face,
friction_term_elem * geometric_factor,
friction_term_neighbor * geometric_factor,
*_face_info,
true);
// Compute face superficial velocity gradient
auto dudn =
_var.gradient(Moose::FV::makeCDFace(*_face_info, faceArgSubdomains())) * _face_info->normal();
if (_face_type == FaceInfo::VarFaceNeighbors::ELEM ||
_face_type == FaceInfo::VarFaceNeighbors::BOTH)
{
const auto dof_number = _face_info->elem().dof_number(_sys.number(), _var.number(), 0);
// A gradient is a linear combination of degrees of freedom so it's safe to straight-up index
// into the derivatives vector at the dof we care about
ADReal ae = dudn.derivatives()[dof_number];
ae *= -diff_face;
_rc_uo.addToA(&fi.elem(), _index, ae * (fi.faceArea() * fi.faceCoord()));
}
if (_face_type == FaceInfo::VarFaceNeighbors::NEIGHBOR ||
_face_type == FaceInfo::VarFaceNeighbors::BOTH)
{
const auto dof_number = _face_info->neighbor().dof_number(_sys.number(), _var.number(), 0);
ADReal an = dudn.derivatives()[dof_number];
an *= diff_face;
_rc_uo.addToA(fi.neighborPtr(), _index, an * (fi.faceArea() * fi.faceCoord()));
}
const auto strong_resid = -diff_face * dudn;
processResidual(strong_resid * (fi.faceArea() * fi.faceCoord()));
#endif
}
<|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 main.cpp
* @author Gav Wood <i@gavwood.com>
* @date 2014
* Ethereum client.
*/
#include <fstream>
#include <iostream>
#include <clocale>
#include <liblll/Compiler.h>
#include <libdevcore/CommonIO.h>
#include <libdevcore/CommonData.h>
#include <libevmasm/Instruction.h>
using namespace std;
using namespace dev;
using namespace dev::solidity;
using namespace dev::eth;
void help()
{
cout
<< "Usage lllc [OPTIONS] <file>" << endl
<< "Options:" << endl
<< " -b,--binary Parse, compile and assemble; output byte code in binary." << endl
<< " -x,--hex Parse, compile and assemble; output byte code in hex." << endl
<< " -a,--assembly Only parse and compile; show assembly." << endl
<< " -t,--parse-tree Only parse; show parse tree." << endl
<< " -h,--help Show this help message and exit." << endl
<< " -V,--version Show the version and exit." << endl;
exit(0);
}
void version()
{
cout << "LLLC, the Lovely Little Language Compiler " << endl;
cout << " By Gav Wood, (c) 2014." << endl;
exit(0);
}
/*
The equivalent of setlocale(LC_ALL, "C") is called before any user code is run.
If the user has an invalid environment setting then it is possible for the call
to set locale to fail, so there are only two possible actions, the first is to
throw a runtime exception and cause the program to quit (default behaviour),
or the second is to modify the environment to something sensible (least
surprising behaviour).
The follow code produces the least surprising behaviour. It will use the user
specified default locale if it is valid, and if not then it will modify the
environment the process is running in to use a sensible default. This also means
that users do not need to install language packs for their OS.
*/
void setDefaultOrCLocale()
{
#if __unix__
if (!std::setlocale(LC_ALL, ""))
{
setenv("LC_ALL", "C", 1);
}
#endif
}
enum Mode { Binary, Hex, Assembly, ParseTree, Disassemble };
int main(int argc, char** argv)
{
setDefaultOrCLocale();
unsigned optimise = 1;
string infile;
Mode mode = Hex;
for (int i = 1; i < argc; ++i)
{
string arg = argv[i];
if (arg == "-h" || arg == "--help")
help();
else if (arg == "-b" || arg == "--binary")
mode = Binary;
else if (arg == "-x" || arg == "--hex")
mode = Hex;
else if (arg == "-a" || arg == "--assembly")
mode = Assembly;
else if (arg == "-t" || arg == "--parse-tree")
mode = ParseTree;
else if ((arg == "-o" || arg == "--optimise") && argc > i + 1)
optimise = atoi(argv[++i]);
else if (arg == "-d" || arg == "--disassemble")
mode = Disassemble;
else if (arg == "-V" || arg == "--version")
version();
else
infile = argv[i];
}
string src;
if (infile.empty())
{
string s;
while (!cin.eof())
{
getline(cin, s);
src.append(s);
}
}
else
src = contentsString(infile);
vector<string> errors;
if (src.empty())
errors.push_back("Empty file.");
else if (mode == Disassemble)
{
cout << disassemble(fromHex(src)) << endl;
}
else if (mode == Binary || mode == Hex)
{
auto bs = compileLLL(src, optimise ? true : false, &errors);
if (mode == Hex)
cout << toHex(bs) << endl;
else if (mode == Binary)
cout.write((char const*)bs.data(), bs.size());
}
else if (mode == ParseTree)
cout << parseLLL(src) << endl;
else if (mode == Assembly)
cout << compileLLLToAsm(src, optimise ? true : false, &errors) << endl;
for (auto const& i: errors)
cerr << i << endl;
if ( errors.size() )
return 1;
return 0;
}
<commit_msg>LLL: document optimise flag<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 main.cpp
* @author Gav Wood <i@gavwood.com>
* @date 2014
* Ethereum client.
*/
#include <fstream>
#include <iostream>
#include <clocale>
#include <liblll/Compiler.h>
#include <libdevcore/CommonIO.h>
#include <libdevcore/CommonData.h>
#include <libevmasm/Instruction.h>
using namespace std;
using namespace dev;
using namespace dev::solidity;
using namespace dev::eth;
void help()
{
cout
<< "Usage lllc [OPTIONS] <file>" << endl
<< "Options:" << endl
<< " -b,--binary Parse, compile and assemble; output byte code in binary." << endl
<< " -x,--hex Parse, compile and assemble; output byte code in hex." << endl
<< " -a,--assembly Only parse and compile; show assembly." << endl
<< " -t,--parse-tree Only parse; show parse tree." << endl
<< " -o,--optimise Turn on/off the optimiser; on by default." << endl
<< " -h,--help Show this help message and exit." << endl
<< " -V,--version Show the version and exit." << endl;
exit(0);
}
void version()
{
cout << "LLLC, the Lovely Little Language Compiler " << endl;
cout << " By Gav Wood, (c) 2014." << endl;
exit(0);
}
/*
The equivalent of setlocale(LC_ALL, "C") is called before any user code is run.
If the user has an invalid environment setting then it is possible for the call
to set locale to fail, so there are only two possible actions, the first is to
throw a runtime exception and cause the program to quit (default behaviour),
or the second is to modify the environment to something sensible (least
surprising behaviour).
The follow code produces the least surprising behaviour. It will use the user
specified default locale if it is valid, and if not then it will modify the
environment the process is running in to use a sensible default. This also means
that users do not need to install language packs for their OS.
*/
void setDefaultOrCLocale()
{
#if __unix__
if (!std::setlocale(LC_ALL, ""))
{
setenv("LC_ALL", "C", 1);
}
#endif
}
enum Mode { Binary, Hex, Assembly, ParseTree, Disassemble };
int main(int argc, char** argv)
{
setDefaultOrCLocale();
unsigned optimise = 1;
string infile;
Mode mode = Hex;
for (int i = 1; i < argc; ++i)
{
string arg = argv[i];
if (arg == "-h" || arg == "--help")
help();
else if (arg == "-b" || arg == "--binary")
mode = Binary;
else if (arg == "-x" || arg == "--hex")
mode = Hex;
else if (arg == "-a" || arg == "--assembly")
mode = Assembly;
else if (arg == "-t" || arg == "--parse-tree")
mode = ParseTree;
else if ((arg == "-o" || arg == "--optimise") && argc > i + 1)
optimise = atoi(argv[++i]);
else if (arg == "-d" || arg == "--disassemble")
mode = Disassemble;
else if (arg == "-V" || arg == "--version")
version();
else
infile = argv[i];
}
string src;
if (infile.empty())
{
string s;
while (!cin.eof())
{
getline(cin, s);
src.append(s);
}
}
else
src = contentsString(infile);
vector<string> errors;
if (src.empty())
errors.push_back("Empty file.");
else if (mode == Disassemble)
{
cout << disassemble(fromHex(src)) << endl;
}
else if (mode == Binary || mode == Hex)
{
auto bs = compileLLL(src, optimise ? true : false, &errors);
if (mode == Hex)
cout << toHex(bs) << endl;
else if (mode == Binary)
cout.write((char const*)bs.data(), bs.size());
}
else if (mode == ParseTree)
cout << parseLLL(src) << endl;
else if (mode == Assembly)
cout << compileLLLToAsm(src, optimise ? true : false, &errors) << endl;
for (auto const& i: errors)
cerr << i << endl;
if ( errors.size() )
return 1;
return 0;
}
<|endoftext|>
|
<commit_before>#include "RdRobotManager.hpp"
//-- This is very important:
rd::RdRobotManager * rd::RdRobotManager::robotManager = NULL;
void rd::RdRobotManager::registerManager(std::string name, rd::RdRobotManager *manager)
{
if ( robotManagerRegistry.find(name) == robotManagerRegistry.end() )
{
robotManagerRegistry[name] = manager;
}
else
{
RD_ERROR("RdManager with name \"%s\" already exists!\n", name.c_str());
}
}
std::vector<std::string> rd::RdRobotManager::listAll()
{
std::vector<std::string> robot_manager_list;
for( std::map<std::string, RdRobotManager*>::const_iterator it = robotManagerRegistry.begin(); it != robotManagerRegistry.end(); ++it)
{
robot_manager_list.push_back(it->first);
}
return robot_manager_list;
}
rd::RdRobotManager *rd::RdRobotManager::getRobotManager(std::string name)
{
if (robotManager == NULL)
{
if ( robotManagerRegistry.find(name) != robotManagerRegistry.end() )
{
robotManager = robotManagerRegistry[name];
}
else
{
RD_ERROR("RdRobotManager requested (\"%s\") does not exist.\n", name.c_str());
}
}
return robotManager;
}
bool rd::RdRobotManager::destroyRobotManager()
{
if (robotManager == NULL)
return false;
delete robotManager;
robotManager = NULL;
return true;
}
rd::RdRobotManager::~RdRobotManager()
{
this->onDestroy();
}
<commit_msg>Now it compiles<commit_after>#include "RdRobotManager.hpp"
<|endoftext|>
|
<commit_before>/*-
* linux_wire.cc
*
* Implementation of Wire for linux, may work on other UN*X systems
* too...
*/
#include "config.h"
#if !HAVE_LIBPCAP
#include <cstring>
#include <cerrno>
#include <sys/types.h>
#include <sys/ioctl.h>
#include <sys/socket.h>
#include <sys/select.h>
#include <net/ethernet.h>
#if 0
/* Including this is incompatible with including linux/if_arp.h */
#include <net/if.h>
#include <netpacket/packet.h>
#else
#include <asm/types.h>
#include <linux/if_packet.h>
#include <linux/if_ether.h>
#include <linux/if_arp.h>
#endif
#include <unistd.h>
#include <sys/types.h> /* Required for class EUID */
#include "nslu2_upgrade.h"
namespace NSLU2Upgrade {
/* The basic class implemented to transmit and receive packets over the
* wire.
*/
class EthernetWire : public Wire {
public:
EthernetWire(int s, int hw_index, const unsigned char address[6]) :
socket(s), broadcast(true) {
/* Most of these fields aren't used in any given request,
* but it does no harm to fill them all correctly.
*/
nslu2To.sll_family = AF_PACKET;
nslu2To.sll_protocol = NSLU2Protocol::UpgradeProtocol;
nslu2To.sll_ifindex = hw_index;
nslu2To.sll_hatype = ARPHRD_IEEE802;
nslu2To.sll_pkttype = address ? PACKET_HOST : PACKET_BROADCAST;
nslu2To.sll_halen = 6;
/* The 255 gives the ethernet hardware broadcast address,
* overwrite this if a host address is provided.
*/
std::memset(nslu2To.sll_addr, 255, sizeof nslu2To.sll_addr);
if (address) {
broadcast = false;
std::memcpy(nslu2To.sll_addr, address, 6);
}
/* This is set just in case of a call to LastAddress before
* Receive has succeeded - the result will be all 0's
*/
std::memset(nslu2From.sll_addr, 0, sizeof nslu2From.sll_addr);
}
virtual ~EthernetWire() {
(void)close(socket);
}
/* Throws SendError on a fatal error. */
virtual void Send(const void *packet, size_t length) {
/* Set no flags (0) - we block on the sendto if
* required, the socket is *not* set O_NONBLOCK.
*/
while (sendto(socket, packet, length, 0,
reinterpret_cast<sockaddr*>(&nslu2To),
sizeof nslu2To) == (-1)) {
if (errno != EINTR)
throw SendError(errno);
}
}
/* Receive throws ReceiveError on a fatal error and must update
* size with the received packet size. 0 must be used to
* indicate failure to receive a packet (and this must not
* be fatal). If timeout is greater than 0 the implementation
* should wait that number of microseconds until a packet is
* received or the timeout has expired (in which case a size
* of 0 must be returned).
*/
virtual void Receive(void *buffer, size_t &size, unsigned long timeout) {
/* The socket is blocking (O_NONBLOCK is not set) therefore
* handle the 'block' option by polling. Even if 'block'
* is true this call must not actually block - just
* time out - because the response packet we are waiting
* for may actually have been dropped.
*/
do {
fd_set readfds;
FD_ZERO(&readfds);
FD_SET(socket, &readfds);
/* Timeout as requested by the caller. */
struct timeval tv;
tv.tv_sec = timeout >> 20;
tv.tv_usec = timeout & 0xfffff;
if (tv.tv_usec >= 1000000)
++tv.tv_sec, tv.tv_usec = 0;
/* See if there is anything to read... */
do {
int fds(select(socket+1, &readfds, 0, 0, &tv));
if (fds == 0) {
size = 0;
return;
}
if (fds != (-1))
break;
if (errno != EINTR)
throw ReceiveError(errno);
} while (1);
/* There is something to read... */
socklen_t resultSize(sizeof nslu2From);
ssize_t result(recvfrom(socket, buffer, size, 0,
reinterpret_cast<sockaddr*>(&nslu2From),
&resultSize));
if (result == (-1)) {
if (errno != EINTR)
throw ReceiveError(errno);
} else if (broadcast || std::memcmp(nslu2To.sll_addr,
nslu2From.sll_addr, 6) == 0) {
/* otherwise this is not a packet for this
* program and it is just ignored.
*/
size = result;
return;
}
} while (1);
}
/* Return the address of the last received packet. This is
* an NSLU2 so the address is a 6 byte Ethernet hardware
* address.
*/
virtual void LastAddress(unsigned char address[6]) {
std::memcpy(address, nslu2From.sll_addr, 6);
}
private:
struct sockaddr_ll nslu2To;
struct sockaddr_ll nslu2From;
int socket;
bool broadcast;
};
/* Class to set and reset the user id to the effective uid. */
/* Requires unistd.h and sys/types.h */
class EUID {
public:
EUID(int uid) : euid(::geteuid()) {
if (uid != -1 && ::seteuid(uid) != 0)
throw WireError(errno);
}
~EUID() {
::seteuid(euid);
}
private:
::uid_t euid;
};
};
/* Make a new wire, which may be deleted with delete. The
* address should be a value (null terminated this time) returned
* by LastAddress, if NULL the Wire will broadcast. 'device'
* is the hardware device name to use - the value of the
* --device parameter on the command line (if given). If not
* given (NULL) a potentially useless default will be used.
*/
NSLU2Upgrade::Wire *NSLU2Upgrade::Wire::MakeWire(const char *device,
const unsigned char *address, int uid) {
int packet_socket;
struct ifreq device_interface;
{
EUID euid(uid);
/* Obtain a datagram low level socket using the 'invented' NSLU2
* protocol number. Change to the effective user id to do
* this (if given).
*/
packet_socket = socket(PF_PACKET, SOCK_DGRAM, NSLU2Protocol::UpgradeProtocol);
if (packet_socket == (-1))
throw WireError(errno);
/* Check the device name. If not given use 'eth0'. */
if (device == NULL)
device = "eth0";
/* We are using a level which requires a hardware specific address,
* that's because the NSLU2 doesn't (for reasons which are far from
* obvious) implement a standard protocol for the upgrade, therefore
* there is no standard way of addressing the NSLU2. Instead we must
* use the hardware, which on the NSLU2 is Ethernet, and which therefore
* has a 6 byte 'name'.
*
* What this means is that we need to be talking on an ethernet device;
* there ain't no way of getting a random ethernet packet onto some
* other network, because there is no way of mapping the address (which
* is an ethernet hardware id) into an appropriate address on another
* network. (NOTE: 'tunnelling' stuff does this, it wraps the whole
* packet up inside another packet and sends it down the tunnel, it gets
* unwrapped at the other end, but that is transparent to this code.)
*
* At this point we need an ethernet device to talk to. Notice that this
* could, in theory, be a fake device - just so long as the NSLU2 has a
* six byte ethernet address to talk back to. We look the given device
* name up on the socket. (See netdevice(7) - this is linux specific)
*
* NOTE: if you are looking at this code and trying to port it the device
* stuff may be irrelevant, what you need to do is receive all packets
* with the protocol 0x8888 (NSLU2Protocol::UpgradeProtocol) from any
* *ethernet* MAC to implement the broadcast stuff and from a specific
* ethernet MAC to implement upgrade. The broadcast stuff isn't necessary
* to implement a working upslug2 - because the ethernet MAC can be
* determined from the label on the bottom of an NSLU2, so the user can
* just be obliged to turn the damn box over. And this is a better GUI.
*/
strncpy(device_interface.ifr_name, device, sizeof device_interface.ifr_name);
device_interface.ifr_name[(sizeof device_interface.ifr_name)-1] = 0;
if (ioctl(packet_socket, SIOCGIFINDEX, &device_interface) == (-1)) {
/* This means the device name is bogus, because if we weren't
* euid 0 the socket call would have EACCESed above.
*/
const int err(errno);
(void)close(packet_socket);
throw WireError(err);
}
}
/* This is enough to make a new wire. */
return new EthernetWire(packet_socket, device_interface.ifr_ifindex, address);
}
#endif
<commit_msg>Fix the use of linux specific header files - not necessary and doesn't work with later versions of glibc.<commit_after>/*-
* linux_wire.cc
*
* Implementation of Wire for linux, may work on other UN*X systems
* too...
*/
#include "config.h"
#if !HAVE_LIBPCAP
#include <cstring>
#include <cerrno>
#include <sys/types.h>
#include <sys/ioctl.h>
#include <sys/socket.h>
#include <sys/select.h>
#include <net/ethernet.h>
#include <net/if.h>
#include <net/if_arp.h>
#include <netpacket/packet.h>
#include <unistd.h>
#include <sys/types.h> /* Required for class EUID */
#include "nslu2_upgrade.h"
namespace NSLU2Upgrade {
/* The basic class implemented to transmit and receive packets over the
* wire.
*/
class EthernetWire : public Wire {
public:
EthernetWire(int s, int hw_index, const unsigned char address[6]) :
socket(s), broadcast(true) {
/* Most of these fields aren't used in any given request,
* but it does no harm to fill them all correctly.
*/
nslu2To.sll_family = AF_PACKET;
nslu2To.sll_protocol = NSLU2Protocol::UpgradeProtocol;
nslu2To.sll_ifindex = hw_index;
nslu2To.sll_hatype = ARPHRD_IEEE802;
nslu2To.sll_pkttype = address ? PACKET_HOST : PACKET_BROADCAST;
nslu2To.sll_halen = 6;
/* The 255 gives the ethernet hardware broadcast address,
* overwrite this if a host address is provided.
*/
std::memset(nslu2To.sll_addr, 255, sizeof nslu2To.sll_addr);
if (address) {
broadcast = false;
std::memcpy(nslu2To.sll_addr, address, 6);
}
/* This is set just in case of a call to LastAddress before
* Receive has succeeded - the result will be all 0's
*/
std::memset(nslu2From.sll_addr, 0, sizeof nslu2From.sll_addr);
}
virtual ~EthernetWire() {
(void)close(socket);
}
/* Throws SendError on a fatal error. */
virtual void Send(const void *packet, size_t length) {
/* Set no flags (0) - we block on the sendto if
* required, the socket is *not* set O_NONBLOCK.
*/
while (sendto(socket, packet, length, 0,
reinterpret_cast<sockaddr*>(&nslu2To),
sizeof nslu2To) == (-1)) {
if (errno != EINTR)
throw SendError(errno);
}
}
/* Receive throws ReceiveError on a fatal error and must update
* size with the received packet size. 0 must be used to
* indicate failure to receive a packet (and this must not
* be fatal). If timeout is greater than 0 the implementation
* should wait that number of microseconds until a packet is
* received or the timeout has expired (in which case a size
* of 0 must be returned).
*/
virtual void Receive(void *buffer, size_t &size, unsigned long timeout) {
/* The socket is blocking (O_NONBLOCK is not set) therefore
* handle the 'block' option by polling. Even if 'block'
* is true this call must not actually block - just
* time out - because the response packet we are waiting
* for may actually have been dropped.
*/
do {
fd_set readfds;
FD_ZERO(&readfds);
FD_SET(socket, &readfds);
/* Timeout as requested by the caller. */
struct timeval tv;
tv.tv_sec = timeout >> 20;
tv.tv_usec = timeout & 0xfffff;
if (tv.tv_usec >= 1000000)
++tv.tv_sec, tv.tv_usec = 0;
/* See if there is anything to read... */
do {
int fds(select(socket+1, &readfds, 0, 0, &tv));
if (fds == 0) {
size = 0;
return;
}
if (fds != (-1))
break;
if (errno != EINTR)
throw ReceiveError(errno);
} while (1);
/* There is something to read... */
socklen_t resultSize(sizeof nslu2From);
ssize_t result(recvfrom(socket, buffer, size, 0,
reinterpret_cast<sockaddr*>(&nslu2From),
&resultSize));
if (result == (-1)) {
if (errno != EINTR)
throw ReceiveError(errno);
} else if (broadcast || std::memcmp(nslu2To.sll_addr,
nslu2From.sll_addr, 6) == 0) {
/* otherwise this is not a packet for this
* program and it is just ignored.
*/
size = result;
return;
}
} while (1);
}
/* Return the address of the last received packet. This is
* an NSLU2 so the address is a 6 byte Ethernet hardware
* address.
*/
virtual void LastAddress(unsigned char address[6]) {
std::memcpy(address, nslu2From.sll_addr, 6);
}
private:
struct sockaddr_ll nslu2To;
struct sockaddr_ll nslu2From;
int socket;
bool broadcast;
};
/* Class to set and reset the user id to the effective uid. */
/* Requires unistd.h and sys/types.h */
class EUID {
public:
EUID(int uid) : euid(::geteuid()) {
if (uid != -1 && ::seteuid(uid) != 0)
throw WireError(errno);
}
~EUID() {
::seteuid(euid);
}
private:
::uid_t euid;
};
};
/* Make a new wire, which may be deleted with delete. The
* address should be a value (null terminated this time) returned
* by LastAddress, if NULL the Wire will broadcast. 'device'
* is the hardware device name to use - the value of the
* --device parameter on the command line (if given). If not
* given (NULL) a potentially useless default will be used.
*/
NSLU2Upgrade::Wire *NSLU2Upgrade::Wire::MakeWire(const char *device,
const unsigned char *address, int uid) {
int packet_socket;
struct ifreq device_interface;
{
EUID euid(uid);
/* Obtain a datagram low level socket using the 'invented' NSLU2
* protocol number. Change to the effective user id to do
* this (if given).
*/
packet_socket = socket(PF_PACKET, SOCK_DGRAM, NSLU2Protocol::UpgradeProtocol);
if (packet_socket == (-1))
throw WireError(errno);
/* Check the device name. If not given use 'eth0'. */
if (device == NULL)
device = "eth0";
/* We are using a level which requires a hardware specific address,
* that's because the NSLU2 doesn't (for reasons which are far from
* obvious) implement a standard protocol for the upgrade, therefore
* there is no standard way of addressing the NSLU2. Instead we must
* use the hardware, which on the NSLU2 is Ethernet, and which therefore
* has a 6 byte 'name'.
*
* What this means is that we need to be talking on an ethernet device;
* there ain't no way of getting a random ethernet packet onto some
* other network, because there is no way of mapping the address (which
* is an ethernet hardware id) into an appropriate address on another
* network. (NOTE: 'tunnelling' stuff does this, it wraps the whole
* packet up inside another packet and sends it down the tunnel, it gets
* unwrapped at the other end, but that is transparent to this code.)
*
* At this point we need an ethernet device to talk to. Notice that this
* could, in theory, be a fake device - just so long as the NSLU2 has a
* six byte ethernet address to talk back to. We look the given device
* name up on the socket. (See netdevice(7) - this is linux specific)
*
* NOTE: if you are looking at this code and trying to port it the device
* stuff may be irrelevant, what you need to do is receive all packets
* with the protocol 0x8888 (NSLU2Protocol::UpgradeProtocol) from any
* *ethernet* MAC to implement the broadcast stuff and from a specific
* ethernet MAC to implement upgrade. The broadcast stuff isn't necessary
* to implement a working upslug2 - because the ethernet MAC can be
* determined from the label on the bottom of an NSLU2, so the user can
* just be obliged to turn the damn box over. And this is a better GUI.
*/
strncpy(device_interface.ifr_name, device, sizeof device_interface.ifr_name);
device_interface.ifr_name[(sizeof device_interface.ifr_name)-1] = 0;
if (ioctl(packet_socket, SIOCGIFINDEX, &device_interface) == (-1)) {
/* This means the device name is bogus, because if we weren't
* euid 0 the socket call would have EACCESed above.
*/
const int err(errno);
(void)close(packet_socket);
throw WireError(err);
}
}
/* This is enough to make a new wire. */
return new EthernetWire(packet_socket, device_interface.ifr_ifindex, address);
}
#endif
<|endoftext|>
|
<commit_before>/**************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2012 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** 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.
**
** 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.
**
** If you have questions regarding the use of this file, please contact
** Nokia at qt-info@nokia.com.
**
**************************************************************************/
#include "baseenginedebugclient.h"
#include "qmldebugconstants.h"
namespace QmlDebug {
struct QmlObjectData {
QUrl url;
int lineNumber;
int columnNumber;
QString idString;
QString objectName;
QString objectType;
int objectId;
int contextId;
};
QDataStream &operator>>(QDataStream &ds, QmlObjectData &data)
{
ds >> data.url >> data.lineNumber >> data.columnNumber >> data.idString
>> data.objectName >> data.objectType >> data.objectId >> data.contextId;
return ds;
}
struct QmlObjectProperty {
enum Type { Unknown, Basic, Object, List, SignalProperty };
Type type;
QString name;
QVariant value;
QString valueTypeName;
QString binding;
bool hasNotifySignal;
};
QDataStream &operator>>(QDataStream &ds, QmlObjectProperty &data)
{
int type;
ds >> type >> data.name >> data.value >> data.valueTypeName
>> data.binding >> data.hasNotifySignal;
data.type = (QmlObjectProperty::Type)type;
return ds;
}
void BaseEngineDebugClient::decode(QDataStream &ds,
QmlDebugObjectReference &o,
bool simple)
{
QmlObjectData data;
ds >> data;
int parentId = -1;
if (objectName() == QLatin1String("QmlDebugger") &&
serviceVersion() >= Constants::CURRENT_SUPPORTED_VERSION )
ds >> parentId;
o.m_debugId = data.objectId;
o.m_className = data.objectType;
o.m_idString = data.idString;
o.m_name = data.objectName;
o.m_source.m_url = data.url;
o.m_source.m_lineNumber = data.lineNumber;
o.m_source.m_columnNumber = data.columnNumber;
o.m_contextDebugId = data.contextId;
o.m_needsMoreData = simple;
o.m_parentId = parentId;
if (simple)
return;
int childCount;
bool recur;
ds >> childCount >> recur;
for (int ii = 0; ii < childCount; ++ii) {
o.m_children.append(QmlDebugObjectReference());
decode(ds, o.m_children.last(), !recur);
}
int propCount;
ds >> propCount;
for (int ii = 0; ii < propCount; ++ii) {
QmlObjectProperty data;
ds >> data;
QmlDebugPropertyReference prop;
prop.m_objectDebugId = o.m_debugId;
prop.m_name = data.name;
prop.m_binding = data.binding;
prop.m_hasNotifySignal = data.hasNotifySignal;
prop.m_valueTypeName = data.valueTypeName;
switch (data.type) {
case QmlObjectProperty::Basic:
case QmlObjectProperty::List:
case QmlObjectProperty::SignalProperty:
{
prop.m_value = data.value;
break;
}
case QmlObjectProperty::Object:
{
QmlDebugObjectReference obj;
obj.m_debugId = prop.m_value.toInt();
prop.m_value = qVariantFromValue(obj);
break;
}
case QmlObjectProperty::Unknown:
break;
}
o.m_properties << prop;
}
}
void BaseEngineDebugClient::decode(QDataStream &ds,
QmlDebugContextReference &c)
{
ds >> c.m_name >> c.m_debugId;
int contextCount;
ds >> contextCount;
for (int ii = 0; ii < contextCount; ++ii) {
c.m_contexts.append(QmlDebugContextReference());
decode(ds, c.m_contexts.last());
}
int objectCount;
ds >> objectCount;
for (int ii = 0; ii < objectCount; ++ii) {
QmlDebugObjectReference obj;
decode(ds, obj, true);
obj.m_contextDebugId = c.m_debugId;
c.m_objects << obj;
}
}
void BaseEngineDebugClient::statusChanged(Status status)
{
emit newStatus(status);
}
void BaseEngineDebugClient::messageReceived(const QByteArray &data)
{
QDataStream ds(data);
int queryId;
QByteArray type;
ds >> type;
if (type == "OBJECT_CREATED") {
emit newObjects();
return;
}
ds >> queryId;
if (type == "LIST_ENGINES_R") {
int count;
ds >> count;
QmlDebugEngineReferenceList engines;
for (int ii = 0; ii < count; ++ii) {
QmlDebugEngineReference eng;
ds >> eng.m_name;
ds >> eng.m_debugId;
engines << eng;
}
emit result(queryId, QVariant::fromValue(engines), type);
} else if (type == "LIST_OBJECTS_R") {
QmlDebugContextReference rootContext;
if (!ds.atEnd())
decode(ds, rootContext);
emit result(queryId, QVariant::fromValue(rootContext), type);
} else if (type == "FETCH_OBJECT_R") {
QmlDebugObjectReference object;
if (!ds.atEnd())
decode(ds, object, false);
emit result(queryId, QVariant::fromValue(object), type);
} else if (type == "EVAL_EXPRESSION_R") {;
QVariant exprResult;
ds >> exprResult;
emit result(queryId, exprResult, type);
} else if (type == "WATCH_PROPERTY_R" ||
type == "WATCH_OBJECT_R" ||
type == "WATCH_EXPR_OBJECT_R") {
bool valid;
ds >> valid;
emit result(queryId, valid, type);
} else if (type == "UPDATE_WATCH") {
int debugId;
QByteArray name;
QVariant value;
ds >> debugId >> name >> value;
emit valueChanged(debugId, name, value);
}
}
BaseEngineDebugClient::BaseEngineDebugClient(const QString &clientName,
QmlDebugConnection *conn)
: QmlDebugClient(clientName, conn),
m_nextId(1)
{
setObjectName(clientName);
}
quint32 BaseEngineDebugClient::addWatch(const QmlDebugPropertyReference &property)
{
quint32 id;
if (status() == QmlDebugClient::Enabled) {
id = getId();
QByteArray message;
QDataStream ds(&message, QIODevice::WriteOnly);
ds << QByteArray("WATCH_PROPERTY") << id << property.m_objectDebugId
<< property.m_name.toUtf8();
sendMessage(message);
}
return id;
}
quint32 BaseEngineDebugClient::addWatch(const QmlDebugContextReference &/*context*/,
const QString &/*id*/)
{
qWarning("QmlEngineDebugClient::addWatch(): Not implemented");
return 0;
}
quint32 BaseEngineDebugClient::addWatch(const QmlDebugObjectReference &object,
const QString &expr)
{
quint32 id = 0;
if (status() == QmlDebugClient::Enabled) {
id = getId();
QByteArray message;
QDataStream ds(&message, QIODevice::WriteOnly);
ds << QByteArray("WATCH_EXPR_OBJECT") << id << object.m_debugId << expr;
sendMessage(message);
}
return id;
}
quint32 BaseEngineDebugClient::addWatch(const QmlDebugObjectReference &object)
{
quint32 id = 0;
if (status() == QmlDebugClient::Enabled) {
id = getId();
QByteArray message;
QDataStream ds(&message, QIODevice::WriteOnly);
ds << QByteArray("WATCH_OBJECT") << id << object.m_debugId;
sendMessage(message);
}
return id;
}
quint32 BaseEngineDebugClient::addWatch(const QmlDebugFileReference &/*file*/)
{
qWarning("QmlEngineDebugClient::addWatch(): Not implemented");
return 0;
}
void BaseEngineDebugClient::removeWatch(quint32 id)
{
if (status() == QmlDebugClient::Enabled) {
QByteArray message;
QDataStream ds(&message, QIODevice::WriteOnly);
ds << QByteArray("NO_WATCH") << id;
sendMessage(message);
}
}
quint32 BaseEngineDebugClient::queryAvailableEngines()
{
quint32 id = 0;
if (status() == QmlDebugClient::Enabled) {
id = getId();
QByteArray message;
QDataStream ds(&message, QIODevice::WriteOnly);
ds << QByteArray("LIST_ENGINES") << id;
sendMessage(message);
}
return id;
}
quint32 BaseEngineDebugClient::queryRootContexts(const QmlDebugEngineReference &engine)
{
quint32 id = 0;
if (status() == QmlDebugClient::Enabled && engine.m_debugId != -1) {
id = getId();
QByteArray message;
QDataStream ds(&message, QIODevice::WriteOnly);
ds << QByteArray("LIST_OBJECTS") << id << engine.m_debugId;
sendMessage(message);
}
return id;
}
quint32 BaseEngineDebugClient::queryObject(const QmlDebugObjectReference &object)
{
quint32 id = 0;
if (status() == QmlDebugClient::Enabled && object.m_debugId != -1) {
id = getId();
QByteArray message;
QDataStream ds(&message, QIODevice::WriteOnly);
ds << QByteArray("FETCH_OBJECT") << id << object.m_debugId << false <<
true;
sendMessage(message);
}
return id;
}
quint32 BaseEngineDebugClient::queryObjectRecursive(const QmlDebugObjectReference &object)
{
quint32 id = 0;
if (status() == QmlDebugClient::Enabled && object.m_debugId != -1) {
id = getId();
QByteArray message;
QDataStream ds(&message, QIODevice::WriteOnly);
ds << QByteArray("FETCH_OBJECT") << id << object.m_debugId << true <<
true;
sendMessage(message);
}
return id;
}
quint32 BaseEngineDebugClient::queryExpressionResult(int objectDebugId,
const QString &expr,
int engineId)
{
quint32 id = 0;
if (status() == QmlDebugClient::Enabled && objectDebugId != -1) {
id = getId();
QByteArray message;
QDataStream ds(&message, QIODevice::WriteOnly);
ds << QByteArray("EVAL_EXPRESSION") << id << objectDebugId << expr
<< engineId;
sendMessage(message);
}
return id;
}
quint32 BaseEngineDebugClient::setBindingForObject(
int objectDebugId,
const QString &propertyName,
const QVariant &bindingExpression,
bool isLiteralValue,
QString source, int line)
{
quint32 id = 0;
if (status() == QmlDebugClient::Enabled && objectDebugId != -1) {
id = getId();
QByteArray message;
QDataStream ds(&message, QIODevice::WriteOnly);
ds << QByteArray("SET_BINDING") << objectDebugId << propertyName
<< bindingExpression << isLiteralValue << source << line;
sendMessage(message);
}
return id;
}
quint32 BaseEngineDebugClient::resetBindingForObject(
int objectDebugId,
const QString &propertyName)
{
quint32 id = 0;
if (status() == QmlDebugClient::Enabled && objectDebugId != -1) {
id = getId();
QByteArray message;
QDataStream ds(&message, QIODevice::WriteOnly);
ds << QByteArray("RESET_BINDING") << objectDebugId << propertyName;
sendMessage(message);
}
return id;
}
quint32 BaseEngineDebugClient::setMethodBody(
int objectDebugId, const QString &methodName,
const QString &methodBody)
{
quint32 id = 0;
if (status() == QmlDebugClient::Enabled && objectDebugId != -1) {
id = getId();
QByteArray message;
QDataStream ds(&message, QIODevice::WriteOnly);
ds << QByteArray("SET_METHOD_BODY") << objectDebugId
<< methodName << methodBody;
sendMessage(message);
}
return id;
}
} // namespace QmlDebug
<commit_msg>QmlDebug: Fix warning about unitialized variable<commit_after>/**************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2012 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** 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.
**
** 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.
**
** If you have questions regarding the use of this file, please contact
** Nokia at qt-info@nokia.com.
**
**************************************************************************/
#include "baseenginedebugclient.h"
#include "qmldebugconstants.h"
namespace QmlDebug {
struct QmlObjectData {
QUrl url;
int lineNumber;
int columnNumber;
QString idString;
QString objectName;
QString objectType;
int objectId;
int contextId;
};
QDataStream &operator>>(QDataStream &ds, QmlObjectData &data)
{
ds >> data.url >> data.lineNumber >> data.columnNumber >> data.idString
>> data.objectName >> data.objectType >> data.objectId >> data.contextId;
return ds;
}
struct QmlObjectProperty {
enum Type { Unknown, Basic, Object, List, SignalProperty };
Type type;
QString name;
QVariant value;
QString valueTypeName;
QString binding;
bool hasNotifySignal;
};
QDataStream &operator>>(QDataStream &ds, QmlObjectProperty &data)
{
int type;
ds >> type >> data.name >> data.value >> data.valueTypeName
>> data.binding >> data.hasNotifySignal;
data.type = (QmlObjectProperty::Type)type;
return ds;
}
void BaseEngineDebugClient::decode(QDataStream &ds,
QmlDebugObjectReference &o,
bool simple)
{
QmlObjectData data;
ds >> data;
int parentId = -1;
if (objectName() == QLatin1String("QmlDebugger") &&
serviceVersion() >= Constants::CURRENT_SUPPORTED_VERSION )
ds >> parentId;
o.m_debugId = data.objectId;
o.m_className = data.objectType;
o.m_idString = data.idString;
o.m_name = data.objectName;
o.m_source.m_url = data.url;
o.m_source.m_lineNumber = data.lineNumber;
o.m_source.m_columnNumber = data.columnNumber;
o.m_contextDebugId = data.contextId;
o.m_needsMoreData = simple;
o.m_parentId = parentId;
if (simple)
return;
int childCount;
bool recur;
ds >> childCount >> recur;
for (int ii = 0; ii < childCount; ++ii) {
o.m_children.append(QmlDebugObjectReference());
decode(ds, o.m_children.last(), !recur);
}
int propCount;
ds >> propCount;
for (int ii = 0; ii < propCount; ++ii) {
QmlObjectProperty data;
ds >> data;
QmlDebugPropertyReference prop;
prop.m_objectDebugId = o.m_debugId;
prop.m_name = data.name;
prop.m_binding = data.binding;
prop.m_hasNotifySignal = data.hasNotifySignal;
prop.m_valueTypeName = data.valueTypeName;
switch (data.type) {
case QmlObjectProperty::Basic:
case QmlObjectProperty::List:
case QmlObjectProperty::SignalProperty:
{
prop.m_value = data.value;
break;
}
case QmlObjectProperty::Object:
{
QmlDebugObjectReference obj;
obj.m_debugId = prop.m_value.toInt();
prop.m_value = qVariantFromValue(obj);
break;
}
case QmlObjectProperty::Unknown:
break;
}
o.m_properties << prop;
}
}
void BaseEngineDebugClient::decode(QDataStream &ds,
QmlDebugContextReference &c)
{
ds >> c.m_name >> c.m_debugId;
int contextCount;
ds >> contextCount;
for (int ii = 0; ii < contextCount; ++ii) {
c.m_contexts.append(QmlDebugContextReference());
decode(ds, c.m_contexts.last());
}
int objectCount;
ds >> objectCount;
for (int ii = 0; ii < objectCount; ++ii) {
QmlDebugObjectReference obj;
decode(ds, obj, true);
obj.m_contextDebugId = c.m_debugId;
c.m_objects << obj;
}
}
void BaseEngineDebugClient::statusChanged(Status status)
{
emit newStatus(status);
}
void BaseEngineDebugClient::messageReceived(const QByteArray &data)
{
QDataStream ds(data);
int queryId;
QByteArray type;
ds >> type;
if (type == "OBJECT_CREATED") {
emit newObjects();
return;
}
ds >> queryId;
if (type == "LIST_ENGINES_R") {
int count;
ds >> count;
QmlDebugEngineReferenceList engines;
for (int ii = 0; ii < count; ++ii) {
QmlDebugEngineReference eng;
ds >> eng.m_name;
ds >> eng.m_debugId;
engines << eng;
}
emit result(queryId, QVariant::fromValue(engines), type);
} else if (type == "LIST_OBJECTS_R") {
QmlDebugContextReference rootContext;
if (!ds.atEnd())
decode(ds, rootContext);
emit result(queryId, QVariant::fromValue(rootContext), type);
} else if (type == "FETCH_OBJECT_R") {
QmlDebugObjectReference object;
if (!ds.atEnd())
decode(ds, object, false);
emit result(queryId, QVariant::fromValue(object), type);
} else if (type == "EVAL_EXPRESSION_R") {;
QVariant exprResult;
ds >> exprResult;
emit result(queryId, exprResult, type);
} else if (type == "WATCH_PROPERTY_R" ||
type == "WATCH_OBJECT_R" ||
type == "WATCH_EXPR_OBJECT_R") {
bool valid;
ds >> valid;
emit result(queryId, valid, type);
} else if (type == "UPDATE_WATCH") {
int debugId;
QByteArray name;
QVariant value;
ds >> debugId >> name >> value;
emit valueChanged(debugId, name, value);
}
}
BaseEngineDebugClient::BaseEngineDebugClient(const QString &clientName,
QmlDebugConnection *conn)
: QmlDebugClient(clientName, conn),
m_nextId(1)
{
setObjectName(clientName);
}
quint32 BaseEngineDebugClient::addWatch(const QmlDebugPropertyReference &property)
{
quint32 id = 0;
if (status() == QmlDebugClient::Enabled) {
id = getId();
QByteArray message;
QDataStream ds(&message, QIODevice::WriteOnly);
ds << QByteArray("WATCH_PROPERTY") << id << property.m_objectDebugId
<< property.m_name.toUtf8();
sendMessage(message);
}
return id;
}
quint32 BaseEngineDebugClient::addWatch(const QmlDebugContextReference &/*context*/,
const QString &/*id*/)
{
qWarning("QmlEngineDebugClient::addWatch(): Not implemented");
return 0;
}
quint32 BaseEngineDebugClient::addWatch(const QmlDebugObjectReference &object,
const QString &expr)
{
quint32 id = 0;
if (status() == QmlDebugClient::Enabled) {
id = getId();
QByteArray message;
QDataStream ds(&message, QIODevice::WriteOnly);
ds << QByteArray("WATCH_EXPR_OBJECT") << id << object.m_debugId << expr;
sendMessage(message);
}
return id;
}
quint32 BaseEngineDebugClient::addWatch(const QmlDebugObjectReference &object)
{
quint32 id = 0;
if (status() == QmlDebugClient::Enabled) {
id = getId();
QByteArray message;
QDataStream ds(&message, QIODevice::WriteOnly);
ds << QByteArray("WATCH_OBJECT") << id << object.m_debugId;
sendMessage(message);
}
return id;
}
quint32 BaseEngineDebugClient::addWatch(const QmlDebugFileReference &/*file*/)
{
qWarning("QmlEngineDebugClient::addWatch(): Not implemented");
return 0;
}
void BaseEngineDebugClient::removeWatch(quint32 id)
{
if (status() == QmlDebugClient::Enabled) {
QByteArray message;
QDataStream ds(&message, QIODevice::WriteOnly);
ds << QByteArray("NO_WATCH") << id;
sendMessage(message);
}
}
quint32 BaseEngineDebugClient::queryAvailableEngines()
{
quint32 id = 0;
if (status() == QmlDebugClient::Enabled) {
id = getId();
QByteArray message;
QDataStream ds(&message, QIODevice::WriteOnly);
ds << QByteArray("LIST_ENGINES") << id;
sendMessage(message);
}
return id;
}
quint32 BaseEngineDebugClient::queryRootContexts(const QmlDebugEngineReference &engine)
{
quint32 id = 0;
if (status() == QmlDebugClient::Enabled && engine.m_debugId != -1) {
id = getId();
QByteArray message;
QDataStream ds(&message, QIODevice::WriteOnly);
ds << QByteArray("LIST_OBJECTS") << id << engine.m_debugId;
sendMessage(message);
}
return id;
}
quint32 BaseEngineDebugClient::queryObject(const QmlDebugObjectReference &object)
{
quint32 id = 0;
if (status() == QmlDebugClient::Enabled && object.m_debugId != -1) {
id = getId();
QByteArray message;
QDataStream ds(&message, QIODevice::WriteOnly);
ds << QByteArray("FETCH_OBJECT") << id << object.m_debugId << false <<
true;
sendMessage(message);
}
return id;
}
quint32 BaseEngineDebugClient::queryObjectRecursive(const QmlDebugObjectReference &object)
{
quint32 id = 0;
if (status() == QmlDebugClient::Enabled && object.m_debugId != -1) {
id = getId();
QByteArray message;
QDataStream ds(&message, QIODevice::WriteOnly);
ds << QByteArray("FETCH_OBJECT") << id << object.m_debugId << true <<
true;
sendMessage(message);
}
return id;
}
quint32 BaseEngineDebugClient::queryExpressionResult(int objectDebugId,
const QString &expr,
int engineId)
{
quint32 id = 0;
if (status() == QmlDebugClient::Enabled && objectDebugId != -1) {
id = getId();
QByteArray message;
QDataStream ds(&message, QIODevice::WriteOnly);
ds << QByteArray("EVAL_EXPRESSION") << id << objectDebugId << expr
<< engineId;
sendMessage(message);
}
return id;
}
quint32 BaseEngineDebugClient::setBindingForObject(
int objectDebugId,
const QString &propertyName,
const QVariant &bindingExpression,
bool isLiteralValue,
QString source, int line)
{
quint32 id = 0;
if (status() == QmlDebugClient::Enabled && objectDebugId != -1) {
id = getId();
QByteArray message;
QDataStream ds(&message, QIODevice::WriteOnly);
ds << QByteArray("SET_BINDING") << objectDebugId << propertyName
<< bindingExpression << isLiteralValue << source << line;
sendMessage(message);
}
return id;
}
quint32 BaseEngineDebugClient::resetBindingForObject(
int objectDebugId,
const QString &propertyName)
{
quint32 id = 0;
if (status() == QmlDebugClient::Enabled && objectDebugId != -1) {
id = getId();
QByteArray message;
QDataStream ds(&message, QIODevice::WriteOnly);
ds << QByteArray("RESET_BINDING") << objectDebugId << propertyName;
sendMessage(message);
}
return id;
}
quint32 BaseEngineDebugClient::setMethodBody(
int objectDebugId, const QString &methodName,
const QString &methodBody)
{
quint32 id = 0;
if (status() == QmlDebugClient::Enabled && objectDebugId != -1) {
id = getId();
QByteArray message;
QDataStream ds(&message, QIODevice::WriteOnly);
ds << QByteArray("SET_METHOD_BODY") << objectDebugId
<< methodName << methodBody;
sendMessage(message);
}
return id;
}
} // namespace QmlDebug
<|endoftext|>
|
<commit_before>//! \file
/*
** Copyright (C) - Triton
**
** This program is under the terms of the BSD License.
*/
#ifndef TRITON_SYMBOLICVARIABLE_H
#define TRITON_SYMBOLICVARIABLE_H
#include <string>
#include "symbolicEnums.hpp"
#include "tritonTypes.hpp"
//! The Triton namespace
namespace triton {
/*!
* \addtogroup triton
* @{
*/
//! The Engines namespace
namespace engines {
/*!
* \ingroup triton
* \addtogroup engines
* @{
*/
//! The Symbolic Execution namespace
namespace symbolic {
/*!
* \ingroup engines
* \addtogroup symbolic
* @{
*/
/*! \class SymbolicVariable
\brief The symbolic variable class. */
class SymbolicVariable {
protected:
//! The symbolic variable kind. \sa triton::engines::symbolic::symkind_e
symkind_e kind;
//! The comment of the symbolic variable.
std::string comment;
//! The name of the symbolic variable. \sa TRITON_SYMVAR_NAME
std::string name;
//! The id of the symbolic variable. This id is unique.
triton::usize id;
//! The kind value of the symbolic variable.
/*!
\brief If the symbolic varialbe is a triton::engines::symbolic::REG, this value contains the register ID.
\biref If the symbolic varialbe is a triton::engines::symbolic::MEM, this value contains the memory access' address.
*/
triton::uint64 kindValue;
//! The size (in bits) of the symbolic variable.
triton::uint32 size;
//! The concrete value of the symbolic variable.
triton::uint512 concreteValue;
public:
//! Constructor.
SymbolicVariable(symkind_e kind, triton::uint64 kindValue, triton::usize id, triton::uint32 size, const std::string& comment, triton::uint512 concreteValue=0);
//! Constructor by copy.
SymbolicVariable(const SymbolicVariable ©);
//! Destructore.
~SymbolicVariable();
//! Returns the symbolic variable kind. \sa triton::engines::symbolic::symkind_e.
symkind_e getKind(void) const;
//! Returns the comment of the symbolic variable.
const std::string& getComment(void) const;
//! Returns the name of the symbolic variable.
const std::string& getName(void) const;
//! Returns the id of the symbolic variable. This id is unique.
triton::usize getId(void) const;
//! Returns the kind value of the symbolic variable.
triton::uint64 getKindValue(void) const;
//! Returns the size (in bits) of the symbolic variable.
triton::uint32 getSize(void) const;
//! Returns the concrete value (if exists) of the symbolic variable.
triton::uint512 getConcreteValue(void) const;
//! Sets the comment of the symbolic variable.
void setComment(const std::string& comment);
//! Sets the concrete value of the symbolic variable.
void setConcreteValue(triton::uint512 value);
};
//! Displays a symbolic variable.
std::ostream& operator<<(std::ostream& stream, const SymbolicVariable& symVar);
//! Displays a symbolic variable.
std::ostream& operator<<(std::ostream& stream, const SymbolicVariable* symVar);
/*! @} End of symbolic namespace */
};
/*! @} End of engines namespace */
};
/*! @} End of triton namespace */
};
#endif /* TRITON_SYMBOLICVARIABLE_H */
<commit_msg>Update doxygen<commit_after>//! \file
/*
** Copyright (C) - Triton
**
** This program is under the terms of the BSD License.
*/
#ifndef TRITON_SYMBOLICVARIABLE_H
#define TRITON_SYMBOLICVARIABLE_H
#include <string>
#include "symbolicEnums.hpp"
#include "tritonTypes.hpp"
//! The Triton namespace
namespace triton {
/*!
* \addtogroup triton
* @{
*/
//! The Engines namespace
namespace engines {
/*!
* \ingroup triton
* \addtogroup engines
* @{
*/
//! The Symbolic Execution namespace
namespace symbolic {
/*!
* \ingroup engines
* \addtogroup symbolic
* @{
*/
/*! \class SymbolicVariable
\brief The symbolic variable class. */
class SymbolicVariable {
protected:
//! The symbolic variable kind. \sa triton::engines::symbolic::symkind_e
symkind_e kind;
//! The comment of the symbolic variable.
std::string comment;
//! The name of the symbolic variable. \sa TRITON_SYMVAR_NAME
std::string name;
//! The id of the symbolic variable. This id is unique.
triton::usize id;
/*! \brief The kind value of the symbolic variable.
*
* \description If the symbolic varialbe is a triton::engines::symbolic::REG, this value contains the register ID.
* Otherwise, if the symbolic varialbe is a triton::engines::symbolic::MEM, this value contains the address of the
* memory access.
*/
triton::uint64 kindValue;
//! The size (in bits) of the symbolic variable.
triton::uint32 size;
//! The concrete value of the symbolic variable.
triton::uint512 concreteValue;
public:
//! Constructor.
SymbolicVariable(symkind_e kind, triton::uint64 kindValue, triton::usize id, triton::uint32 size, const std::string& comment, triton::uint512 concreteValue=0);
//! Constructor by copy.
SymbolicVariable(const SymbolicVariable ©);
//! Destructore.
~SymbolicVariable();
//! Returns the symbolic variable kind. \sa triton::engines::symbolic::symkind_e.
symkind_e getKind(void) const;
//! Returns the comment of the symbolic variable.
const std::string& getComment(void) const;
//! Returns the name of the symbolic variable.
const std::string& getName(void) const;
//! Returns the id of the symbolic variable. This id is unique.
triton::usize getId(void) const;
//! Returns the kind value of the symbolic variable.
triton::uint64 getKindValue(void) const;
//! Returns the size (in bits) of the symbolic variable.
triton::uint32 getSize(void) const;
//! Returns the concrete value (if exists) of the symbolic variable.
triton::uint512 getConcreteValue(void) const;
//! Sets the comment of the symbolic variable.
void setComment(const std::string& comment);
//! Sets the concrete value of the symbolic variable.
void setConcreteValue(triton::uint512 value);
};
//! Displays a symbolic variable.
std::ostream& operator<<(std::ostream& stream, const SymbolicVariable& symVar);
//! Displays a symbolic variable.
std::ostream& operator<<(std::ostream& stream, const SymbolicVariable* symVar);
/*! @} End of symbolic namespace */
};
/*! @} End of engines namespace */
};
/*! @} End of triton namespace */
};
#endif /* TRITON_SYMBOLICVARIABLE_H */
<|endoftext|>
|
<commit_before>/* -*- Mode: C++; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- */
#include "config.h"
#include <string>
#include <map>
#include "common.hh"
#include "stats.hh"
#include "kvstore.hh"
#include "sqlite-kvstore.hh"
KVStore *KVStore::create(db_type type, EPStats &stats,
const KVStoreConfig &conf) {
SqliteStrategy *sqliteInstance = NULL;
if (type == multi_db) {
sqliteInstance = new MultiDBSingleTableSqliteStrategy(conf.location,
conf.shardPattern,
conf.initFile,
conf.postInitFile,
conf.shards);
} else if (type == single_db) {
sqliteInstance = new SingleTableSqliteStrategy(conf.location,
conf.initFile,
conf.postInitFile);
} else if (type == single_mt_db) {
sqliteInstance = new MultiTableSqliteStrategy(conf.location,
conf.initFile,
conf.postInitFile);
} else {
abort();
}
return new StrategicSqlite3(stats,
shared_ptr<SqliteStrategy>(sqliteInstance));
}
<commit_msg>KVStore::create should switch over the enum.<commit_after>/* -*- Mode: C++; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- */
#include "config.h"
#include <string>
#include <map>
#include "common.hh"
#include "stats.hh"
#include "kvstore.hh"
#include "sqlite-kvstore.hh"
KVStore *KVStore::create(db_type type, EPStats &stats,
const KVStoreConfig &conf) {
SqliteStrategy *sqliteInstance = NULL;
switch (type) {
case multi_db:
sqliteInstance = new MultiDBSingleTableSqliteStrategy(conf.location,
conf.shardPattern,
conf.initFile,
conf.postInitFile,
conf.shards);
break;
case single_db:
sqliteInstance = new SingleTableSqliteStrategy(conf.location,
conf.initFile,
conf.postInitFile);
break;
case single_mt_db:
sqliteInstance = new MultiTableSqliteStrategy(conf.location,
conf.initFile,
conf.postInitFile);
break;
}
return new StrategicSqlite3(stats,
shared_ptr<SqliteStrategy>(sqliteInstance));
}
<|endoftext|>
|
<commit_before>#include <iostream>
#include <windows.h>
#include <TlHelp32.h>
#include <TCHAR.h>
#include <string>
#include <sstream>
//Here is where the hax begin
using namespace std;
//FUNCTIONS
DWORD GetModuleBaseAddress(DWORD dwProcessIdentifier, TCHAR *lpszModuleName)
{
HANDLE hSnapshot = CreateToolhelp32Snapshot(TH32CS_SNAPMODULE, dwProcessIdentifier);
DWORD dwModuleBaseAddress = 0;
if (hSnapshot != INVALID_HANDLE_VALUE)
{
MODULEENTRY32 ModuleEntry32 = { 0 };
ModuleEntry32.dwSize = sizeof(MODULEENTRY32);
if (Module32First(hSnapshot, &ModuleEntry32))
{
do
{
if (_tcscmp(ModuleEntry32.szModule, lpszModuleName) == 0)
{
dwModuleBaseAddress = (DWORD)ModuleEntry32.modBaseAddr;
break;
}
} while (Module32Next(hSnapshot, &ModuleEntry32));
}
CloseHandle(hSnapshot);
}
return dwModuleBaseAddress;
}
int Main() {
//Here is where the magic starts
}
<commit_msg>Update main.cpp<commit_after>#include <iostream>
#include <windows.h>
#include <TlHelp32.h>
#include <TCHAR.h>
#include <string>
#include <sstream>
//Here is where the hax begin
using namespace std;
//FUNCTIONS
DWORD GetModuleBaseAddress(DWORD dwProcessIdentifier, TCHAR *lpszModuleName)
{
HANDLE hSnapshot = CreateToolhelp32Snapshot(TH32CS_SNAPMODULE, dwProcessIdentifier);
DWORD dwModuleBaseAddress = 0;
if (hSnapshot != INVALID_HANDLE_VALUE)
{
MODULEENTRY32 ModuleEntry32 = { 0 };
ModuleEntry32.dwSize = sizeof(MODULEENTRY32);
if (Module32First(hSnapshot, &ModuleEntry32))
{
do
{
if (_tcscmp(ModuleEntry32.szModule, lpszModuleName) == 0)
{
dwModuleBaseAddress = (DWORD)ModuleEntry32.modBaseAddr;
break;
}
} while (Module32Next(hSnapshot, &ModuleEntry32));
}
CloseHandle(hSnapshot);
}
return dwModuleBaseAddress;
}
//Costum function for you guys to sleep a thread
int sleepthread(int amountoftime) {
SetConsoleTitle("Thread is sleeping for " + amtTime + " ;*");
Sleep(amountoftime);
}
int Main() {
//Here is where the magic starts
HWND hWnd = FindWindow(0, "ROBLOX"); //Finding RBLX window this is a low quality process if you know how to code and use this i recommened you to change this
std::cout << "Waiting for Roblox...";
while (hWnd == 0) { // Waiting until found
Sleep(250);
hWnd = FindWindow(0, "ROBLOX");
}
system("cls");//making this better later
//Definition of pId
DWORD pId;
//Get process id
GetWindowThreadProcessId(hWnd, &pId);
//Here is where we start getting the modulebase
DWORD RBLXBASEAddr = GetModuleBaseAddress(pId, "RobloxPlayerBeta.exe"); // Getting base address of GD
std::cout << "Base Address: " << hex << GetModuleBaseAddress(;
return 0;
}
<|endoftext|>
|
<commit_before>// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
#include "searchable_feed_view.h"
#include "forcecommitcontext.h"
#include "operationdonecontext.h"
#include "removedonecontext.h"
#include <vespa/searchcore/proton/feedoperation/compact_lid_space_operation.h>
#include <vespa/vespalib/util/isequencedtaskexecutor.h>
#include <vespa/document/fieldvalue/document.h>
#include <vespa/log/log.h>
LOG_SETUP(".proton.server.searchable_feed_view");
using document::BucketId;
using document::Document;
using document::DocumentId;
using document::DocumentTypeRepo;
using document::DocumentUpdate;
using search::index::Schema;
using storage::spi::BucketInfoResult;
using storage::spi::Timestamp;
using vespalib::makeLambdaTask;
namespace proton {
SearchableFeedView::Context::Context(const IIndexWriter::SP &indexWriter)
: _indexWriter(indexWriter)
{}
SearchableFeedView::Context::~Context() = default;
SearchableFeedView::SearchableFeedView(StoreOnlyFeedView::Context storeOnlyCtx, const PersistentParams ¶ms,
const FastAccessFeedView::Context &fastUpdateCtx, Context ctx)
: Parent(std::move(storeOnlyCtx), params, fastUpdateCtx),
_indexWriter(ctx._indexWriter),
_hasIndexedFields(_schema->getNumIndexFields() > 0)
{ }
SearchableFeedView::~SearchableFeedView() = default;
void
SearchableFeedView::putIndexedFields(SerialNum serialNum, search::DocumentIdT lid, const DocumentSP &newDoc,
OnOperationDoneType onWriteDone)
{
if (!hasIndexedFields()) {
return;
}
_writeService.index().execute(
makeLambdaTask([this, serialNum, lid, newDoc, onWriteDone] {
performIndexPut(serialNum, lid, newDoc, onWriteDone);
}));
}
void
SearchableFeedView::performIndexPut(SerialNum serialNum, search::DocumentIdT lid, const Document &doc, OnOperationDoneType onWriteDone)
{
(void) onWriteDone;
assert(_writeService.index().isCurrentThread());
VLOG(getDebugLevel(lid, doc.getId()),
"database(%s): performIndexPut: serialNum(%" PRIu64 "), docId(%s), lid(%d)",
_params._docTypeName.toString().c_str(), serialNum, doc.getId().toString().c_str(), lid);
_indexWriter->put(serialNum, doc, lid, onWriteDone);
}
void
SearchableFeedView::performIndexPut(SerialNum serialNum, search::DocumentIdT lid, const DocumentSP &doc, OnOperationDoneType onWriteDone)
{
performIndexPut(serialNum, lid, *doc, onWriteDone);
}
void
SearchableFeedView::performIndexPut(SerialNum serialNum, search::DocumentIdT lid, FutureDoc futureDoc, OnOperationDoneType onWriteDone)
{
const auto &doc = futureDoc.get();
if (doc) {
performIndexPut(serialNum, lid, *doc, onWriteDone);
}
}
void
SearchableFeedView::heartBeatIndexedFields(SerialNum serialNum, DoneCallback onDone)
{
_writeService.index().execute(makeLambdaTask([this, serialNum, onDone] {
(void) onDone;
performIndexHeartBeat(serialNum);
}));
}
void
SearchableFeedView::performIndexHeartBeat(SerialNum serialNum)
{
_indexWriter->heartBeat(serialNum);
}
void
SearchableFeedView::updateIndexedFields(SerialNum serialNum, search::DocumentIdT lid, FutureDoc futureDoc, OnOperationDoneType onWriteDone)
{
_writeService.index().execute(
makeLambdaTask([serialNum, lid, futureDoc = std::move(futureDoc),
onWriteDone = std::move(onWriteDone), this]() mutable {
performIndexPut(serialNum, lid, std::move(futureDoc), std::move(onWriteDone));
}));
}
void
SearchableFeedView::removeIndexedFields(SerialNum serialNum, search::DocumentIdT lid, OnRemoveDoneType onWriteDone)
{
if (!hasIndexedFields()) {
return;
}
_writeService.index().execute(
makeLambdaTask([this, serialNum, lid, onWriteDone]() {
performIndexRemove(serialNum, lid, onWriteDone);
}));
}
void
SearchableFeedView::performIndexRemove(SerialNum serialNum, search::DocumentIdT lid, OnRemoveDoneType onWriteDone)
{
(void) onWriteDone;
assert(_writeService.index().isCurrentThread());
VLOG(getDebugLevel(lid, nullptr),
"database(%s): performIndexRemove: serialNum(%" PRIu64 "), lid(%d)",
_params._docTypeName.toString().c_str(), serialNum, lid);
_indexWriter->remove(serialNum, lid);
}
void
SearchableFeedView::performIndexRemove(SerialNum serialNum, const LidVector &lidsToRemove, OnWriteDoneType onWriteDone)
{
(void) onWriteDone;
assert(_writeService.index().isCurrentThread());
for (const auto lid : lidsToRemove) {
VLOG(getDebugLevel(lid, nullptr),
"database(%s): performIndexRemove: serialNum(%" PRIu64 "), lid(%d)",
_params._docTypeName.toString().c_str(), serialNum, lid);
}
_indexWriter->removeDocs(serialNum, lidsToRemove);
}
void
SearchableFeedView::removeIndexedFields(SerialNum serialNum, const LidVector &lidsToRemove,
OnWriteDoneType onWriteDone)
{
if (!hasIndexedFields())
return;
_writeService.index().execute(
makeLambdaTask([this, serialNum, lidsToRemove, onWriteDone]() {
performIndexRemove(serialNum, lidsToRemove, onWriteDone);
}));
}
void
SearchableFeedView::internalDeleteBucket(const DeleteBucketOperation &delOp, DoneCallback onDone)
{
Parent::internalDeleteBucket(delOp, onDone);
}
void
SearchableFeedView::performIndexForceCommit(SerialNum serialNum, OnForceCommitDoneType onCommitDone)
{
assert(_writeService.index().isCurrentThread());
_indexWriter->commit(serialNum, onCommitDone);
}
void
SearchableFeedView::handleCompactLidSpace(const CompactLidSpaceOperation &op, DoneCallback onDone)
{
Parent::handleCompactLidSpace(op, onDone);
vespalib::Gate gate;
_writeService.index().execute(
makeLambdaTask([this, &op, &gate]() {
_indexWriter->compactLidSpace(op.getSerialNum(), op.getLidLimit());
gate.countDown();
}));
gate.await();
}
void
SearchableFeedView::internalForceCommit(const CommitParam & param, OnForceCommitDoneType onCommitDone)
{
Parent::internalForceCommit(param, onCommitDone);
_writeService.index().execute(
makeLambdaTask([this, serialNum=param.lastSerialNum(), onCommitDone]() {
performIndexForceCommit(serialNum, onCommitDone);
}));
_writeService.index().wakeup();
}
} // namespace proton
<commit_msg>Remove noop std::move.<commit_after>// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
#include "searchable_feed_view.h"
#include "forcecommitcontext.h"
#include "operationdonecontext.h"
#include "removedonecontext.h"
#include <vespa/searchcore/proton/feedoperation/compact_lid_space_operation.h>
#include <vespa/vespalib/util/isequencedtaskexecutor.h>
#include <vespa/document/fieldvalue/document.h>
#include <vespa/log/log.h>
LOG_SETUP(".proton.server.searchable_feed_view");
using document::BucketId;
using document::Document;
using document::DocumentId;
using document::DocumentTypeRepo;
using document::DocumentUpdate;
using search::index::Schema;
using storage::spi::BucketInfoResult;
using storage::spi::Timestamp;
using vespalib::makeLambdaTask;
namespace proton {
SearchableFeedView::Context::Context(const IIndexWriter::SP &indexWriter)
: _indexWriter(indexWriter)
{}
SearchableFeedView::Context::~Context() = default;
SearchableFeedView::SearchableFeedView(StoreOnlyFeedView::Context storeOnlyCtx, const PersistentParams ¶ms,
const FastAccessFeedView::Context &fastUpdateCtx, Context ctx)
: Parent(std::move(storeOnlyCtx), params, fastUpdateCtx),
_indexWriter(ctx._indexWriter),
_hasIndexedFields(_schema->getNumIndexFields() > 0)
{ }
SearchableFeedView::~SearchableFeedView() = default;
void
SearchableFeedView::putIndexedFields(SerialNum serialNum, search::DocumentIdT lid, const DocumentSP &newDoc,
OnOperationDoneType onWriteDone)
{
if (!hasIndexedFields()) {
return;
}
_writeService.index().execute(
makeLambdaTask([this, serialNum, lid, newDoc, onWriteDone] {
performIndexPut(serialNum, lid, newDoc, onWriteDone);
}));
}
void
SearchableFeedView::performIndexPut(SerialNum serialNum, search::DocumentIdT lid, const Document &doc, OnOperationDoneType onWriteDone)
{
(void) onWriteDone;
assert(_writeService.index().isCurrentThread());
VLOG(getDebugLevel(lid, doc.getId()),
"database(%s): performIndexPut: serialNum(%" PRIu64 "), docId(%s), lid(%d)",
_params._docTypeName.toString().c_str(), serialNum, doc.getId().toString().c_str(), lid);
_indexWriter->put(serialNum, doc, lid, onWriteDone);
}
void
SearchableFeedView::performIndexPut(SerialNum serialNum, search::DocumentIdT lid, const DocumentSP &doc, OnOperationDoneType onWriteDone)
{
performIndexPut(serialNum, lid, *doc, onWriteDone);
}
void
SearchableFeedView::performIndexPut(SerialNum serialNum, search::DocumentIdT lid, FutureDoc futureDoc, OnOperationDoneType onWriteDone)
{
const auto &doc = futureDoc.get();
if (doc) {
performIndexPut(serialNum, lid, *doc, onWriteDone);
}
}
void
SearchableFeedView::heartBeatIndexedFields(SerialNum serialNum, DoneCallback onDone)
{
_writeService.index().execute(makeLambdaTask([this, serialNum, onDone] {
(void) onDone;
performIndexHeartBeat(serialNum);
}));
}
void
SearchableFeedView::performIndexHeartBeat(SerialNum serialNum)
{
_indexWriter->heartBeat(serialNum);
}
void
SearchableFeedView::updateIndexedFields(SerialNum serialNum, search::DocumentIdT lid, FutureDoc futureDoc, OnOperationDoneType onWriteDone)
{
_writeService.index().execute(
makeLambdaTask([serialNum, lid, futureDoc = std::move(futureDoc),
onWriteDone, this]() mutable {
performIndexPut(serialNum, lid, std::move(futureDoc), onWriteDone);
}));
}
void
SearchableFeedView::removeIndexedFields(SerialNum serialNum, search::DocumentIdT lid, OnRemoveDoneType onWriteDone)
{
if (!hasIndexedFields()) {
return;
}
_writeService.index().execute(
makeLambdaTask([this, serialNum, lid, onWriteDone]() {
performIndexRemove(serialNum, lid, onWriteDone);
}));
}
void
SearchableFeedView::performIndexRemove(SerialNum serialNum, search::DocumentIdT lid, OnRemoveDoneType onWriteDone)
{
(void) onWriteDone;
assert(_writeService.index().isCurrentThread());
VLOG(getDebugLevel(lid, nullptr),
"database(%s): performIndexRemove: serialNum(%" PRIu64 "), lid(%d)",
_params._docTypeName.toString().c_str(), serialNum, lid);
_indexWriter->remove(serialNum, lid);
}
void
SearchableFeedView::performIndexRemove(SerialNum serialNum, const LidVector &lidsToRemove, OnWriteDoneType onWriteDone)
{
(void) onWriteDone;
assert(_writeService.index().isCurrentThread());
for (const auto lid : lidsToRemove) {
VLOG(getDebugLevel(lid, nullptr),
"database(%s): performIndexRemove: serialNum(%" PRIu64 "), lid(%d)",
_params._docTypeName.toString().c_str(), serialNum, lid);
}
_indexWriter->removeDocs(serialNum, lidsToRemove);
}
void
SearchableFeedView::removeIndexedFields(SerialNum serialNum, const LidVector &lidsToRemove,
OnWriteDoneType onWriteDone)
{
if (!hasIndexedFields())
return;
_writeService.index().execute(
makeLambdaTask([this, serialNum, lidsToRemove, onWriteDone]() {
performIndexRemove(serialNum, lidsToRemove, onWriteDone);
}));
}
void
SearchableFeedView::internalDeleteBucket(const DeleteBucketOperation &delOp, DoneCallback onDone)
{
Parent::internalDeleteBucket(delOp, onDone);
}
void
SearchableFeedView::performIndexForceCommit(SerialNum serialNum, OnForceCommitDoneType onCommitDone)
{
assert(_writeService.index().isCurrentThread());
_indexWriter->commit(serialNum, onCommitDone);
}
void
SearchableFeedView::handleCompactLidSpace(const CompactLidSpaceOperation &op, DoneCallback onDone)
{
Parent::handleCompactLidSpace(op, onDone);
vespalib::Gate gate;
_writeService.index().execute(
makeLambdaTask([this, &op, &gate]() {
_indexWriter->compactLidSpace(op.getSerialNum(), op.getLidLimit());
gate.countDown();
}));
gate.await();
}
void
SearchableFeedView::internalForceCommit(const CommitParam & param, OnForceCommitDoneType onCommitDone)
{
Parent::internalForceCommit(param, onCommitDone);
_writeService.index().execute(
makeLambdaTask([this, serialNum=param.lastSerialNum(), onCommitDone]() {
performIndexForceCommit(serialNum, onCommitDone);
}));
_writeService.index().wakeup();
}
} // namespace proton
<|endoftext|>
|
<commit_before>#include <lua.hpp>
#include "brotli/dec/decode.h"
#include "brotli/enc/encode.h"
#include "brotli/enc/streams.h"
class MemReader : public brotli::BrotliIn
{
public:
MemReader(const void *data, size_t len) : data_(data), len_(len) { }
virtual ~MemReader() { }
virtual const void* Read(size_t n, size_t* nread)
{
const void *d = data_;
*nread = len_;
data_ = NULL;
len_ = 0;
return d;
}
private:
const void *data_;
size_t len_;
};
class LuaWriter : public brotli::BrotliOut
{
public:
LuaWriter(luaL_Buffer *b_) : b(b_) { }
virtual ~LuaWriter() { }
virtual bool Write(const void *buf, size_t n)
{
luaL_addlstring(b, (const char *)buf, n);
return true;
}
private:
luaL_Buffer *b;
};
int lb_compress(lua_State *L)
{
size_t in_len;
const char *in = luaL_checklstring(L, 1, &in_len);
luaL_Buffer b;
#if LUA_VERSION_NUM >= 502
luaL_buffinitsize(L, &b, in_len / 2);
#else
luaL_buffinit(L, &b);
#endif
brotli::BrotliParams params;
MemReader input(in, in_len);
LuaWriter output(&b);
if (!brotli::BrotliCompress(params, &input, &output))
return luaL_error(L, "compression failed");
luaL_pushresult(&b);
return 1;
}
int BrotliLuaOutputFunction(void *data, const uint8_t *buf, size_t count)
{
luaL_Buffer *b = (luaL_Buffer *)data;
luaL_addlstring(b, (const char *)buf, count);
return (int)count;
}
BrotliOutput BrotliInitLuaOutput(luaL_Buffer *b)
{
BrotliOutput output;
output.cb_ = &BrotliLuaOutputFunction;
output.data_ = b;
return output;
}
int lb_decompress(lua_State *L)
{
size_t in_len;
const char *in = luaL_checklstring(L, 1, &in_len);
luaL_Buffer b;
#if LUA_VERSION_NUM >= 502
luaL_buffinitsize(L, &b, in_len);
#else
luaL_buffinit(L, &b);
#endif
BrotliMemInput mem_input;
BrotliInput input = BrotliInitMemInput((const uint8_t *)in, in_len, &mem_input);
BrotliOutput output = BrotliInitLuaOutput(&b);
if (!BrotliDecompress(input, output))
return luaL_error(L, "corrupt input");
luaL_pushresult(&b);
return 1;
}
extern "C"
{
static const luaL_Reg export_functions[] = {
{ "compress", lb_compress },
{ "decompress", lb_decompress },
{ NULL, NULL },
};
LUALIB_API int luaopen_brotli(lua_State *L)
{
#if LUA_VERSION_NUM >= 502
luaL_newlib(L, export_functions);
#else
lua_newtable(L);
luaL_register(L, NULL, export_functions);
#endif
return 1;
}
}
<commit_msg>fix read buffer bug<commit_after>#include <lua.hpp>
#include "brotli/dec/decode.h"
#include "brotli/enc/encode.h"
#include "brotli/enc/streams.h"
class MemReader : public brotli::BrotliIn
{
public:
MemReader(const void *data, size_t len) : data_((const uint8_t *)data), len_(len) { }
virtual ~MemReader() { }
virtual const void* Read(size_t n, size_t* nread)
{
const void *d = data_;
if (n >= len_)
{
*nread = len_;
data_ = NULL;
len_ = 0;
}
else
{
*nread = n;
data_ += n;
len_ -= n;
}
return d;
}
private:
const uint8_t *data_;
size_t len_;
};
class LuaWriter : public brotli::BrotliOut
{
public:
LuaWriter(luaL_Buffer *b_) : b(b_) { }
virtual ~LuaWriter() { }
virtual bool Write(const void *buf, size_t n)
{
luaL_addlstring(b, (const char *)buf, n);
return true;
}
private:
luaL_Buffer *b;
};
static int lb_compress(lua_State *L)
{
size_t in_len;
const char *in = luaL_checklstring(L, 1, &in_len);
luaL_Buffer b;
#if LUA_VERSION_NUM >= 502
luaL_buffinitsize(L, &b, in_len / 2);
#else
luaL_buffinit(L, &b);
#endif
brotli::BrotliParams params;
MemReader input(in, in_len);
LuaWriter output(&b);
if (!brotli::BrotliCompress(params, &input, &output))
return luaL_error(L, "compression failed");
luaL_pushresult(&b);
return 1;
}
static int BrotliLuaOutputFunction(void *data, const uint8_t *buf, size_t count)
{
luaL_Buffer *b = (luaL_Buffer *)data;
luaL_addlstring(b, (const char *)buf, count);
return (int)count;
}
static BrotliOutput BrotliInitLuaOutput(luaL_Buffer *b)
{
BrotliOutput output;
output.cb_ = &BrotliLuaOutputFunction;
output.data_ = b;
return output;
}
static int lb_decompress(lua_State *L)
{
size_t in_len;
const char *in = luaL_checklstring(L, 1, &in_len);
luaL_Buffer b;
#if LUA_VERSION_NUM >= 502
luaL_buffinitsize(L, &b, in_len);
#else
luaL_buffinit(L, &b);
#endif
BrotliMemInput mem_input;
BrotliInput input = BrotliInitMemInput((const uint8_t *)in, in_len, &mem_input);
BrotliOutput output = BrotliInitLuaOutput(&b);
if (!BrotliDecompress(input, output))
return luaL_error(L, "corrupt input");
luaL_pushresult(&b);
return 1;
}
extern "C"
{
static const luaL_Reg export_functions[] = {
{ "compress", lb_compress },
{ "decompress", lb_decompress },
{ NULL, NULL },
};
LUALIB_API int luaopen_brotli(lua_State *L)
{
#if LUA_VERSION_NUM >= 502
luaL_newlib(L, export_functions);
#else
lua_newtable(L);
luaL_register(L, NULL, export_functions);
#endif
return 1;
}
}
<|endoftext|>
|
<commit_before>/**
* @file gaussian_kernel.hpp
* @author Wei Guan
* @author James Cline
* @author Ryan Curtin
*
* Implementation of the Gaussian kernel (GaussianKernel).
*/
#ifndef __MLPACK_CORE_KERNELS_GAUSSIAN_KERNEL_HPP
#define __MLPACK_CORE_KERNELS_GAUSSIAN_KERNEL_HPP
#include <mlpack/core.hpp>
#include <mlpack/core/metrics/lmetric.hpp>
namespace mlpack {
namespace kernel {
/**
* The standard Gaussian kernel. Given two vectors @f$ x @f$, @f$ y @f$, and a
* bandwidth @f$ \mu @f$ (set in the constructor),
*
* @f[
* K(x, y) = \exp(-\frac{|| x - y ||^2}{2 \mu^2}).
* @f]
*
* The implementation is all in the header file because it is so simple.
*/
class GaussianKernel
{
public:
/**
* Default constructor; sets bandwidth to 1.0.
*/
GaussianKernel() : bandwidth(1.0), gamma(-0.5)
{ }
/**
* Construct the Gaussian kernel with a custom bandwidth.
*
* @param bandwidth The bandwidth of the kernel (@f$\mu@f$).
*/
GaussianKernel(double bandwidth) :
bandwidth(bandwidth),
gamma(-0.5 * pow(bandwidth, -2.0))
{ }
/**
* Evaluation of the Gaussian kernel. This could be generalized to use any
* distance metric, not the Euclidean distance, but for now, the Euclidean
* distance is used.
*
* @tparam VecType Type of vector (likely arma::vec or arma::spvec).
* @param a First vector.
* @param b Second vector.
* @return K(a, b) using the bandwidth (@f$\mu@f$) specified in the
* constructor.
*/
template<typename VecType>
double Evaluate(const VecType& a, const VecType& b) const
{
// The precalculation of gamma saves us a little computation time.
return exp(gamma * metric::SquaredEuclideanDistance::Evaluate(a, b));
}
/**
* Evaluation of the Gaussian kernel using a double precision argument.
*
* @param t double value.
* @return K(t) using the bandwidth (@f$\mu@f$) specified in the
* constructor.
*/
double Evaluate(double t) const
{
// The precalculation of gamma saves us a little computation time.
return exp(gamma * t * t);
}
/**
* Obtain the normalization constant of the Gaussian kernel.
*
* @param dimension
* @return the normalization constant
*/
double Normalizer(size_t dimension)
{
return pow(sqrt(2.0 * M_PI) * bandwidth, (double) dimension);
}
/**
* Obtain a convolution integral of the Gaussian kernel.
*
* @param a, first vector
* @param b, second vector
* @return the convolution integral
*/
template<typename VecType>
double ConvolutionIntegral(const VecType& a, const VecType& b)
{
return Evaluate(sqrt(metric::SquaredEuclideanDistance::Evaluate(a, b) / 2.0)) /
(Normalizer(a.n_rows) * pow(2.0, (double) a.n_rows / 2.0));
}
//! Get the bandwidth.
double Bandwidth() const { return bandwidth; }
//! Modify the bandwidth. This takes an argument because we must update the
//! precalculated constant (gamma).
void Bandwidth(const double bandwidth)
{
this->bandwidth = bandwidth;
this->gamma = -0.5 * pow(bandwidth, -2.0);
}
//! Get the precalculated constant.
double Gamma() const { return gamma; }
private:
//! Kernel bandwidth.
double bandwidth;
//! Precalculated constant depending on the bandwidth;
//! @f$ \gamma = -\frac{1}{2 \mu^2} @f$.
double gamma;
};
class GaussianStaticKernel
{
public:
GaussianStaticKernel() { }
template<typename VecType>
static double Evaluate(const VecType& a, const VecType& b)
{
return exp(-0.5 * metric::SquaredEuclideanDistance::Evaluate(a, b));
}
};
}; // namespace kernel
}; // namespace mlpack
#endif
<commit_msg>Remove static Gaussian kernel hack.<commit_after>/**
* @file gaussian_kernel.hpp
* @author Wei Guan
* @author James Cline
* @author Ryan Curtin
*
* Implementation of the Gaussian kernel (GaussianKernel).
*/
#ifndef __MLPACK_CORE_KERNELS_GAUSSIAN_KERNEL_HPP
#define __MLPACK_CORE_KERNELS_GAUSSIAN_KERNEL_HPP
#include <mlpack/core.hpp>
#include <mlpack/core/metrics/lmetric.hpp>
namespace mlpack {
namespace kernel {
/**
* The standard Gaussian kernel. Given two vectors @f$ x @f$, @f$ y @f$, and a
* bandwidth @f$ \mu @f$ (set in the constructor),
*
* @f[
* K(x, y) = \exp(-\frac{|| x - y ||^2}{2 \mu^2}).
* @f]
*
* The implementation is all in the header file because it is so simple.
*/
class GaussianKernel
{
public:
/**
* Default constructor; sets bandwidth to 1.0.
*/
GaussianKernel() : bandwidth(1.0), gamma(-0.5)
{ }
/**
* Construct the Gaussian kernel with a custom bandwidth.
*
* @param bandwidth The bandwidth of the kernel (@f$\mu@f$).
*/
GaussianKernel(double bandwidth) :
bandwidth(bandwidth),
gamma(-0.5 * pow(bandwidth, -2.0))
{ }
/**
* Evaluation of the Gaussian kernel. This could be generalized to use any
* distance metric, not the Euclidean distance, but for now, the Euclidean
* distance is used.
*
* @tparam VecType Type of vector (likely arma::vec or arma::spvec).
* @param a First vector.
* @param b Second vector.
* @return K(a, b) using the bandwidth (@f$\mu@f$) specified in the
* constructor.
*/
template<typename VecType>
double Evaluate(const VecType& a, const VecType& b) const
{
// The precalculation of gamma saves us a little computation time.
return exp(gamma * metric::SquaredEuclideanDistance::Evaluate(a, b));
}
/**
* Evaluation of the Gaussian kernel using a double precision argument.
*
* @param t double value.
* @return K(t) using the bandwidth (@f$\mu@f$) specified in the
* constructor.
*/
double Evaluate(double t) const
{
// The precalculation of gamma saves us a little computation time.
return exp(gamma * t * t);
}
/**
* Obtain the normalization constant of the Gaussian kernel.
*
* @param dimension
* @return the normalization constant
*/
double Normalizer(size_t dimension)
{
return pow(sqrt(2.0 * M_PI) * bandwidth, (double) dimension);
}
/**
* Obtain a convolution integral of the Gaussian kernel.
*
* @param a, first vector
* @param b, second vector
* @return the convolution integral
*/
template<typename VecType>
double ConvolutionIntegral(const VecType& a, const VecType& b)
{
return Evaluate(sqrt(metric::SquaredEuclideanDistance::Evaluate(a, b) / 2.0)) /
(Normalizer(a.n_rows) * pow(2.0, (double) a.n_rows / 2.0));
}
//! Get the bandwidth.
double Bandwidth() const { return bandwidth; }
//! Modify the bandwidth. This takes an argument because we must update the
//! precalculated constant (gamma).
void Bandwidth(const double bandwidth)
{
this->bandwidth = bandwidth;
this->gamma = -0.5 * pow(bandwidth, -2.0);
}
//! Get the precalculated constant.
double Gamma() const { return gamma; }
private:
//! Kernel bandwidth.
double bandwidth;
//! Precalculated constant depending on the bandwidth;
//! @f$ \gamma = -\frac{1}{2 \mu^2} @f$.
double gamma;
};
}; // namespace kernel
}; // namespace mlpack
#endif
<|endoftext|>
|
<commit_before>//=======================================================================
// Copyright Baptiste Wicht 2011.
// 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 "assert.hpp"
#include "Variable.hpp"
#include "FunctionContext.hpp"
#include "Type.hpp"
#include "iterators.hpp"
#include "mtac/CommonSubexpressionElimination.hpp"
#include "mtac/Utils.hpp"
using namespace eddic;
typedef mtac::CommonSubexpressionElimination::ProblemDomain ProblemDomain;
std::ostream& mtac::operator<<(std::ostream& stream, Expression& /*expression*/){
return stream << "Expression {expression = {}}";
}
inline bool are_equivalent(std::shared_ptr<mtac::Quadruple> first, std::shared_ptr<mtac::Quadruple> second){
return first->op == second->op && *first->arg1 == *second->arg1 && *first->arg2 == *second->arg2;
}
ProblemDomain mtac::CommonSubexpressionElimination::meet(ProblemDomain& in, ProblemDomain& out){
ASSERT(!in.top() || !out.top(), "At least one lattice should not be a top element");
if(in.top()){
return out;
} else if(out.top()){
return in;
} else {
typename ProblemDomain::Values values;
for(auto& in_value : in.values()){
for(auto& out_value : out.values()){
if(are_equivalent(in_value.expression, out_value.expression)){
values.push_back(in_value);
}
}
}
ProblemDomain result(values);
return result;
}
}
ProblemDomain mtac::CommonSubexpressionElimination::transfer(std::shared_ptr<mtac::BasicBlock> basic_block, mtac::Statement& statement, ProblemDomain& in){
auto out = in;
if(auto* ptr = boost::get<std::shared_ptr<mtac::Quadruple>>(&statement)){
auto op = (*ptr)->op;
if(mtac::erase_result(op)){
auto it = iterate(out.values());
while(it.has_next()){
auto& expression = (*it).expression;
if(expression->arg1){
if(auto* var_ptr = boost::get<std::shared_ptr<Variable>>(&*expression->arg1)){
if(*var_ptr == (*ptr)->result){
it.erase();
continue;
}
}
}
if(expression->arg2){
if(auto* var_ptr = boost::get<std::shared_ptr<Variable>>(&*expression->arg2)){
if(*var_ptr == (*ptr)->result){
it.erase();
continue;
}
}
}
++it;
}
}
if(mtac::is_expression((*ptr)->op)){
bool exists = false;
for(auto& expression : out.values()){
if(are_equivalent(*ptr, expression.expression)){
exists = true;
break;
}
}
if(!exists){
Expression expression;
expression.expression = *ptr;
expression.source = basic_block;
out.values().push_back(expression);
}
}
}
return out;
}
ProblemDomain mtac::CommonSubexpressionElimination::Boundary(std::shared_ptr<mtac::Function> /*function*/){
return default_element();
}
ProblemDomain mtac::CommonSubexpressionElimination::Init(std::shared_ptr<mtac::Function> function){
if(init){
ProblemDomain result(*init);
return result;
}
typename ProblemDomain::Values values;
for(auto& block : function->getBasicBlocks()){
for(auto& statement : block->statements){
if(auto* ptr = boost::get<std::shared_ptr<mtac::Quadruple>>(&statement)){
if(mtac::is_expression((*ptr)->op)){
bool exists = false;
for(auto& expression : values){
if(are_equivalent(*ptr, expression.expression)){
exists = true;
break;
}
}
if(!exists){
Expression expression;
expression.expression = *ptr;
expression.source = block;
values.push_back(expression);
}
}
}
}
}
init = values;
ProblemDomain result(values);
return result;
}
bool mtac::CommonSubexpressionElimination::optimize(mtac::Statement& statement, std::shared_ptr<mtac::DataFlowResults<ProblemDomain>>& global_results){
auto& results = global_results->IN_S[statement];
bool changes = false;
if(auto* ptr = boost::get<std::shared_ptr<mtac::Quadruple>>(&statement)){
if(mtac::is_expression((*ptr)->op)){
for(auto& expression : results.values()){
if(are_equivalent(expression.expression, *ptr)){
auto source_statement = expression.expression;
mtac::Operator assign_op;
if((*ptr)->op >= mtac::Operator::ADD && (*ptr)->op <= mtac::Operator::MOD){
assign_op = mtac::Operator::ASSIGN;
} else if((*ptr)->op >= mtac::Operator::FADD && (*ptr)->op <= mtac::Operator::FDIV){
assign_op = mtac::Operator::FASSIGN;
}
if(optimized.find(source_statement->result) == optimized.end()){
std::shared_ptr<Variable> temp;
if((*ptr)->op >= mtac::Operator::ADD && (*ptr)->op <= mtac::Operator::MOD){
temp = expression.source->context->new_temporary(INT);
} else if((*ptr)->op >= mtac::Operator::FADD && (*ptr)->op <= mtac::Operator::FDIV){
temp = expression.source->context->new_temporary(FLOAT);
}
auto it = expression.source->statements.begin();
auto end = expression.source->statements.end();
while(it != end){
if(boost::get<std::shared_ptr<Quadruple>>(&*it)){
auto target = boost::get<std::shared_ptr<Quadruple>>(*it);
if(target == source_statement){
auto quadruple = std::make_shared<mtac::Quadruple>(source_statement->result, temp, assign_op);
expression.source->statements.insert(it+1, quadruple);
break;
}
}
++it;
}
source_statement->result = temp;
(*ptr)->op = assign_op;
(*ptr)->arg1 = temp;
optimized[source_statement->result] = temp;
} else {
(*ptr)->op = assign_op;
(*ptr)->arg1 = source_statement->result;
}
changes = true;
}
}
}
}
return changes;
}
<commit_msg>Fix the optimization<commit_after>//=======================================================================
// Copyright Baptiste Wicht 2011.
// 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 "assert.hpp"
#include "Variable.hpp"
#include "FunctionContext.hpp"
#include "Type.hpp"
#include "iterators.hpp"
#include "mtac/CommonSubexpressionElimination.hpp"
#include "mtac/Utils.hpp"
#include "mtac/Printer.hpp"
using namespace eddic;
typedef mtac::CommonSubexpressionElimination::ProblemDomain ProblemDomain;
std::ostream& mtac::operator<<(std::ostream& stream, Expression& /*expression*/){
return stream << "Expression {expression = {}}";
}
inline bool are_equivalent(std::shared_ptr<mtac::Quadruple> first, std::shared_ptr<mtac::Quadruple> second){
return first->op == second->op && *first->arg1 == *second->arg1 && *first->arg2 == *second->arg2;
}
ProblemDomain mtac::CommonSubexpressionElimination::meet(ProblemDomain& in, ProblemDomain& out){
ASSERT(!in.top() || !out.top(), "At least one lattice should not be a top element");
if(in.top()){
return out;
} else if(out.top()){
return in;
} else {
typename ProblemDomain::Values values;
for(auto& in_value : in.values()){
for(auto& out_value : out.values()){
if(are_equivalent(in_value.expression, out_value.expression)){
values.push_back(in_value);
}
}
}
ProblemDomain result(values);
return result;
}
}
ProblemDomain mtac::CommonSubexpressionElimination::transfer(std::shared_ptr<mtac::BasicBlock> basic_block, mtac::Statement& statement, ProblemDomain& in){
auto out = in;
if(auto* ptr = boost::get<std::shared_ptr<mtac::Quadruple>>(&statement)){
auto op = (*ptr)->op;
if(mtac::erase_result(op)){
auto it = iterate(out.values());
while(it.has_next()){
auto& expression = (*it).expression;
if(expression->arg1){
if(auto* var_ptr = boost::get<std::shared_ptr<Variable>>(&*expression->arg1)){
if(*var_ptr == (*ptr)->result){
it.erase();
continue;
}
}
}
if(expression->arg2){
if(auto* var_ptr = boost::get<std::shared_ptr<Variable>>(&*expression->arg2)){
if(*var_ptr == (*ptr)->result){
it.erase();
continue;
}
}
}
++it;
}
}
if(mtac::is_expression((*ptr)->op)){
bool exists = false;
for(auto& expression : out.values()){
if(are_equivalent(*ptr, expression.expression)){
exists = true;
break;
}
}
if(!exists){
Expression expression;
expression.expression = *ptr;
expression.source = basic_block;
out.values().push_back(expression);
}
}
}
return out;
}
ProblemDomain mtac::CommonSubexpressionElimination::Boundary(std::shared_ptr<mtac::Function> /*function*/){
return default_element();
}
ProblemDomain mtac::CommonSubexpressionElimination::Init(std::shared_ptr<mtac::Function> function){
if(init){
ProblemDomain result(*init);
return result;
}
typename ProblemDomain::Values values;
for(auto& block : function->getBasicBlocks()){
for(auto& statement : block->statements){
if(auto* ptr = boost::get<std::shared_ptr<mtac::Quadruple>>(&statement)){
if(mtac::is_expression((*ptr)->op)){
bool exists = false;
for(auto& expression : values){
if(are_equivalent(*ptr, expression.expression)){
exists = true;
break;
}
}
if(!exists){
Expression expression;
expression.expression = *ptr;
expression.source = block;
values.push_back(expression);
}
}
}
}
}
init = values;
ProblemDomain result(values);
return result;
}
bool mtac::CommonSubexpressionElimination::optimize(mtac::Statement& statement, std::shared_ptr<mtac::DataFlowResults<ProblemDomain>>& global_results){
auto& results = global_results->IN_S[statement];
if(auto* ptr = boost::get<std::shared_ptr<mtac::Quadruple>>(&statement)){
auto quadruple = *ptr;
if(mtac::is_expression(quadruple->op)){
for(auto& expression : results.values()){
if(are_equivalent(expression.expression, quadruple)){
auto source_statement = expression.expression;
mtac::Operator assign_op;
if(quadruple->op >= mtac::Operator::ADD && quadruple->op <= mtac::Operator::MOD){
assign_op = mtac::Operator::ASSIGN;
} else if(quadruple->op >= mtac::Operator::FADD && quadruple->op <= mtac::Operator::FDIV){
assign_op = mtac::Operator::FASSIGN;
}
if(optimized.find(source_statement->result) == optimized.end()){
std::shared_ptr<Variable> temp;
if(quadruple->op >= mtac::Operator::ADD && quadruple->op <= mtac::Operator::MOD){
temp = expression.source->context->new_temporary(INT);
} else if(quadruple->op >= mtac::Operator::FADD && quadruple->op <= mtac::Operator::FDIV){
temp = expression.source->context->new_temporary(FLOAT);
}
auto it = expression.source->statements.begin();
auto end = expression.source->statements.end();
while(it != end){
if(boost::get<std::shared_ptr<Quadruple>>(&*it)){
auto target = boost::get<std::shared_ptr<Quadruple>>(*it);
if(target == source_statement){
source_statement->result = temp;
auto quadruple = std::make_shared<mtac::Quadruple>(source_statement->result, temp, assign_op);
++it;
expression.source->statements.insert(it, quadruple);
break;
}
}
}
quadruple->op = assign_op;
quadruple->arg1 = temp;
quadruple->arg2.reset();
optimized[source_statement->result] = temp;
}
quadruple->op = assign_op;
quadruple->arg1 = source_statement->result;
quadruple->arg2.reset();
return true;
}
}
}
}
return false;
}
<|endoftext|>
|
<commit_before>#include <QApplication>
#include <QDebug>
#include <QSysInfo>
#include <QFile>
#include <QFont>
#include <QLibrary>
using namespace std;
#ifdef QT_OS_ANDROID
#include <jni.h>
extern "C" int state_run (int,char **,char *,bool,void *,void *);
extern "C" void javaOnLoad(JavaVM * vm, JNIEnv * env);
#else
typedef int (*Run)(int,char **,char *,bool,void *,void *);
extern "C" char * jepath1(char* arg);
#endif
int main(int argc, char *argv[])
{
#if defined(__MACH__) && !defined(QT50)
if ( QSysInfo::MacintoshVersion > QSysInfo::MV_10_8 ) {
// fix Mac OS X 10.9 (mavericks) font issue
// https://bugreports.qt-project.org/browse/QTBUG-32789
QFont::insertSubstitution(".Lucida Grande UI", "Lucida Grande");
}
#endif
#ifdef QT_OS_ANDROID
char path[1]= {'\0'};
#else
char *path=jepath1(argv[0]); // get path to JFE folder
#endif
bool fhs = false;
#ifdef _WIN32
QString s= QString::fromUtf8(path)+ "/jqt";
if(!(QFile(s.append(".dll"))).exists()) {
s= "jqt.dll";
fhs = true;
}
#else
QString s= QString::fromUtf8(path)+ "/libjqt";
#if defined(__MACH__)
if(!(QFile(s.append(".dylib"))).exists()) {
#else
if(!(QFile(s.append(".so"))).exists()) {
#endif
#if defined(__MACH__)
s= "libjqt.dylib";
#else
s= "libjqt.so";
#endif
fhs = true;
}
#ifdef QT_OS_ANDROID
return state_run(argc, argv, s.toUtf8().data(),fhs,0,(void *)-1);
#else
QLibrary *lib=new QLibrary(s);
Run state_run=(Run) lib->resolve("state_run");
if (state_run)
return state_run(argc, argv, lib->fileName().toUtf8().data(),fhs,0,(void *)-1);
#endif
#ifndef QT_OS_ANDROID
qDebug() << lib->fileName();
qDebug() << "could not resolve: state_run:\n\n" + lib->errorString();
#endif
return -1;
#endif
}
#ifdef QT_OS_ANDROID
JNIEXPORT jint JNI_OnLoad(JavaVM* vm, void*)
{
JNIEnv *jnienv;
if (vm->GetEnv(reinterpret_cast<void**>(&jnienv), JNI_VERSION_1_6) != JNI_OK) {
qCritical() << "JNI_OnLoad GetEnv Failed";
return -1;
}
javaOnLoad(vm, jnienv);
return JNI_VERSION_1_6;
}
#endif
<commit_msg>fix main.cpp #endif error<commit_after>#include <QApplication>
#include <QDebug>
#include <QSysInfo>
#include <QFile>
#include <QFont>
#include <QLibrary>
using namespace std;
#ifdef QT_OS_ANDROID
#include <jni.h>
extern "C" int state_run (int,char **,char *,bool,void *,void *);
extern "C" void javaOnLoad(JavaVM * vm, JNIEnv * env);
#else
typedef int (*Run)(int,char **,char *,bool,void *,void *);
extern "C" char * jepath1(char* arg);
#endif
int main(int argc, char *argv[])
{
#if defined(__MACH__) && !defined(QT50)
if ( QSysInfo::MacintoshVersion > QSysInfo::MV_10_8 ) {
// fix Mac OS X 10.9 (mavericks) font issue
// https://bugreports.qt-project.org/browse/QTBUG-32789
QFont::insertSubstitution(".Lucida Grande UI", "Lucida Grande");
}
#endif
#ifdef QT_OS_ANDROID
char path[1]= {'\0'};
#else
char *path=jepath1(argv[0]); // get path to JFE folder
#endif
bool fhs = false;
#ifdef _WIN32
QString s= QString::fromUtf8(path)+ "/jqt";
if(!(QFile(s.append(".dll"))).exists()) {
s= "jqt.dll";
fhs = true;
}
#else
QString s= QString::fromUtf8(path)+ "/libjqt";
#if defined(__MACH__)
if(!(QFile(s.append(".dylib"))).exists()) {
#else
if(!(QFile(s.append(".so"))).exists()) {
#endif
#if defined(__MACH__)
s= "libjqt.dylib";
#else
s= "libjqt.so";
#endif
fhs = true;
}
#endif
#ifdef QT_OS_ANDROID
return state_run(argc, argv, s.toUtf8().data(),fhs,0,(void *)-1);
#else
QLibrary *lib=new QLibrary(s);
Run state_run=(Run) lib->resolve("state_run");
if (state_run)
return state_run(argc, argv, lib->fileName().toUtf8().data(),fhs,0,(void *)-1);
#endif
#ifndef QT_OS_ANDROID
qDebug() << lib->fileName();
qDebug() << "could not resolve: state_run:\n\n" + lib->errorString();
#endif
return -1;
}
#ifdef QT_OS_ANDROID
JNIEXPORT jint JNI_OnLoad(JavaVM* vm, void*)
{
JNIEnv *jnienv;
if (vm->GetEnv(reinterpret_cast<void**>(&jnienv), JNI_VERSION_1_6) != JNI_OK) {
qCritical() << "JNI_OnLoad GetEnv Failed";
return -1;
}
javaOnLoad(vm, jnienv);
return JNI_VERSION_1_6;
}
#endif
<|endoftext|>
|
<commit_before>/****************************************************************************
**
** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/legal
**
** This file is part of Qt Creator.
**
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Digia. For licensing terms and
** conditions see http://qt.digia.com/licensing. For further information
** use the contact form at http://qt.digia.com/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, 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, Digia gives you certain additional
** rights. These rights are described in the Digia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
****************************************************************************/
#include "documentmanager.h"
#include "qmldesignerplugin.h"
#include <modelnode.h>
#include <nodemetainfo.h>
#include <nodeproperty.h>
#include <bindingproperty.h>
namespace QmlDesigner {
static inline DesignDocument* currentDesignDocument()
{
return QmlDesignerPlugin::instance()->documentManager().currentDesignDocument();
}
static inline void getProperties(const ModelNode node, QHash<PropertyName, QVariant> &propertyHash)
{
if (QmlObjectNode::isValidQmlObjectNode(node)) {
foreach (const AbstractProperty &abstractProperty, node.properties()) {
if (abstractProperty.isVariantProperty()
|| (abstractProperty.isBindingProperty()
&& !abstractProperty.name().contains("anchors.")))
propertyHash.insert(abstractProperty.name(), QmlObjectNode(node).instanceValue(abstractProperty.name()));
}
if (QmlItemNode::isValidQmlItemNode(node)) {
QmlItemNode itemNode(node);
propertyHash.insert("width", itemNode.instanceValue("width"));
propertyHash.insert("height", itemNode.instanceValue("height"));
propertyHash.remove("x");
propertyHash.remove("y");
propertyHash.remove("rotation");
propertyHash.remove("opacity");
}
}
}
static inline void applyProperties(ModelNode &node, const QHash<PropertyName, QVariant> &propertyHash)
{
QHash<PropertyName, QVariant> auxiliaryData = node.auxiliaryData();
foreach (const PropertyName &propertyName, auxiliaryData.keys()) {
if (node.hasAuxiliaryData(propertyName))
node.setAuxiliaryData(propertyName, QVariant());
}
QHashIterator<PropertyName, QVariant> propertyIterator(propertyHash);
while (propertyIterator.hasNext()) {
propertyIterator.next();
const PropertyName propertyName = propertyIterator.key();
if (propertyName == "width" || propertyName == "height") {
node.setAuxiliaryData(propertyIterator.key(), propertyIterator.value());
} else if (node.property(propertyIterator.key()).isDynamic() &&
node.property(propertyIterator.key()).dynamicTypeName() == "alias" &&
node.property(propertyIterator.key()).isBindingProperty()) {
AbstractProperty targetProperty = node.bindingProperty(propertyIterator.key()).resolveToProperty();
if (targetProperty.isValid())
targetProperty.parentModelNode().setAuxiliaryData(targetProperty.name() + "@NodeInstance", propertyIterator.value());
} else {
node.setAuxiliaryData(propertyIterator.key() + "@NodeInstance", propertyIterator.value());
}
}
}
static inline void openFileForComponent(const ModelNode &node)
{
QmlDesignerPlugin::instance()->viewManager().nextFileIsCalledInternally();
//int width = 0;
//int height = 0;
QHash<PropertyName, QVariant> propertyHash;
if (node.metaInfo().isFileComponent()) {
//getWidthHeight(node, width, height);
getProperties(node, propertyHash);
Core::EditorManager::openEditor(node.metaInfo().componentFileName(), Core::Id(), Core::EditorManager::DoNotMakeVisible);
} else if (node.metaInfo().isView() &&
node.hasNodeProperty("delegate") &&
node.nodeProperty("delegate").modelNode().metaInfo().isFileComponent()) {
//getWidthHeight(node, width, height);
getProperties(node, propertyHash);
Core::EditorManager::openEditor(node.nodeProperty("delegate").modelNode().metaInfo().componentFileName(),
Core::Id(), Core::EditorManager::DoNotMakeVisible);
}
ModelNode rootModelNode = currentDesignDocument()->rewriterView()->rootModelNode();
applyProperties(rootModelNode, propertyHash);
//rootModelNode.setAuxiliaryData("width", width);
//rootModelNode.setAuxiliaryData("height", height);
}
static inline void openInlineComponent(const ModelNode &node)
{
if (!node.isValid() || !node.metaInfo().isValid())
return;
if (!currentDesignDocument())
return;
QHash<PropertyName, QVariant> propertyHash;
if (node.nodeSourceType() == ModelNode::NodeWithComponentSource) {
//getWidthHeight(node, width, height);
getProperties(node, propertyHash);
currentDesignDocument()->changeToSubComponent(node);
} else if (node.metaInfo().isView()
&& node.hasNodeProperty("delegate")
&& node.nodeProperty("delegate").modelNode().nodeSourceType() == ModelNode::NodeWithComponentSource) {
//getWidthHeight(node, width, height);
getProperties(node, propertyHash);
currentDesignDocument()->changeToSubComponent(node.nodeProperty("delegate").modelNode());
}
ModelNode rootModelNode = currentDesignDocument()->rewriterView()->rootModelNode();
applyProperties(rootModelNode, propertyHash);
//rootModelNode.setAuxiliaryData("width", width);
//rootModelNode.setAuxiliaryData("height", height);
}
static inline bool isFileComponent(const ModelNode &node)
{
if (!node.isValid() || !node.metaInfo().isValid())
return false;
if (node.metaInfo().isFileComponent())
return true;
if (node.metaInfo().isView() &&
node.hasNodeProperty("delegate")) {
if (node.nodeProperty("delegate").modelNode().metaInfo().isFileComponent())
return true;
}
return false;
}
DocumentManager::DocumentManager()
: QObject()
{
}
DocumentManager::~DocumentManager()
{
foreach (const QWeakPointer<DesignDocument> &designDocument, m_designDocumentHash)
delete designDocument.data();
}
void DocumentManager::setCurrentDesignDocument(Core::IEditor *editor)
{
if (editor) {
m_currentDesignDocument = m_designDocumentHash.value(editor);
if (m_currentDesignDocument == 0) {
m_currentDesignDocument = new DesignDocument;
m_designDocumentHash.insert(editor, m_currentDesignDocument);
m_currentDesignDocument->setEditor(editor);
}
} else {
m_currentDesignDocument->resetToDocumentModel();
m_currentDesignDocument.clear();
}
}
DesignDocument *DocumentManager::currentDesignDocument() const
{
return m_currentDesignDocument.data();
}
bool DocumentManager::hasCurrentDesignDocument() const
{
return m_currentDesignDocument.data();
}
void DocumentManager::removeEditors(QList<Core::IEditor *> editors)
{
foreach (Core::IEditor *editor, editors)
delete m_designDocumentHash.take(editor).data();
}
void DocumentManager::goIntoComponent(const ModelNode &modelNode)
{
if (modelNode.isValid() && modelNode.isComponent()) {
QmlDesignerPlugin::instance()->viewManager().setComponentNode(modelNode);
if (isFileComponent(modelNode))
openFileForComponent(modelNode);
else
openInlineComponent(modelNode);
}
}
} // namespace QmlDesigner
<commit_msg>QmlDesigner: adding missing include<commit_after>/****************************************************************************
**
** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/legal
**
** This file is part of Qt Creator.
**
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Digia. For licensing terms and
** conditions see http://qt.digia.com/licensing. For further information
** use the contact form at http://qt.digia.com/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, 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, Digia gives you certain additional
** rights. These rights are described in the Digia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
****************************************************************************/
#include "documentmanager.h"
#include "qmldesignerplugin.h"
#include <modelnode.h>
#include <qmlitemnode.h>
#include <nodemetainfo.h>
#include <nodeproperty.h>
#include <bindingproperty.h>
namespace QmlDesigner {
static inline DesignDocument* currentDesignDocument()
{
return QmlDesignerPlugin::instance()->documentManager().currentDesignDocument();
}
static inline void getProperties(const ModelNode node, QHash<PropertyName, QVariant> &propertyHash)
{
if (QmlObjectNode::isValidQmlObjectNode(node)) {
foreach (const AbstractProperty &abstractProperty, node.properties()) {
if (abstractProperty.isVariantProperty()
|| (abstractProperty.isBindingProperty()
&& !abstractProperty.name().contains("anchors.")))
propertyHash.insert(abstractProperty.name(), QmlObjectNode(node).instanceValue(abstractProperty.name()));
}
if (QmlItemNode::isValidQmlItemNode(node)) {
QmlItemNode itemNode(node);
propertyHash.insert("width", itemNode.instanceValue("width"));
propertyHash.insert("height", itemNode.instanceValue("height"));
propertyHash.remove("x");
propertyHash.remove("y");
propertyHash.remove("rotation");
propertyHash.remove("opacity");
}
}
}
static inline void applyProperties(ModelNode &node, const QHash<PropertyName, QVariant> &propertyHash)
{
QHash<PropertyName, QVariant> auxiliaryData = node.auxiliaryData();
foreach (const PropertyName &propertyName, auxiliaryData.keys()) {
if (node.hasAuxiliaryData(propertyName))
node.setAuxiliaryData(propertyName, QVariant());
}
QHashIterator<PropertyName, QVariant> propertyIterator(propertyHash);
while (propertyIterator.hasNext()) {
propertyIterator.next();
const PropertyName propertyName = propertyIterator.key();
if (propertyName == "width" || propertyName == "height") {
node.setAuxiliaryData(propertyIterator.key(), propertyIterator.value());
} else if (node.property(propertyIterator.key()).isDynamic() &&
node.property(propertyIterator.key()).dynamicTypeName() == "alias" &&
node.property(propertyIterator.key()).isBindingProperty()) {
AbstractProperty targetProperty = node.bindingProperty(propertyIterator.key()).resolveToProperty();
if (targetProperty.isValid())
targetProperty.parentModelNode().setAuxiliaryData(targetProperty.name() + "@NodeInstance", propertyIterator.value());
} else {
node.setAuxiliaryData(propertyIterator.key() + "@NodeInstance", propertyIterator.value());
}
}
}
static inline void openFileForComponent(const ModelNode &node)
{
QmlDesignerPlugin::instance()->viewManager().nextFileIsCalledInternally();
//int width = 0;
//int height = 0;
QHash<PropertyName, QVariant> propertyHash;
if (node.metaInfo().isFileComponent()) {
//getWidthHeight(node, width, height);
getProperties(node, propertyHash);
Core::EditorManager::openEditor(node.metaInfo().componentFileName(), Core::Id(), Core::EditorManager::DoNotMakeVisible);
} else if (node.metaInfo().isView() &&
node.hasNodeProperty("delegate") &&
node.nodeProperty("delegate").modelNode().metaInfo().isFileComponent()) {
//getWidthHeight(node, width, height);
getProperties(node, propertyHash);
Core::EditorManager::openEditor(node.nodeProperty("delegate").modelNode().metaInfo().componentFileName(),
Core::Id(), Core::EditorManager::DoNotMakeVisible);
}
ModelNode rootModelNode = currentDesignDocument()->rewriterView()->rootModelNode();
applyProperties(rootModelNode, propertyHash);
//rootModelNode.setAuxiliaryData("width", width);
//rootModelNode.setAuxiliaryData("height", height);
}
static inline void openInlineComponent(const ModelNode &node)
{
if (!node.isValid() || !node.metaInfo().isValid())
return;
if (!currentDesignDocument())
return;
QHash<PropertyName, QVariant> propertyHash;
if (node.nodeSourceType() == ModelNode::NodeWithComponentSource) {
//getWidthHeight(node, width, height);
getProperties(node, propertyHash);
currentDesignDocument()->changeToSubComponent(node);
} else if (node.metaInfo().isView()
&& node.hasNodeProperty("delegate")
&& node.nodeProperty("delegate").modelNode().nodeSourceType() == ModelNode::NodeWithComponentSource) {
//getWidthHeight(node, width, height);
getProperties(node, propertyHash);
currentDesignDocument()->changeToSubComponent(node.nodeProperty("delegate").modelNode());
}
ModelNode rootModelNode = currentDesignDocument()->rewriterView()->rootModelNode();
applyProperties(rootModelNode, propertyHash);
//rootModelNode.setAuxiliaryData("width", width);
//rootModelNode.setAuxiliaryData("height", height);
}
static inline bool isFileComponent(const ModelNode &node)
{
if (!node.isValid() || !node.metaInfo().isValid())
return false;
if (node.metaInfo().isFileComponent())
return true;
if (node.metaInfo().isView() &&
node.hasNodeProperty("delegate")) {
if (node.nodeProperty("delegate").modelNode().metaInfo().isFileComponent())
return true;
}
return false;
}
DocumentManager::DocumentManager()
: QObject()
{
}
DocumentManager::~DocumentManager()
{
foreach (const QWeakPointer<DesignDocument> &designDocument, m_designDocumentHash)
delete designDocument.data();
}
void DocumentManager::setCurrentDesignDocument(Core::IEditor *editor)
{
if (editor) {
m_currentDesignDocument = m_designDocumentHash.value(editor);
if (m_currentDesignDocument == 0) {
m_currentDesignDocument = new DesignDocument;
m_designDocumentHash.insert(editor, m_currentDesignDocument);
m_currentDesignDocument->setEditor(editor);
}
} else {
m_currentDesignDocument->resetToDocumentModel();
m_currentDesignDocument.clear();
}
}
DesignDocument *DocumentManager::currentDesignDocument() const
{
return m_currentDesignDocument.data();
}
bool DocumentManager::hasCurrentDesignDocument() const
{
return m_currentDesignDocument.data();
}
void DocumentManager::removeEditors(QList<Core::IEditor *> editors)
{
foreach (Core::IEditor *editor, editors)
delete m_designDocumentHash.take(editor).data();
}
void DocumentManager::goIntoComponent(const ModelNode &modelNode)
{
if (modelNode.isValid() && modelNode.isComponent()) {
QmlDesignerPlugin::instance()->viewManager().setComponentNode(modelNode);
if (isFileComponent(modelNode))
openFileForComponent(modelNode);
else
openInlineComponent(modelNode);
}
}
} // namespace QmlDesigner
<|endoftext|>
|
<commit_before>/* IBM_PROLOG_BEGIN_TAG */
/* This is an automatically generated prolog. */
/* */
/* $Source: src/import/chips/ocmb/explorer/procedures/hwp/memory/lib/mc/exp_port.H $ */
/* */
/* OpenPOWER HostBoot Project */
/* */
/* Contributors Listed Below - COPYRIGHT 2019,2022 */
/* [+] International Business Machines Corp. */
/* */
/* */
/* 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. */
/* */
/* IBM_PROLOG_END_TAG */
///
/// @file exp_port.H
/// @brief Code to support ports
///
// *HWP HWP Owner: Stephen Glancy <sglancy@us.ibm.com>
// *HWP HWP Backup: Louis Stermole <stermole@us.ibm.com>
// *HWP Team: Memory
// *HWP Level: 3
// *HWP Consumed by: HB:FSP
#ifndef __MSS_EXP_PORT_H_
#define __MSS_EXP_PORT_H_
#include <fapi2.H>
#include <explorer_scom_addresses.H>
#include <explorer_scom_addresses_fld.H>
#include <explorer_scom_addresses_fld_fixes.H>
#include <lib/exp_attribute_accessors_manual.H>
#include <lib/utils/mss_exp_conversions.H>
#include <mss_explorer_attribute_getters.H>
#include <lib/shared/exp_consts.H>
#include <lib/dimm/exp_rank.H>
#include <generic/memory/lib/utils/mc/gen_mss_port.H>
#include <generic/memory/lib/utils/mc/gen_mss_restore_repairs.H>
#include <generic/memory/lib/utils/shared/mss_generic_consts.H>
#include <mss_generic_attribute_getters.H>
namespace mss
{
//////////////////////////////////////////////////////////////
// Traits values for EXPLORER
//////////////////////////////////////////////////////////////
///
/// @class Traits and policy class for port code - specialization for Explorer. The target of registers is TARGET_TYPE_OCMB_CHIP
///
template<>
class portTraits< mss::mc_type::EXPLORER >
{
public:
// MC_TYPE
static constexpr fapi2::TargetType MC_TARGET_TYPE = fapi2::TARGET_TYPE_OCMB_CHIP;
// PORT_TYPE
static constexpr fapi2::TargetType PORT_TYPE = fapi2::TARGET_TYPE_MEM_PORT;
// scom register definition
static constexpr uint64_t MBARPC0Q_REG = EXPLR_SRQ_MBARPC0Q;
static constexpr uint64_t FARB0Q_REG = EXPLR_SRQ_MBA_FARB0Q;
static constexpr uint64_t FARB5Q_REG = EXPLR_SRQ_MBA_FARB5Q;
static constexpr uint64_t FARB6Q_REG = EXPLR_SRQ_MBA_FARB6Q;
static constexpr uint64_t FARB9Q_REG = EXPLR_SRQ_MBA_FARB9Q;
static constexpr uint64_t PMU8Q_REG = EXPLR_SRQ_MBA_PMU8Q;
static constexpr uint64_t REFRESH_REG = EXPLR_SRQ_MBAREF0Q;
static constexpr uint64_t STR0Q_REG = EXPLR_SRQ_MBASTR0Q;
static constexpr uint64_t ECC_REG = EXPLR_RDF_RECR;
static constexpr uint64_t CTCR_REG = EXPLR_RDF_CTCR;
static constexpr uint64_t DSM0Q_REG = EXPLR_SRQ_MBA_DSM0Q;
static constexpr uint64_t FWMS_REG = EXPLR_RDF_FWMS0;
static constexpr uint64_t RRQ_REG = EXPLR_SRQ_MBA_RRQ0Q;
static constexpr uint64_t WRQ_REG = EXPLR_SRQ_MBA_WRQ0Q;
static constexpr uint64_t MAGIC_NUMBER_SIM = 765;
static constexpr uint64_t MAGIC_NUMBER_NOT_SIM = 196605;
// This number includes the two spare nibbles, it is compared against
// the actual nibble index we're at
static constexpr uint8_t MAX_NIBBLE_IDX = 19;
// scom register field definition
enum
{
CFG_MIN_MAX_DOMAINS_ENABLE = EXPLR_SRQ_MBARPC0Q_CFG_MIN_MAX_DOMAINS_ENABLE,
CFG_CCS_INST_RESET_ENABLE = EXPLR_SRQ_MBA_FARB5Q_CFG_CCS_INST_RESET_ENABLE,
CFG_DDR_RESETN = EXPLR_SRQ_MBA_FARB5Q_CFG_DDR_RESETN,
CFG_CCS_ADDR_MUX_SEL = EXPLR_SRQ_MBA_FARB5Q_CFG_CCS_ADDR_MUX_SEL,
CFG_INIT_COMPLETE = EXPLR_SRQ_MBA_PMU8Q_CFG_INIT_COMPLETE,
CFG_ZQ_PER_CAL_ENABLE = EXPLR_SRQ_MBA_FARB9Q_CFG_ZQ_PER_CAL_ENABLE,
REFRESH_ENABLE = EXPLR_SRQ_MBAREF0Q_CFG_REFRESH_ENABLE,
CFG_FORCE_STR = EXPLR_SRQ_MBASTR0Q_CFG_FORCE_STR,
ECC_CHECK_DISABLE = EXPLR_RDF_RECR_MBSECCQ_DISABLE_MEMORY_ECC_CHECK_CORRECT,
ECC_CORRECT_DISABLE = EXPLR_RDF_RECR_MBSECCQ_DISABLE_MEMORY_ECC_CORRECT,
ECC_USE_ADDR_HASH = EXPLR_RDF_RECR_MBSECCQ_USE_ADDRESS_HASH,
PORT_FAIL_DISABLE = EXPLR_SRQ_MBA_FARB0Q_CFG_PORT_FAIL_DISABLE,
DFI_INIT_START = EXPLR_SRQ_MBA_FARB0Q_CFG_INIT_START,
RCD_RECOVERY_DISABLE = EXPLR_SRQ_MBA_FARB0Q_CFG_DISABLE_RCD_RECOVERY,
BW_WINDOW_SIZE = EXPLR_SRQ_MBA_FARB0Q_CFG_BW_WINDOW_SIZE,
BW_WINDOW_SIZE_LEN = EXPLR_SRQ_MBA_FARB0Q_CFG_BW_WINDOW_SIZE_LEN,
BW_SNAPSHOT = EXPLR_SRQ_MBA_FARB6Q_CFG_BW_SNAPSHOT,
BW_SNAPSHOT_LEN = EXPLR_SRQ_MBA_FARB6Q_CFG_BW_SNAPSHOT_LEN,
RECR_ENABLE_MPE_NOISE_WINDOW = EXPLR_RDF_RECR_MBSECCQ_ENABLE_MPE_NOISE_WINDOW,
RECR_ENABLE_UE_NOISE_WINDOW = EXPLR_RDF_RECR_MBSECCQ_ENABLE_UE_NOISE_WINDOW,
RECR_TCE_CORRECTION = EXPLR_RDF_RECR_MBSECCQ_ENABLE_TCE_CORRECTION,
RECR_MBSECCQ_DATA_INVERSION = EXPLR_RDF_RECR_MBSECCQ_DATA_INVERSION,
RECR_MBSECCQ_DATA_INVERSION_LEN = EXPLR_RDF_RECR_MBSECCQ_DATA_INVERSION_LEN,
RECR_RETRY_UNMARKED_ERRORS = EXPLR_RDF_RECR_RETRY_UNMARKED_ERRORS,
RECR_CFG_MAINT_USE_TIMERS = EXPLR_RDF_RECR_CFG_MAINT_USE_TIMERS,
RECR_MBSECCQ_MAINT_NO_RETRY_UE = EXPLR_RDF_RECR_MBSECCQ_MAINT_NO_RETRY_UE,
RECR_MBSECCQ_MAINT_NO_RETRY_MPE = EXPLR_RDF_RECR_MBSECCQ_MAINT_NO_RETRY_MPE,
CFG_CTRLUPD_AFTER_ERR = EXPLR_SRQ_MBA_FARB9Q_CFG_CTRLUPD_AFTER_ERR,
CFG_MC_PER_CAL_ENABLE = EXPLR_SRQ_MBA_FARB9Q_CFG_MC_PER_CAL_ENABLE,
CFG_MC_PER_CAL_INTERVAL_TB = EXPLR_SRQ_MBA_FARB9Q_CFG_MC_PER_CAL_INTERVAL_TB,
CFG_MC_PER_CAL_INTERVAL_TB_LEN = EXPLR_SRQ_MBA_FARB9Q_CFG_MC_PER_CAL_INTERVAL_TB_LEN,
CFG_MC_PER_CAL_INTERVAL = EXPLR_SRQ_MBA_FARB9Q_CFG_MC_PER_CAL_INTERVAL,
CFG_MC_PER_CAL_INTERVAL_LEN = EXPLR_SRQ_MBA_FARB9Q_CFG_MC_PER_CAL_INTERVAL_LEN,
CFG_MC_PER_CAL_FIXED_RUN_LENGTH_EN = EXPLR_SRQ_MBA_FARB9Q_CFG_MC_PER_CAL_FIXED_RUN_LENGTH_EN,
CFG_MC_PER_CAL_RUN_LENGTH = EXPLR_SRQ_MBA_FARB9Q_CFG_MC_PER_CAL_RUN_LENGTH,
CFG_MC_PER_CAL_RUN_LENGTH_LEN = EXPLR_SRQ_MBA_FARB9Q_CFG_MC_PER_CAL_RUN_LENGTH_LEN,
CFG_MC_PER_CAL_CTRLUPD_MIN = EXPLR_SRQ_MBA_FARB9Q_CFG_MC_PER_CAL_CTRLUPD_MIN,
CFG_MC_PER_CAL_CTRLUPD_MIN_LEN = EXPLR_SRQ_MBA_FARB9Q_CFG_MC_PER_CAL_CTRLUPD_MIN_LEN,
CTCR_MPE_TIMER = EXPLR_RDF_CTCR_MPE_TIMER,
CTCR_MPE_TIMER_LEN = EXPLR_RDF_CTCR_MPE_TIMER_LEN,
CTCR_MPE_TIMEBASE = EXPLR_RDF_CTCR_MPE_TIMEBASE,
CTCR_MPE_TIMEBASE_LEN = EXPLR_RDF_CTCR_MPE_TIMEBASE_LEN,
CTCR_UE_TIMER = EXPLR_RDF_CTCR_UE_TIMER,
CTCR_UE_TIMER_LEN = EXPLR_RDF_CTCR_UE_TIMER_LEN,
CTCR_UE_TIMEBASE = EXPLR_RDF_CTCR_UE_TIMEBASE,
CTCR_UE_TIMEBASE_LEN = EXPLR_RDF_CTCR_UE_TIMEBASE_LEN,
CTCR_UE_LOCKOUT_ENABLE = EXPLR_RDF_CTCR_UE_LOCKOUT_ENABLE,
DSM0Q_RDTAG_DLY = EXPLR_SRQ_MBA_DSM0Q_CFG_RDTAG_DLY,
DSM0Q_RDTAG_DLY_LEN = EXPLR_SRQ_MBA_DSM0Q_CFG_RDTAG_DLY_LEN,
DSM0Q_WRDONE_DLY = EXPLR_SRQ_MBA_DSM0Q_CFG_WRDONE_DLY,
DSM0Q_WRDONE_DLY_LEN = EXPLR_SRQ_MBA_DSM0Q_CFG_WRDONE_DLY_LEN,
FARB0Q_RCD_PROTECTION_TIME = EXPLR_SRQ_MBA_FARB0Q_CFG_RCD_PROTECTION_TIME,
FARB0Q_RCD_PROTECTION_TIME_LEN = EXPLR_SRQ_MBA_FARB0Q_CFG_RCD_PROTECTION_TIME_LEN,
FWMS0_MARK = EXPLR_RDF_FWMS0_MARK,
FWMS0_MARK_LEN = EXPLR_RDF_FWMS0_MARK_LEN,
FWMS0_EXIT_1 = EXPLR_RDF_FWMS0_EXIT_1,
RRQ_FIFO_MODE = EXPLR_SRQ_MBA_RRQ0Q_CFG_RRQ_FIFO_MODE,
WRQ_FIFO_MODE = EXPLR_SRQ_MBA_WRQ0Q_CFG_WRQ_FIFO_MODE,
};
};
/// @brief Get the attributes for the reorder queue setting
/// @param[in] const ref to the mc target
/// @param[out] uint8_t& reference to store the value
/// @return fapi2::ReturnCode - FAPI2_RC_SUCCESS iff get is OK
/// @note Contains the settings for write/read reorder
/// queue
///
template< >
inline fapi2::ReturnCode reorder_queue_setting<mss::mc_type::EXPLORER>(
const fapi2::Target<fapi2::TARGET_TYPE_OCMB_CHIP>& i_target,
uint8_t& o_value)
{
return mss::attr::get_reorder_queue_setting(i_target, o_value);
}
///
/// @brief ATTR_MEM_EFF_DIMM_SPARE getter
/// @param[in] const ref to the TARGET_TYPE_DIMM
/// @param[out] uint32_t&[] array reference to store the value
/// @return fapi2::ReturnCode - FAPI2_RC_SUCCESS iff get is OK
/// @note Spare DRAM availability. Used in various locations and is computed in mss_eff_cnfg.
/// Array indexes are [DIMM][RANK]
///
template<>
inline fapi2::ReturnCode dimm_spare< mss::mc_type::EXPLORER >(
const fapi2::Target<fapi2::TARGET_TYPE_DIMM>& i_target,
uint8_t (&o_array)[mss::MAX_RANK_PER_DIMM_ATTR])
{
return mss::attr::get_dimm_spare(i_target, o_array);
}
///
/// @brief Change the state of the force_str bit - mc_type::EXPLORER specialization
/// @tparam MC the memory controller type
/// @param[in] i_target the target
/// @param[in] i_state the state
/// @return FAPI2_RC_SUCCESS if and only if ok
///
template< >
inline fapi2::ReturnCode change_force_str<DEFAULT_MC_TYPE>(
const fapi2::Target<fapi2::TARGET_TYPE_OCMB_CHIP>& i_target,
const states i_state )
{
using TT = portTraits<mss::mc_type::EXPLORER>;
fapi2::buffer<uint64_t> l_data;
FAPI_DBG("Change force_str to %s %s", (i_state == HIGH ? "high" : "low"), mss::c_str(i_target));
FAPI_TRY( mss::getScom(i_target, TT::STR0Q_REG, l_data) );
l_data.writeBit<TT::CFG_FORCE_STR>(i_state);
FAPI_TRY( mss::putScom(i_target, TT::STR0Q_REG, l_data) );
fapi_try_exit:
return fapi2::current_err;
}
///
/// @brief Round the symbol from dq_to_symbol to its base multiple of 4, for use with steering
/// @param[in] i_symbol symbol from dq_to_symbol
/// @return uint8_t rounded DQ symbol
///
uint8_t symbol_rounder(const uint8_t i_symbol);
///
/// @brief Configure clock stabilization time field
/// @param[in] i_target the OCMB target to operate on
/// @param[in] i_has_rcd flag to signify existence of RCD on DIMM
/// @return FAPI2_RC_SUCCESS iff ok
///
fapi2::ReturnCode configure_tstab(const fapi2::Target<fapi2::TARGET_TYPE_OCMB_CHIP>& i_target, const bool i_has_rcd);
}// mss
#endif
<commit_msg>Fix default template type in configure_wrq and configure_rrq<commit_after>/* IBM_PROLOG_BEGIN_TAG */
/* This is an automatically generated prolog. */
/* */
/* $Source: src/import/chips/ocmb/explorer/procedures/hwp/memory/lib/mc/exp_port.H $ */
/* */
/* OpenPOWER HostBoot Project */
/* */
/* Contributors Listed Below - COPYRIGHT 2019,2022 */
/* [+] International Business Machines Corp. */
/* */
/* */
/* 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. */
/* */
/* IBM_PROLOG_END_TAG */
///
/// @file exp_port.H
/// @brief Code to support ports
///
// *HWP HWP Owner: Stephen Glancy <sglancy@us.ibm.com>
// *HWP HWP Backup: Louis Stermole <stermole@us.ibm.com>
// *HWP Team: Memory
// *HWP Level: 3
// *HWP Consumed by: HB:FSP
#ifndef __MSS_EXP_PORT_H_
#define __MSS_EXP_PORT_H_
#include <fapi2.H>
#include <explorer_scom_addresses.H>
#include <explorer_scom_addresses_fld.H>
#include <explorer_scom_addresses_fld_fixes.H>
#include <lib/exp_attribute_accessors_manual.H>
#include <lib/utils/mss_exp_conversions.H>
#include <mss_explorer_attribute_getters.H>
#include <lib/mc/exp_port_traits.H>
#include <lib/shared/exp_consts.H>
#include <lib/dimm/exp_rank.H>
#include <generic/memory/lib/utils/mc/gen_mss_port.H>
#include <generic/memory/lib/utils/mc/gen_mss_restore_repairs.H>
#include <generic/memory/lib/utils/shared/mss_generic_consts.H>
#include <mss_generic_attribute_getters.H>
namespace mss
{
///
/// @brief Round the symbol from dq_to_symbol to its base multiple of 4, for use with steering
/// @param[in] i_symbol symbol from dq_to_symbol
/// @return uint8_t rounded DQ symbol
///
uint8_t symbol_rounder(const uint8_t i_symbol);
///
/// @brief Configure clock stabilization time field
/// @param[in] i_target the OCMB target to operate on
/// @param[in] i_has_rcd flag to signify existence of RCD on DIMM
/// @return FAPI2_RC_SUCCESS iff ok
///
fapi2::ReturnCode configure_tstab(const fapi2::Target<fapi2::TARGET_TYPE_OCMB_CHIP>& i_target, const bool i_has_rcd);
}// mss
#endif
<|endoftext|>
|
<commit_before>/**
* The Seeks proxy and plugin framework are part of the SEEKS project.
* Copyright (C) 2009 Emmanuel Benazera, juban@free.fr
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
**/
#include "query_interceptor.h"
#include "websearch.h"
#include "cgi.h"
#include "miscutil.h"
#include "errlog.h"
#include <iostream>
namespace seeks_plugins
{
std::string query_interceptor::_p_filename = "websearch/patterns/qi_patterns";
query_interceptor::query_interceptor(plugin *parent)
:interceptor_plugin(std::string(plugin_manager::_plugin_repository
+ query_interceptor::_p_filename).c_str(),parent)
{
}
http_response* query_interceptor::plugin_response(client_state *csp)
{
// - parse intercepted query.
hash_map<const char*,const char*,hash<const char*>,eqstr> *params
= parse_query(&csp->_http);
if (!params)
{
errlog::log_error(LOG_LEVEL_ERROR, "No parameters to intercepted query: %s%s",
csp->_http._host, csp->_http._path);
return cgi::cgi_error_memory(); // ok, this is not a memory error, but this does the job for now.
}
// debug
/* std::cerr << "params size: " << params->size() << std::endl;
hash_map<const char*, const char*, hash<const char*>, eqstr>::const_iterator hit
= params->begin();
while(hit!=params->end())
{
std::cerr << (*hit).first << " --> " << (*hit).second << std::endl;
++hit;
} */
// debug
// - send it to the generic search interface.
http_response *rsp;
if (NULL == (rsp = new http_response()))
{
return cgi::cgi_error_memory();
}
// - return the response to the client.
// default query detection.
const char *intercepted_query = miscutil::lookup(params,"q");
//if (!intercepted_query || strlen(intercepted_query) == 0)
// otherwise fall back onto se specific translation tables.
// std::cout << "intercepted query: " << intercepted_query << std::endl;
// build up query to seeks proxy.
char *q = strdup(CGI_PREFIX);
miscutil::string_append(&q,"search?q=");
miscutil::string_append(&q,intercepted_query);
miscutil::string_append(&q,"&page=1");
miscutil::string_append(&q,"&expansion=1");
miscutil::string_append(&q,"&action=expand");
cgi::cgi_redirect(rsp,q);
return cgi::finish_http_response(csp,rsp);
}
hash_map<const char*,const char*,hash<const char*>,eqstr>* query_interceptor::parse_query(http_request *http) const
{
if (http->_path)
{
hash_map<const char*,const char*,hash<const char*>,eqstr> *search_params
= cgi::parse_cgi_parameters(http->_path);
return search_params;
}
else return NULL;
}
} /* end of namespace. */
<commit_msg>fix wrong interception cases in query interceptor<commit_after>/**
* The Seeks proxy and plugin framework are part of the SEEKS project.
* Copyright (C) 2009 Emmanuel Benazera, juban@free.fr
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
**/
#include "query_interceptor.h"
#include "websearch.h"
#include "cgi.h"
#include "miscutil.h"
#include "errlog.h"
#include <iostream>
namespace seeks_plugins
{
std::string query_interceptor::_p_filename = "websearch/patterns/qi_patterns";
query_interceptor::query_interceptor(plugin *parent)
:interceptor_plugin(std::string(plugin_manager::_plugin_repository
+ query_interceptor::_p_filename).c_str(),parent)
{
}
http_response* query_interceptor::plugin_response(client_state *csp)
{
// - parse intercepted query.
hash_map<const char*,const char*,hash<const char*>,eqstr> *params
= parse_query(&csp->_http);
if (!params)
{
errlog::log_error(LOG_LEVEL_ERROR, "No parameters to intercepted query: %s%s",
csp->_http._host, csp->_http._path);
return cgi::cgi_error_memory(); // ok, this is not a memory error, but this does the job for now.
}
// debug
/* std::cerr << "params size: " << params->size() << std::endl;
hash_map<const char*, const char*, hash<const char*>, eqstr>::const_iterator hit
= params->begin();
while(hit!=params->end())
{
std::cerr << (*hit).first << " --> " << (*hit).second << std::endl;
++hit;
} */
// debug
// - send it to the generic search interface.
http_response *rsp;
if (NULL == (rsp = new http_response()))
{
return cgi::cgi_error_memory();
}
// - return the response to the client.
// default query detection.
const char *intercepted_query = miscutil::lookup(params,"q");
if (!intercepted_query)
{
return NULL; // wrong interception, cancel.
}
// build up query to seeks proxy.
char *q = strdup(CGI_PREFIX);
miscutil::string_append(&q,"search?q=");
miscutil::string_append(&q,intercepted_query);
miscutil::string_append(&q,"&page=1");
miscutil::string_append(&q,"&expansion=1");
miscutil::string_append(&q,"&action=expand");
cgi::cgi_redirect(rsp,q);
return cgi::finish_http_response(csp,rsp);
}
hash_map<const char*,const char*,hash<const char*>,eqstr>* query_interceptor::parse_query(http_request *http) const
{
if (http->_path)
{
hash_map<const char*,const char*,hash<const char*>,eqstr> *search_params
= cgi::parse_cgi_parameters(http->_path);
return search_params;
}
else return NULL;
}
} /* end of namespace. */
<|endoftext|>
|
<commit_before>#ifndef HMLIB_MATH_ROOT_INC
#define HMLIB_MATH_ROOT_INC 100
#
#include<utility>
#include<iterator>
#include<boost/math/tools/roots.hpp>
namespace hmLib {
namespace math {
template<typename T>
struct toms748_root_stepper {
using value_type = T;
private:
value_type step;
value_type error;
public:
toms748_root_stepper(value_type step_, value_type error_):step(step_),error(error_){}
template<typename fn, typename ans_type>
std::pair<value_type, value_typeT> operator()(fn Fn, value_type& start, ans_type& startFnVal, value_type end)const {
value_type a = start;
ans_type fa = startFnVal;
while(a < end) {
auto b = std::min(a + step, end);
auto fb = Fn(b);
if(fb == 0) {
start = b;
startFnVal = fb;
return std::make_pair(b, b);
} else if(fa * fb < 0.0) {
boost::uintmax_t max_iter = 128;
auto ans = boost::math::tools::toms748_solve(Fn, a, b, fa, fb, [error](ans_type v1, ans_type v2) {return v2 - v1 < error; }, max_iter);
start = b;
startFnVal = fb;
return ans;
}
a = b;
fa = fb;
}
start = a;
startFnVal = fa;
return std::make_pair(a, a);
}
void reset(value_type step_, value_type error_) {
step = step_;
error = error_;
}
};
template<typename T>
struct bisect_root_stepper {
using value_type = T;
private:
value_type step;
value_type error;
public:
bisect_root_stepper(value_type step_, value_type error_):step(step_), error(error_) {}
template<typename fn, typename ans_type>
std::pair<value_type, value_typeT> operator()(fn Fn, value_type& start, ans_type& startFnVal, value_type end)const {
value_type a = start;
ans_type fa = startFnVal;
while(a < end) {
auto b = std::min(a + step, end);
auto fb = Fn(b);
if(fb == 0) {
start = b;
startFnVal = fb;
return std::make_pair(b, b);
} else if(fa * fb < 0.0) {
boost::uintmax_t max_iter = 128;
auto ans = boost::math::tools::bisect(Fn, a, b, [error](ans_type v1, ans_type v2) {return v2 - v1 < error; });
start = b;
startFnVal = fb;
return ans;
}
a = b;
fa = fb;
}
start = a;
startFnVal = fa;
return std::make_pair(a, a);
}
void reset(value_type step_, value_type error_) {
step = step_;
error = error_;
}
};
template<typename root_stepper, typename fn, typename T, typename output_iterator>
output_iterator root(root_stepper Stepper, fn Fn, T minval, T maxval, output_iterator out) {
auto FnVal = Fn(minval);
while (minval<maxval) {
auto Ans = Stepper(Fn, minval, FnVal, maxval);
if (Ans.first < maxval) {
*(out++) = (Ans.first + Ans.second) / 2.0;
}
}
return out;
}
template<typename root_stepper, typename fn, typename T, typename output_iterator>
output_iterator root_with_stability(root_stepper Stepper, fn Fn, T minval, T maxval, output_iterator out) {
auto FnVal = Fn(minval);
while(minval<maxval) {
auto Ans = Stepper(Fn, minval, FnVal, maxval);
if(Ans.first < maxval) {
*(out++) = std::make_pair((Ans.first + Ans.second) / 2.0, FnVal<0);
}
}
return out;
}
template<typename root_stepper, typename fn, typename T, typename output_iterator>
output_iterator convergent_root(root_stepper Stepper, fn Fn, T minval, T maxval, output_iterator out) {
auto FnVal = Fn(minval);
while(minval<maxval) {
auto Ans = Stepper(Fn, minval, FnVal);
if(Ans.first < maxval && FnVal<0) {
*(out++) = (Ans.first + Ans.second) / 2.0;
}
}
return out;
}
template<typename fn, typename T, typename output_iterator>
output_iterator root_toms748(fn Fn, T minval, T maxval, T step, T error, output_iterator out) {
toms748_root_stepper<T> Stepper(step, error);
return root(Stepper, Fn, minval, maxval, out);
}
template<typename root_stepper, typename fn, typename T, typename output_iterator>
output_iterator root_with_stability_toms748(fn Fn, T minval, T maxval, T step, T error, output_iterator out) {
toms748_root_stepper<T> Stepper(step, error);
return root_with_stability(Stepper, Fn, minval, maxval, out);
}
template<typename root_stepper, typename fn, typename T, typename output_iterator>
output_iterator convergent_root(fn Fn, T minval, T maxval, T step, T error, output_iterator out) {
toms748_root_stepper<T> Stepper(step, error);
return convergent_root(Stepper, Fn, minval, maxval, out);
}
}
}
#
#endif
<commit_msg>Fix: typo in root <commit_after>#ifndef HMLIB_MATH_ROOT_INC
#define HMLIB_MATH_ROOT_INC 100
#
#include<utility>
#include<iterator>
#include<boost/math/tools/roots.hpp>
namespace hmLib {
namespace math {
template<typename T>
struct toms748_root_stepper {
using value_type = T;
private:
value_type step;
value_type error;
public:
toms748_root_stepper(value_type step_, value_type error_):step(step_),error(error_){}
template<typename fn, typename ans_type>
std::pair<value_type, value_type> operator()(fn Fn, value_type& start, ans_type& startFnVal, value_type end)const {
value_type a = start;
ans_type fa = startFnVal;
while(a < end) {
auto b = std::min(a + step, end);
auto fb = Fn(b);
if(fb == 0) {
start = b;
startFnVal = fb;
return std::make_pair(b, b);
} else if(fa * fb < 0.0) {
boost::uintmax_t max_iter = 128;
auto ans = boost::math::tools::toms748_solve(Fn, a, b, fa, fb, [error=error](ans_type v1, ans_type v2) {return v2 - v1 < error; }, max_iter);
start = b;
startFnVal = fb;
return ans;
}
a = b;
fa = fb;
}
start = a;
startFnVal = fa;
return std::make_pair(a, a);
}
void reset(value_type step_, value_type error_) {
step = step_;
error = error_;
}
};
template<typename T>
struct bisect_root_stepper {
using value_type = T;
private:
value_type step;
value_type error;
public:
bisect_root_stepper(value_type step_, value_type error_):step(step_), error(error_) {}
template<typename fn, typename ans_type>
std::pair<value_type, value_type> operator()(fn Fn, value_type& start, ans_type& startFnVal, value_type end)const {
value_type a = start;
ans_type fa = startFnVal;
while(a < end) {
auto b = std::min(a + step, end);
auto fb = Fn(b);
if(fb == 0) {
start = b;
startFnVal = fb;
return std::make_pair(b, b);
} else if(fa * fb < 0.0) {
boost::uintmax_t max_iter = 128;
auto ans = boost::math::tools::bisect(Fn, a, b, [error=error](ans_type v1, ans_type v2) {return v2 - v1 < error; });
start = b;
startFnVal = fb;
return ans;
}
a = b;
fa = fb;
}
start = a;
startFnVal = fa;
return std::make_pair(a, a);
}
void reset(value_type step_, value_type error_) {
step = step_;
error = error_;
}
};
template<typename root_stepper, typename fn, typename T, typename output_iterator>
output_iterator root(root_stepper Stepper, fn Fn, T minval, T maxval, output_iterator out) {
auto FnVal = Fn(minval);
while (minval<maxval) {
auto Ans = Stepper(Fn, minval, FnVal, maxval);
if (Ans.first < maxval) {
*(out++) = (Ans.first + Ans.second) / 2.0;
}
}
return out;
}
template<typename root_stepper, typename fn, typename T, typename output_iterator>
output_iterator root_with_stability(root_stepper Stepper, fn Fn, T minval, T maxval, output_iterator out) {
auto FnVal = Fn(minval);
while(minval<maxval) {
auto Ans = Stepper(Fn, minval, FnVal, maxval);
if(Ans.first < maxval) {
*(out++) = std::make_pair((Ans.first + Ans.second) / 2.0, FnVal<0);
}
}
return out;
}
template<typename root_stepper, typename fn, typename T, typename output_iterator>
output_iterator stable_root(root_stepper Stepper, fn Fn, T minval, T maxval, output_iterator out) {
auto FnVal = Fn(minval);
while(minval<maxval) {
auto Ans = Stepper(Fn, minval, FnVal, maxval);
if(Ans.first < maxval && FnVal<0) {
*(out++) = (Ans.first + Ans.second) / 2.0;
}
}
return out;
}
template<typename fn, typename T, typename output_iterator>
output_iterator root_toms748(fn Fn, T minval, T maxval, T step, T error, output_iterator out) {
toms748_root_stepper<T> Stepper(step, error);
return root(Stepper, std::forward<fn>(Fn), minval, maxval, out);
}
template<typename fn, typename T, typename output_iterator>
output_iterator root_with_stability_toms748(fn Fn, T minval, T maxval, T step, T error, output_iterator out) {
toms748_root_stepper<T> Stepper(step, error);
return root_with_stability(Stepper, std::forward<fn>(Fn), minval, maxval, out);
}
template<typename fn, typename T, typename output_iterator>
output_iterator stable_root_toms748(fn Fn, T minval, T maxval, T step, T error, output_iterator out) {
toms748_root_stepper<T> Stepper(step, error);
return stable_root(Stepper, std::forward<fn>(Fn), minval, maxval, out);
}
}
}
#
#endif
<|endoftext|>
|
<commit_before>//
// Copyright 2019 The ANGLE 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.
//
// EGLChooseConfigTest.cpp:
// Tests of proper default-value semantics for eglChooseConfig
#include <gtest/gtest.h>
#include "test_utils/ANGLETest.h"
#include "test_utils/angle_test_configs.h"
#include "util/EGLWindow.h"
using namespace angle;
namespace angle
{
class EGLChooseConfigTest : public ANGLETest
{
protected:
EGLChooseConfigTest() {}
};
// Test that the EGL_COLOR_BUFFER_TYPE is defaulted to EGL_RGB_BUFFER
TEST_P(EGLChooseConfigTest, Defaults)
{
EGLDisplay display = getEGLWindow()->getDisplay();
EGLint nConfigs = 0;
EGLint allConfigCount = 0;
ASSERT_EGL_TRUE(eglGetConfigs(display, nullptr, 0, &nConfigs));
ASSERT_NE(nConfigs, 0);
std::vector<EGLConfig> allConfigs(nConfigs);
ASSERT_EGL_TRUE(eglGetConfigs(display, allConfigs.data(), nConfigs, &allConfigCount));
ASSERT_EQ(nConfigs, allConfigCount);
// Choose configs that have the default attribute values:
const EGLint defaultConfigAttributes[] = {EGL_NONE};
EGLint defaultConfigCount;
std::vector<EGLConfig> defaultConfigs(allConfigCount);
ASSERT_EGL_TRUE(eglChooseConfig(display, defaultConfigAttributes, defaultConfigs.data(),
defaultConfigs.size(), &defaultConfigCount));
ASSERT_EGL_SUCCESS();
ASSERT_LE(defaultConfigCount, allConfigCount);
// Check that the default configs all have the default attribute values we care about:
for (EGLConfig config : defaultConfigs)
{
EGLint colorBufferType, level, renderableType, surfaceType, transparentType;
EGLint colorComponentType;
eglGetConfigAttrib(display, config, EGL_COLOR_BUFFER_TYPE, &colorBufferType);
ASSERT_EQ(colorBufferType, EGL_RGB_BUFFER);
eglGetConfigAttrib(display, config, EGL_LEVEL, &level);
ASSERT_EQ(level, 0);
eglGetConfigAttrib(display, config, EGL_RENDERABLE_TYPE, &renderableType);
ASSERT_EQ(renderableType & EGL_OPENGL_ES_BIT, EGL_OPENGL_ES_BIT);
eglGetConfigAttrib(display, config, EGL_SURFACE_TYPE, &surfaceType);
ASSERT_EQ(surfaceType & EGL_WINDOW_BIT, EGL_WINDOW_BIT);
eglGetConfigAttrib(display, config, EGL_TRANSPARENT_TYPE, &transparentType);
ASSERT_EQ(transparentType, EGL_NONE);
if (IsEGLDisplayExtensionEnabled(display, "EGL_EXT_pixel_format_float"))
{
eglGetConfigAttrib(display, config, EGL_COLOR_COMPONENT_TYPE_EXT, &colorComponentType);
ASSERT_EQ(colorComponentType, EGL_COLOR_COMPONENT_TYPE_FIXED_EXT);
}
}
// Check that all of the configs that have the default attribute values are are defaultConfigs,
// and all that don't aren't:
for (EGLConfig config : allConfigs)
{
EGLint colorBufferType, level, renderableType, surfaceType, transparentType;
EGLint colorComponentType = EGL_COLOR_COMPONENT_TYPE_FIXED_EXT;
eglGetConfigAttrib(display, config, EGL_COLOR_BUFFER_TYPE, &colorBufferType);
eglGetConfigAttrib(display, config, EGL_LEVEL, &level);
eglGetConfigAttrib(display, config, EGL_RENDERABLE_TYPE, &renderableType);
eglGetConfigAttrib(display, config, EGL_SURFACE_TYPE, &surfaceType);
eglGetConfigAttrib(display, config, EGL_TRANSPARENT_TYPE, &transparentType);
if (IsEGLDisplayExtensionEnabled(display, "EGL_EXT_pixel_format_float"))
{
eglGetConfigAttrib(display, config, EGL_COLOR_COMPONENT_TYPE_EXT, &colorComponentType);
}
bool isADefault =
((colorBufferType == EGL_RGB_BUFFER) && (level == 0) &&
((renderableType & EGL_OPENGL_ES_BIT) == EGL_OPENGL_ES_BIT) &&
((surfaceType & EGL_WINDOW_BIT) == EGL_WINDOW_BIT) && (transparentType == EGL_NONE) &&
(colorComponentType == EGL_COLOR_COMPONENT_TYPE_FIXED_EXT));
EGLint thisConfigID;
eglGetConfigAttrib(display, config, EGL_CONFIG_ID, &thisConfigID);
bool foundInDefaultConfigs = false;
// Attempt to find this config ID in defaultConfigs:
for (EGLConfig defaultConfig : defaultConfigs)
{
EGLint defaultConfigID;
eglGetConfigAttrib(display, defaultConfig, EGL_CONFIG_ID, &defaultConfigID);
if (defaultConfigID == thisConfigID)
{
foundInDefaultConfigs = true;
}
}
ASSERT_EQ(isADefault, foundInDefaultConfigs);
}
}
} // namespace angle
ANGLE_INSTANTIATE_TEST(EGLChooseConfigTest,
ES2_D3D11(),
ES2_D3D9(),
ES2_METAL(),
ES2_OPENGL(),
ES2_OPENGLES(),
ES2_VULKAN());
<commit_msg>Vulkan: Resize the result vector in EGLChooseConfigTest end2end test<commit_after>//
// Copyright 2019 The ANGLE 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.
//
// EGLChooseConfigTest.cpp:
// Tests of proper default-value semantics for eglChooseConfig
#include <gtest/gtest.h>
#include "test_utils/ANGLETest.h"
#include "test_utils/angle_test_configs.h"
#include "util/EGLWindow.h"
using namespace angle;
namespace angle
{
class EGLChooseConfigTest : public ANGLETest
{
protected:
EGLChooseConfigTest() {}
};
// Test that the EGL_COLOR_BUFFER_TYPE is defaulted to EGL_RGB_BUFFER
TEST_P(EGLChooseConfigTest, Defaults)
{
EGLDisplay display = getEGLWindow()->getDisplay();
EGLint nConfigs = 0;
EGLint allConfigCount = 0;
ASSERT_EGL_TRUE(eglGetConfigs(display, nullptr, 0, &nConfigs));
ASSERT_NE(nConfigs, 0);
std::vector<EGLConfig> allConfigs(nConfigs);
ASSERT_EGL_TRUE(eglGetConfigs(display, allConfigs.data(), nConfigs, &allConfigCount));
ASSERT_EQ(nConfigs, allConfigCount);
// Choose configs that have the default attribute values:
const EGLint defaultConfigAttributes[] = {EGL_NONE};
EGLint defaultConfigCount;
std::vector<EGLConfig> defaultConfigs(allConfigCount);
ASSERT_EGL_TRUE(eglChooseConfig(display, defaultConfigAttributes, defaultConfigs.data(),
defaultConfigs.size(), &defaultConfigCount));
ASSERT_EGL_SUCCESS();
ASSERT_LE(defaultConfigCount, allConfigCount);
defaultConfigs.resize(defaultConfigCount);
// Check that the default configs all have the default attribute values we care about:
for (EGLConfig config : defaultConfigs)
{
EGLint colorBufferType, level, renderableType, surfaceType, transparentType;
EGLint colorComponentType;
eglGetConfigAttrib(display, config, EGL_COLOR_BUFFER_TYPE, &colorBufferType);
ASSERT_EQ(colorBufferType, EGL_RGB_BUFFER);
eglGetConfigAttrib(display, config, EGL_LEVEL, &level);
ASSERT_EQ(level, 0);
eglGetConfigAttrib(display, config, EGL_RENDERABLE_TYPE, &renderableType);
ASSERT_EQ(renderableType & EGL_OPENGL_ES_BIT, EGL_OPENGL_ES_BIT);
eglGetConfigAttrib(display, config, EGL_SURFACE_TYPE, &surfaceType);
ASSERT_EQ(surfaceType & EGL_WINDOW_BIT, EGL_WINDOW_BIT);
eglGetConfigAttrib(display, config, EGL_TRANSPARENT_TYPE, &transparentType);
ASSERT_EQ(transparentType, EGL_NONE);
if (IsEGLDisplayExtensionEnabled(display, "EGL_EXT_pixel_format_float"))
{
eglGetConfigAttrib(display, config, EGL_COLOR_COMPONENT_TYPE_EXT, &colorComponentType);
ASSERT_EQ(colorComponentType, EGL_COLOR_COMPONENT_TYPE_FIXED_EXT);
}
}
// Check that all of the configs that have the default attribute values are are defaultConfigs,
// and all that don't aren't:
for (EGLConfig config : allConfigs)
{
EGLint colorBufferType, level, renderableType, surfaceType, transparentType;
EGLint colorComponentType = EGL_COLOR_COMPONENT_TYPE_FIXED_EXT;
eglGetConfigAttrib(display, config, EGL_COLOR_BUFFER_TYPE, &colorBufferType);
eglGetConfigAttrib(display, config, EGL_LEVEL, &level);
eglGetConfigAttrib(display, config, EGL_RENDERABLE_TYPE, &renderableType);
eglGetConfigAttrib(display, config, EGL_SURFACE_TYPE, &surfaceType);
eglGetConfigAttrib(display, config, EGL_TRANSPARENT_TYPE, &transparentType);
if (IsEGLDisplayExtensionEnabled(display, "EGL_EXT_pixel_format_float"))
{
eglGetConfigAttrib(display, config, EGL_COLOR_COMPONENT_TYPE_EXT, &colorComponentType);
}
bool isADefault =
((colorBufferType == EGL_RGB_BUFFER) && (level == 0) &&
((renderableType & EGL_OPENGL_ES_BIT) == EGL_OPENGL_ES_BIT) &&
((surfaceType & EGL_WINDOW_BIT) == EGL_WINDOW_BIT) && (transparentType == EGL_NONE) &&
(colorComponentType == EGL_COLOR_COMPONENT_TYPE_FIXED_EXT));
EGLint thisConfigID;
eglGetConfigAttrib(display, config, EGL_CONFIG_ID, &thisConfigID);
bool foundInDefaultConfigs = false;
// Attempt to find this config ID in defaultConfigs:
for (EGLConfig defaultConfig : defaultConfigs)
{
EGLint defaultConfigID;
eglGetConfigAttrib(display, defaultConfig, EGL_CONFIG_ID, &defaultConfigID);
if (defaultConfigID == thisConfigID)
{
foundInDefaultConfigs = true;
}
}
ASSERT_EQ(isADefault, foundInDefaultConfigs);
}
}
} // namespace angle
ANGLE_INSTANTIATE_TEST(EGLChooseConfigTest,
ES2_D3D11(),
ES2_D3D9(),
ES2_METAL(),
ES2_OPENGL(),
ES2_OPENGLES(),
ES2_VULKAN());
<|endoftext|>
|
<commit_before>#include "GlQuadTreeLODCalculator.h"
#include "Utils.h"
#include "QuadTree.h"
#include "GlEntity.h"
#include "GlLayer.h"
#ifdef _OPENMP
#include <omp.h>
#endif
#include <tulip/Matrix.h>
#include <tulip/LayoutProperty.h>
#include <tulip/PropertyInterface.h>
using namespace std;
using namespace tlp;
GlQuadTreeLODCalculator::GlQuadTreeLODCalculator() : _nodesQuadTree(NULL), _edgesQuadTree(NULL), _haveToCompute(true) {
#ifdef __EMSCRIPTEN__
_haveToCompute = false;
#endif
}
GlQuadTreeLODCalculator::~GlQuadTreeLODCalculator() {
std::map<GlLayer*, QuadTreeNode<GlEntity*> *>::iterator it = _glEntitiesQuadTree.begin();
for (; it != _glEntitiesQuadTree.end() ; ++it) {
delete it->second;
}
delete _nodesQuadTree;
delete _edgesQuadTree;
}
void GlQuadTreeLODCalculator::setGraph(tlp::Graph *graph, GlGraphRenderingParameters *renderingParameters) {
_haveToCompute = true;
GlCPULODCalculator::setGraph(graph, renderingParameters);
}
void GlQuadTreeLODCalculator::initQuadTree() {
std::map<GlLayer*, QuadTreeNode<GlEntity*> *>::iterator it = _glEntitiesQuadTree.begin();
for (; it != _glEntitiesQuadTree.end() ; ++it) {
delete it->second;
}
_glEntitiesQuadTree.clear();
delete _nodesQuadTree;
delete _edgesQuadTree;
_nodesQuadTree = new QuadTreeNode<node>(_sceneBoundingBox);
_edgesQuadTree = new QuadTreeNode<edge>(_sceneBoundingBox);
}
void GlQuadTreeLODCalculator::clear() {
GlCPULODCalculator::clear();
initQuadTree();
}
void GlQuadTreeLODCalculator::setSceneBoundingBox(const tlp::BoundingBox &sceneBoundingBox) {
GlCPULODCalculator::setSceneBoundingBox(sceneBoundingBox);
initQuadTree();
}
void GlQuadTreeLODCalculator::addGlEntity(GlLayer *layer, GlEntity *glEntity) {
if (_sceneBoundingBox.isValid() && _glEntitiesQuadTree.find(layer) == _glEntitiesQuadTree.end()) {
_glEntitiesQuadTree[layer] = new QuadTreeNode<GlEntity*>(_sceneBoundingBox);
}
if (_sceneBoundingBox.isValid() && _glEntitiesQuadTree[layer]->getCellForElement(glEntity) == NULL) {
_glEntitiesQuadTree[layer]->insert(glEntity->getBoundingBox(), glEntity);
}
GlCPULODCalculator::addGlEntity(layer, glEntity);
}
void GlQuadTreeLODCalculator::removeGlEntity(GlLayer *layer, GlEntity *glEntity) {
if (_glEntitiesQuadTree.find(layer) != _glEntitiesQuadTree.end()) {
_glEntitiesQuadTree[layer]->remove(glEntity);
}
}
void GlQuadTreeLODCalculator::removeLayer(GlLayer *layer) {
if (_glEntitiesQuadTree.find(layer) != _glEntitiesQuadTree.end()) {
delete _glEntitiesQuadTree[layer];
_glEntitiesQuadTree.erase(layer);
}
}
void GlQuadTreeLODCalculator::addNode(const tlp::node n) {
GlCPULODCalculator::addNode(n);
insertNodeInQuadTree(_nodesLODVector.back().boundingBox, n);
}
void GlQuadTreeLODCalculator::addEdge(const tlp::edge e) {
GlCPULODCalculator::addEdge(e);
insertEdgeInQuadTree(_edgesLODVector.back().boundingBox, e);
}
void GlQuadTreeLODCalculator::insertNodeInQuadTree(const tlp::BoundingBox &nodeBoundingBox, const tlp::node n) {
_nodesQuadTree->insert(nodeBoundingBox, n);
}
void GlQuadTreeLODCalculator::insertEdgeInQuadTree(BoundingBox edgeBoundingBox, const tlp::edge e) {
// This code is here to expand edge bounding box when we have an edge with direction (0,0,x)
if(edgeBoundingBox[0][0] == edgeBoundingBox[1][0] && edgeBoundingBox[0][1] == edgeBoundingBox[1][1]) {
edgeBoundingBox.expand(edgeBoundingBox[1]+Coord(0.01,0.01,0));
}
_edgesQuadTree->insert(edgeBoundingBox, e);
}
void GlQuadTreeLODCalculator::computeFor3DCamera(const Coord &eye, const Matrix<float, 4> &transformMatrix,
const Vector<int,4>& globalViewport, const Vector<int,4>& currentViewport) {
// aX,aY : rotation on the camera in x and y
Coord eyeCenter=camera->getCenter()-camera->getEyes();
double aX=atan(eyeCenter[1]/eyeCenter[2]);
double aY=atan(eyeCenter[0]/eyeCenter[2]);
_glEntitiesLODVector.clear();
_nodesLODVector.clear();
_edgesLODVector.clear();
MatrixGL invTransformMatrix(transformMatrix);
invTransformMatrix.inverse();
Coord pSrc = projectPoint(Coord(0,0,0), transformMatrix, globalViewport);
Vector<int,4> transformedViewport=currentViewport;
transformedViewport[1]=globalViewport[3]-(currentViewport[1]+currentViewport[3]);
BoundingBox cameraBoundingBox;
// Project camera bounding box to known visible part of the quadtree
pSrc[0] = transformedViewport[0];
pSrc[1] = (globalViewport[1] + globalViewport[3]) - (transformedViewport[1] + transformedViewport[3]);
cameraBoundingBox.expand(unprojectPoint(pSrc, invTransformMatrix, globalViewport));
pSrc[1] = transformedViewport[1]+transformedViewport[3];
cameraBoundingBox.expand(unprojectPoint(pSrc, invTransformMatrix, globalViewport));
pSrc[0] = transformedViewport[0]+transformedViewport[2];
cameraBoundingBox.expand(unprojectPoint(pSrc, invTransformMatrix, globalViewport));
pSrc[1] = transformedViewport[1];
cameraBoundingBox.expand(unprojectPoint(pSrc, invTransformMatrix, globalViewport));
// Get result of quadtrees
#ifdef _OPENMP
#pragma omp parallel
#endif
{
#ifdef _OPENMP
#pragma omp sections nowait
#endif
{
#ifdef _OPENMP
#pragma omp section
#endif
{
if((_renderingEntitiesFlag & RenderingGlEntities)!=0) {
std::map<GlLayer*, QuadTreeNode<GlEntity*> *>::iterator it = _glEntitiesQuadTree.begin();
for (; it != _glEntitiesQuadTree.end() ; ++it) {
vector<GlEntity*> resGlEntities;
if(aX==0 && aY==0) {
it->second->getElements(cameraBoundingBox,resGlEntities);
}
else {
it->second->getElements(resGlEntities);
}
for(size_t i = 0 ; i < resGlEntities.size() ; ++i) {
_glEntitiesLODVector[it->first].push_back(GlEntityLODUnit(resGlEntities[i]));
}
}
}
}
#ifdef _OPENMP
#pragma omp section
#endif
{
if(_graph && (_renderingEntitiesFlag & RenderingNodes)!=0) {
vector<node> resNodes;
resNodes.reserve(_graph->numberOfNodes());
if(aX==0 && aY==0) {
if(_nodesQuadTree)
_nodesQuadTree->getElements(cameraBoundingBox,resNodes);
}
else {
if(_nodesQuadTree)
_nodesQuadTree->getElements(resNodes);
}
_nodesLODVector.reserve(resNodes.size());
for(size_t i = 0 ; i < resNodes.size() ; ++i) {
_nodesLODVector.push_back(NodeEntityLODUnit(resNodes[i], _nodesBBCache[resNodes[i]]));
}
}
}
#ifdef _OPENMP
#pragma omp section
#endif
{
if(_graph && (_renderingEntitiesFlag & RenderingEdges)!=0) {
vector<edge> resEdges;
resEdges.reserve(_graph->numberOfEdges());
if(aX==0 && aY==0) {
if(_edgesQuadTree)
_edgesQuadTree->getElements(cameraBoundingBox,resEdges);
}
else {
if(_edgesQuadTree)
_edgesQuadTree->getElements(resEdges);
}
for(size_t i = 0 ; i < resEdges.size() ; ++i) {
_edgesLODVector.push_back(EdgeEntityLODUnit(resEdges[i], _edgesBBCache[resEdges[i]]));
}
}
}
}
}
GlCPULODCalculator::computeFor3DCamera(eye,transformMatrix,globalViewport,currentViewport);
}
<commit_msg>fix GlQuadTreeLODCalculator implementation after last commit<commit_after>#include "GlQuadTreeLODCalculator.h"
#include "Utils.h"
#include "QuadTree.h"
#include "GlEntity.h"
#include "GlLayer.h"
#ifdef _OPENMP
#include <omp.h>
#endif
#include <tulip/Matrix.h>
#include <tulip/LayoutProperty.h>
#include <tulip/PropertyInterface.h>
using namespace std;
using namespace tlp;
GlQuadTreeLODCalculator::GlQuadTreeLODCalculator() : _nodesQuadTree(NULL), _edgesQuadTree(NULL), _haveToCompute(true) {
#ifdef __EMSCRIPTEN__
_haveToCompute = false;
#endif
}
GlQuadTreeLODCalculator::~GlQuadTreeLODCalculator() {
std::map<GlLayer*, QuadTreeNode<GlEntity*> *>::iterator it = _glEntitiesQuadTree.begin();
for (; it != _glEntitiesQuadTree.end() ; ++it) {
delete it->second;
}
delete _nodesQuadTree;
delete _edgesQuadTree;
}
void GlQuadTreeLODCalculator::setGraph(tlp::Graph *graph, GlGraphRenderingParameters *renderingParameters) {
_haveToCompute = true;
GlCPULODCalculator::setGraph(graph, renderingParameters);
}
void GlQuadTreeLODCalculator::initQuadTree() {
std::map<GlLayer*, QuadTreeNode<GlEntity*> *>::iterator it = _glEntitiesQuadTree.begin();
for (; it != _glEntitiesQuadTree.end() ; ++it) {
delete it->second;
}
_glEntitiesQuadTree.clear();
delete _nodesQuadTree;
delete _edgesQuadTree;
_nodesQuadTree = new QuadTreeNode<node>(_sceneBoundingBox);
_edgesQuadTree = new QuadTreeNode<edge>(_sceneBoundingBox);
}
void GlQuadTreeLODCalculator::clear() {
GlCPULODCalculator::clear();
initQuadTree();
}
void GlQuadTreeLODCalculator::setSceneBoundingBox(const tlp::BoundingBox &sceneBoundingBox) {
GlCPULODCalculator::setSceneBoundingBox(sceneBoundingBox);
initQuadTree();
}
void GlQuadTreeLODCalculator::addGlEntity(GlLayer *layer, GlEntity *glEntity) {
if (_sceneBoundingBox.isValid() && _glEntitiesQuadTree.find(layer) == _glEntitiesQuadTree.end()) {
_glEntitiesQuadTree[layer] = new QuadTreeNode<GlEntity*>(_sceneBoundingBox);
}
if (_sceneBoundingBox.isValid() && _glEntitiesQuadTree[layer]->getCellForElement(glEntity) == NULL) {
_glEntitiesQuadTree[layer]->insert(glEntity->getBoundingBox(), glEntity);
}
GlCPULODCalculator::addGlEntity(layer, glEntity);
}
void GlQuadTreeLODCalculator::removeGlEntity(GlLayer *layer, GlEntity *glEntity) {
if (_glEntitiesQuadTree.find(layer) != _glEntitiesQuadTree.end()) {
_glEntitiesQuadTree[layer]->remove(glEntity);
}
}
void GlQuadTreeLODCalculator::removeLayer(GlLayer *layer) {
if (_glEntitiesQuadTree.find(layer) != _glEntitiesQuadTree.end()) {
delete _glEntitiesQuadTree[layer];
_glEntitiesQuadTree.erase(layer);
}
}
void GlQuadTreeLODCalculator::addNode(const tlp::node n) {
GlCPULODCalculator::addNode(n);
insertNodeInQuadTree(_nodesLODVector.back().boundingBox, n);
}
void GlQuadTreeLODCalculator::addEdge(const tlp::edge e) {
GlCPULODCalculator::addEdge(e);
insertEdgeInQuadTree(_edgesLODVector.back().boundingBox, e);
}
void GlQuadTreeLODCalculator::insertNodeInQuadTree(const tlp::BoundingBox &nodeBoundingBox, const tlp::node n) {
_nodesQuadTree->insert(nodeBoundingBox, n);
}
void GlQuadTreeLODCalculator::insertEdgeInQuadTree(BoundingBox edgeBoundingBox, const tlp::edge e) {
// This code is here to expand edge bounding box when we have an edge with direction (0,0,x)
if(edgeBoundingBox[0][0] == edgeBoundingBox[1][0] && edgeBoundingBox[0][1] == edgeBoundingBox[1][1]) {
edgeBoundingBox.expand(edgeBoundingBox[1]+Coord(0.01,0.01,0));
}
_edgesQuadTree->insert(edgeBoundingBox, e);
}
void GlQuadTreeLODCalculator::computeFor3DCamera(const Coord &eye, const Matrix<float, 4> &transformMatrix,
const Vector<int,4>& globalViewport, const Vector<int,4>& currentViewport) {
// aX,aY : rotation on the camera in x and y
Coord eyeCenter=camera->getCenter()-camera->getEyes();
double aX=atan(eyeCenter[1]/eyeCenter[2]);
double aY=atan(eyeCenter[0]/eyeCenter[2]);
_glEntitiesLODVector.clear();
_nodesLODVector.clear();
_edgesLODVector.clear();
MatrixGL invTransformMatrix(transformMatrix);
invTransformMatrix.inverse();
Coord pSrc = projectPoint(Coord(0,0,0), transformMatrix, globalViewport);
BoundingBox cameraBoundingBox;
// Project camera bounding box to known visible part of the quadtree
pSrc[0] = currentViewport[0];
pSrc[1] = (globalViewport[1] + globalViewport[3]) - (currentViewport[1] + currentViewport[3]);
cameraBoundingBox.expand(unprojectPoint(pSrc, invTransformMatrix, globalViewport));
pSrc[1] = currentViewport[1]+currentViewport[3];
cameraBoundingBox.expand(unprojectPoint(pSrc, invTransformMatrix, globalViewport));
pSrc[0] = currentViewport[0]+currentViewport[2];
cameraBoundingBox.expand(unprojectPoint(pSrc, invTransformMatrix, globalViewport));
pSrc[1] = currentViewport[1];
cameraBoundingBox.expand(unprojectPoint(pSrc, invTransformMatrix, globalViewport));
// Get result of quadtrees
#ifdef _OPENMP
#pragma omp parallel
#endif
{
#ifdef _OPENMP
#pragma omp sections nowait
#endif
{
#ifdef _OPENMP
#pragma omp section
#endif
{
if((_renderingEntitiesFlag & RenderingGlEntities)!=0) {
std::map<GlLayer*, QuadTreeNode<GlEntity*> *>::iterator it = _glEntitiesQuadTree.begin();
for (; it != _glEntitiesQuadTree.end() ; ++it) {
vector<GlEntity*> resGlEntities;
if(aX==0 && aY==0) {
it->second->getElements(cameraBoundingBox,resGlEntities);
}
else {
it->second->getElements(resGlEntities);
}
for(size_t i = 0 ; i < resGlEntities.size() ; ++i) {
_glEntitiesLODVector[it->first].push_back(GlEntityLODUnit(resGlEntities[i]));
}
}
}
}
#ifdef _OPENMP
#pragma omp section
#endif
{
if(_graph && (_renderingEntitiesFlag & RenderingNodes)!=0) {
vector<node> resNodes;
resNodes.reserve(_graph->numberOfNodes());
if(aX==0 && aY==0) {
if(_nodesQuadTree)
_nodesQuadTree->getElements(cameraBoundingBox,resNodes);
}
else {
if(_nodesQuadTree)
_nodesQuadTree->getElements(resNodes);
}
_nodesLODVector.reserve(resNodes.size());
for(size_t i = 0 ; i < resNodes.size() ; ++i) {
_nodesLODVector.push_back(NodeEntityLODUnit(resNodes[i], _nodesBBCache[resNodes[i]]));
}
}
}
#ifdef _OPENMP
#pragma omp section
#endif
{
if(_graph && (_renderingEntitiesFlag & RenderingEdges)!=0) {
vector<edge> resEdges;
resEdges.reserve(_graph->numberOfEdges());
if(aX==0 && aY==0) {
if(_edgesQuadTree)
_edgesQuadTree->getElements(cameraBoundingBox,resEdges);
}
else {
if(_edgesQuadTree)
_edgesQuadTree->getElements(resEdges);
}
for(size_t i = 0 ; i < resEdges.size() ; ++i) {
_edgesLODVector.push_back(EdgeEntityLODUnit(resEdges[i], _edgesBBCache[resEdges[i]]));
}
}
}
}
}
GlCPULODCalculator::computeFor3DCamera(eye,transformMatrix,globalViewport,currentViewport);
}
<|endoftext|>
|
<commit_before>/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#if !defined(XALANLOCATOR_HEADER_GUARD_1357924680)
#define XALANLOCATOR_HEADER_GUARD_1357924680
// Base include file. Must be first.
#include <xalanc/PlatformSupport/PlatformSupportDefinitions.hpp>
#include <xercesc/sax/Locator.hpp>
XALAN_CPP_NAMESPACE_BEGIN
XALAN_USING_XERCES(Locator)
/**
* This class defines a base class for Locator derivations in Xalan. It was defined
* because Xerces made changes in their Locator class which caused turbulence.
*/
class XALAN_PLATFORMSUPPORT_EXPORT XalanLocator : public Locator
{
public:
typedef Locator ParentType;
XalanLocator() {}
virtual
~XalanLocator() {}
virtual const XMLCh*
getPublicId() const = 0;
virtual const XMLCh*
getSystemId() const = 0;
virtual XalanFileLoc
getLineNumber() const = 0;
virtual XalanFileLoc
getColumnNumber() const = 0;
static const XalanDOMChar*
getPublicId(
const Locator* theLocator,
const XalanDOMChar* theAlternateId = &s_dczero)
{
return theLocator == 0 ? theAlternateId : (theLocator->getPublicId() ?
theLocator->getPublicId() : theAlternateId);
}
static const XalanDOMChar*
getSystemId(
const Locator* theLocator,
const XalanDOMChar* theAlternateId = &s_dczero)
{
return theLocator == 0 ? theAlternateId : (theLocator->getSystemId() ?
theLocator->getPublicId() : theAlternateId);
}
static XalanFileLoc
getLineNumber(const ParentType* theLocator)
{
return theLocator == 0 ? getUnknownValue() : theLocator->getLineNumber();
}
static XalanFileLoc
getColumnNumber(const ParentType* theLocator)
{
return theLocator == 0 ? getUnknownValue() : theLocator->getColumnNumber();
}
static XalanFileLoc
getUnknownValue()
{
// The parser reports the maximum value of the XalanFileLoc
// type for an unknown value.
return ~static_cast<XalanFileLoc>(0);
}
static XalanFileLoc
getUnknownDisplayValue()
{
// The parser reports the maximum value of the XalanFileLoc
// type for an unknown value, but that is really non-sensical
// for display purposes, so we use 0 instead.
return static_cast<XalanFileLoc>(0);
}
static bool
isUnknownValue(XalanFileLoc theLocation)
{
return theLocation == getUnknownValue();
}
private:
// Not defined...
XalanLocator(const XalanLocator&);
XalanLocator&
operator=(const XalanLocator&);
const static XalanDOMChar s_dczero = 0;
};
XALAN_CPP_NAMESPACE_END
#endif // PREFIXRESOLVER_HEADER_GUARD_1357924680
<commit_msg>XALANC-733 Ensure that XalanLocator::getSystemId() and getPublicId() do not return NULL<commit_after>/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#if !defined(XALANLOCATOR_HEADER_GUARD_1357924680)
#define XALANLOCATOR_HEADER_GUARD_1357924680
// Base include file. Must be first.
#include <xalanc/PlatformSupport/PlatformSupportDefinitions.hpp>
#include <xercesc/sax/Locator.hpp>
XALAN_CPP_NAMESPACE_BEGIN
XALAN_USING_XERCES(Locator)
/**
* This class defines a base class for Locator derivations in Xalan. It was defined
* because Xerces made changes in their Locator class which caused turbulence.
*/
class XALAN_PLATFORMSUPPORT_EXPORT XalanLocator : public Locator
{
public:
typedef Locator ParentType;
XalanLocator() {}
virtual
~XalanLocator() {}
virtual const XMLCh*
getPublicId() const = 0;
virtual const XMLCh*
getSystemId() const = 0;
virtual XalanFileLoc
getLineNumber() const = 0;
virtual XalanFileLoc
getColumnNumber() const = 0;
/**
* Get the public identifier from a locator object.
* @param theLocator A locator object inherited from Xerces.
* @param theAlternateId A default name for a public identifier.
* @return a null terminated XalanDOMChar string.
*/
static const XalanDOMChar*
getPublicId(
const Locator* theLocator,
const XalanDOMChar* theAlternateId = getEmptyPtr())
{
return theLocator == 0 ? theAlternateId : (theLocator->getPublicId() ?
theLocator->getPublicId() : theAlternateId);
}
/**
* Get the system identifier from a locator object.
* @param theLocator A locator object inherited from Xerces.
* @param theAlternateId A default name for a public identifier.
* @return a null terminated XalanDOMChar string.
*/
static const XalanDOMChar*
getSystemId(
const Locator* theLocator,
const XalanDOMChar* theAlternateId = getEmptyPtr())
{
return theLocator == 0 ? theAlternateId : (theLocator->getSystemId() ?
theLocator->getPublicId() : theAlternateId);
}
/**
* Get the line number from a locator object.
*/
static XalanFileLoc
getLineNumber(const ParentType* theLocator)
{
return theLocator == 0 ? getUnknownValue() : theLocator->getLineNumber();
}
/**
* Get the column number from a locator object.
*/
static XalanFileLoc
getColumnNumber(const ParentType* theLocator)
{
return theLocator == 0 ? getUnknownValue() : theLocator->getColumnNumber();
}
static XalanFileLoc
getUnknownValue()
{
// The parser reports the maximum value of the XalanFileLoc
// type for an unknown value.
return ~static_cast<XalanFileLoc>(0);
}
static XalanFileLoc
getUnknownDisplayValue()
{
// The parser reports the maximum value of the XalanFileLoc
// type for an unknown value, but that is really non-sensical
// for display purposes, so we use 0 instead.
return static_cast<XalanFileLoc>(0);
}
static bool
isUnknownValue(XalanFileLoc theLocation)
{
return theLocation == getUnknownValue();
}
private:
// Not defined...
XalanLocator(const XalanLocator&);
XalanLocator&
operator=(const XalanLocator&);
/**
* Return static pointer to null XalanDOMChar.
* This is crafted to overcome issues with compilers/linkers that
* have problems initializing static integer members within a class.
*
* Replaces: static const int s_zero = 0;
* Reference: &s_zero;
*/
static const XalanDOMChar * getEmptyPtr()
{
static const XalanDOMChar theZero = 0;
static const XalanDOMChar * theEmpty = &theZero;
return theEmpty;
}
};
XALAN_CPP_NAMESPACE_END
#endif // PREFIXRESOLVER_HEADER_GUARD_1357924680
<|endoftext|>
|
<commit_before>/*
* Copyright (C) 2020 ScyllaDB
*/
/*
* This file is part of Scylla.
*
* Scylla is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Scylla is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Scylla. If not, see <http://www.gnu.org/licenses/>.
*/
#include "size_tiered_compaction_strategy.hh"
#include <boost/range/adaptor/transformed.hpp>
#include <boost/range/adaptors.hpp>
#include <boost/range/algorithm.hpp>
namespace sstables {
size_tiered_compaction_strategy_options::size_tiered_compaction_strategy_options(const std::map<sstring, sstring>& options) {
using namespace cql3::statements;
auto tmp_value = compaction_strategy_impl::get_value(options, MIN_SSTABLE_SIZE_KEY);
min_sstable_size = property_definitions::to_long(MIN_SSTABLE_SIZE_KEY, tmp_value, DEFAULT_MIN_SSTABLE_SIZE);
tmp_value = compaction_strategy_impl::get_value(options, BUCKET_LOW_KEY);
bucket_low = property_definitions::to_double(BUCKET_LOW_KEY, tmp_value, DEFAULT_BUCKET_LOW);
tmp_value = compaction_strategy_impl::get_value(options, BUCKET_HIGH_KEY);
bucket_high = property_definitions::to_double(BUCKET_HIGH_KEY, tmp_value, DEFAULT_BUCKET_HIGH);
tmp_value = compaction_strategy_impl::get_value(options, COLD_READS_TO_OMIT_KEY);
cold_reads_to_omit = property_definitions::to_double(COLD_READS_TO_OMIT_KEY, tmp_value, DEFAULT_COLD_READS_TO_OMIT);
}
size_tiered_compaction_strategy_options::size_tiered_compaction_strategy_options() {
min_sstable_size = DEFAULT_MIN_SSTABLE_SIZE;
bucket_low = DEFAULT_BUCKET_LOW;
bucket_high = DEFAULT_BUCKET_HIGH;
cold_reads_to_omit = DEFAULT_COLD_READS_TO_OMIT;
}
std::vector<std::pair<sstables::shared_sstable, uint64_t>>
size_tiered_compaction_strategy::create_sstable_and_length_pairs(const std::vector<sstables::shared_sstable>& sstables) {
std::vector<std::pair<sstables::shared_sstable, uint64_t>> sstable_length_pairs;
sstable_length_pairs.reserve(sstables.size());
for(auto& sstable : sstables) {
auto sstable_size = sstable->data_size();
assert(sstable_size != 0);
sstable_length_pairs.emplace_back(sstable, sstable_size);
}
return sstable_length_pairs;
}
std::vector<std::vector<sstables::shared_sstable>>
size_tiered_compaction_strategy::get_buckets(const std::vector<sstables::shared_sstable>& sstables, size_tiered_compaction_strategy_options options) {
// sstables sorted by size of its data file.
auto sorted_sstables = create_sstable_and_length_pairs(sstables);
std::sort(sorted_sstables.begin(), sorted_sstables.end(), [] (auto& i, auto& j) {
return i.second < j.second;
});
using bucket_type = std::vector<sstables::shared_sstable>;
std::vector<bucket_type> bucket_list;
std::vector<double> bucket_average_size_list;
for (auto& pair : sorted_sstables) {
size_t size = pair.second;
// look for a bucket containing similar-sized files:
// group in the same bucket if it's w/in (bucket_low, bucket_high) of the average for this bucket,
// or this file and the bucket are all considered "small" (less than `minSSTableSize`)
if (!bucket_list.empty()) {
auto& bucket_average_size = bucket_average_size_list.back();
if ((size > (bucket_average_size * options.bucket_low) && size < (bucket_average_size * options.bucket_high)) ||
(size < options.min_sstable_size && bucket_average_size < options.min_sstable_size)) {
auto& bucket = bucket_list.back();
auto total_size = bucket.size() * bucket_average_size;
auto new_average_size = (total_size + size) / (bucket.size() + 1);
auto smallest_sstable_in_bucket = bucket[0]->data_size();
// SSTables are added in increasing size order so the bucket's
// average might drift upwards.
// Don't let it drift too high, to a point where the smallest
// SSTable might fall out of range.
if (size < options.min_sstable_size || smallest_sstable_in_bucket > new_average_size * options.bucket_low) {
// FIXME: reindent
bucket.push_back(pair.first);
bucket_average_size = new_average_size;
continue;
}
}
}
// no similar bucket found; put it in a new one
bucket_type new_bucket = {pair.first};
bucket_list.push_back(std::move(new_bucket));
bucket_average_size_list.push_back(size);
}
return bucket_list;
}
std::vector<std::vector<sstables::shared_sstable>>
size_tiered_compaction_strategy::get_buckets(const std::vector<sstables::shared_sstable>& sstables) const {
return get_buckets(sstables, _options);
}
std::vector<sstables::shared_sstable>
size_tiered_compaction_strategy::most_interesting_bucket(std::vector<std::vector<sstables::shared_sstable>> buckets,
unsigned min_threshold, unsigned max_threshold)
{
std::vector<std::pair<std::vector<sstables::shared_sstable>, uint64_t>> pruned_buckets_and_hotness;
pruned_buckets_and_hotness.reserve(buckets.size());
// FIXME: add support to get hotness for each bucket.
for (auto& bucket : buckets) {
// FIXME: the coldest sstables will be trimmed to meet the threshold, so we must add support to this feature
// by converting SizeTieredCompactionStrategy::trimToThresholdWithHotness.
// By the time being, we will only compact buckets that meet the threshold.
bucket.resize(std::min(bucket.size(), size_t(max_threshold)));
if (is_bucket_interesting(bucket, min_threshold)) {
auto avg = avg_size(bucket);
pruned_buckets_and_hotness.push_back({ std::move(bucket), avg });
}
}
if (pruned_buckets_and_hotness.empty()) {
return std::vector<sstables::shared_sstable>();
}
// NOTE: Compacting smallest sstables first, located at the beginning of the sorted vector.
auto& min = *std::min_element(pruned_buckets_and_hotness.begin(), pruned_buckets_and_hotness.end(), [] (auto& i, auto& j) {
// FIXME: ignoring hotness by the time being.
return i.second < j.second;
});
auto hottest = std::move(min.first);
return hottest;
}
compaction_descriptor
size_tiered_compaction_strategy::get_sstables_for_compaction(column_family& cfs, std::vector<sstables::shared_sstable> candidates) {
// make local copies so they can't be changed out from under us mid-method
int min_threshold = cfs.min_compaction_threshold();
int max_threshold = cfs.schema()->max_compaction_threshold();
auto gc_before = gc_clock::now() - cfs.schema()->gc_grace_seconds();
// TODO: Add support to filter cold sstables (for reference: SizeTieredCompactionStrategy::filterColdSSTables).
auto buckets = get_buckets(candidates);
if (is_any_bucket_interesting(buckets, min_threshold)) {
std::vector<sstables::shared_sstable> most_interesting = most_interesting_bucket(std::move(buckets), min_threshold, max_threshold);
return sstables::compaction_descriptor(std::move(most_interesting), cfs.get_sstable_set(), service::get_local_compaction_priority());
}
// If we are not enforcing min_threshold explicitly, try any pair of SStables in the same tier.
if (!cfs.compaction_enforce_min_threshold() && is_any_bucket_interesting(buckets, 2)) {
std::vector<sstables::shared_sstable> most_interesting = most_interesting_bucket(std::move(buckets), 2, max_threshold);
return sstables::compaction_descriptor(std::move(most_interesting), cfs.get_sstable_set(), service::get_local_compaction_priority());
}
// if there is no sstable to compact in standard way, try compacting single sstable whose droppable tombstone
// ratio is greater than threshold.
// prefer oldest sstables from biggest size tiers because they will be easier to satisfy conditions for
// tombstone purge, i.e. less likely to shadow even older data.
for (auto&& sstables : buckets | boost::adaptors::reversed) {
// filter out sstables which droppable tombstone ratio isn't greater than the defined threshold.
auto e = boost::range::remove_if(sstables, [this, &gc_before] (const sstables::shared_sstable& sst) -> bool {
return !worth_dropping_tombstones(sst, gc_before);
});
sstables.erase(e, sstables.end());
if (sstables.empty()) {
continue;
}
// find oldest sstable from current tier
auto it = std::min_element(sstables.begin(), sstables.end(), [] (auto& i, auto& j) {
return i->get_stats_metadata().min_timestamp < j->get_stats_metadata().min_timestamp;
});
return sstables::compaction_descriptor({ *it }, cfs.get_sstable_set(), service::get_local_compaction_priority());
}
return sstables::compaction_descriptor();
}
int64_t size_tiered_compaction_strategy::estimated_pending_compactions(const std::vector<sstables::shared_sstable>& sstables,
int min_threshold, int max_threshold, size_tiered_compaction_strategy_options options) {
int64_t n = 0;
for (auto& bucket : get_buckets(sstables, options)) {
if (bucket.size() >= size_t(min_threshold)) {
n += std::ceil(double(bucket.size()) / max_threshold);
}
}
return n;
}
int64_t size_tiered_compaction_strategy::estimated_pending_compactions(column_family& cf) const {
int min_threshold = cf.min_compaction_threshold();
int max_threshold = cf.schema()->max_compaction_threshold();
std::vector<sstables::shared_sstable> sstables;
sstables.reserve(cf.sstables_count());
for (auto all_sstables = cf.get_sstables(); auto& entry : *all_sstables) {
sstables.push_back(entry);
}
return estimated_pending_compactions(sstables, min_threshold, max_threshold, _options);
}
std::vector<sstables::shared_sstable>
size_tiered_compaction_strategy::most_interesting_bucket(const std::vector<sstables::shared_sstable>& candidates,
int min_threshold, int max_threshold, size_tiered_compaction_strategy_options options) {
size_tiered_compaction_strategy cs(options);
auto buckets = cs.get_buckets(candidates);
std::vector<sstables::shared_sstable> most_interesting = cs.most_interesting_bucket(std::move(buckets),
min_threshold, max_threshold);
return most_interesting;
}
compaction_descriptor
size_tiered_compaction_strategy::get_reshaping_job(std::vector<shared_sstable> input, schema_ptr schema, const ::io_priority_class& iop, reshape_mode mode)
{
size_t offstrategy_threshold = std::max(schema->min_compaction_threshold(), 4);
size_t max_sstables = std::max(schema->max_compaction_threshold(), int(offstrategy_threshold));
if (mode == reshape_mode::relaxed) {
offstrategy_threshold = max_sstables;
}
for (auto& bucket : get_buckets(input)) {
if (bucket.size() >= offstrategy_threshold) {
// reshape job can work on #max_sstables sstables at once, so by reshaping sstables with the smallest tokens first,
// token contiguity is preserved iff sstables are disjoint.
if (bucket.size() > max_sstables) {
std::partial_sort(bucket.begin(), bucket.begin() + max_sstables, bucket.end(), [&schema](const sstables::shared_sstable& a, const sstables::shared_sstable& b) {
return a->get_first_decorated_key().tri_compare(*schema, b->get_first_decorated_key()) <= 0;
});
bucket.resize(max_sstables);
}
compaction_descriptor desc(std::move(bucket), std::optional<sstables::sstable_set>(), iop);
desc.options = compaction_options::make_reshape();
return desc;
}
}
return compaction_descriptor();
}
}
<commit_msg>compaction: size_tiered_compaction_strategy: get_buckets: fixup indentation<commit_after>/*
* Copyright (C) 2020 ScyllaDB
*/
/*
* This file is part of Scylla.
*
* Scylla is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Scylla is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Scylla. If not, see <http://www.gnu.org/licenses/>.
*/
#include "size_tiered_compaction_strategy.hh"
#include <boost/range/adaptor/transformed.hpp>
#include <boost/range/adaptors.hpp>
#include <boost/range/algorithm.hpp>
namespace sstables {
size_tiered_compaction_strategy_options::size_tiered_compaction_strategy_options(const std::map<sstring, sstring>& options) {
using namespace cql3::statements;
auto tmp_value = compaction_strategy_impl::get_value(options, MIN_SSTABLE_SIZE_KEY);
min_sstable_size = property_definitions::to_long(MIN_SSTABLE_SIZE_KEY, tmp_value, DEFAULT_MIN_SSTABLE_SIZE);
tmp_value = compaction_strategy_impl::get_value(options, BUCKET_LOW_KEY);
bucket_low = property_definitions::to_double(BUCKET_LOW_KEY, tmp_value, DEFAULT_BUCKET_LOW);
tmp_value = compaction_strategy_impl::get_value(options, BUCKET_HIGH_KEY);
bucket_high = property_definitions::to_double(BUCKET_HIGH_KEY, tmp_value, DEFAULT_BUCKET_HIGH);
tmp_value = compaction_strategy_impl::get_value(options, COLD_READS_TO_OMIT_KEY);
cold_reads_to_omit = property_definitions::to_double(COLD_READS_TO_OMIT_KEY, tmp_value, DEFAULT_COLD_READS_TO_OMIT);
}
size_tiered_compaction_strategy_options::size_tiered_compaction_strategy_options() {
min_sstable_size = DEFAULT_MIN_SSTABLE_SIZE;
bucket_low = DEFAULT_BUCKET_LOW;
bucket_high = DEFAULT_BUCKET_HIGH;
cold_reads_to_omit = DEFAULT_COLD_READS_TO_OMIT;
}
std::vector<std::pair<sstables::shared_sstable, uint64_t>>
size_tiered_compaction_strategy::create_sstable_and_length_pairs(const std::vector<sstables::shared_sstable>& sstables) {
std::vector<std::pair<sstables::shared_sstable, uint64_t>> sstable_length_pairs;
sstable_length_pairs.reserve(sstables.size());
for(auto& sstable : sstables) {
auto sstable_size = sstable->data_size();
assert(sstable_size != 0);
sstable_length_pairs.emplace_back(sstable, sstable_size);
}
return sstable_length_pairs;
}
std::vector<std::vector<sstables::shared_sstable>>
size_tiered_compaction_strategy::get_buckets(const std::vector<sstables::shared_sstable>& sstables, size_tiered_compaction_strategy_options options) {
// sstables sorted by size of its data file.
auto sorted_sstables = create_sstable_and_length_pairs(sstables);
std::sort(sorted_sstables.begin(), sorted_sstables.end(), [] (auto& i, auto& j) {
return i.second < j.second;
});
using bucket_type = std::vector<sstables::shared_sstable>;
std::vector<bucket_type> bucket_list;
std::vector<double> bucket_average_size_list;
for (auto& pair : sorted_sstables) {
size_t size = pair.second;
// look for a bucket containing similar-sized files:
// group in the same bucket if it's w/in (bucket_low, bucket_high) of the average for this bucket,
// or this file and the bucket are all considered "small" (less than `minSSTableSize`)
if (!bucket_list.empty()) {
auto& bucket_average_size = bucket_average_size_list.back();
if ((size > (bucket_average_size * options.bucket_low) && size < (bucket_average_size * options.bucket_high)) ||
(size < options.min_sstable_size && bucket_average_size < options.min_sstable_size)) {
auto& bucket = bucket_list.back();
auto total_size = bucket.size() * bucket_average_size;
auto new_average_size = (total_size + size) / (bucket.size() + 1);
auto smallest_sstable_in_bucket = bucket[0]->data_size();
// SSTables are added in increasing size order so the bucket's
// average might drift upwards.
// Don't let it drift too high, to a point where the smallest
// SSTable might fall out of range.
if (size < options.min_sstable_size || smallest_sstable_in_bucket > new_average_size * options.bucket_low) {
bucket.push_back(pair.first);
bucket_average_size = new_average_size;
continue;
}
}
}
// no similar bucket found; put it in a new one
bucket_type new_bucket = {pair.first};
bucket_list.push_back(std::move(new_bucket));
bucket_average_size_list.push_back(size);
}
return bucket_list;
}
std::vector<std::vector<sstables::shared_sstable>>
size_tiered_compaction_strategy::get_buckets(const std::vector<sstables::shared_sstable>& sstables) const {
return get_buckets(sstables, _options);
}
std::vector<sstables::shared_sstable>
size_tiered_compaction_strategy::most_interesting_bucket(std::vector<std::vector<sstables::shared_sstable>> buckets,
unsigned min_threshold, unsigned max_threshold)
{
std::vector<std::pair<std::vector<sstables::shared_sstable>, uint64_t>> pruned_buckets_and_hotness;
pruned_buckets_and_hotness.reserve(buckets.size());
// FIXME: add support to get hotness for each bucket.
for (auto& bucket : buckets) {
// FIXME: the coldest sstables will be trimmed to meet the threshold, so we must add support to this feature
// by converting SizeTieredCompactionStrategy::trimToThresholdWithHotness.
// By the time being, we will only compact buckets that meet the threshold.
bucket.resize(std::min(bucket.size(), size_t(max_threshold)));
if (is_bucket_interesting(bucket, min_threshold)) {
auto avg = avg_size(bucket);
pruned_buckets_and_hotness.push_back({ std::move(bucket), avg });
}
}
if (pruned_buckets_and_hotness.empty()) {
return std::vector<sstables::shared_sstable>();
}
// NOTE: Compacting smallest sstables first, located at the beginning of the sorted vector.
auto& min = *std::min_element(pruned_buckets_and_hotness.begin(), pruned_buckets_and_hotness.end(), [] (auto& i, auto& j) {
// FIXME: ignoring hotness by the time being.
return i.second < j.second;
});
auto hottest = std::move(min.first);
return hottest;
}
compaction_descriptor
size_tiered_compaction_strategy::get_sstables_for_compaction(column_family& cfs, std::vector<sstables::shared_sstable> candidates) {
// make local copies so they can't be changed out from under us mid-method
int min_threshold = cfs.min_compaction_threshold();
int max_threshold = cfs.schema()->max_compaction_threshold();
auto gc_before = gc_clock::now() - cfs.schema()->gc_grace_seconds();
// TODO: Add support to filter cold sstables (for reference: SizeTieredCompactionStrategy::filterColdSSTables).
auto buckets = get_buckets(candidates);
if (is_any_bucket_interesting(buckets, min_threshold)) {
std::vector<sstables::shared_sstable> most_interesting = most_interesting_bucket(std::move(buckets), min_threshold, max_threshold);
return sstables::compaction_descriptor(std::move(most_interesting), cfs.get_sstable_set(), service::get_local_compaction_priority());
}
// If we are not enforcing min_threshold explicitly, try any pair of SStables in the same tier.
if (!cfs.compaction_enforce_min_threshold() && is_any_bucket_interesting(buckets, 2)) {
std::vector<sstables::shared_sstable> most_interesting = most_interesting_bucket(std::move(buckets), 2, max_threshold);
return sstables::compaction_descriptor(std::move(most_interesting), cfs.get_sstable_set(), service::get_local_compaction_priority());
}
// if there is no sstable to compact in standard way, try compacting single sstable whose droppable tombstone
// ratio is greater than threshold.
// prefer oldest sstables from biggest size tiers because they will be easier to satisfy conditions for
// tombstone purge, i.e. less likely to shadow even older data.
for (auto&& sstables : buckets | boost::adaptors::reversed) {
// filter out sstables which droppable tombstone ratio isn't greater than the defined threshold.
auto e = boost::range::remove_if(sstables, [this, &gc_before] (const sstables::shared_sstable& sst) -> bool {
return !worth_dropping_tombstones(sst, gc_before);
});
sstables.erase(e, sstables.end());
if (sstables.empty()) {
continue;
}
// find oldest sstable from current tier
auto it = std::min_element(sstables.begin(), sstables.end(), [] (auto& i, auto& j) {
return i->get_stats_metadata().min_timestamp < j->get_stats_metadata().min_timestamp;
});
return sstables::compaction_descriptor({ *it }, cfs.get_sstable_set(), service::get_local_compaction_priority());
}
return sstables::compaction_descriptor();
}
int64_t size_tiered_compaction_strategy::estimated_pending_compactions(const std::vector<sstables::shared_sstable>& sstables,
int min_threshold, int max_threshold, size_tiered_compaction_strategy_options options) {
int64_t n = 0;
for (auto& bucket : get_buckets(sstables, options)) {
if (bucket.size() >= size_t(min_threshold)) {
n += std::ceil(double(bucket.size()) / max_threshold);
}
}
return n;
}
int64_t size_tiered_compaction_strategy::estimated_pending_compactions(column_family& cf) const {
int min_threshold = cf.min_compaction_threshold();
int max_threshold = cf.schema()->max_compaction_threshold();
std::vector<sstables::shared_sstable> sstables;
sstables.reserve(cf.sstables_count());
for (auto all_sstables = cf.get_sstables(); auto& entry : *all_sstables) {
sstables.push_back(entry);
}
return estimated_pending_compactions(sstables, min_threshold, max_threshold, _options);
}
std::vector<sstables::shared_sstable>
size_tiered_compaction_strategy::most_interesting_bucket(const std::vector<sstables::shared_sstable>& candidates,
int min_threshold, int max_threshold, size_tiered_compaction_strategy_options options) {
size_tiered_compaction_strategy cs(options);
auto buckets = cs.get_buckets(candidates);
std::vector<sstables::shared_sstable> most_interesting = cs.most_interesting_bucket(std::move(buckets),
min_threshold, max_threshold);
return most_interesting;
}
compaction_descriptor
size_tiered_compaction_strategy::get_reshaping_job(std::vector<shared_sstable> input, schema_ptr schema, const ::io_priority_class& iop, reshape_mode mode)
{
size_t offstrategy_threshold = std::max(schema->min_compaction_threshold(), 4);
size_t max_sstables = std::max(schema->max_compaction_threshold(), int(offstrategy_threshold));
if (mode == reshape_mode::relaxed) {
offstrategy_threshold = max_sstables;
}
for (auto& bucket : get_buckets(input)) {
if (bucket.size() >= offstrategy_threshold) {
// reshape job can work on #max_sstables sstables at once, so by reshaping sstables with the smallest tokens first,
// token contiguity is preserved iff sstables are disjoint.
if (bucket.size() > max_sstables) {
std::partial_sort(bucket.begin(), bucket.begin() + max_sstables, bucket.end(), [&schema](const sstables::shared_sstable& a, const sstables::shared_sstable& b) {
return a->get_first_decorated_key().tri_compare(*schema, b->get_first_decorated_key()) <= 0;
});
bucket.resize(max_sstables);
}
compaction_descriptor desc(std::move(bucket), std::optional<sstables::sstable_set>(), iop);
desc.options = compaction_options::make_reshape();
return desc;
}
}
return compaction_descriptor();
}
}
<|endoftext|>
|
<commit_before>#ifndef STAN_MATH_REV_CORE_AUTODIFFSTACKSTORAGE_HPP
#define STAN_MATH_REV_CORE_AUTODIFFSTACKSTORAGE_HPP
#include <stan/math/memory/stack_alloc.hpp>
#include <vector>
namespace stan {
namespace math {
/**
* Provides a thread_local singleton if needed. Read warnings below!
* For performance reasons the singleton is a global static for the
* case of no threading which is returned by a function. This design
* should allow the compiler to apply necessary inlining to get
* maximal performance. However, this design suffers from "the static
* init order fiasco"[0]. Anywhere this is used, we must be
* absolutely positive that it doesn't matter when the singleton will
* get initialized relative to other static variables. In exchange,
* we get a more performant singleton pattern for the non-threading
* case. In the threading case we use the defacto standard C++11
* singleton pattern relying on a function wrapping a static local
* variable. This standard pattern is expected to be well supported
* by the major compilers (as its standard), but it does incur some
* performance penalty. There has been some discussion on this; see
* [1] and [2] and the discussions those PRs link to as well.
*
* These are thread_local only if the user asks for it with
* -DSTAN_THREADS. This is primarily because Apple clang compilers
* before 2016 don't support thread_local and the additional
* performance cost. We have proposed removing support for those[3],
* and at that time we should evaluate the performance of a switch to
* thread_local. If there is no loss in performance, we can remove
* this ifdef.
*
* [0] https://isocpp.org/wiki/faq/ctors#static-init-order
* [1] https://github.com/stan-dev/math/pull/840
* [2] https://github.com/stan-dev/math/pull/826
* [3]
* http://discourse.mc-stan.org/t/potentially-dropping-support-for-older-versions-of-apples-version-of-clang/3780/
*/
template <typename ChainableT, typename ChainableAllocT>
struct AutodiffStackSingleton {
typedef AutodiffStackSingleton<ChainableT, ChainableAllocT>
AutodiffStackSingleton_t;
struct AutodiffStackStorage {
AutodiffStackStorage &operator=(const AutodiffStackStorage &) = delete;
std::vector<ChainableT *> var_stack_;
std::vector<ChainableT *> var_nochain_stack_;
std::vector<ChainableAllocT *> var_alloc_stack_;
stack_alloc memalloc_;
// nested positions
std::vector<size_t> nested_var_stack_sizes_;
std::vector<size_t> nested_var_nochain_stack_sizes_;
std::vector<size_t> nested_var_alloc_stack_starts_;
};
AutodiffStackSingleton() = delete;
explicit AutodiffStackSingleton(AutodiffStackSingleton_t const &) = delete;
AutodiffStackSingleton &operator=(const AutodiffStackSingleton_t &) = delete;
static inline AutodiffStackStorage &instance() {
#ifdef STAN_THREADS
thread_local static AutodiffStackStorage instance_;
return instance_;
#else
return *instance_;
#endif
}
#ifndef STAN_THREADS
private:
static AutodiffStackStorage* instance_;
#endif
};
#ifndef STAN_THREADS
template <typename ChainableT, typename ChainableAllocT>
typename AutodiffStackSingleton<ChainableT,
ChainableAllocT>::AutodiffStackStorage*
AutodiffStackSingleton<ChainableT, ChainableAllocT>::instance_
= new typename AutodiffStackSingleton<ChainableT,
ChainableAllocT>::AutodiffStackStorage;
#endif
} // namespace math
} // namespace stan
#endif
<commit_msg>[Jenkins] auto-formatting by clang-format version 5.0.2-svn328729-1~exp1~20180509124008.99 (branches/release_50)<commit_after>#ifndef STAN_MATH_REV_CORE_AUTODIFFSTACKSTORAGE_HPP
#define STAN_MATH_REV_CORE_AUTODIFFSTACKSTORAGE_HPP
#include <stan/math/memory/stack_alloc.hpp>
#include <vector>
namespace stan {
namespace math {
/**
* Provides a thread_local singleton if needed. Read warnings below!
* For performance reasons the singleton is a global static for the
* case of no threading which is returned by a function. This design
* should allow the compiler to apply necessary inlining to get
* maximal performance. However, this design suffers from "the static
* init order fiasco"[0]. Anywhere this is used, we must be
* absolutely positive that it doesn't matter when the singleton will
* get initialized relative to other static variables. In exchange,
* we get a more performant singleton pattern for the non-threading
* case. In the threading case we use the defacto standard C++11
* singleton pattern relying on a function wrapping a static local
* variable. This standard pattern is expected to be well supported
* by the major compilers (as its standard), but it does incur some
* performance penalty. There has been some discussion on this; see
* [1] and [2] and the discussions those PRs link to as well.
*
* These are thread_local only if the user asks for it with
* -DSTAN_THREADS. This is primarily because Apple clang compilers
* before 2016 don't support thread_local and the additional
* performance cost. We have proposed removing support for those[3],
* and at that time we should evaluate the performance of a switch to
* thread_local. If there is no loss in performance, we can remove
* this ifdef.
*
* [0] https://isocpp.org/wiki/faq/ctors#static-init-order
* [1] https://github.com/stan-dev/math/pull/840
* [2] https://github.com/stan-dev/math/pull/826
* [3]
* http://discourse.mc-stan.org/t/potentially-dropping-support-for-older-versions-of-apples-version-of-clang/3780/
*/
template <typename ChainableT, typename ChainableAllocT>
struct AutodiffStackSingleton {
typedef AutodiffStackSingleton<ChainableT, ChainableAllocT>
AutodiffStackSingleton_t;
struct AutodiffStackStorage {
AutodiffStackStorage &operator=(const AutodiffStackStorage &) = delete;
std::vector<ChainableT *> var_stack_;
std::vector<ChainableT *> var_nochain_stack_;
std::vector<ChainableAllocT *> var_alloc_stack_;
stack_alloc memalloc_;
// nested positions
std::vector<size_t> nested_var_stack_sizes_;
std::vector<size_t> nested_var_nochain_stack_sizes_;
std::vector<size_t> nested_var_alloc_stack_starts_;
};
AutodiffStackSingleton() = delete;
explicit AutodiffStackSingleton(AutodiffStackSingleton_t const &) = delete;
AutodiffStackSingleton &operator=(const AutodiffStackSingleton_t &) = delete;
static inline AutodiffStackStorage &instance() {
#ifdef STAN_THREADS
thread_local static AutodiffStackStorage instance_;
return instance_;
#else
return *instance_;
#endif
}
#ifndef STAN_THREADS
private:
static AutodiffStackStorage *instance_;
#endif
};
#ifndef STAN_THREADS
template <typename ChainableT, typename ChainableAllocT>
typename AutodiffStackSingleton<ChainableT,
ChainableAllocT>::AutodiffStackStorage
*AutodiffStackSingleton<ChainableT, ChainableAllocT>::instance_
= new
typename AutodiffStackSingleton<ChainableT,
ChainableAllocT>::AutodiffStackStorage;
#endif
} // namespace math
} // namespace stan
#endif
<|endoftext|>
|
<commit_before>#include "Elk.h"
#include "MooseFactory.h"
// misc
#include "BodyForceRZ.h"
#include "CoefDiffusion.h"
#include "Convection.h"
#include "InternalVolume.h"
#include "InternalVolumeRZ.h"
#include "NeumannRZ.h"
// heat_conduction
#include "HeatConduction.h"
#include "HeatConductionRZ.h"
#include "HeatConductionImplicitEuler.h"
#include "HeatConductionImplicitEulerRZ.h"
#include "HeatConductionMaterial.h"
// navier_stokes
#include "MassInviscidFlux.h"
#include "MomentumInviscidFlux.h"
#include "MomentumViscousFlux.h"
#include "EnergyInviscidFlux.h"
#include "EnergyViscousFlux.h"
#include "GravityPower.h"
#include "GravityForce.h"
#include "PressureNeumannBC.h"
#include "ThermalBC.h"
#include "VelocityAux.h"
// linear_elasticity
#include "SolidMechX.h"
#include "SolidMechY.h"
#include "SolidMechZ.h"
#include "SolidMechImplicitEuler.h"
#include "SolidMechTempCoupleX.h"
#include "SolidMechTempCoupleY.h"
#include "SolidMechTempCoupleZ.h"
// solid_mechanics
#include "CLSHPlasticMaterial.h"
#include "Elastic.h"
#include "Gravity.h"
#include "GravityRZ.h"
#include "LinearIsotropicMaterial.h"
#include "LinearStrainHardening.h"
#include "LSHPlasticMaterial.h"
#include "LSHPlasticMaterialRZ.h"
#include "MaterialTensorAux.h"
#include "PLC_LSH.h"
#include "PowerLawCreepMaterial.h"
#include "PowerLawCreep.h"
#include "PlenumPressure.h"
#include "PlenumPressureRZ.h"
#include "Pressure.h"
#include "PressureRZ.h"
#include "PLSHPlasticMaterial.h"
#include "ElasticEnergyAux.h"
#include "StressDivergence.h"
#include "StressDivergenceRZ.h"
// phase_field
#include "AC.h"
#include "ACBulk.h"
#include "ACInterface.h"
#include "CHBulk.h"
#include "CHSplit1.h"
#include "CHSplit2LaPl.h"
#include "CHSplit2ChemPot.h"
#include "CHInterface.h"
#include "CrossIC.h"
#include "SmoothCircleIC.h"
#include "RndSmoothCircleIC.h"
#include "RndBoundingBoxIC.h"
// contact
#include "ContactMaster.h"
#include "SlaveConstraint.h"
void
Elk::registerObjects()
{
// misc
registerKernel(BodyForceRZ);
registerKernel(CoefDiffusion);
registerKernel(Convection);
registerPostprocessor(InternalVolume);
registerPostprocessor(InternalVolumeRZ);
registerBoundaryCondition(NeumannRZ);
// heat_conduction
registerKernel(HeatConduction);
registerKernel(HeatConductionRZ);
registerKernel(HeatConductionImplicitEuler);
registerKernel(HeatConductionImplicitEulerRZ);
registerNamedMaterial(HeatConductionMaterial, "HeatConduction");
// navier_stokes
registerKernel(MassInviscidFlux);
registerKernel(MomentumInviscidFlux);
registerKernel(MomentumViscousFlux);
registerKernel(EnergyInviscidFlux);
registerKernel(EnergyViscousFlux);
registerKernel(GravityPower);
registerKernel(GravityForce);
registerBoundaryCondition(PressureNeumannBC);
registerBoundaryCondition(ThermalBC);
registerAux(VelocityAux);
// linear_elasticity
registerKernel(SolidMechX);
registerKernel(SolidMechY);
registerKernel(SolidMechZ);
registerKernel(SolidMechImplicitEuler);
registerKernel(SolidMechTempCoupleX);
registerKernel(SolidMechTempCoupleY);
registerKernel(SolidMechTempCoupleZ);
// solid_mechanics
registerMaterial(CLSHPlasticMaterial);
registerMaterial(Elastic);
registerKernel(Gravity);
registerKernel(GravityRZ);
registerNamedMaterial(LinearIsotropicMaterial, "LinearIsotropic");
registerNamedMaterial(LinearIsotropicMaterialRZ, "LinearIsotropicRZ");
registerMaterial(LinearStrainHardening);
registerMaterial(LSHPlasticMaterial);
registerMaterial(LSHPlasticMaterialRZ);
registerAux(MaterialTensorAux);
registerMaterial(PLC_LSH);
registerMaterial(PLSHPlasticMaterial);
registerMaterial(PowerLawCreepMaterial);
registerMaterial(PowerLawCreep);
registerBoundaryCondition(PlenumPressure);
registerBoundaryCondition(PlenumPressureRZ);
registerBoundaryCondition(Pressure);
registerBoundaryCondition(PressureRZ);
registerAux(ElasticEnergyAux);
registerKernel(StressDivergence);
registerKernel(StressDivergenceRZ);
// phase_field
registerKernel(AC);
registerKernel(ACBulk);
registerKernel(ACInterface);
registerKernel(CHBulk);
registerKernel(CHSplit1);
registerKernel(CHSplit2LaPl);
registerKernel(CHSplit2ChemPot);
registerKernel(CHInterface);
registerInitialCondition(CrossIC);
registerInitialCondition(SmoothCircleIC);
registerInitialCondition(RndSmoothCircleIC);
registerInitialCondition(RndBoundingBoxIC);
// contact
registerDiracKernel(ContactMaster);
registerDiracKernel(SlaveConstraint);
}
<commit_msg>New test for anisotropic elasticity<commit_after>#include "Elk.h"
#include "MooseFactory.h"
// misc
#include "BodyForceRZ.h"
#include "CoefDiffusion.h"
#include "Convection.h"
#include "InternalVolume.h"
#include "InternalVolumeRZ.h"
#include "NeumannRZ.h"
// heat_conduction
#include "HeatConduction.h"
#include "HeatConductionRZ.h"
#include "HeatConductionImplicitEuler.h"
#include "HeatConductionImplicitEulerRZ.h"
#include "HeatConductionMaterial.h"
// navier_stokes
#include "MassInviscidFlux.h"
#include "MomentumInviscidFlux.h"
#include "MomentumViscousFlux.h"
#include "EnergyInviscidFlux.h"
#include "EnergyViscousFlux.h"
#include "GravityPower.h"
#include "GravityForce.h"
#include "PressureNeumannBC.h"
#include "ThermalBC.h"
#include "VelocityAux.h"
// linear_elasticity
#include "SolidMechX.h"
#include "SolidMechY.h"
#include "SolidMechZ.h"
#include "SolidMechImplicitEuler.h"
#include "SolidMechTempCoupleX.h"
#include "SolidMechTempCoupleY.h"
#include "SolidMechTempCoupleZ.h"
// solid_mechanics
#include "CLSHPlasticMaterial.h"
#include "Elastic.h"
#include "Gravity.h"
#include "GravityRZ.h"
#include "LinearAnisotropicMaterial.h"
#include "LinearIsotropicMaterial.h"
#include "LinearIsotropicMaterialRZ.h"
#include "LinearStrainHardening.h"
#include "LSHPlasticMaterial.h"
#include "LSHPlasticMaterialRZ.h"
#include "MaterialTensorAux.h"
#include "PLC_LSH.h"
#include "PowerLawCreepMaterial.h"
#include "PowerLawCreep.h"
#include "PlenumPressure.h"
#include "PlenumPressureRZ.h"
#include "Pressure.h"
#include "PressureRZ.h"
#include "PLSHPlasticMaterial.h"
#include "ElasticEnergyAux.h"
#include "StressDivergence.h"
#include "StressDivergenceRZ.h"
// phase_field
#include "AC.h"
#include "ACBulk.h"
#include "ACInterface.h"
#include "CHBulk.h"
#include "CHSplit1.h"
#include "CHSplit2LaPl.h"
#include "CHSplit2ChemPot.h"
#include "CHInterface.h"
#include "CrossIC.h"
#include "SmoothCircleIC.h"
#include "RndSmoothCircleIC.h"
#include "RndBoundingBoxIC.h"
// contact
#include "ContactMaster.h"
#include "SlaveConstraint.h"
void
Elk::registerObjects()
{
// misc
registerKernel(BodyForceRZ);
registerKernel(CoefDiffusion);
registerKernel(Convection);
registerPostprocessor(InternalVolume);
registerPostprocessor(InternalVolumeRZ);
registerBoundaryCondition(NeumannRZ);
// heat_conduction
registerKernel(HeatConduction);
registerKernel(HeatConductionRZ);
registerKernel(HeatConductionImplicitEuler);
registerKernel(HeatConductionImplicitEulerRZ);
registerNamedMaterial(HeatConductionMaterial, "HeatConduction");
// navier_stokes
registerKernel(MassInviscidFlux);
registerKernel(MomentumInviscidFlux);
registerKernel(MomentumViscousFlux);
registerKernel(EnergyInviscidFlux);
registerKernel(EnergyViscousFlux);
registerKernel(GravityPower);
registerKernel(GravityForce);
registerBoundaryCondition(PressureNeumannBC);
registerBoundaryCondition(ThermalBC);
registerAux(VelocityAux);
// linear_elasticity
registerKernel(SolidMechX);
registerKernel(SolidMechY);
registerKernel(SolidMechZ);
registerKernel(SolidMechImplicitEuler);
registerKernel(SolidMechTempCoupleX);
registerKernel(SolidMechTempCoupleY);
registerKernel(SolidMechTempCoupleZ);
// solid_mechanics
registerMaterial(CLSHPlasticMaterial);
registerMaterial(Elastic);
registerKernel(Gravity);
registerKernel(GravityRZ);
registerNamedMaterial(LinearAnisotropicMaterial, "LinearAnisotropic");
registerNamedMaterial(LinearIsotropicMaterial, "LinearIsotropic");
registerNamedMaterial(LinearIsotropicMaterialRZ, "LinearIsotropicRZ");
registerMaterial(LinearStrainHardening);
registerMaterial(LSHPlasticMaterial);
registerMaterial(LSHPlasticMaterialRZ);
registerAux(MaterialTensorAux);
registerMaterial(PLC_LSH);
registerMaterial(PLSHPlasticMaterial);
registerMaterial(PowerLawCreepMaterial);
registerMaterial(PowerLawCreep);
registerBoundaryCondition(PlenumPressure);
registerBoundaryCondition(PlenumPressureRZ);
registerBoundaryCondition(Pressure);
registerBoundaryCondition(PressureRZ);
registerAux(ElasticEnergyAux);
registerKernel(StressDivergence);
registerKernel(StressDivergenceRZ);
// phase_field
registerKernel(AC);
registerKernel(ACBulk);
registerKernel(ACInterface);
registerKernel(CHBulk);
registerKernel(CHSplit1);
registerKernel(CHSplit2LaPl);
registerKernel(CHSplit2ChemPot);
registerKernel(CHInterface);
registerInitialCondition(CrossIC);
registerInitialCondition(SmoothCircleIC);
registerInitialCondition(RndSmoothCircleIC);
registerInitialCondition(RndBoundingBoxIC);
// contact
registerDiracKernel(ContactMaster);
registerDiracKernel(SlaveConstraint);
}
<|endoftext|>
|
<commit_before>//-----------------------------------------------------------------------bl-
//--------------------------------------------------------------------------
//
// GRINS - General Reacting Incompressible Navier-Stokes
//
// Copyright (C) 2014-2015 Paul T. Bauman, Roy H. Stogner
// Copyright (C) 2010-2013 The PECOS Development Team
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the Version 2.1 GNU Lesser General
// Public License as published by the Free Software Foundation.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc. 51 Franklin Street, Fifth Floor,
// Boston, MA 02110-1301 USA
//
//-----------------------------------------------------------------------el-
#include "grins_config.h"
#include <iostream>
// GRINS
#include "grins/simulation.h"
#include "grins/simulation_builder.h"
// GRVY
#ifdef HAVE_GRVY
#include "grvy.h"
#endif
// libMesh
#include "libmesh/parallel.h"
#include "libmesh/exact_solution.h"
// Function for getting initial temperature field
libMesh::Real
initial_values( const libMesh::Point& p, const libMesh::Parameters ¶ms,
const std::string& system_name, const std::string& unknown_name );
int run( int argc, char* argv[], const GetPot& input );
int main(int argc, char* argv[])
{
#ifdef USE_GRVY_TIMERS
GRVY::GRVY_Timer_Class grvy_timer;
grvy_timer.Init("GRINS Timer");
#endif
// Check command line count.
if( argc < 3 )
{
// TODO: Need more consistent error handling.
std::cerr << "Error: Must specify libMesh input file and exact solution file." << std::endl;
exit(1); // TODO: something more sophisticated for parallel runs?
}
// libMesh input file should be first argument
std::string libMesh_input_filename = argv[1];
// Create our GetPot object.
GetPot libMesh_inputfile( libMesh_input_filename );
int return_flag = 0;
std::string chem_lib = libMesh_inputfile("Physics/ReactingLowMachNavierStokes/thermochemistry_library", "DIE!");
if( chem_lib == std::string("cantera") )
{
#ifdef GRINS_HAVE_CANTERA
return_flag = run(argc,argv,libMesh_inputfile);
#else
return_flag = 77;
#endif
}
else if( chem_lib == std::string("antioch") )
{
#ifdef GRINS_HAVE_ANTIOCH
return_flag = run(argc,argv,libMesh_inputfile);
#else
return_flag = 77;
#endif
}
else
{
return_flag = 1;
}
return return_flag;
}
int run( int argc, char* argv[], const GetPot& input )
{
#ifdef USE_GRVY_TIMERS
grvy_timer.BeginTimer("Initialize Solver");
#endif
// Initialize libMesh library.
libMesh::LibMeshInit libmesh_init(argc, argv);
GRINS::SimulationBuilder sim_builder;
GRINS::Simulation grins( input,
sim_builder,
libmesh_init.comm() );
//FIXME: We need to move this to within the Simulation object somehow...
std::string restart_file = input( "restart-options/restart_file", "none" );
if( restart_file == "none" )
{
// Asssign initial temperature value
std::string system_name = input( "screen-options/system_name", "GRINS" );
GRINS::SharedPtr<libMesh::EquationSystems> es = grins.get_equation_system();
const libMesh::System& system = es->get_system(system_name);
libMesh::Parameters ¶ms = es->parameters;
libMesh::Real& w_N2 = params.set<libMesh::Real>( "w_N2" );
w_N2 = input( "Physics/ReactingLowMachNavierStokes/bound_species_3", 0.0, 0 );
libMesh::Real& w_N = params.set<libMesh::Real>( "w_N" );
w_N = input( "Physics/ReactingLowMachNavierStokes/bound_species_3", 0.0, 1 );
system.project_solution( initial_values, NULL, params );
}
#ifdef USE_GRVY_TIMERS
grvy_timer.EndTimer("Initialize Solver");
// Attach GRVY timer to solver
grins.attach_grvy_timer( &grvy_timer );
#endif
grins.run();
#ifdef USE_GRVY_TIMERS
grvy_timer.Finalize();
if( Parallel::Communicator_World.rank() == 0 ) grvy_timer.Summarize();
#endif
// Get equation systems to create ExactSolution object
GRINS::SharedPtr<libMesh::EquationSystems>
es = grins.get_equation_system();
//es->write("foobar.xdr");
// Create Exact solution object and attach exact solution quantities
libMesh::ExactSolution exact_sol(*es);
libMesh::EquationSystems es_ref( es->get_mesh() );
// Filename of file where comparison solution is stashed
std::string solution_file = std::string(argv[2]);
es_ref.read( solution_file );
exact_sol.attach_reference_solution( &es_ref );
// Compute error and get it in various norms
exact_sol.compute_error("GRINS", "u");
exact_sol.compute_error("GRINS", "v");
if( (es->get_mesh()).mesh_dimension() == 3 )
exact_sol.compute_error("GRINS", "w");
exact_sol.compute_error("GRINS", "p");
exact_sol.compute_error("GRINS", "T");
exact_sol.compute_error("GRINS", "w_N2");
exact_sol.compute_error("GRINS", "w_N");
double u_l2error = exact_sol.l2_error("GRINS", "u");
double u_h1error = exact_sol.h1_error("GRINS", "u");
double v_l2error = exact_sol.l2_error("GRINS", "v");
double v_h1error = exact_sol.h1_error("GRINS", "v");
double p_l2error = exact_sol.l2_error("GRINS", "p");
double p_h1error = exact_sol.h1_error("GRINS", "p");
double T_l2error = exact_sol.l2_error("GRINS", "T");
double T_h1error = exact_sol.h1_error("GRINS", "T");
double wN_l2error = exact_sol.l2_error("GRINS", "w_N");
double wN_h1error = exact_sol.h1_error("GRINS", "w_N");
double wN2_l2error = exact_sol.l2_error("GRINS", "w_N2");
double wN2_h1error = exact_sol.h1_error("GRINS", "w_N2");
double w_l2error = 0.0,
w_h1error = 0.0;
if( (es->get_mesh()).mesh_dimension() == 3 )
{
w_l2error = exact_sol.l2_error("GRINS", "w");
w_h1error = exact_sol.h1_error("GRINS", "w");
}
int return_flag = 0;
double tol = 1.5e-8;
if( u_l2error > tol || u_h1error > tol ||
v_l2error > tol || v_h1error > tol ||
w_l2error > tol || w_h1error > tol ||
p_l2error > tol || p_h1error > tol ||
T_l2error > tol || T_h1error > tol ||
wN_l2error > tol || wN_h1error > tol ||
wN2_l2error > tol || wN2_h1error > tol )
{
return_flag = 1;
std::cout << "Tolerance exceeded for thermally driven flow test." << std::endl
<< "tolerance = " << tol << std::endl
<< "u l2 error = " << u_l2error << std::endl
<< "u h1 error = " << u_h1error << std::endl
<< "v l2 error = " << v_l2error << std::endl
<< "v h1 error = " << v_h1error << std::endl
<< "w l2 error = " << w_l2error << std::endl
<< "w h1 error = " << w_h1error << std::endl
<< "p l2 error = " << p_l2error << std::endl
<< "p h1 error = " << p_h1error << std::endl
<< "T l2 error = " << T_l2error << std::endl
<< "T h1 error = " << T_h1error << std::endl
<< "w_N l2 error = " << wN_l2error << std::endl
<< "w_N h1 error = " << wN_h1error << std::endl
<< "w_N2 l2 error = " << wN2_l2error << std::endl
<< "w_N2 h1 error = " << wN2_h1error << std::endl;
}
return return_flag;
}
libMesh::Real
initial_values( const libMesh::Point& p, const libMesh::Parameters ¶ms,
const std::string& , const std::string& unknown_name )
{
libMesh::Real value = 0.0;
if( unknown_name == "w_N2" )
value = params.get<libMesh::Real>("w_N2");
else if( unknown_name == "w_N" )
value = params.get<libMesh::Real>("w_N");
else if( unknown_name == "T" )
value = 300;
else if( unknown_name == "u" )
{
const libMesh::Real y = p(1);
value = 1.0*(-y*y+1);
}
else
value = 0.0;
return value;
}
<commit_msg>Use PhysicsFactoryHelper::parse_thermochemistry_model in test<commit_after>//-----------------------------------------------------------------------bl-
//--------------------------------------------------------------------------
//
// GRINS - General Reacting Incompressible Navier-Stokes
//
// Copyright (C) 2014-2015 Paul T. Bauman, Roy H. Stogner
// Copyright (C) 2010-2013 The PECOS Development Team
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the Version 2.1 GNU Lesser General
// Public License as published by the Free Software Foundation.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc. 51 Franklin Street, Fifth Floor,
// Boston, MA 02110-1301 USA
//
//-----------------------------------------------------------------------el-
#include "grins_config.h"
#include <iostream>
// GRINS
#include "grins/simulation.h"
#include "grins/simulation_builder.h"
#include "grins/physics_factory_helper.h"
// GRVY
#ifdef HAVE_GRVY
#include "grvy.h"
#endif
// libMesh
#include "libmesh/parallel.h"
#include "libmesh/exact_solution.h"
// Function for getting initial temperature field
libMesh::Real
initial_values( const libMesh::Point& p, const libMesh::Parameters ¶ms,
const std::string& system_name, const std::string& unknown_name );
int run( int argc, char* argv[], const GetPot& input );
int main(int argc, char* argv[])
{
#ifdef USE_GRVY_TIMERS
GRVY::GRVY_Timer_Class grvy_timer;
grvy_timer.Init("GRINS Timer");
#endif
// Check command line count.
if( argc < 3 )
{
// TODO: Need more consistent error handling.
std::cerr << "Error: Must specify libMesh input file and exact solution file." << std::endl;
exit(1); // TODO: something more sophisticated for parallel runs?
}
// libMesh input file should be first argument
std::string libMesh_input_filename = argv[1];
// Create our GetPot object.
GetPot libMesh_inputfile( libMesh_input_filename );
int return_flag = 0;
std::string chem_lib;
GRINS::PhysicsFactoryHelper::parse_thermochemistry_model( libMesh_inputfile,
GRINS::reacting_low_mach_navier_stokes,
chem_lib );
if( chem_lib == std::string("cantera") )
{
#ifdef GRINS_HAVE_CANTERA
return_flag = run(argc,argv,libMesh_inputfile);
#else
return_flag = 77;
#endif
}
else if( chem_lib == std::string("antioch") )
{
#ifdef GRINS_HAVE_ANTIOCH
return_flag = run(argc,argv,libMesh_inputfile);
#else
return_flag = 77;
#endif
}
else
{
std::cerr << "ERROR: Invalid thermochemistry library!" << std::endl;
return_flag = 1;
}
return return_flag;
}
int run( int argc, char* argv[], const GetPot& input )
{
#ifdef USE_GRVY_TIMERS
grvy_timer.BeginTimer("Initialize Solver");
#endif
// Initialize libMesh library.
libMesh::LibMeshInit libmesh_init(argc, argv);
GRINS::SimulationBuilder sim_builder;
GRINS::Simulation grins( input,
sim_builder,
libmesh_init.comm() );
//FIXME: We need to move this to within the Simulation object somehow...
std::string restart_file = input( "restart-options/restart_file", "none" );
if( restart_file == "none" )
{
// Asssign initial temperature value
std::string system_name = input( "screen-options/system_name", "GRINS" );
GRINS::SharedPtr<libMesh::EquationSystems> es = grins.get_equation_system();
const libMesh::System& system = es->get_system(system_name);
libMesh::Parameters ¶ms = es->parameters;
libMesh::Real& w_N2 = params.set<libMesh::Real>( "w_N2" );
w_N2 = input( "Physics/ReactingLowMachNavierStokes/bound_species_3", 0.0, 0 );
libMesh::Real& w_N = params.set<libMesh::Real>( "w_N" );
w_N = input( "Physics/ReactingLowMachNavierStokes/bound_species_3", 0.0, 1 );
system.project_solution( initial_values, NULL, params );
}
#ifdef USE_GRVY_TIMERS
grvy_timer.EndTimer("Initialize Solver");
// Attach GRVY timer to solver
grins.attach_grvy_timer( &grvy_timer );
#endif
grins.run();
#ifdef USE_GRVY_TIMERS
grvy_timer.Finalize();
if( Parallel::Communicator_World.rank() == 0 ) grvy_timer.Summarize();
#endif
// Get equation systems to create ExactSolution object
GRINS::SharedPtr<libMesh::EquationSystems>
es = grins.get_equation_system();
//es->write("foobar.xdr");
// Create Exact solution object and attach exact solution quantities
libMesh::ExactSolution exact_sol(*es);
libMesh::EquationSystems es_ref( es->get_mesh() );
// Filename of file where comparison solution is stashed
std::string solution_file = std::string(argv[2]);
es_ref.read( solution_file );
exact_sol.attach_reference_solution( &es_ref );
// Compute error and get it in various norms
exact_sol.compute_error("GRINS", "u");
exact_sol.compute_error("GRINS", "v");
if( (es->get_mesh()).mesh_dimension() == 3 )
exact_sol.compute_error("GRINS", "w");
exact_sol.compute_error("GRINS", "p");
exact_sol.compute_error("GRINS", "T");
exact_sol.compute_error("GRINS", "w_N2");
exact_sol.compute_error("GRINS", "w_N");
double u_l2error = exact_sol.l2_error("GRINS", "u");
double u_h1error = exact_sol.h1_error("GRINS", "u");
double v_l2error = exact_sol.l2_error("GRINS", "v");
double v_h1error = exact_sol.h1_error("GRINS", "v");
double p_l2error = exact_sol.l2_error("GRINS", "p");
double p_h1error = exact_sol.h1_error("GRINS", "p");
double T_l2error = exact_sol.l2_error("GRINS", "T");
double T_h1error = exact_sol.h1_error("GRINS", "T");
double wN_l2error = exact_sol.l2_error("GRINS", "w_N");
double wN_h1error = exact_sol.h1_error("GRINS", "w_N");
double wN2_l2error = exact_sol.l2_error("GRINS", "w_N2");
double wN2_h1error = exact_sol.h1_error("GRINS", "w_N2");
double w_l2error = 0.0,
w_h1error = 0.0;
if( (es->get_mesh()).mesh_dimension() == 3 )
{
w_l2error = exact_sol.l2_error("GRINS", "w");
w_h1error = exact_sol.h1_error("GRINS", "w");
}
int return_flag = 0;
double tol = 1.5e-8;
if( u_l2error > tol || u_h1error > tol ||
v_l2error > tol || v_h1error > tol ||
w_l2error > tol || w_h1error > tol ||
p_l2error > tol || p_h1error > tol ||
T_l2error > tol || T_h1error > tol ||
wN_l2error > tol || wN_h1error > tol ||
wN2_l2error > tol || wN2_h1error > tol )
{
return_flag = 1;
std::cout << "Tolerance exceeded for thermally driven flow test." << std::endl
<< "tolerance = " << tol << std::endl
<< "u l2 error = " << u_l2error << std::endl
<< "u h1 error = " << u_h1error << std::endl
<< "v l2 error = " << v_l2error << std::endl
<< "v h1 error = " << v_h1error << std::endl
<< "w l2 error = " << w_l2error << std::endl
<< "w h1 error = " << w_h1error << std::endl
<< "p l2 error = " << p_l2error << std::endl
<< "p h1 error = " << p_h1error << std::endl
<< "T l2 error = " << T_l2error << std::endl
<< "T h1 error = " << T_h1error << std::endl
<< "w_N l2 error = " << wN_l2error << std::endl
<< "w_N h1 error = " << wN_h1error << std::endl
<< "w_N2 l2 error = " << wN2_l2error << std::endl
<< "w_N2 h1 error = " << wN2_h1error << std::endl;
}
return return_flag;
}
libMesh::Real
initial_values( const libMesh::Point& p, const libMesh::Parameters ¶ms,
const std::string& , const std::string& unknown_name )
{
libMesh::Real value = 0.0;
if( unknown_name == "w_N2" )
value = params.get<libMesh::Real>("w_N2");
else if( unknown_name == "w_N" )
value = params.get<libMesh::Real>("w_N");
else if( unknown_name == "T" )
value = 300;
else if( unknown_name == "u" )
{
const libMesh::Real y = p(1);
value = 1.0*(-y*y+1);
}
else
value = 0.0;
return value;
}
<|endoftext|>
|
<commit_before>#include "dsa/crypto.h"
#include "dsa/responder.h"
#include <gtest/gtest.h>
#include <boost/filesystem/operations.hpp>
#include <boost/format.hpp>
#include <thread>
#include "../test_config.h"
#include "dslink.h"
#include "module/default/console_logger.h"
#include "module/logger.h"
#include "util/string.h"
#include "../async_test.h"
#include "dsa/stream.h"
#include "message/request/invoke_request_message.h"
using boost::format;
using namespace dsa;
using namespace std;
using DslinkTest = SetUpBase;
class MockNodeChild : public NodeModel {
public:
explicit MockNodeChild(LinkStrandRef strand, Var v)
: NodeModel(std::move(strand)) {
update_property("$is", Var(v));
};
bool save_child(const string_ &name) const override { return true; };
};
class MockNodeMain : public NodeModel {
public:
explicit MockNodeMain(LinkStrandRef strand) : NodeModel(std::move(strand)){};
bool save_child(const string_ &name) const override {
if (name == "Add_Child")
return false;
else
return true;
};
void on_load_child(const string_ &name, VarMap &map) override {
add_list_child(
name, make_ref_<MockNodeChild>(this->_strand->get_ref(), Var(name)));
};
};
TEST_F(DslinkTest, SaveMainNode) {
shared_ptr<App> app = make_shared<App>();
const char *argv[] = {"./testResp", "--broker", "ds://127.0.0.1:4121",
"-l", "info", "--thread",
"4", "--server-port", "4121"};
int argc = 9;
auto link = make_ref_<DsLink>(argc, argv, "mydslink", "1.0.0", app);
// filter log for unit test
static_cast<ConsoleLogger &>(Logger::_()).filter =
Logger::FATAL_ | Logger::ERROR_ | Logger::WARN__;
ref_<MockNodeMain> main_node =
make_ref_<MockNodeMain>(link->strand->get_ref());
main_node->add_list_child(
"Add_Child",
make_ref_<SimpleInvokeNode>(
link->strand->get_ref(),
[&](Var &&v, SimpleInvokeNode &node, OutgoingInvokeStream &stream,
ref_<NodeState> &&parent) {
auto *parent_model = parent->model_cast<NodeModel>();
// add new child node
parent_model->add_list_child(
v.to_string(),
make_ref_<MockNodeChild>(link->strand->get_ref(), v));
stream.close();
}));
link->init_responder(main_node);
bool invoked = false;
bool invoked2 = false;
ref_<IncomingListCache> list_cache;
link->connect([&](const shared_ptr_<Connection> connection,
ref_<DsLinkRequester> link_req) {
// invoke the Add_Child node to add new child
auto request = make_ref_<InvokeRequestMessage>();
request->set_target_path("Main/Add_Child");
request->set_body(Var("Child_A").to_msgpack());
link_req->invoke(
[&](IncomingInvokeStream &, ref_<const InvokeResponseMessage> &&msg) {
EXPECT_EQ(msg->get_status(), MessageStatus::CLOSED);
invoked = true;
},
std::move(request));
// invoke the Add_Child node to add second child
auto request2 = make_ref_<InvokeRequestMessage>();
request2->set_target_path("Main/Add_Child");
request2->set_body(Var("Child_B").to_msgpack());
link_req->invoke(
[&](IncomingInvokeStream &, ref_<const InvokeResponseMessage> &&msg) {
EXPECT_EQ(msg->get_status(), MessageStatus::CLOSED);
invoked2 = true;
},
std::move(request2));
});
WAIT_EXPECT_TRUE(1000, [&]() -> bool { return invoked && invoked2; });
SimpleStorage simple_storage(nullptr);
std::string storage_key("vk123");
std::unique_ptr<StorageBucket> storage_bucket =
simple_storage.get_bucket("node");
storage_bucket->remove_all();
//save main node
main_node->save(*storage_bucket, "Main", false, true);
destroy_dslink_in_strand(link);
main_node.reset();
typedef std::vector<std::vector<string_>> ListResponses;
auto link2 = make_ref_<DsLink>(argc, argv, "mydslink", "1.0.0", app);
// filter log for unit test
static_cast<ConsoleLogger &>(Logger::_()).filter =
Logger::FATAL_ | Logger::ERROR_ | Logger::WARN__;
ref_<MockNodeMain> main_node2 =
make_ref_<MockNodeMain>(link2->strand->get_ref());
main_node2->add_list_child(
"Add_Child",
make_ref_<SimpleInvokeNode>(
link2->strand->get_ref(),
[&](Var &&v, SimpleInvokeNode &node, OutgoingInvokeStream &stream,
ref_<NodeState> &&parent) {
auto *parent_model = parent->model_cast<NodeModel>();
parent_model->add_list_child(
v.to_string(),
make_ref_<MockNodeChild>(link2->strand->get_ref(), v));
stream.close();
}));
bool connected = false;
bool flag1 = false;
ListResponses root_list_responses;
ref_<IncomingListCache> list_cache2;
SimpleStorage simple_storage2(nullptr);
std::unique_ptr<StorageBucket> storage_bucket2 =
simple_storage2.get_bucket("node");
int read_order = 0;
auto read_all_callback = [&](std::string storage_key,
std::vector<uint8_t> vec,
BucketReadStatus read_status) {
if (storage_key == "Main") {
std::string str(vec.begin(), vec.end());
auto v = Var::from_json(str);
//load main node
main_node2->load(v.get_map());
}
return;
};
storage_bucket2->read_all(read_all_callback, [&]() {
EXPECT_EQ(read_order, 0);
return;
});
link2->init_responder(std::move(main_node2));
link2->connect([&](const shared_ptr_<Connection> connection,
ref_<DsLinkRequester> link_req) {
connected = true;
// list on Main node
auto list_cache1 = link_req->list(
"Main",
[
&,
link_req = static_cast<ref_<DsLinkRequester>>(link_req->get_ref())
](IncomingListCache & cache, const std::vector<string_> &str) {
root_list_responses.push_back(str);
//verify structure of Main node
EXPECT_TRUE(cache.get_map().size() != 0);
{
EXPECT_TRUE(root_list_responses.size() == 1);
EXPECT_TRUE(root_list_responses[0].size() == 0);
EXPECT_TRUE(cache.get_map().at("Child_A").is_map());
EXPECT_EQ(
cache.get_map().at("Child_A").get_map().at("$is").to_string(),
"Child_A");
EXPECT_TRUE(cache.get_map().at("Child_B").is_map());
EXPECT_EQ(
cache.get_map().at("Child_B").get_map().at("$is").to_string(),
"Child_B");
}
flag1 = true;
});
});
WAIT_EXPECT_TRUE(1000, [&]() -> bool { return connected && flag1; });
destroy_dslink_in_strand(link2);
storage_bucket2->remove_all();
app->close();
WAIT_EXPECT_TRUE(3000, [&]() -> bool { return app->is_stopped(); });
if (!app->is_stopped()) {
app->force_stop();
}
app->wait();
}
<commit_msg>fix shared bucket<commit_after>#include "dsa/crypto.h"
#include "dsa/responder.h"
#include <gtest/gtest.h>
#include <boost/filesystem/operations.hpp>
#include <boost/format.hpp>
#include <thread>
#include "../test_config.h"
#include "dslink.h"
#include "module/default/console_logger.h"
#include "module/logger.h"
#include "util/string.h"
#include "../async_test.h"
#include "dsa/stream.h"
#include "message/request/invoke_request_message.h"
using boost::format;
using namespace dsa;
using namespace std;
using DslinkTest = SetUpBase;
class MockNodeChild : public NodeModel {
public:
explicit MockNodeChild(LinkStrandRef strand, Var v)
: NodeModel(std::move(strand)) {
update_property("$is", Var(v));
};
bool save_child(const string_ &name) const override { return true; };
};
class MockNodeMain : public NodeModel {
public:
explicit MockNodeMain(LinkStrandRef strand) : NodeModel(std::move(strand)){};
bool save_child(const string_ &name) const override {
if (name == "Add_Child")
return false;
else
return true;
};
void on_load_child(const string_ &name, VarMap &map) override {
add_list_child(
name, make_ref_<MockNodeChild>(this->_strand->get_ref(), Var(name)));
};
};
TEST_F(DslinkTest, SaveMainNode) {
shared_ptr<App> app = make_shared<App>();
const char *argv[] = {"./testResp", "--broker", "ds://127.0.0.1:4121",
"-l", "info", "--thread",
"4", "--server-port", "4121"};
int argc = 9;
auto link = make_ref_<DsLink>(argc, argv, "mydslink", "1.0.0", app);
// filter log for unit test
static_cast<ConsoleLogger &>(Logger::_()).filter =
Logger::FATAL_ | Logger::ERROR_ | Logger::WARN__;
ref_<MockNodeMain> main_node =
make_ref_<MockNodeMain>(link->strand->get_ref());
main_node->add_list_child(
"Add_Child",
make_ref_<SimpleInvokeNode>(
link->strand->get_ref(),
[&](Var &&v, SimpleInvokeNode &node, OutgoingInvokeStream &stream,
ref_<NodeState> &&parent) {
auto *parent_model = parent->model_cast<NodeModel>();
// add new child node
parent_model->add_list_child(
v.to_string(),
make_ref_<MockNodeChild>(link->strand->get_ref(), v));
stream.close();
}));
link->init_responder(main_node);
bool invoked = false;
bool invoked2 = false;
ref_<IncomingListCache> list_cache;
link->connect([&](const shared_ptr_<Connection> connection,
ref_<DsLinkRequester> link_req) {
// invoke the Add_Child node to add new child
auto request = make_ref_<InvokeRequestMessage>();
request->set_target_path("Main/Add_Child");
request->set_body(Var("Child_A").to_msgpack());
link_req->invoke(
[&](IncomingInvokeStream &, ref_<const InvokeResponseMessage> &&msg) {
EXPECT_EQ(msg->get_status(), MessageStatus::CLOSED);
invoked = true;
},
std::move(request));
// invoke the Add_Child node to add second child
auto request2 = make_ref_<InvokeRequestMessage>();
request2->set_target_path("Main/Add_Child");
request2->set_body(Var("Child_B").to_msgpack());
link_req->invoke(
[&](IncomingInvokeStream &, ref_<const InvokeResponseMessage> &&msg) {
EXPECT_EQ(msg->get_status(), MessageStatus::CLOSED);
invoked2 = true;
},
std::move(request2));
});
WAIT_EXPECT_TRUE(1000, [&]() -> bool { return invoked && invoked2; });
SimpleStorage simple_storage(nullptr);
std::string storage_key("vk123");
shared_ptr_<StorageBucket> storage_bucket =
simple_storage.get_shared_bucket("node");
storage_bucket->remove_all();
//save main node
main_node->save(*storage_bucket, "Main", false, true);
destroy_dslink_in_strand(link);
main_node.reset();
typedef std::vector<std::vector<string_>> ListResponses;
auto link2 = make_ref_<DsLink>(argc, argv, "mydslink", "1.0.0", app);
// filter log for unit test
static_cast<ConsoleLogger &>(Logger::_()).filter =
Logger::FATAL_ | Logger::ERROR_ | Logger::WARN__;
ref_<MockNodeMain> main_node2 =
make_ref_<MockNodeMain>(link2->strand->get_ref());
main_node2->add_list_child(
"Add_Child",
make_ref_<SimpleInvokeNode>(
link2->strand->get_ref(),
[&](Var &&v, SimpleInvokeNode &node, OutgoingInvokeStream &stream,
ref_<NodeState> &&parent) {
auto *parent_model = parent->model_cast<NodeModel>();
parent_model->add_list_child(
v.to_string(),
make_ref_<MockNodeChild>(link2->strand->get_ref(), v));
stream.close();
}));
bool connected = false;
bool flag1 = false;
ListResponses root_list_responses;
ref_<IncomingListCache> list_cache2;
SimpleStorage simple_storage2(nullptr);
shared_ptr_<StorageBucket> storage_bucket2 =
simple_storage2.get_shared_bucket("node");
int read_order = 0;
auto read_all_callback = [&](std::string storage_key,
std::vector<uint8_t> vec,
BucketReadStatus read_status) {
if (storage_key == "Main") {
std::string str(vec.begin(), vec.end());
auto v = Var::from_json(str);
//load main node
main_node2->load(v.get_map());
}
return;
};
storage_bucket2->read_all(read_all_callback, [&]() {
EXPECT_EQ(read_order, 0);
return;
});
link2->init_responder(std::move(main_node2));
link2->connect([&](const shared_ptr_<Connection> connection,
ref_<DsLinkRequester> link_req) {
connected = true;
// list on Main node
auto list_cache1 = link_req->list(
"Main",
[
&,
link_req = static_cast<ref_<DsLinkRequester>>(link_req->get_ref())
](IncomingListCache & cache, const std::vector<string_> &str) {
root_list_responses.push_back(str);
//verify structure of Main node
EXPECT_TRUE(cache.get_map().size() != 0);
{
EXPECT_TRUE(root_list_responses.size() == 1);
EXPECT_TRUE(root_list_responses[0].size() == 0);
EXPECT_TRUE(cache.get_map().at("Child_A").is_map());
EXPECT_EQ(
cache.get_map().at("Child_A").get_map().at("$is").to_string(),
"Child_A");
EXPECT_TRUE(cache.get_map().at("Child_B").is_map());
EXPECT_EQ(
cache.get_map().at("Child_B").get_map().at("$is").to_string(),
"Child_B");
}
flag1 = true;
});
});
WAIT_EXPECT_TRUE(1000, [&]() -> bool { return connected && flag1; });
destroy_dslink_in_strand(link2);
storage_bucket2->remove_all();
app->close();
WAIT_EXPECT_TRUE(3000, [&]() -> bool { return app->is_stopped(); });
if (!app->is_stopped()) {
app->force_stop();
}
app->wait();
}
<|endoftext|>
|
<commit_before>/*****************************************************************************
*
* This file is part of Mapnik (c++ mapping toolkit)
*
* Copyright (C) 2015 Artem Pavlenko
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*
*****************************************************************************/
#include "catch.hpp"
#include <mapnik/datasource.hpp>
#include <mapnik/datasource_cache.hpp>
#include <mapnik/mapped_memory_cache.hpp>
#include <mapnik/util/fs.hpp>
#include <cstdlib>
#include <fstream>
#pragma GCC diagnostic push
#include <mapnik/warning_ignore.hpp>
#include <boost/algorithm/string.hpp>
#pragma GCC diagnostic pop
namespace {
std::size_t count_shapefile_features(std::string const& filename)
{
#if defined(MAPNIK_MEMORY_MAPPED_FILE)
mapnik::mapped_memory_cache::instance().clear();
#endif
mapnik::parameters params;
params["type"] = "shape";
params["file"] = filename;
auto ds = mapnik::datasource_cache::instance().create(params);
REQUIRE(ds != nullptr);
CHECK(ds->type() == mapnik::datasource::datasource_t::Vector);
auto fields = ds->get_descriptor().get_descriptors();
mapnik::query query(ds->envelope());
for (auto const& field : fields)
{
query.add_property_name(field.get_name());
}
auto features = ds->features(query);
REQUIRE(features != nullptr);
std::size_t feature_count = 0;
auto feature = features->next();
while (feature)
{
++feature_count;
feature = features->next();
}
return feature_count;
}
int create_shapefile_index(std::string const& filename, bool index_parts, bool silent = true)
{
std::string cmd;
if (std::getenv("DYLD_LIBRARY_PATH") != nullptr)
{
cmd += std::string("DYLD_LIBRARY_PATH=") + std::getenv("DYLD_LIBRARY_PATH") + " ";
}
cmd += "shapeindex ";
if (index_parts) cmd+= "--index-parts ";
cmd += filename;
if (silent)
{
#ifndef _WINDOWS
cmd += " 2>/dev/null";
#else
cmd += " 2> nul";
#endif
}
return std::system(cmd.c_str());
}
}
TEST_CASE("invalid shapeindex")
{
std::string shape_plugin("./plugins/input/shape.input");
if (mapnik::util::exists(shape_plugin))
{
SECTION("Invalid index")
{
std::string path = "test/data/shp/boundaries.shp";
std::string index_path = path.substr(0, path.rfind(".")) + ".index";
// remove *.index if present
if (mapnik::util::exists(index_path))
{
mapnik::util::remove(index_path);
}
// count features
std::size_t feature_count = count_shapefile_features(path);
// create invalid index
std::ofstream index(index_path.c_str(), std::ios::binary);
std::string buf("mapnik-invalid-index.................");
index.write(buf.c_str(), buf.size());
index.close();
// count features
std::size_t feature_count_indexed = count_shapefile_features(path);
// ensure number of features are the same
REQUIRE(feature_count == feature_count_indexed);
// remove *.index if present
if (mapnik::util::exists(index_path))
{
mapnik::util::remove(index_path);
}
}
}
}
TEST_CASE("shapeindex")
{
std::string shape_plugin("./plugins/input/shape.input");
if (mapnik::util::exists(shape_plugin))
{
SECTION("Index")
{
for (auto const& path : mapnik::util::list_directory("test/data/shp/"))
{
if (boost::iends_with(path,".shp"))
{
for (bool index_parts : {false, true} )
{
CAPTURE(path);
CAPTURE(index_parts);
std::string index_path = path.substr(0, path.rfind(".")) + ".index";
// remove *.index if present
if (mapnik::util::exists(index_path))
{
mapnik::util::remove(index_path);
}
// count features
std::size_t feature_count = count_shapefile_features(path);
// create *.index
REQUIRE(create_shapefile_index(path, index_parts) == 0);
if (feature_count == 0)
{
REQUIRE(!mapnik::util::exists(index_path)); // index won't be created if there's no features
}
// count features
std::size_t feature_count_indexed = count_shapefile_features(path);
// ensure number of features are the same
REQUIRE(feature_count == feature_count_indexed);
// remove *.index if present
if (mapnik::util::exists(index_path))
{
mapnik::util::remove(index_path);
}
}
}
}
}
}
}
<commit_msg>test bogus *.index files are handled correctly (ref #3300) + indirectly tests #3306 via requiring `mapped_memory_cache::instance().clear()`<commit_after>/*****************************************************************************
*
* This file is part of Mapnik (c++ mapping toolkit)
*
* Copyright (C) 2015 Artem Pavlenko
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*
*****************************************************************************/
#include "catch.hpp"
#include <mapnik/datasource.hpp>
#include <mapnik/datasource_cache.hpp>
#include <mapnik/mapped_memory_cache.hpp>
#include <mapnik/util/fs.hpp>
#include <cstdlib>
#include <fstream>
#pragma GCC diagnostic push
#include <mapnik/warning_ignore.hpp>
#include <boost/algorithm/string.hpp>
#pragma GCC diagnostic pop
namespace {
std::size_t count_shapefile_features(std::string const& filename)
{
#if defined(MAPNIK_MEMORY_MAPPED_FILE)
mapnik::mapped_memory_cache::instance().clear();
#endif
mapnik::parameters params;
params["type"] = "shape";
params["file"] = filename;
auto ds = mapnik::datasource_cache::instance().create(params);
REQUIRE(ds != nullptr);
CHECK(ds->type() == mapnik::datasource::datasource_t::Vector);
auto fields = ds->get_descriptor().get_descriptors();
mapnik::query query(ds->envelope());
for (auto const& field : fields)
{
query.add_property_name(field.get_name());
}
auto features = ds->features(query);
REQUIRE(features != nullptr);
std::size_t feature_count = 0;
auto feature = features->next();
while (feature)
{
++feature_count;
feature = features->next();
}
return feature_count;
}
int create_shapefile_index(std::string const& filename, bool index_parts, bool silent = true)
{
std::string cmd;
if (std::getenv("DYLD_LIBRARY_PATH") != nullptr)
{
cmd += std::string("DYLD_LIBRARY_PATH=") + std::getenv("DYLD_LIBRARY_PATH") + " ";
}
cmd += "shapeindex ";
if (index_parts) cmd+= "--index-parts ";
cmd += filename;
if (silent)
{
#ifndef _WINDOWS
cmd += " 2>/dev/null";
#else
cmd += " 2> nul";
#endif
}
return std::system(cmd.c_str());
}
}
TEST_CASE("invalid shapeindex")
{
std::string shape_plugin("./plugins/input/shape.input");
if (mapnik::util::exists(shape_plugin))
{
SECTION("Invalid index")
{
for (auto val : {std::make_tuple(true, std::string("mapnik-invalid-index.................")), // invalid header
std::make_tuple(false, std::string("mapnik-index................."))}) // valid header + invalid index
{
std::string path = "test/data/shp/boundaries.shp";
std::string index_path = path.substr(0, path.rfind(".")) + ".index";
// remove *.index if present
if (mapnik::util::exists(index_path))
{
mapnik::util::remove(index_path);
}
// count features
std::size_t feature_count = count_shapefile_features(path);
// create index
std::ofstream index(index_path.c_str(), std::ios::binary);
index.write(std::get<1>(val).c_str(), std::get<1>(val).size());
index.close();
// count features
std::size_t feature_count_indexed = count_shapefile_features(path);
if (std::get<0>(val)) // fallback to un-indexed access
{
// ensure number of features are the same
CHECK(feature_count == feature_count_indexed);
}
else // the header is valid but index file itself is not - expect datasource to fail and return 0 features.
{
CHECK(feature_count_indexed == 0);
}
// remove *.index if present
if (mapnik::util::exists(index_path))
{
mapnik::util::remove(index_path);
}
}
}
}
}
TEST_CASE("shapeindex")
{
std::string shape_plugin("./plugins/input/shape.input");
if (mapnik::util::exists(shape_plugin))
{
SECTION("Index")
{
for (auto const& path : mapnik::util::list_directory("test/data/shp/"))
{
if (boost::iends_with(path,".shp"))
{
for (bool index_parts : {false, true} )
{
CAPTURE(path);
CAPTURE(index_parts);
std::string index_path = path.substr(0, path.rfind(".")) + ".index";
// remove *.index if present
if (mapnik::util::exists(index_path))
{
mapnik::util::remove(index_path);
}
// count features
std::size_t feature_count = count_shapefile_features(path);
// create *.index
REQUIRE(create_shapefile_index(path, index_parts) == 0);
if (feature_count == 0)
{
REQUIRE(!mapnik::util::exists(index_path)); // index won't be created if there's no features
}
// count features
std::size_t feature_count_indexed = count_shapefile_features(path);
// ensure number of features are the same
REQUIRE(feature_count == feature_count_indexed);
// remove *.index if present
if (mapnik::util::exists(index_path))
{
mapnik::util::remove(index_path);
}
}
}
}
}
}
}
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* $RCSfile: operators_new_delete.cxx,v $
*
* $Revision: 1.2 $
*
* last change: $Author: hr $ $Date: 2003-03-26 16:45:33 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#ifdef WNT /* avoid 'std::bad_alloc' unresolved externals */
#define _CRTIMP
#define _NTSDK
#endif /* WNT */
#ifndef INCLUDED_ALGORITHM
#include <algorithm>
#define INCLUDED_ALGORITHM
#endif
#ifndef INCLUDED_NEW
#include <new>
#define INCLUDED_NEW
#endif
#ifndef INCLUDED_STRING_H
#include <string.h>
#define INCLUDED_STRING_H
#endif
#ifndef _OSL_DIAGNOSE_H_
#include <osl/diagnose.h>
#endif
#ifndef _RTL_ALLOC_H_
#include <rtl/alloc.h>
#endif
using std::nothrow_t;
// =======================================================================
// AllocatorTraits
// =======================================================================
namespace
{
struct AllocatorTraits
{
typedef char const signature_type[8];
const signature_type & m_signature;
explicit AllocatorTraits (signature_type const & s) SAL_THROW(())
: m_signature (s)
{}
std::size_t size (std::size_t n) const SAL_THROW(())
{
n = std::max(n, std::size_t(1));
#if defined(DEBUG) || defined(_DEBUG)
n += sizeof(signature_type);
#endif /* DEBUG */
return n;
}
void* init (void * p) const SAL_THROW(())
{
#if defined(DEBUG) || defined(_DEBUG)
memcpy (p, m_signature, sizeof(signature_type));
p = static_cast<char*>(p) + sizeof(signature_type);
#endif /* DEBUG */
return p;
}
void* fini (void * p) const SAL_THROW(())
{
#if defined(DEBUG) || defined(_DEBUG)
p = static_cast<char*>(p) - sizeof(signature_type);
if (memcmp (p, m_signature, sizeof(signature_type)) != 0)
{
OSL_ENSURE(0, "operator delete mismatch");
}
#endif /* DEBUG */
return p;
}
};
// =======================================================================
struct VectorTraits : public AllocatorTraits
{
static const signature_type g_signature;
VectorTraits() SAL_THROW(())
: AllocatorTraits (g_signature)
{}
};
struct ScalarTraits : public AllocatorTraits
{
static const signature_type g_signature;
ScalarTraits() SAL_THROW(())
: AllocatorTraits (g_signature)
{}
};
const AllocatorTraits::signature_type VectorTraits::g_signature = "new[]()";
const AllocatorTraits::signature_type ScalarTraits::g_signature = "new() ";
} // anonymous namespace
// =======================================================================
// Allocator
// =======================================================================
static void default_handler (void)
{
// Multithreading race in 'std::set_new_handler()' call sequence below.
throw std::bad_alloc();
}
// =======================================================================
static void* allocate (
std::size_t n, AllocatorTraits const & rTraits)
SAL_THROW((std::bad_alloc))
{
n = rTraits.size (n);
for (;;)
{
void * p = rtl_allocateMemory (sal_uInt32(n));
if (p != 0)
return rTraits.init (p);
std::new_handler d = default_handler, f = std::set_new_handler (d);
if (f != d)
std::set_new_handler (f);
if (f == 0)
throw std::bad_alloc();
(*f)();
}
}
// =======================================================================
static void* allocate (
std::size_t n, AllocatorTraits const & rTraits, std::nothrow_t const &)
SAL_THROW(())
{
try
{
return allocate (n, rTraits);
}
catch (std::bad_alloc const &)
{
return (0);
}
}
// =======================================================================
static void deallocate (void * p, AllocatorTraits const & rTraits)
SAL_THROW(())
{
if (p)
{
rtl_freeMemory (rTraits.fini(p));
}
}
// =======================================================================
// T * p = new T; delete p;
// =======================================================================
void* SAL_CALL operator new (std::size_t n) throw (std::bad_alloc)
{
return allocate (n, ScalarTraits());
}
// =======================================================================
void SAL_CALL operator delete (void * p) throw ()
{
deallocate (p, ScalarTraits());
}
// =======================================================================
// T * p = new(nothrow) T; delete(nothrow) p;
// =======================================================================
void* SAL_CALL operator new (std::size_t n, std::nothrow_t const &) throw ()
{
return allocate (n, ScalarTraits(), nothrow_t());
}
// =======================================================================
void SAL_CALL operator delete (void * p, std::nothrow_t const &) throw ()
{
deallocate (p, ScalarTraits());
}
// =======================================================================
// T * p = new T[n]; delete[] p;
// =======================================================================
void* SAL_CALL operator new[] (std::size_t n) throw (std::bad_alloc)
{
return allocate (n, VectorTraits());
}
// =======================================================================
void SAL_CALL operator delete[] (void * p) throw ()
{
deallocate (p, VectorTraits());
}
// =======================================================================
// T * p = new(nothrow) T[n]; delete(nothrow)[] p;
// =======================================================================
void* SAL_CALL operator new[] (std::size_t n, std::nothrow_t const &) throw ()
{
return allocate (n, VectorTraits(), nothrow_t());
}
// =======================================================================
void SAL_CALL operator delete[] (void * p, std::nothrow_t const &) throw ()
{
deallocate (p, VectorTraits());
}
// =======================================================================
<commit_msg>INTEGRATION: CWS dbgmacros1 (1.1.4.1.42); FILE MERGED 2003/04/09 12:08:11 kso 1.1.4.1.42.1: #108413# - debug macro unification.<commit_after>/*************************************************************************
*
* $RCSfile: operators_new_delete.cxx,v $
*
* $Revision: 1.3 $
*
* last change: $Author: vg $ $Date: 2003-04-15 17:40:45 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#ifdef WNT /* avoid 'std::bad_alloc' unresolved externals */
#define _CRTIMP
#define _NTSDK
#endif /* WNT */
#ifndef INCLUDED_ALGORITHM
#include <algorithm>
#define INCLUDED_ALGORITHM
#endif
#ifndef INCLUDED_NEW
#include <new>
#define INCLUDED_NEW
#endif
#ifndef INCLUDED_STRING_H
#include <string.h>
#define INCLUDED_STRING_H
#endif
#ifndef _OSL_DIAGNOSE_H_
#include <osl/diagnose.h>
#endif
#ifndef _RTL_ALLOC_H_
#include <rtl/alloc.h>
#endif
using std::nothrow_t;
// =======================================================================
// AllocatorTraits
// =======================================================================
namespace
{
struct AllocatorTraits
{
typedef char const signature_type[8];
const signature_type & m_signature;
explicit AllocatorTraits (signature_type const & s) SAL_THROW(())
: m_signature (s)
{}
std::size_t size (std::size_t n) const SAL_THROW(())
{
n = std::max(n, std::size_t(1));
#if OSL_DEBUG_LEVEL > 0
n += sizeof(signature_type);
#endif /* OSL_DEBUG_LEVEL */
return n;
}
void* init (void * p) const SAL_THROW(())
{
#if OSL_DEBUG_LEVEL > 0
memcpy (p, m_signature, sizeof(signature_type));
p = static_cast<char*>(p) + sizeof(signature_type);
#endif /* OSL_DEBUG_LEVEL */
return p;
}
void* fini (void * p) const SAL_THROW(())
{
#if OSL_DEBUG_LEVEL > 0
p = static_cast<char*>(p) - sizeof(signature_type);
if (memcmp (p, m_signature, sizeof(signature_type)) != 0)
{
OSL_ENSURE(0, "operator delete mismatch");
}
#endif /* OSL_DEBUG_LEVEL */
return p;
}
};
// =======================================================================
struct VectorTraits : public AllocatorTraits
{
static const signature_type g_signature;
VectorTraits() SAL_THROW(())
: AllocatorTraits (g_signature)
{}
};
struct ScalarTraits : public AllocatorTraits
{
static const signature_type g_signature;
ScalarTraits() SAL_THROW(())
: AllocatorTraits (g_signature)
{}
};
const AllocatorTraits::signature_type VectorTraits::g_signature = "new[]()";
const AllocatorTraits::signature_type ScalarTraits::g_signature = "new() ";
} // anonymous namespace
// =======================================================================
// Allocator
// =======================================================================
static void default_handler (void)
{
// Multithreading race in 'std::set_new_handler()' call sequence below.
throw std::bad_alloc();
}
// =======================================================================
static void* allocate (
std::size_t n, AllocatorTraits const & rTraits)
SAL_THROW((std::bad_alloc))
{
n = rTraits.size (n);
for (;;)
{
void * p = rtl_allocateMemory (sal_uInt32(n));
if (p != 0)
return rTraits.init (p);
std::new_handler d = default_handler, f = std::set_new_handler (d);
if (f != d)
std::set_new_handler (f);
if (f == 0)
throw std::bad_alloc();
(*f)();
}
}
// =======================================================================
static void* allocate (
std::size_t n, AllocatorTraits const & rTraits, std::nothrow_t const &)
SAL_THROW(())
{
try
{
return allocate (n, rTraits);
}
catch (std::bad_alloc const &)
{
return (0);
}
}
// =======================================================================
static void deallocate (void * p, AllocatorTraits const & rTraits)
SAL_THROW(())
{
if (p)
{
rtl_freeMemory (rTraits.fini(p));
}
}
// =======================================================================
// T * p = new T; delete p;
// =======================================================================
void* SAL_CALL operator new (std::size_t n) throw (std::bad_alloc)
{
return allocate (n, ScalarTraits());
}
// =======================================================================
void SAL_CALL operator delete (void * p) throw ()
{
deallocate (p, ScalarTraits());
}
// =======================================================================
// T * p = new(nothrow) T; delete(nothrow) p;
// =======================================================================
void* SAL_CALL operator new (std::size_t n, std::nothrow_t const &) throw ()
{
return allocate (n, ScalarTraits(), nothrow_t());
}
// =======================================================================
void SAL_CALL operator delete (void * p, std::nothrow_t const &) throw ()
{
deallocate (p, ScalarTraits());
}
// =======================================================================
// T * p = new T[n]; delete[] p;
// =======================================================================
void* SAL_CALL operator new[] (std::size_t n) throw (std::bad_alloc)
{
return allocate (n, VectorTraits());
}
// =======================================================================
void SAL_CALL operator delete[] (void * p) throw ()
{
deallocate (p, VectorTraits());
}
// =======================================================================
// T * p = new(nothrow) T[n]; delete(nothrow)[] p;
// =======================================================================
void* SAL_CALL operator new[] (std::size_t n, std::nothrow_t const &) throw ()
{
return allocate (n, VectorTraits(), nothrow_t());
}
// =======================================================================
void SAL_CALL operator delete[] (void * p, std::nothrow_t const &) throw ()
{
deallocate (p, VectorTraits());
}
// =======================================================================
<|endoftext|>
|
<commit_before>/*
* Copyright 2010 Apple Inc. All rights reserved.
* Copyright (C) 2012 Samsung Electronics. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ``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 "config.h"
#include "modules/device_orientation/NewDeviceOrientationController.h"
#include "core/dom/Document.h"
#include "modules/device_orientation/DeviceOrientationData.h"
#include "modules/device_orientation/DeviceOrientationDispatcher.h"
#include "modules/device_orientation/DeviceOrientationEvent.h"
namespace WebCore {
NewDeviceOrientationController::NewDeviceOrientationController(Document* document)
: DeviceSensorEventController(document)
{
}
NewDeviceOrientationController::~NewDeviceOrientationController()
{
}
void NewDeviceOrientationController::didChangeDeviceOrientation(DeviceOrientationData* deviceOrientationData)
{
dispatchDeviceEvent(DeviceOrientationEvent::create(eventNames().deviceorientationEvent, deviceOrientationData));
}
const char* NewDeviceOrientationController::supplementName()
{
return "NewDeviceOrientationController";
}
NewDeviceOrientationController* NewDeviceOrientationController::from(Document* document)
{
NewDeviceOrientationController* controller = static_cast<NewDeviceOrientationController*>(Supplement<ScriptExecutionContext>::from(document, supplementName()));
if (!controller) {
controller = new NewDeviceOrientationController(document);
Supplement<ScriptExecutionContext>::provideTo(document, supplementName(), adoptPtr(controller));
}
return controller;
}
bool NewDeviceOrientationController::hasLastData()
{
return DeviceOrientationDispatcher::instance().latestDeviceOrientationData();
}
PassRefPtr<Event> NewDeviceOrientationController::getLastEvent()
{
return DeviceOrientationEvent::create(eventNames().deviceorientationEvent,
DeviceOrientationDispatcher::instance().latestDeviceOrientationData());
}
void NewDeviceOrientationController::registerWithDispatcher()
{
DeviceOrientationDispatcher::instance().addDeviceOrientationController(this);
}
void NewDeviceOrientationController::unregisterWithDispatcher()
{
DeviceOrientationDispatcher::instance().removeDeviceOrientationController(this);
}
bool NewDeviceOrientationController::isNullEvent(Event* event)
{
ASSERT(event->type() == eventNames().devicemotionEvent);
DeviceOrientationEvent* orientationEvent = static_cast<DeviceOrientationEvent*>(event);
return !orientationEvent->orientation()->canProvideEventData();
}
} // namespace WebCore
<commit_msg>Fix buggy ASSERT in NewDeviceOrientationController.<commit_after>/*
* Copyright 2010 Apple Inc. All rights reserved.
* Copyright (C) 2012 Samsung Electronics. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ``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 "config.h"
#include "modules/device_orientation/NewDeviceOrientationController.h"
#include "core/dom/Document.h"
#include "modules/device_orientation/DeviceOrientationData.h"
#include "modules/device_orientation/DeviceOrientationDispatcher.h"
#include "modules/device_orientation/DeviceOrientationEvent.h"
namespace WebCore {
NewDeviceOrientationController::NewDeviceOrientationController(Document* document)
: DeviceSensorEventController(document)
{
}
NewDeviceOrientationController::~NewDeviceOrientationController()
{
}
void NewDeviceOrientationController::didChangeDeviceOrientation(DeviceOrientationData* deviceOrientationData)
{
dispatchDeviceEvent(DeviceOrientationEvent::create(eventNames().deviceorientationEvent, deviceOrientationData));
}
const char* NewDeviceOrientationController::supplementName()
{
return "NewDeviceOrientationController";
}
NewDeviceOrientationController* NewDeviceOrientationController::from(Document* document)
{
NewDeviceOrientationController* controller = static_cast<NewDeviceOrientationController*>(Supplement<ScriptExecutionContext>::from(document, supplementName()));
if (!controller) {
controller = new NewDeviceOrientationController(document);
Supplement<ScriptExecutionContext>::provideTo(document, supplementName(), adoptPtr(controller));
}
return controller;
}
bool NewDeviceOrientationController::hasLastData()
{
return DeviceOrientationDispatcher::instance().latestDeviceOrientationData();
}
PassRefPtr<Event> NewDeviceOrientationController::getLastEvent()
{
return DeviceOrientationEvent::create(eventNames().deviceorientationEvent,
DeviceOrientationDispatcher::instance().latestDeviceOrientationData());
}
void NewDeviceOrientationController::registerWithDispatcher()
{
DeviceOrientationDispatcher::instance().addDeviceOrientationController(this);
}
void NewDeviceOrientationController::unregisterWithDispatcher()
{
DeviceOrientationDispatcher::instance().removeDeviceOrientationController(this);
}
bool NewDeviceOrientationController::isNullEvent(Event* event)
{
ASSERT(event->type() == eventNames().deviceorientationEvent);
DeviceOrientationEvent* orientationEvent = static_cast<DeviceOrientationEvent*>(event);
return !orientationEvent->orientation()->canProvideEventData();
}
} // namespace WebCore
<|endoftext|>
|
<commit_before>/********************************************************************
Motor.cpp - A Library for Controlling the Motors of the MRK-1
An Introduction to Robot Programming
Author - Eric Ryan Harrison <me@ericharrison.info>
http://github.com/SumoRobotLeague/MRK-1/
Improved motor control library with an attack() method that will
instantly charge forward at full speed on both motors.
********************************************************************/
#include "Arduino.h"
#include "Motor.h"
// Define our minimum and maximum speeds for error checking.
#define maxSpeed 255
#define minSpeed -255
// This is our class constructor. When this method is called
// the class will create an object of this instance. We don't
// need our motor constructor to do anything, so we will leave
// it empty.
Motor::Motor() {
// Intentionally do nothing
}
void Motor::setupRight(int rightSpeed_pin, int rightDirection_pin) {
// Store the pin in a private variable for later use
_rightMotorSpeedPin = rightSpeed_pin;
_rightMotorDirectionPin = rightDirection_pin;
// Set up pins for output
pinMode(_rightMotorSpeedPin, OUTPUT);
pinMode(_rightMotorDirectionPin, OUTPUT);
}
void Motor::setupLeft(int leftSpeed_pin, int leftDirection_pin) {
// Store the pin in a private variable for later use
_leftMotorSpeedPin = leftSpeed_pin;
_leftMotorDirectionPin = leftDirection_pin;
// Set up pins for output
pinMode(_leftMotorSpeedPin, OUTPUT);
pinMode(_leftMotorDirectionPin, OUTPUT);
}
void Motor::right(int speed) {
// Simple check to make sure our speed does not exceed
// the defined speed limits.
if ( speed > maxSpeed ) {
speed = maxSpeed;
} else if ( speed < minSpeed ) {
speed = minSpeed;
}
if ( speed < 0 ) {
digitalWrite(_rightMotorDirectionPin, HIGH);
analogWrite(_rightMotorSpeedPin, abs(speed));
} else {
digitalWrite(_rightMotorDirectionPin, LOW);
analogWrite(_rightMotorSpeedPin, speed);
}
}
void Motor::left(int speed) {
if ( speed > maxSpeed ) {
speed = maxSpeed;
} else if ( speed < minSpeed ) {
speed = minSpeed;
}
if ( speed < 0 ) {
digitalWrite(_leftMotorDirectionPin, LOW);
analogWrite(_leftMotorSpeedPin, speed);
} else {
digitalWrite(_leftMotorDirectionPin, HIGH);
analogWrite(_leftMotorSpeedPin, abs(speed));
}
}
// Our attack() method is a very simple function that will
// tell both motors to charge forward at full speed.
void Motor::attack() {
right(maxSpeed);
left(maxSpeed);
}
// Our abort() method is a very simple function that will
// tell both motors to reverse at full speed.
void Motor::abort() {
right(minSpeed);
left(minSpeed);
}
<commit_msg>Fixed the misplaced abs()<commit_after>/********************************************************************
Motor.cpp - A Library for Controlling the Motors of the MRK-1
An Introduction to Robot Programming
Author - Eric Ryan Harrison <me@ericharrison.info>
http://github.com/SumoRobotLeague/MRK-1/
Improved motor control library with an attack() method that will
instantly charge forward at full speed on both motors.
********************************************************************/
#include "Arduino.h"
#include "Motor.h"
// Define our minimum and maximum speeds for error checking.
#define maxSpeed 255
#define minSpeed -255
// This is our class constructor. When this method is called
// the class will create an object of this instance. We don't
// need our motor constructor to do anything, so we will leave
// it empty.
Motor::Motor() {
// Intentionally do nothing
}
void Motor::setupRight(int rightSpeed_pin, int rightDirection_pin) {
// Store the pin in a private variable for later use
_rightMotorSpeedPin = rightSpeed_pin;
_rightMotorDirectionPin = rightDirection_pin;
// Set up pins for output
pinMode(_rightMotorSpeedPin, OUTPUT);
pinMode(_rightMotorDirectionPin, OUTPUT);
}
void Motor::setupLeft(int leftSpeed_pin, int leftDirection_pin) {
// Store the pin in a private variable for later use
_leftMotorSpeedPin = leftSpeed_pin;
_leftMotorDirectionPin = leftDirection_pin;
// Set up pins for output
pinMode(_leftMotorSpeedPin, OUTPUT);
pinMode(_leftMotorDirectionPin, OUTPUT);
}
void Motor::right(int speed) {
// Simple check to make sure our speed does not exceed
// the defined speed limits.
if ( speed > maxSpeed ) {
speed = maxSpeed;
} else if ( speed < minSpeed ) {
speed = minSpeed;
}
if ( speed < 0 ) {
digitalWrite(_rightMotorDirectionPin, HIGH);
analogWrite(_rightMotorSpeedPin, abs(speed));
} else {
digitalWrite(_rightMotorDirectionPin, LOW);
analogWrite(_rightMotorSpeedPin, speed);
}
}
void Motor::left(int speed) {
if ( speed > maxSpeed ) {
speed = maxSpeed;
} else if ( speed < minSpeed ) {
speed = minSpeed;
}
if ( speed < 0 ) {
digitalWrite(_leftMotorDirectionPin, LOW);
analogWrite(_leftMotorSpeedPin, abs(speed));
} else {
digitalWrite(_leftMotorDirectionPin, HIGH);
analogWrite(_leftMotorSpeedPin, speed);
}
}
// Our attack() method is a very simple function that will
// tell both motors to charge forward at full speed.
void Motor::attack() {
right(maxSpeed);
left(maxSpeed);
}
// Our abort() method is a very simple function that will
// tell both motors to reverse at full speed.
void Motor::abort() {
right(minSpeed);
left(minSpeed);
}
<|endoftext|>
|
<commit_before>
#include <synext.hpp>
#include "../ast/expr.hpp"
#include "../ast/ast.hpp"
#include "../parse/common.hpp"
#include "macro_rules.hpp"
class CMacroRulesExpander:
public ExpandProcMacro
{
bool expand_early() const override { return true; }
::std::unique_ptr<TokenStream> expand(Span sp, const ::AST::Crate& crate, const ::std::string& ident, const TokenTree& tt, AST::Module& mod) override
{
if( ident == "" )
ERROR(sp, E0000, "macro_rules! requires an identifier" );
TTStream lex(tt);
auto mac = Parse_MacroRules(lex);
mod.add_macro( false, ident, mac );
return box$( TTStreamO(TokenTree()) );
}
};
class CMacroUseHandler:
public ExpandDecorator
{
AttrStage stage() const override { return AttrStage::EarlyPost; }
void handle(const AST::MetaItem& mi, ::AST::Crate& crate, const AST::Path& path, AST::Module& mod, AST::Item& i) const override
{
TRACE_FUNCTION_F("path=" << path);
if( !i.is_Module() )
throw ::std::runtime_error("ERROR: Use of #[macro_use] on non-module");
const auto& submod = i.as_Module().e;
if( mi.has_sub_items() )
{
throw ::std::runtime_error("TODO: #[macro_use]");
}
else
{
for( const auto& mr : submod.macros() )
{
DEBUG("Imported " << mr.name);
mod.add_macro_import( mr.name, mr.data );
}
for( const auto& mri : submod.macro_imports_res() )
{
DEBUG("Imported " << mri.name << " (propagate)");
mod.add_macro_import( mri.name, *mri.data );
}
}
}
};
::std::unique_ptr<TokenStream> Macro_Invoke(const char* name, const MacroRules& rules, const TokenTree& tt, AST::Module& mod)
{
return Macro_InvokeRules(name, rules, tt);
}
STATIC_MACRO("macro_rules", CMacroRulesExpander);
STATIC_DECORATOR("macro_use", CMacroUseHandler);
<commit_msg>Expand - macro_use with ident list<commit_after>
#include <synext.hpp>
#include "../ast/expr.hpp"
#include "../ast/ast.hpp"
#include "../parse/common.hpp"
#include "macro_rules.hpp"
class CMacroRulesExpander:
public ExpandProcMacro
{
bool expand_early() const override { return true; }
::std::unique_ptr<TokenStream> expand(Span sp, const ::AST::Crate& crate, const ::std::string& ident, const TokenTree& tt, AST::Module& mod) override
{
if( ident == "" )
ERROR(sp, E0000, "macro_rules! requires an identifier" );
TTStream lex(tt);
auto mac = Parse_MacroRules(lex);
mod.add_macro( false, ident, mac );
return box$( TTStreamO(TokenTree()) );
}
};
class CMacroUseHandler:
public ExpandDecorator
{
AttrStage stage() const override { return AttrStage::EarlyPost; }
void handle(const AST::MetaItem& mi, ::AST::Crate& crate, const AST::Path& path, AST::Module& mod, AST::Item& i) const override
{
TRACE_FUNCTION_F("path=" << path);
if( !i.is_Module() )
throw ::std::runtime_error("ERROR: Use of #[macro_use] on non-module");
const auto& submod = i.as_Module().e;
if( mi.has_sub_items() )
{
for( const auto& si : mi.items() )
{
const auto& name = si.name();
for( const auto& mr : submod.macros() )
{
if( mr.name == name ) {
DEBUG("Imported " << mr.name);
mod.add_macro_import( mr.name, mr.data );
goto _good;
}
}
for( const auto& mri : submod.macro_imports_res() )
{
if( mri.name == name ) {
DEBUG("Imported " << mri.name << " (propagate)");
mod.add_macro_import( mri.name, *mri.data );
goto _good;
}
}
ERROR(Span(), E0000, "Couldn't find macro " << name);
_good:
(void)0;
}
}
else
{
for( const auto& mr : submod.macros() )
{
DEBUG("Imported " << mr.name);
mod.add_macro_import( mr.name, mr.data );
}
for( const auto& mri : submod.macro_imports_res() )
{
DEBUG("Imported " << mri.name << " (propagate)");
mod.add_macro_import( mri.name, *mri.data );
}
}
}
};
::std::unique_ptr<TokenStream> Macro_Invoke(const char* name, const MacroRules& rules, const TokenTree& tt, AST::Module& mod)
{
return Macro_InvokeRules(name, rules, tt);
}
STATIC_MACRO("macro_rules", CMacroRulesExpander);
STATIC_DECORATOR("macro_use", CMacroUseHandler);
<|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 "otbVectorImage.h"
#include "otbImageFileReader.h"
#include <otbImageKeywordlist.h>
#include <iostream>
#include <sstream>
#include <iterator>
double convertToDouble(const std::string& s)
{
std::istringstream i(s);
double x;
i >> x;
return x;
}
int otbTestImageKeywordlist(int argc, char* argv[])
{
if (argc != 6)
{
std::cout << argv[0]
<< " <input img filename> <input needed keyword list> <input list of tols for each needed kw> "
<<" <output kw list filename> <bool test all kw>" << std::endl;
return EXIT_FAILURE;
}
const unsigned int Dimension = 2;
typedef double InputPixelType;
typedef otb::VectorImage<InputPixelType, Dimension> InputImageType;
typedef otb::ImageFileReader<InputImageType> ReaderType;
const char* inputFilename = argv[1];
std::istringstream issNeededKw(argv[2]);
std::istringstream issTols(argv[3]);
char * outGeomFilename = argv[4];
bool checkAllKw = argv[5];
ReaderType::Pointer reader = ReaderType::New();
reader->SetFileName(inputFilename);
reader->UpdateOutputInformation();
otb::ImageKeywordlist kwlist = reader->GetOutput()->GetImageKeywordlist();
if (!(kwlist.GetSize() > 0))
{
std::cerr<<"Error : imageKeywordlist is empty."<<std::endl;
return EXIT_FAILURE;
}
typedef otb::ImageKeywordlist::KeywordlistMap KeywordlistMapType;
KeywordlistMapType kwmap = kwlist.GetKeywordlist();
if (checkAllKw) // Check all keywords (ignore argv[2] and argv[3])
{
// Write keywordlist, read it, compare it to the original list
WriteGeometry(kwlist,outGeomFilename);
otb::ImageKeywordlist kwlist2 = otb::ReadGeometryFromGEOMFile(outGeomFilename);
KeywordlistMapType kwmap2 = kwlist2.GetKeywordlist();
if (kwmap.size() != kwmap2.size() )
{
std::cerr << "Error : keyword lists don't have the same size (orig / reloaded): " << kwmap.size() << " / " << kwmap2.size() << std::endl;
return EXIT_FAILURE;
}
KeywordlistMapType::iterator kwlistIt = kwmap.begin();
double val1,val2;
while ( kwlistIt!=kwmap.end() )
{
val1 = convertToDouble(kwlistIt->second);
KeywordlistMapType::iterator it = kwmap2.find(kwlistIt->first);
if (it != kwmap2.end() )
{
val2 = convertToDouble(it->second);
}
else
{
std::cerr << "Error : couldn't find key " << kwlistIt->first << " in reloaded keyword list." << std::endl;
return EXIT_FAILURE;
}
if ( fabs( val2 - val1 ) > 0.01 )
{
std::cerr << "Error : orig key/value (" << kwlistIt->first << " " << kwlistIt->second << ")"<< std::endl
<< "reloaded key/value (" << kwlistIt->first << " " << kwmap2[kwlistIt->first] << ")"<< std::endl;
return EXIT_FAILURE;
}
++kwlistIt;
}
}
else // Check only needed keywords
{
// #1 keywordlist, only check the needed keywords
/*-------------------------------------*/
//Split the string into many tokens, with whitespaces as separators
std::list<std::string> neededKw;
copy(std::istream_iterator<std::string>(issNeededKw),
std::istream_iterator<std::string>(),
back_inserter(neededKw));
std::list<std::string> missingKw;
for(std::list<std::string>::iterator neededIt=neededKw.begin(); neededIt!=neededKw.end(); ++neededIt)
{
bool foundNeededKw = false;
for(KeywordlistMapType::iterator kwlistIt=kwmap.begin(); kwlistIt!=kwmap.end(); ++kwlistIt)
{
std::size_t found = kwlistIt->first.find(*neededIt);
if (found!=std::string::npos)
{
foundNeededKw = true;
}
}
if (!foundNeededKw)
missingKw.push_back(*neededIt);
}
if ( (neededKw.size()>0) && (missingKw.size()>0) )
{
std::cerr << "Error : some keywords were not found; missing keywords : " << std::endl;
for (std::list<std::string>::iterator itm = missingKw.begin(); itm != missingKw.end(); ++itm)
std::cerr << *itm << std::endl;
return EXIT_FAILURE;
}
/*-------------------------------------*/
// #2 Write keywordlist, read it, compare it to the original list
WriteGeometry(kwlist,outGeomFilename);
otb::ImageKeywordlist kwlist2 = otb::ReadGeometryFromGEOMFile(outGeomFilename);
KeywordlistMapType kwmap2 = kwlist2.GetKeywordlist();
//Split the string into many tokens, with whitespaces as separators
std::list<std::string> tols;
copy(std::istream_iterator<std::string>(issTols),
std::istream_iterator<std::string>(),
back_inserter(tols));
if (tols.size() != neededKw.size() )
{
std::cerr << "Error : needed keywords list should have the same size as the tolerances one (needed / tols): "
<< neededKw.size() << " " << tols.size() << std::endl;
return EXIT_FAILURE;
}
std::map<std::string,double> mapKwTol;
std::pair<std::map<std::string,double>::iterator,bool> ret;
std::list<std::string>::iterator tolsIt=tols.begin();
std::list<std::string>::iterator neededKwIt=neededKw.begin();
while ( (tolsIt!=tols.end()) && (neededKwIt!=neededKw.end()) )
{
mapKwTol.insert( std::pair<std::string,double>(*neededKwIt, convertToDouble(*tolsIt) ) );
++tolsIt;
++neededKwIt;
}
if (kwmap.size() != kwmap2.size() )
{
std::cerr << "Error : keyword lists don't have the same size (orig / reloaded): " << kwmap.size() << " / " << kwmap2.size() << std::endl;
return EXIT_FAILURE;
}
for(std::list<std::string>::iterator neededIt=neededKw.begin(); neededIt!=neededKw.end(); ++neededIt)
{
KeywordlistMapType::iterator kwlistIt = kwmap.begin();
KeywordlistMapType::iterator kwlistIt2 = kwmap2.begin();
while ( (kwlistIt!=kwmap.end()) && (kwlistIt2!=kwmap2.end()) )
{
std::size_t found = kwlistIt->first.find(*neededIt);
if (found!=std::string::npos) // keyword found
{
if ( fabs( convertToDouble(kwlistIt->second) - convertToDouble(kwlistIt2->second)) > mapKwTol[*neededIt] )
{
std::cerr << "Error : orig key/value (" << kwlistIt->first << " " << kwlistIt->second << ")"<< std::endl
<< "reloaded key/value (" << kwlistIt2->first << " " << kwlistIt2->second << ")"<< std::endl;
return EXIT_FAILURE;
}
}
++kwlistIt;
++kwlistIt2;
}
}
}
return EXIT_SUCCESS;
}
<commit_msg>BUG: fixed a pb concerning string to double conversion (green dashboard)<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 "otbVectorImage.h"
#include "otbImageFileReader.h"
#include <otbImageKeywordlist.h>
#include <iostream>
#include <sstream>
#include <iterator>
double convertStringToDouble(const std::string& s)
{
std::istringstream i(s);
double x;
if (!(i >> x))
return 0;
return x;
}
int otbTestImageKeywordlist(int argc, char* argv[])
{
if (argc != 6)
{
std::cout << argv[0]
<< " <input img filename> <input needed keyword list> <input list of tols for each needed kw> "
<<" <output kw list filename> <bool test all kw>" << std::endl;
return EXIT_FAILURE;
}
const unsigned int Dimension = 2;
typedef double InputPixelType;
typedef otb::VectorImage<InputPixelType, Dimension> InputImageType;
typedef otb::ImageFileReader<InputImageType> ReaderType;
const char* inputFilename = argv[1];
std::istringstream issNeededKw(argv[2]);
std::istringstream issTols(argv[3]);
char * outGeomFilename = argv[4];
bool checkAllKw = argv[5];
ReaderType::Pointer reader = ReaderType::New();
reader->SetFileName(inputFilename);
reader->UpdateOutputInformation();
otb::ImageKeywordlist kwlist = reader->GetOutput()->GetImageKeywordlist();
if (!(kwlist.GetSize() > 0))
{
std::cerr<<"Error : imageKeywordlist is empty."<<std::endl;
return EXIT_FAILURE;
}
typedef otb::ImageKeywordlist::KeywordlistMap KeywordlistMapType;
KeywordlistMapType kwmap = kwlist.GetKeywordlist();
if (checkAllKw) // Check all keywords (ignore argv[2] and argv[3])
{
// Write keywordlist, read it, compare it to the original list
WriteGeometry(kwlist,outGeomFilename);
otb::ImageKeywordlist kwlist2 = otb::ReadGeometryFromGEOMFile(outGeomFilename);
KeywordlistMapType kwmap2 = kwlist2.GetKeywordlist();
if (kwmap.size() != kwmap2.size() )
{
std::cerr << "Error : keyword lists don't have the same size (orig / reloaded): " << kwmap.size() << " / " << kwmap2.size() << std::endl;
return EXIT_FAILURE;
}
KeywordlistMapType::iterator kwlistIt = kwmap.begin();
double val1,val2;
while ( kwlistIt!=kwmap.end() )
{
val1 = convertStringToDouble(kwlistIt->second);
KeywordlistMapType::iterator it = kwmap2.find(kwlistIt->first);
if (it != kwmap2.end() )
{
val2 = convertStringToDouble(it->second);
}
else
{
std::cerr << "Error : couldn't find key " << kwlistIt->first << " in reloaded keyword list." << std::endl;
return EXIT_FAILURE;
}
if ( fabs( val2 - val1 ) > 0.01 )
{
std::cerr << "Error : orig key/value (" << kwlistIt->first << " " << kwlistIt->second << ")"<< std::endl
<< "reloaded key/value (" << kwlistIt->first << " " << kwmap2[kwlistIt->first] << ")"<< std::endl;
return EXIT_FAILURE;
}
++kwlistIt;
}
}
else // Check only needed keywords
{
// #1 keywordlist, only check the needed keywords
/*-------------------------------------*/
//Split the string into many tokens, with whitespaces as separators
std::list<std::string> neededKw;
copy(std::istream_iterator<std::string>(issNeededKw),
std::istream_iterator<std::string>(),
back_inserter(neededKw));
std::list<std::string> missingKw;
for(std::list<std::string>::iterator neededIt=neededKw.begin(); neededIt!=neededKw.end(); ++neededIt)
{
bool foundNeededKw = false;
for(KeywordlistMapType::iterator kwlistIt=kwmap.begin(); kwlistIt!=kwmap.end(); ++kwlistIt)
{
std::size_t found = kwlistIt->first.find(*neededIt);
if (found!=std::string::npos)
{
foundNeededKw = true;
}
}
if (!foundNeededKw)
missingKw.push_back(*neededIt);
}
if ( (neededKw.size()>0) && (missingKw.size()>0) )
{
std::cerr << "Error : some keywords were not found; missing keywords : " << std::endl;
for (std::list<std::string>::iterator itm = missingKw.begin(); itm != missingKw.end(); ++itm)
std::cerr << *itm << std::endl;
return EXIT_FAILURE;
}
/*-------------------------------------*/
// #2 Write keywordlist, read it, compare it to the original list
WriteGeometry(kwlist,outGeomFilename);
otb::ImageKeywordlist kwlist2 = otb::ReadGeometryFromGEOMFile(outGeomFilename);
KeywordlistMapType kwmap2 = kwlist2.GetKeywordlist();
//Split the string into many tokens, with whitespaces as separators
std::list<std::string> tols;
copy(std::istream_iterator<std::string>(issTols),
std::istream_iterator<std::string>(),
back_inserter(tols));
if (tols.size() != neededKw.size() )
{
std::cerr << "Error : needed keywords list should have the same size as the tolerances one (needed / tols): "
<< neededKw.size() << " " << tols.size() << std::endl;
return EXIT_FAILURE;
}
std::map<std::string,double> mapKwTol;
std::pair<std::map<std::string,double>::iterator,bool> ret;
std::list<std::string>::iterator tolsIt=tols.begin();
std::list<std::string>::iterator neededKwIt=neededKw.begin();
while ( (tolsIt!=tols.end()) && (neededKwIt!=neededKw.end()) )
{
mapKwTol.insert( std::pair<std::string,double>(*neededKwIt, convertStringToDouble(*tolsIt) ) );
++tolsIt;
++neededKwIt;
}
if (kwmap.size() != kwmap2.size() )
{
std::cerr << "Error : keyword lists don't have the same size (orig / reloaded): " << kwmap.size() << " / " << kwmap2.size() << std::endl;
return EXIT_FAILURE;
}
for(std::list<std::string>::iterator neededIt=neededKw.begin(); neededIt!=neededKw.end(); ++neededIt)
{
KeywordlistMapType::iterator kwlistIt = kwmap.begin();
KeywordlistMapType::iterator kwlistIt2 = kwmap2.begin();
while ( (kwlistIt!=kwmap.end()) && (kwlistIt2!=kwmap2.end()) )
{
std::size_t found = kwlistIt->first.find(*neededIt);
if (found!=std::string::npos) // keyword found
{
if ( fabs( convertStringToDouble(kwlistIt->second) - convertStringToDouble(kwlistIt2->second)) > mapKwTol[*neededIt] )
{
std::cerr << "Error : orig key/value (" << kwlistIt->first << " " << kwlistIt->second << ")"<< std::endl
<< "reloaded key/value (" << kwlistIt2->first << " " << kwlistIt2->second << ")"<< std::endl;
return EXIT_FAILURE;
}
}
++kwlistIt;
++kwlistIt2;
}
}
}
return EXIT_SUCCESS;
}
<|endoftext|>
|
<commit_before>/*
* nt loader
*
* Copyright 2006-2008 Mike McCormack
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
*/
#include "config.h"
#include <unistd.h>
#include <fcntl.h>
#include <stdio.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/mman.h>
#include <sys/time.h>
#include <assert.h>
#include <sys/wait.h>
#include <sched.h>
#include <sys/ptrace.h>
#ifdef HAVE_ASM_PTRACE_H
#include <asm/ptrace.h>
#endif
#include "windef.h"
#include "winnt.h"
#include "mem.h"
#include "thread.h"
#include "ptrace_if.h"
#include "debug.h"
#include "platform.h"
#include "client.h"
#include "ptrace_base.h"
class tt_address_space_impl: public ptrace_address_space_impl
{
enum stub_state {
stub_running,
stub_suspended,
};
long stub_regs[FRAME_SIZE];
char buffer[64]; // same size as tt stub's buffer
stub_state state;
int in_fd;
int out_fd;
pid_t child_pid;
protected:
//int ptrace_run( PCONTEXT ctx, int single_step );
int readwrite( struct tt_req *req );
void run_stub();
void suspend();
public:
static pid_t create_tracee( int& in_fd, int& out_fd );
tt_address_space_impl( pid_t pid, int in_fd, int out_fd );
virtual pid_t get_child_pid();
virtual ~tt_address_space_impl();
virtual int mmap( BYTE *address, size_t length, int prot, int flags, int file, off_t offset );
virtual int munmap( BYTE *address, size_t length );
virtual void run( void *TebBaseAddress, PCONTEXT ctx, int single_step, LARGE_INTEGER& timeout, execution_context_t *exec );
virtual unsigned short get_userspace_fs();
};
pid_t tt_address_space_impl::get_child_pid()
{
return child_pid;
}
pid_t tt_address_space_impl::create_tracee( int& in_fd, int& out_fd )
{
int r;
pid_t pid;
int infds[2], outfds[2];
r = pipe( infds );
if (r != 0)
return 0;
r = pipe( outfds );
if (r != 0)
return 0;
pid = fork();
if (pid == -1)
return pid;
if (pid == 0)
{
// close stdin and stdout
close(0);
close(1);
dup2( infds[0], STDIN_FILENO );
close( infds[1] );
dup2( outfds[1], STDOUT_FILENO );
close( outfds[0] );
::ptrace( PTRACE_TRACEME, 0, 0, 0 );
r = ::execl("./ttclient", "./ttclient", NULL );
// the next line should not be reached
die("exec failed %d\n", r);
}
close( infds[0] );
close( outfds[1] );
in_fd = infds[1];
out_fd = outfds[0];
// wait for the child
int status;
if (pid != wait4( pid, &status, WUNTRACED, NULL ))
return -1;
r = ::ptrace( PTRACE_CONT, pid, 0, 0 );
// read a single character from the stub to synchronize
do {
char dummy;
r = read(out_fd, &dummy, 1);
} while (r == -1 && errno == EINTR);
//fprintf(stderr, "created process %d\n", pid );
return pid;
}
tt_address_space_impl::tt_address_space_impl(pid_t pid, int in, int out) :
state(stub_running),
in_fd(in),
out_fd(out),
child_pid(pid)
{
//dprintf("tt_address_space_impl()\n");
}
tt_address_space_impl::~tt_address_space_impl()
{
assert( sig_target == 0 );
//dprintf(stderr,"~tt_address_space_impl()\n");
destroy();
ptrace( PTRACE_KILL, child_pid, 0, 0 );
assert( child_pid != -1 );
kill( child_pid, SIGTERM );
child_pid = -1;
}
address_space_impl* create_tt_address_space()
{
//dprintf("create_tt_address_space\n");
// Set up the signal handler and unmask it first.
// The child's signal handler will be unmasked too.
int in_fd = -1, out_fd = -1;
pid_t pid = tt_address_space_impl::create_tracee( in_fd, out_fd );
if (pid < 0)
return 0;
return new tt_address_space_impl( pid, in_fd, out_fd );
}
int tt_address_space_impl::readwrite( struct tt_req *req )
{
int r;
// getting a signal here can deadlock
assert( sig_target == 0 );
// send the buffer to the stub
do {
r = write(in_fd, req, sizeof *req);
} while (r == -1 && errno == EINTR);
if (r != sizeof *req)
{
fprintf(stderr, "write failed %d\n", r);
return r;
}
// read the stub's response
struct tt_reply reply;
do {
r = read(out_fd, &reply, sizeof reply);
} while (r == -1 && errno == EINTR);
if (r != sizeof reply)
{
fprintf(stderr, "read failed\n");
return r;
}
return reply.r;
}
int tt_address_space_impl::mmap( BYTE *address, size_t length, int prot, int flags, int file, off_t offset )
{
//dprintf("tt_address_space_impl::mmap()\n");
run_stub();
struct tt_req req;
struct tt_req_map &map = req.u.map;
req.type = tt_req_map;
map.pid = getpid();
map.fd = file;
map.addr = (int) address;
map.len = length;
map.ofs = offset;
map.prot = prot;
// send our pid to the stub
//dprintf("tt_address_space_impl::mmap()\n");
return readwrite( &req );
}
int tt_address_space_impl::munmap( BYTE *address, size_t length )
{
//dprintf("tt_address_space_impl::munmap()\n");
run_stub();
struct tt_req req;
struct tt_req_umap &umap = req.u.umap;
req.type = tt_req_umap;
umap.addr = (int) address;
umap.len = length;
return readwrite( &req );
}
void tt_address_space_impl::run( void *TebBaseAddress, PCONTEXT ctx, int single_step, LARGE_INTEGER& timeout, execution_context_t *exec )
{
//dprintf("tt_address_space_impl::run()\n");
suspend();
ptrace_address_space_impl::run( TebBaseAddress, ctx, single_step, timeout, exec );
}
unsigned short tt_address_space_impl::get_userspace_fs()
{
suspend();
return stub_regs[FS];
}
void tt_address_space_impl::suspend()
{
if (state == stub_suspended)
return;
// no signals!
assert( sig_target == 0 );
assert( child_pid != -1 );
kill( child_pid, SIGSTOP );
while (1)
{
int status;
pid_t pid = wait4( child_pid, &status, WUNTRACED, NULL );
if (pid < 0)
die("wait failed\n");
if (pid != child_pid)
continue;
if (WIFEXITED(status) )
die("Client died\n");
if (WIFSTOPPED(status) && WEXITSTATUS(status) == SIGSTOP)
{
break;
}
dprintf("stray signal %d\n", WEXITSTATUS(status));
// start the child again so we can get the next signal
ptrace( PTRACE_CONT, child_pid, 0, 0 );
}
if (state == stub_running)
{
//dprintf("saving registers\n");
int r = ptrace_get_regs( child_pid, stub_regs );
if (r < 0)
die("failed to save stub registers\n");
}
state = stub_suspended;
}
void tt_address_space_impl::run_stub()
{
int r;
suspend();
r = ptrace_set_regs( child_pid, stub_regs );
if (r < 0)
die("ptrace_set_regs failed\n");
r = ::ptrace( PTRACE_CONT, child_pid, 0, 0 );
if (r < 0)
die("ptrace( PTRACE_CONT ) failed\n");
state = stub_running;
}
bool init_tt()
{
dprintf("using tt\n");
ptrace_address_space_impl::set_signals();
pcreate_address_space = &create_tt_address_space;
return true;
}
<commit_msg>Wait for signals properly<commit_after>/*
* nt loader
*
* Copyright 2006-2008 Mike McCormack
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
*/
#include "config.h"
#include <unistd.h>
#include <fcntl.h>
#include <stdio.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/mman.h>
#include <sys/time.h>
#include <assert.h>
#include <sys/wait.h>
#include <sched.h>
#include <sys/ptrace.h>
#ifdef HAVE_ASM_PTRACE_H
#include <asm/ptrace.h>
#endif
#include "windef.h"
#include "winnt.h"
#include "mem.h"
#include "thread.h"
#include "ptrace_if.h"
#include "debug.h"
#include "platform.h"
#include "client.h"
#include "ptrace_base.h"
class tt_address_space_impl: public ptrace_address_space_impl
{
enum stub_state {
stub_running,
stub_suspended,
};
long stub_regs[FRAME_SIZE];
char buffer[64]; // same size as tt stub's buffer
stub_state state;
int in_fd;
int out_fd;
pid_t child_pid;
protected:
//int ptrace_run( PCONTEXT ctx, int single_step );
int readwrite( struct tt_req *req );
void run_stub();
void suspend();
public:
static void wait_for_signal( pid_t pid, int signal );
static pid_t create_tracee( int& in_fd, int& out_fd );
tt_address_space_impl( pid_t pid, int in_fd, int out_fd );
virtual pid_t get_child_pid();
virtual ~tt_address_space_impl();
virtual int mmap( BYTE *address, size_t length, int prot, int flags, int file, off_t offset );
virtual int munmap( BYTE *address, size_t length );
virtual void run( void *TebBaseAddress, PCONTEXT ctx, int single_step, LARGE_INTEGER& timeout, execution_context_t *exec );
virtual unsigned short get_userspace_fs();
};
pid_t tt_address_space_impl::get_child_pid()
{
return child_pid;
}
void tt_address_space_impl::wait_for_signal( pid_t pid, int signal )
{
while (1)
{
int r, status = 0;
r = wait4( pid, &status, WUNTRACED, NULL );
if (r < 0)
die("wait_for_signal: wait4() failed %d\n", errno);
if (r != pid)
continue;
if (WIFEXITED(status) )
die("Client died\n");
if (WIFSTOPPED(status) && WEXITSTATUS(status) == signal)
return;
dprintf("stray signal %d\n", WEXITSTATUS(status));
// start the child again so we can get the next signal
ptrace( PTRACE_CONT, pid, 0, 0 );
}
}
pid_t tt_address_space_impl::create_tracee( int& in_fd, int& out_fd )
{
int r;
pid_t pid;
int infds[2], outfds[2];
r = pipe( infds );
if (r != 0)
return -1;
r = pipe( outfds );
if (r != 0)
return -1;
pid = fork();
if (pid == -1)
{
dprintf("fork() failed %d\n", errno);
return pid;
}
if (pid == 0)
{
// close stdin and stdout
close(0);
close(1);
dup2( infds[0], STDIN_FILENO );
close( infds[1] );
dup2( outfds[1], STDOUT_FILENO );
close( outfds[0] );
::ptrace( PTRACE_TRACEME, 0, 0, 0 );
r = ::execl("./ttclient", "./ttclient", NULL );
// the next line should not be reached
die("exec failed %d\n", r);
}
close( infds[0] );
close( outfds[1] );
in_fd = infds[1];
out_fd = outfds[0];
wait_for_signal( pid, SIGTRAP );
r = ::ptrace( PTRACE_CONT, pid, 0, 0 );
// read a single character from the stub to synchronize
do {
char dummy;
r = read(out_fd, &dummy, 1);
} while (r == -1 && errno == EINTR);
//fprintf(stderr, "created process %d\n", pid );
return pid;
}
tt_address_space_impl::tt_address_space_impl(pid_t pid, int in, int out) :
state(stub_running),
in_fd(in),
out_fd(out),
child_pid(pid)
{
//dprintf("tt_address_space_impl()\n");
}
tt_address_space_impl::~tt_address_space_impl()
{
assert( sig_target == 0 );
//dprintf(stderr,"~tt_address_space_impl()\n");
destroy();
ptrace( PTRACE_KILL, child_pid, 0, 0 );
assert( child_pid != -1 );
kill( child_pid, SIGTERM );
child_pid = -1;
}
address_space_impl* create_tt_address_space()
{
//dprintf("create_tt_address_space\n");
// Set up the signal handler and unmask it first.
// The child's signal handler will be unmasked too.
int in_fd = -1, out_fd = -1;
pid_t pid = tt_address_space_impl::create_tracee( in_fd, out_fd );
if (pid < 0)
return 0;
return new tt_address_space_impl( pid, in_fd, out_fd );
}
int tt_address_space_impl::readwrite( struct tt_req *req )
{
int r;
// getting a signal here can deadlock
assert( sig_target == 0 );
// send the buffer to the stub
do {
r = write(in_fd, req, sizeof *req);
} while (r == -1 && errno == EINTR);
if (r != sizeof *req)
{
fprintf(stderr, "write failed %d\n", r);
return r;
}
// read the stub's response
struct tt_reply reply;
do {
r = read(out_fd, &reply, sizeof reply);
} while (r == -1 && errno == EINTR);
if (r != sizeof reply)
{
fprintf(stderr, "read failed\n");
return r;
}
return reply.r;
}
int tt_address_space_impl::mmap( BYTE *address, size_t length, int prot, int flags, int file, off_t offset )
{
//dprintf("tt_address_space_impl::mmap()\n");
run_stub();
struct tt_req req;
struct tt_req_map &map = req.u.map;
req.type = tt_req_map;
map.pid = getpid();
map.fd = file;
map.addr = (int) address;
map.len = length;
map.ofs = offset;
map.prot = prot;
// send our pid to the stub
//dprintf("tt_address_space_impl::mmap()\n");
return readwrite( &req );
}
int tt_address_space_impl::munmap( BYTE *address, size_t length )
{
//dprintf("tt_address_space_impl::munmap()\n");
run_stub();
struct tt_req req;
struct tt_req_umap &umap = req.u.umap;
req.type = tt_req_umap;
umap.addr = (int) address;
umap.len = length;
return readwrite( &req );
}
void tt_address_space_impl::run( void *TebBaseAddress, PCONTEXT ctx, int single_step, LARGE_INTEGER& timeout, execution_context_t *exec )
{
//dprintf("tt_address_space_impl::run()\n");
suspend();
ptrace_address_space_impl::run( TebBaseAddress, ctx, single_step, timeout, exec );
}
unsigned short tt_address_space_impl::get_userspace_fs()
{
suspend();
return stub_regs[FS];
}
void tt_address_space_impl::suspend()
{
if (state == stub_suspended)
return;
// no signals!
assert( sig_target == 0 );
assert( child_pid != -1 );
kill( child_pid, SIGSTOP );
wait_for_signal( child_pid, SIGSTOP );
if (state == stub_running)
{
//dprintf("saving registers\n");
int r = ptrace_get_regs( child_pid, stub_regs );
if (r < 0)
die("failed to save stub registers\n");
}
state = stub_suspended;
}
void tt_address_space_impl::run_stub()
{
int r;
suspend();
r = ptrace_set_regs( child_pid, stub_regs );
if (r < 0)
die("ptrace_set_regs failed\n");
r = ::ptrace( PTRACE_CONT, child_pid, 0, 0 );
if (r < 0)
die("ptrace( PTRACE_CONT ) failed\n");
state = stub_running;
}
bool init_tt()
{
dprintf("using tt\n");
ptrace_address_space_impl::set_signals();
pcreate_address_space = &create_tt_address_space;
return true;
}
<|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 "otbWrapperApplication.h"
#include "otbWrapperApplicationFactory.h"
#include "otbStreamingMinMaxVectorImageFilter.h"
#include "otbVectorRescaleIntensityImageFilter.h"
namespace otb
{
namespace Wrapper
{
class Rescale : public Application
{
public:
/** Standard class typedefs. */
typedef Rescale Self;
typedef Application Superclass;
typedef itk::SmartPointer<Self> Pointer;
typedef itk::SmartPointer<const Self> ConstPointer;
/** Standard macro */
itkNewMacro(Self);
itkTypeMacro(Rescale, otb::Application);
/** Filters typedef */
typedef otb::StreamingMinMaxVectorImageFilter<FloatVectorImageType> MinMaxFilterType;
typedef otb::VectorRescaleIntensityImageFilter<FloatVectorImageType> RescaleImageFilterType;
private:
Rescale()
{
SetName("Rescale");
SetDescription("Rescale the image between two given values.");
}
virtual ~Rescale()
{
}
void DoCreateParameters()
{
AddParameter(ParameterType_InputImage, "in", "Input Image");
AddParameter(ParameterType_OutputImage, "out", "Output Image");
AddParameter(ParameterType_Float, "outmin", "Output min value");
AddParameter(ParameterType_Float, "outmax", "Output max value");
SetParameterFloat("outmin", 0);
SetParameterDescription( "outmin", "Minimum value of the output image." );
SetParameterFloat("outmax", 255);
SetParameterDescription( "outmax", "Maximum value of the output image." );
MandatoryOff("outmin");
MandatoryOff("outmax");
}
void DoUpdateParameters()
{
// Nothing to do here for the parameters : all are independent
// Reinitialize the object
m_RescaleFilter = RescaleImageFilterType::New();
m_MinMaxFilter = MinMaxFilterType::New();
}
void DoExecute()
{
FloatVectorImageType::Pointer inImage = GetParameterImage("in");
otbAppLogDEBUG( << "Starting Min/Max computation" )
m_MinMaxFilter->GetStreamer()->SetNumberOfLinesStrippedStreaming( 50 );
m_MinMaxFilter->SetInput( inImage );
AddProcess(m_MinMaxFilter->GetStreamer(), "Min/Max computing");
m_MinMaxFilter->Update();
otbAppLogDEBUG( << "Min/Max computation done : min=" << m_MinMaxFilter->GetMinimum()
<< " max=" << m_MinMaxFilter->GetMaximum() )
FloatVectorImageType::PixelType inMin, inMax;
m_RescaleFilter->SetInput( inImage );
m_RescaleFilter->SetInputMinimum( m_MinMaxFilter->GetMinimum() );
m_RescaleFilter->SetInputMaximum( m_MinMaxFilter->GetMaximum() );
FloatVectorImageType::PixelType outMin, outMax;
outMin.SetSize( inImage->GetNumberOfComponentsPerPixel() );
outMax.SetSize( inImage->GetNumberOfComponentsPerPixel() );
outMin.Fill( GetParameterFloat("outmin") );
outMax.Fill( GetParameterFloat("outmax") );
m_RescaleFilter->SetOutputMinimum( outMin );
m_RescaleFilter->SetOutputMaximum( outMax );
m_RescaleFilter->UpdateOutputInformation();
SetParameterOutputImage("out", m_RescaleFilter->GetOutput());
}
RescaleImageFilterType::Pointer m_RescaleFilter;
MinMaxFilterType::Pointer m_MinMaxFilter;
};
}
}
OTB_APPLICATION_EXPORT(otb::Wrapper::Rescale)
<commit_msg>BUG: fix initialization of Rescale application<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 "otbWrapperApplication.h"
#include "otbWrapperApplicationFactory.h"
#include "otbStreamingMinMaxVectorImageFilter.h"
#include "otbVectorRescaleIntensityImageFilter.h"
namespace otb
{
namespace Wrapper
{
class Rescale : public Application
{
public:
/** Standard class typedefs. */
typedef Rescale Self;
typedef Application Superclass;
typedef itk::SmartPointer<Self> Pointer;
typedef itk::SmartPointer<const Self> ConstPointer;
/** Standard macro */
itkNewMacro(Self);
itkTypeMacro(Rescale, otb::Application);
/** Filters typedef */
typedef otb::StreamingMinMaxVectorImageFilter<FloatVectorImageType> MinMaxFilterType;
typedef otb::VectorRescaleIntensityImageFilter<FloatVectorImageType> RescaleImageFilterType;
private:
Rescale()
{
SetName("Rescale");
SetDescription("Rescale the image between two given values.");
}
virtual ~Rescale()
{
}
void DoCreateParameters()
{
AddParameter(ParameterType_InputImage, "in", "Input Image");
AddParameter(ParameterType_OutputImage, "out", "Output Image");
AddParameter(ParameterType_Float, "outmin", "Output min value");
AddParameter(ParameterType_Float, "outmax", "Output max value");
SetParameterFloat("outmin", 0);
SetParameterDescription( "outmin", "Minimum value of the output image." );
SetParameterFloat("outmax", 255);
SetParameterDescription( "outmax", "Maximum value of the output image." );
MandatoryOff("outmin");
MandatoryOff("outmax");
}
void DoUpdateParameters()
{
// Nothing to do here for the parameters : all are independent
}
void DoExecute()
{
FloatVectorImageType::Pointer inImage = GetParameterImage("in");
otbAppLogDEBUG( << "Starting Min/Max computation" )
m_MinMaxFilter = MinMaxFilterType::New();
m_MinMaxFilter->SetInput( inImage );
m_MinMaxFilter->GetStreamer()->SetNumberOfLinesStrippedStreaming( 50 );
AddProcess(m_MinMaxFilter->GetStreamer(), "Min/Max computing");
m_MinMaxFilter->Update();
otbAppLogDEBUG( << "Min/Max computation done : min=" << m_MinMaxFilter->GetMinimum()
<< " max=" << m_MinMaxFilter->GetMaximum() )
FloatVectorImageType::PixelType inMin, inMax;
m_RescaleFilter = RescaleImageFilterType::New();
m_RescaleFilter->SetInput( inImage );
m_RescaleFilter->SetInputMinimum( m_MinMaxFilter->GetMinimum() );
m_RescaleFilter->SetInputMaximum( m_MinMaxFilter->GetMaximum() );
FloatVectorImageType::PixelType outMin, outMax;
outMin.SetSize( inImage->GetNumberOfComponentsPerPixel() );
outMax.SetSize( inImage->GetNumberOfComponentsPerPixel() );
outMin.Fill( GetParameterFloat("outmin") );
outMax.Fill( GetParameterFloat("outmax") );
m_RescaleFilter->SetOutputMinimum( outMin );
m_RescaleFilter->SetOutputMaximum( outMax );
m_RescaleFilter->UpdateOutputInformation();
SetParameterOutputImage("out", m_RescaleFilter->GetOutput());
}
RescaleImageFilterType::Pointer m_RescaleFilter;
MinMaxFilterType::Pointer m_MinMaxFilter;
};
}
}
OTB_APPLICATION_EXPORT(otb::Wrapper::Rescale)
<|endoftext|>
|
<commit_before>#include "TDirectory.h"
#include "TMath.h"
#include "TString.h"
#include <iostream>
#include <sstream>
#include <string>
#include <vector>
AliAnalysisTask *AddTaskJFFlucJCMAPsMaster(TString taskName = "JFFlucJCMAP_Run2_pass2", UInt_t period = 0, double ptMin = 0.2, double ptMax = 5.0,
std::string configArray = "0 1 2 4 5 8 11 13", bool saveQA = kFALSE, bool ESDpileup = false, double intercept = 15000, bool saveQApileup = false)
{
AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();
// Less essential global variables.
bool removeBadArea = kFALSE;
int debug = 0;
bool useTightCuts = kFALSE;
double slope = 3.38;
// Prepare the configuration of the wagons.
enum { lhc15o = 0, lhc18q = 1, lhc18r = 2 };
TString speriod[3] = { "15o", "18q", "18r" }; // Needed to load correct map config.
std::cout << "AddTaskJFFlucJCMAPsMaster:: period =" << period << "\t pT range = ("
<< ptMin << "," << ptMax << ")." << std::endl;
int iConfig = -1;
int iOldConfig = -2;
int index = 0;
std::vector<TString> configNames;
std::istringstream sConfig(configArray);
do {
sConfig >> iConfig;
if (iOldConfig == iConfig) {break;}
switch(iConfig) { // Hardcoded names to prevent typo in phi weights files.
// For the "syst" selection: only the changed variables is indicated, all the others are left as in default.
case 0 : // Default selection. // V0M + |zVtx < 8| + (pileup > 15000)
configNames.push_back("default"); // + global tracks 96 + (NTPC < 70) + (chi2 in [0.1, 4]).
break;
case 1 : // Syst: global changed to hybrid.
configNames.push_back("hybrid");
break;
case 2 : // Syst: V0M changed to SPD clusters.
configNames.push_back("SPD");
break;
case 3 : // Syst: (pileup > 15000) changed to (no pileup cut).
configNames.push_back("noPileup");
break;
case 4 : // Syst: (pileup > 15000) changed to (pileup > 10000).
configNames.push_back("pileup10");
break;
case 5 : // Syst: |zVtx < 8| changed to |zVtx < 10|.
configNames.push_back("zvtx10");
break;
case 6 : // Syst: |zVtx < 8| changed to |zVtx < 9|.
configNames.push_back("zvtx9");
break;
case 7 : // Syst: |zVtx < 8| changed to |zVtx < 7|.
configNames.push_back("zvtx7");
break;
case 8 : // Syst: (NTPC > 70) changed to (NTPC > 80).
configNames.push_back("NTPC80");
break;
case 9 : // Syst: (NTPC > 70) changed to (NTPC > 90).
configNames.push_back("NTPC90");
break;
case 10 : // Syst: (NTPC > 70) changed to (NTPC > 100).
configNames.push_back("NTPC100");
break;
case 11 : // Syst: (chi2 in [0.1, 4]) changed to (chi2 < 4).
configNames.push_back("chi2def");
break;
case 12 : // Syst: (chi2 in [0.1, 4]) changed to (chi2 < 2.5).
configNames.push_back("chi2tight");
break;
case 13 : // Syst: (DCAz < 2cm - default in global) changed to (DCAz < 1cm).
configNames.push_back("DCAz1");
break;
case 14 : // Syst: (DCAz < 2cm - default in global) changed to (DCAz < 0.5cm).
configNames.push_back("DCAz05");
break;
case 15 : // Syst: (all charges) changed to (negative charges only).
configNames.push_back("nqq");
break;
case 16 : // Syst: (all charges) changed to (positive charges only).
configNames.push_back("pqq");
break;
case 17 : // Syst: subA. TBI
configNames.push_back("subA");
break;
default :
std::cout << "ERROR: Invalid configuration index. Skipping this element."
<< std::endl;
}
index++;
iOldConfig = iConfig;
} while (sConfig);
// Load the correction maps.
// We assume the same maps for all minPt values.
TString MAPfilenames; // Azimuthal corrections.
TString MAPdirname = "alien:///alice/cern.ch/user/a/aonnerst/legotrain/NUAError/";
AliJCorrectionMapTask *cmaptask = new AliJCorrectionMapTask("JCorrectionMapTask");
TString sCorrection[3] = { "15o", "18q", "18r" }; // 17i2a for 15o?
if (period == lhc18q || period == lhc18r) { // 2018 PbPb datasets.
cmaptask->EnableCentFlattening(Form("alien:///alice/cern.ch/user/j/jparkkil/legotrain/Cent/CentWeights_LHC%s_pass13.root", speriod[period].Data()));
cmaptask->EnableEffCorrection(Form("alien:///alice/cern.ch/user/d/djkim/legotrain/efficieny/data/Eff--LHC%s-LHC18l8-0-Lists.root", speriod[period].Data()));
} else if (period == lhc15o) { // 2015 PbPb dataset.
cmaptask->EnableEffCorrection(Form("alien:///alice/cern.ch/user/d/djkim/legotrain/efficieny/data/Eff--LHC%s-LHC16g-0-Lists.root", speriod[period].Data()));
}
MAPfilenames = Form("%sPhiWeights_LHC%s_Error_pt02_s_%s.root", MAPdirname.Data(), sCorrection[period].Data(), configName.Data());
cmaptask->EnablePhiCorrection(0, MAPfilenames); // i = 0: index for 'SetPhiCorrectionIndex(i)'.
mgr->AddTask((AliAnalysisTask *) cmaptask);
// Set the general variables.
int globalCut = 96; // Global tracks - default.
int hybridCut = 768; // Hybrid tracks.
UInt_t selEvt; // Trigger.
if (period == lhc15o) { // Minimum bias.
selEvt = AliVEvent::kINT7;
} else if (period == lhc18q || period == lhc18r) { // Minimum bias + central + semicentral.
selEvt = AliVEvent::kINT7 | AliVEvent::kCentral | AliVEvent::kSemiCentral;
}
// Configure the catalyst tasks for each config.
// taskName added in the name of the catalyst to prevent merging issues between wagons.
const int Nsets = index;
AliJCatalystTask *fJCatalyst[Nsets]; // One catalyst needed per configuration.
for (int i = 0; i < Nsets; i++) {
fJCatalyst[i] = new AliJCatalystTask(Form("JCatalystTask_%s_s_%s", taskName.Data(), configNames[i].Data()));
std::cout << "Setting the catalyst: " << fJCatalyst[i]->GetJCatalystTaskName() << std::endl;
fJCatalyst[i]->SetSaveAllQA(saveQA);
/// Trigger and centrality selection.
fJCatalyst[i]->SelectCollisionCandidates(selEvt);
fJCatalyst[i]->SetCentrality(0.,5.,10.,20.,30.,40.,50.,60.,70.,80.,-10.,-10.,-10.,-10.,-10.,-10.,-10.);
fJCatalyst[i]->SetInitializeCentralityArray();
if (strcmp(configNames[i].Data(), "SPD") == 0) {
fJCatalyst[i]->SetCentDetName("CL1");
} else { // Default: V0M.
fJCatalyst[i]->SetCentDetName("V0M");
}
/// Event selection: pileup cuts and Zvtx.
if (strcmp(configNames[i].Data(), "noPileup") != 0) { // Set flag only if we cut on pileup.
fJCatalyst[i]->AddFlags(AliJCatalystTask::FLUC_CUT_OUTLIERS);
if (strcmp(configNames[i].Data(), "pileup10") == 0) {fJCatalyst[i]->SetESDpileupCuts(true, slope, 10000, saveQApileup);}
else {fJCatalyst[i]->SetESDpileupCuts(ESDpileup, slope, intercept, saveQApileup);}
}
if (period == lhc18q || period == lhc18r) {fJCatalyst[i]->AddFlags(AliJCatalystTask::FLUC_CENT_FLATTENING);}
if (strcmp(configNames[i].Data(), "zvtx10") == 0) {
fJCatalyst[i]->SetZVertexCut(10.0);
} else if (strcmp(configNames[i].Data(), "zvtx9") == 0) {
fJCatalyst[i]->SetZVertexCut(9.0);
} else if (strcmp(configNames[i].Data(), "zvtx7") == 0) {
fJCatalyst[i]->SetZVertexCut(7.0);
} else { // Default value for JCorran analyses in Run 2.
fJCatalyst[i]->SetZVertexCut(8.0);
}
/// Filtering, kinematic and detector cuts.
if (strcmp(configNames[i].Data(), "hybrid") == 0) {
fJCatalyst[i]->SetTestFilterBit(hybridCut);
} else { // Default: global tracks.
fJCatalyst[i]->SetTestFilterBit(globalCut);
}
if (strcmp(configNames[i].Data(), "NTPC80") == 0) {
fJCatalyst[i]->SetNumTPCClusters(80);
} else if (strcmp(configNames[i].Data(), "NTPC90") == 0) {
fJCatalyst[i]->SetNumTPCClusters(90);
} else if (strcmp(configNames[i].Data(), "NTPC100") == 0) {
fJCatalyst[i]->SetNumTPCClusters(100);
} else { // Default value for JCorran analyses in Run 2.
fJCatalyst[i]->SetNumTPCClusters(70);
}
if (strcmp(configNames[i].Data(), "chi2def") == 0) {
fJCatalyst[i]->SetChi2Cuts(0.0, 4.0);
} else if (strcmp(configNames[i].Data(), "chi2tight") == 0) {
fJCatalyst[i]->SetChi2Cuts(0.0, 2.5);
} else { // Default value for JCorran analyses in Run 2.
fJCatalyst[i]->SetChi2Cuts(0.1, 4.0);
}
if (strcmp(configNames[i].Data(), "DCAz1") == 0) {
fJCatalyst[i]->SetDCAzCut(1.0);
} else if (strcmp(configNames[i].Data(), "DCAz05") == 0) {
fJCatalyst[i]->SetDCAzCut(0.5);
} else { // Default value for JCorran analyses in Run 2.
fJCatalyst[i]->SetDCAzCut(2.0);
}
if (strcmp(configNames[i].Data(), "nqq") == 0) {
fJCatalyst[i]->SetParticleCharge(-1);
} else if (strcmp(configNames[i].Data(), "pqq") == 0) {
fJCatalyst[i]->SetParticleCharge(1);
} // Default: charge = 0 to accept all charges.
// TBA: subA systematics.
fJCatalyst[i]->SetPtRange(ptMin, ptMax);
fJCatalyst[i]->SetEtaRange(-0.8, 0.8);
fJCatalyst[i]->SetPhiCorrectionIndex(i);
fJCatalyst[i]->SetRemoveBadArea(removeBadArea);
fJCatalyst[i]->SetTightCuts(useTightCuts);
mgr->AddTask((AliAnalysisTask *)fJCatalyst[i]);
}
// Configure the analysis task wagons.
AliJFFlucJCTask *myTask[Nsets];
for (int i = 0; i < Nsets; i++) {
myTask[i] = new AliJFFlucJCTask(Form("%s_s_%s",
taskName.Data(), configNames[i].Data()));
myTask[i]->SetJCatalystTaskName(fJCatalyst[i]->GetJCatalystTaskName());
mgr->AddTask((AliAnalysisTask *)myTask[i]);
}
// Create the containers for input/output.
AliAnalysisDataContainer *cinput = mgr->GetCommonInputContainer();
AliAnalysisDataContainer *jHist[2*Nsets];
for (int i = 0; i < Nsets; i++) {
mgr->ConnectInput(fJCatalyst[i], 0, cinput);
mgr->ConnectInput(myTask[i], 0, cinput);
jHist[i] = new AliAnalysisDataContainer();
jHist[i] = mgr->CreateContainer(Form("%s", myTask[i]->GetName()), TDirectory::Class(), AliAnalysisManager::kOutputContainer,
Form("%s:%s", AliAnalysisManager::GetCommonFileName(), myTask[i]->GetName()));
mgr->ConnectOutput(myTask[i], 1, jHist[i]);
jHist[Nsets+i] = new AliAnalysisDataContainer();
jHist[Nsets+i] = mgr->CreateContainer(Form("%s", fJCatalyst[i]->GetName()),
TList::Class(), AliAnalysisManager::kOutputContainer,
Form("%s", AliAnalysisManager::GetCommonFileName()));
mgr->ConnectOutput(fJCatalyst[i], 1, jHist[Nsets+i]);
}
return myTask[0];
}
<commit_msg>Adding macro with corrections switched on<commit_after>#include "TDirectory.h"
#include "TMath.h"
#include "TString.h"
#include <iostream>
#include <sstream>
#include <string>
#include <vector>
AliAnalysisTask *AddTaskJFFlucJCMasterCorrOn(TString taskName = "JFFlucJCMAP_Run2_pass2", UInt_t period = 0, double ptMin = 0.2, double ptMax = 5.0,
std::string configArray = "0", bool saveQA = kFALSE, bool ESDpileup = false, double intercept = 15000, bool saveQApileup = false)
{
AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();
// Less essential global variables.
// Enable only one Config for now because of map memory
bool removeBadArea = kFALSE;
int debug = 0;
bool useTightCuts = kFALSE;
double slope = 3.38;
// Prepare the configuration of the wagons.
enum { lhc15o = 0, lhc18q = 1, lhc18r = 2 };
TString speriod[3] = { "15o", "18q", "18r" }; // Needed to load correct map config.
std::cout << "AddTaskJFFlucJCMAPsMaster:: period =" << period << "\t pT range = ("
<< ptMin << "," << ptMax << ")." << std::endl;
int iConfig = -1;
int iOldConfig = -2;
int index = 0;
std::vector<TString> configNames;
std::istringstream sConfig(configArray);
do {
sConfig >> iConfig;
if (iOldConfig == iConfig) {break;}
switch(iConfig) { // Hardcoded names to prevent typo in phi weights files.
// For the "syst" selection: only the changed variables is indicated, all the others are left as in default.
case 0 : // Default selection. // V0M + |zVtx < 8| + (pileup > 15000)
configNames.push_back("default"); // + global tracks 96 + (NTPC < 70) + (chi2 in [0.1, 4]).
break;
case 1 : // Syst: global changed to hybrid.
configNames.push_back("hybrid");
break;
case 2 : // Syst: V0M changed to SPD clusters.
configNames.push_back("SPD");
break;
case 3 : // Syst: (pileup > 15000) changed to (no pileup cut).
configNames.push_back("noPileup");
break;
case 4 : // Syst: (pileup > 15000) changed to (pileup > 10000).
configNames.push_back("pileup10");
break;
case 5 : // Syst: |zVtx < 8| changed to |zVtx < 10|.
configNames.push_back("zvtx10");
break;
case 6 : // Syst: |zVtx < 8| changed to |zVtx < 9|.
configNames.push_back("zvtx9");
break;
case 7 : // Syst: |zVtx < 8| changed to |zVtx < 7|.
configNames.push_back("zvtx7");
break;
case 8 : // Syst: (NTPC > 70) changed to (NTPC > 80).
configNames.push_back("NTPC80");
break;
case 9 : // Syst: (NTPC > 70) changed to (NTPC > 90).
configNames.push_back("NTPC90");
break;
case 10 : // Syst: (NTPC > 70) changed to (NTPC > 100).
configNames.push_back("NTPC100");
break;
case 11 : // Syst: (chi2 in [0.1, 4]) changed to (chi2 < 4).
configNames.push_back("chi2def");
break;
case 12 : // Syst: (chi2 in [0.1, 4]) changed to (chi2 < 2.5).
configNames.push_back("chi2tight");
break;
case 13 : // Syst: (DCAz < 2cm - default in global) changed to (DCAz < 1cm).
configNames.push_back("DCAz1");
break;
case 14 : // Syst: (DCAz < 2cm - default in global) changed to (DCAz < 0.5cm).
configNames.push_back("DCAz05");
break;
case 15 : // Syst: (all charges) changed to (negative charges only).
configNames.push_back("nqq");
break;
case 16 : // Syst: (all charges) changed to (positive charges only).
configNames.push_back("pqq");
break;
case 17 : // Syst: subA. TBI
configNames.push_back("subA");
break;
default :
std::cout << "ERROR: Invalid configuration index. Skipping this element."
<< std::endl;
}
index++;
iOldConfig = iConfig;
} while (sConfig);
// Load the correction maps.
// We assume the same maps for all minPt values.
TString MAPfilenames; // Azimuthal corrections.
TString MAPdirname = "alien:///alice/cern.ch/user/a/aonnerst/legotrain/NUAError/";
AliJCorrectionMapTask *cmaptask = new AliJCorrectionMapTask("JCorrectionMapTask");
if (period == lhc18q || period == lhc18r) { // 2018 PbPb datasets.
cmaptask->EnableCentFlattening(Form("alien:///alice/cern.ch/user/j/jparkkil/legotrain/Cent/CentWeights_LHC%s_pass13.root", speriod[period].Data()));
cmaptask->EnableEffCorrection(Form("alien:///alice/cern.ch/user/d/djkim/legotrain/efficieny/data/Eff--LHC%s-LHC18l8-0-Lists.root", speriod[period].Data()));
} else if (period == lhc15o) { // 2015 PbPb dataset.
cmaptask->EnableEffCorrection(Form("alien:///alice/cern.ch/user/d/djkim/legotrain/efficieny/data/Eff--LHC%s-LHC16g-0-Lists.root", speriod[period].Data()));
}
// Set the general variables.
int globalCut = 96; // Global tracks - default.
int hybridCut = 768; // Hybrid tracks.
UInt_t selEvt; // Trigger.
if (period == lhc15o) { // Minimum bias.
selEvt = AliVEvent::kINT7;
} else if (period == lhc18q || period == lhc18r) { // Minimum bias + central + semicentral.
selEvt = AliVEvent::kINT7 | AliVEvent::kCentral | AliVEvent::kSemiCentral;
}
// Configure the catalyst tasks for each config.
// taskName added in the name of the catalyst to prevent merging issues between wagons.
const int Nsets = index;
AliJCatalystTask *fJCatalyst[Nsets]; // One catalyst needed per configuration.
for (int i = 0; i < Nsets; i++) {
MAPfilenames = Form("%sPhiWeights_LHC%s_Error_finerBins_pt02_s_%s.root", MAPdirname.Data(), speriod[period].Data(), configNames[i].Data());
cmaptask->EnablePhiCorrection(i, MAPfilenames); // i = 0: index for 'SetPhiCorrectionIndex(i)'.
mgr->AddTask((AliAnalysisTask *) cmaptask);
fJCatalyst[i] = new AliJCatalystTask(Form("JCatalystTask_%s_s_%s", taskName.Data(), configNames[i].Data()));
std::cout << "Setting the catalyst: " << fJCatalyst[i]->GetJCatalystTaskName() << std::endl;
fJCatalyst[i]->SetSaveAllQA(saveQA);
fJCatalyst[i]->SetPhiCorrectionIndex(i); // same as line for cmaptask
/// Trigger and centrality selection.
fJCatalyst[i]->SelectCollisionCandidates(selEvt);
fJCatalyst[i]->SetCentrality(0.,5.,10.,20.,30.,40.,50.,60.,70.,80.,-10.,-10.,-10.,-10.,-10.,-10.,-10.);
fJCatalyst[i]->SetInitializeCentralityArray();
if (strcmp(configNames[i].Data(), "SPD") == 0) {
fJCatalyst[i]->SetCentDetName("CL1");
} else { // Default: V0M.
fJCatalyst[i]->SetCentDetName("V0M");
}
/// Event selection: pileup cuts and Zvtx.
if (strcmp(configNames[i].Data(), "noPileup") != 0) { // Set flag only if we cut on pileup.
fJCatalyst[i]->AddFlags(AliJCatalystTask::FLUC_CUT_OUTLIERS);
if (strcmp(configNames[i].Data(), "pileup10") == 0) {fJCatalyst[i]->SetESDpileupCuts(true, slope, 10000, saveQApileup);}
else {fJCatalyst[i]->SetESDpileupCuts(ESDpileup, slope, intercept, saveQApileup);}
}
if (period == lhc18q || period == lhc18r) {fJCatalyst[i]->AddFlags(AliJCatalystTask::FLUC_CENT_FLATTENING);}
if (strcmp(configNames[i].Data(), "zvtx10") == 0) {
fJCatalyst[i]->SetZVertexCut(10.0);
} else if (strcmp(configNames[i].Data(), "zvtx9") == 0) {
fJCatalyst[i]->SetZVertexCut(9.0);
} else if (strcmp(configNames[i].Data(), "zvtx7") == 0) {
fJCatalyst[i]->SetZVertexCut(7.0);
} else { // Default value for JCorran analyses in Run 2.
fJCatalyst[i]->SetZVertexCut(8.0);
}
/// Filtering, kinematic and detector cuts.
if (strcmp(configNames[i].Data(), "hybrid") == 0) {
fJCatalyst[i]->SetTestFilterBit(hybridCut);
} else { // Default: global tracks.
fJCatalyst[i]->SetTestFilterBit(globalCut);
}
if (strcmp(configNames[i].Data(), "NTPC80") == 0) {
fJCatalyst[i]->SetNumTPCClusters(80);
} else if (strcmp(configNames[i].Data(), "NTPC90") == 0) {
fJCatalyst[i]->SetNumTPCClusters(90);
} else if (strcmp(configNames[i].Data(), "NTPC100") == 0) {
fJCatalyst[i]->SetNumTPCClusters(100);
} else { // Default value for JCorran analyses in Run 2.
fJCatalyst[i]->SetNumTPCClusters(70);
}
if (strcmp(configNames[i].Data(), "chi2def") == 0) {
fJCatalyst[i]->SetChi2Cuts(0.0, 4.0);
} else if (strcmp(configNames[i].Data(), "chi2tight") == 0) {
fJCatalyst[i]->SetChi2Cuts(0.0, 2.5);
} else { // Default value for JCorran analyses in Run 2.
fJCatalyst[i]->SetChi2Cuts(0.1, 4.0);
}
if (strcmp(configNames[i].Data(), "DCAz1") == 0) {
fJCatalyst[i]->SetDCAzCut(1.0);
} else if (strcmp(configNames[i].Data(), "DCAz05") == 0) {
fJCatalyst[i]->SetDCAzCut(0.5);
} else { // Default value for JCorran analyses in Run 2.
fJCatalyst[i]->SetDCAzCut(2.0);
}
if (strcmp(configNames[i].Data(), "nqq") == 0) {
fJCatalyst[i]->SetParticleCharge(-1);
} else if (strcmp(configNames[i].Data(), "pqq") == 0) {
fJCatalyst[i]->SetParticleCharge(1);
} // Default: charge = 0 to accept all charges.
// TBA: subA systematics.
fJCatalyst[i]->SetPtRange(ptMin, ptMax);
fJCatalyst[i]->SetEtaRange(-0.8, 0.8);
fJCatalyst[i]->SetPhiCorrectionIndex(i);
fJCatalyst[i]->SetRemoveBadArea(removeBadArea);
fJCatalyst[i]->SetTightCuts(useTightCuts);
mgr->AddTask((AliAnalysisTask *)fJCatalyst[i]);
}
// Configure the analysis task wagons.
AliJFFlucJCTask *myTask[Nsets];
for (int i = 0; i < Nsets; i++) {
myTask[i] = new AliJFFlucJCTask(Form("%s_s_%s",
taskName.Data(), configNames[i].Data()));
myTask[i]->SetJCatalystTaskName(fJCatalyst[i]->GetJCatalystTaskName());
mgr->AddTask((AliAnalysisTask *)myTask[i]);
}
// Create the containers for input/output.
AliAnalysisDataContainer *cinput = mgr->GetCommonInputContainer();
AliAnalysisDataContainer *jHist[2*Nsets];
for (int i = 0; i < Nsets; i++) {
mgr->ConnectInput(fJCatalyst[i], 0, cinput);
mgr->ConnectInput(myTask[i], 0, cinput);
jHist[i] = new AliAnalysisDataContainer();
jHist[i] = mgr->CreateContainer(Form("%s", myTask[i]->GetName()), TDirectory::Class(), AliAnalysisManager::kOutputContainer,
Form("%s:%s", AliAnalysisManager::GetCommonFileName(), myTask[i]->GetName()));
mgr->ConnectOutput(myTask[i], 1, jHist[i]);
jHist[Nsets+i] = new AliAnalysisDataContainer();
jHist[Nsets+i] = mgr->CreateContainer(Form("%s", fJCatalyst[i]->GetName()),
TList::Class(), AliAnalysisManager::kOutputContainer,
Form("%s", AliAnalysisManager::GetCommonFileName()));
mgr->ConnectOutput(fJCatalyst[i], 1, jHist[Nsets+i]);
}
return myTask[0];
}
<|endoftext|>
|
<commit_before>/*============================================================================
The Medical Imaging Interaction Toolkit (MITK)
Copyright (c) German Cancer Research Center (DKFZ)
All rights reserved.
Use of this source code is governed by a 3-clause BSD license that can be
found in the LICENSE file.
============================================================================*/
#include "QmitkNodeSelectionButton.h"
// berry includes
#include <berryWorkbenchPlugin.h>
#include <berryQtStyleManager.h>
#include "QPainter"
#include "QTextDocument"
#include "QEvent"
#include <mitkDataNode.h>
#include <QmitkNodeDescriptorManager.h>
// mitk core
#include <mitkBaseRenderer.h>
#include <mitkDataNode.h>
#include <mitkExtractSliceFilter.h>
#include <vtkMitkLevelWindowFilter.h>
#include <mitkPlanarFigure.h>
#include <mitkPropertyNameHelper.h>
// vtk
#include <vtkLookupTable.h>
QPixmap GetPixmapFromImageNode(const mitk::DataNode* dataNode, int height)
{
if (nullptr == dataNode)
{
return QPixmap();
}
const mitk::Image* image = dynamic_cast<const mitk::Image*>(dataNode->GetData());
if ((nullptr == image || !image->IsInitialized()) || // -> must be an image
(image->GetPixelType().GetNumberOfComponents() != 1)) // -> for now only single component are allowed
{
auto descManager = QmitkNodeDescriptorManager::GetInstance();
auto desc = descManager->GetDescriptor(dataNode);
auto icon = desc->GetIcon(dataNode);
auto fallBackMap = icon.pixmap(height, height);
return fallBackMap;
}
mitk::PlaneGeometry::Pointer planeGeometry = mitk::PlaneGeometry::New();
int sliceNumber = image->GetDimension(2) / 2;
planeGeometry->InitializeStandardPlane(image->GetGeometry(), mitk::PlaneGeometry::Axial, sliceNumber);
mitk::ExtractSliceFilter::Pointer extractSliceFilter = mitk::ExtractSliceFilter::New();
extractSliceFilter->SetInput(image);
extractSliceFilter->SetInterpolationMode(mitk::ExtractSliceFilter::RESLICE_CUBIC);
extractSliceFilter->SetResliceTransformByGeometry(image->GetGeometry());
extractSliceFilter->SetWorldGeometry(planeGeometry);
extractSliceFilter->SetOutputDimensionality(2);
extractSliceFilter->SetVtkOutputRequest(true);
extractSliceFilter->Update();
vtkImageData* imageData = extractSliceFilter->GetVtkOutput();
mitk::LevelWindow levelWindow;
dataNode->GetLevelWindow(levelWindow);
vtkSmartPointer<vtkLookupTable> lookupTable = vtkSmartPointer<vtkLookupTable>::New();
lookupTable->SetRange(levelWindow.GetLowerWindowBound(), levelWindow.GetUpperWindowBound());
lookupTable->SetSaturationRange(0.0, 0.0);
lookupTable->SetValueRange(0.0, 1.0);
lookupTable->SetHueRange(0.0, 0.0);
lookupTable->SetRampToLinear();
vtkSmartPointer<vtkMitkLevelWindowFilter> levelWindowFilter = vtkSmartPointer<vtkMitkLevelWindowFilter>::New();
levelWindowFilter->SetLookupTable(lookupTable);
levelWindowFilter->SetInputData(imageData);
levelWindowFilter->SetMinOpacity(0.0);
levelWindowFilter->SetMaxOpacity(1.0);
int dims[3];
imageData->GetDimensions(dims);
double clippingBounds[] = { 0.0, static_cast<double>(dims[0]), 0.0, static_cast<double>(dims[1]) };
levelWindowFilter->SetClippingBounds(clippingBounds);
levelWindowFilter->Update();
imageData = levelWindowFilter->GetOutput();
QImage thumbnailImage(reinterpret_cast<const unsigned char*>(imageData->GetScalarPointer()), dims[0], dims[1], QImage::Format_ARGB32);
thumbnailImage = thumbnailImage.scaledToHeight(height,Qt::SmoothTransformation).rgbSwapped();
return QPixmap::fromImage(thumbnailImage);
}
QmitkNodeSelectionButton::QmitkNodeSelectionButton(QWidget *parent)
: QPushButton(parent), m_OutDatedThumpNail(true), m_IsOptional(true), m_NodeModifiedObserverTag(0), m_NodeObserved(false), m_DataMTime(0), m_SelectionPropMTime(0)
{ }
QmitkNodeSelectionButton::~QmitkNodeSelectionButton()
{
this->RemoveNodeObserver();
this->m_SelectedNode = nullptr;
}
void QmitkNodeSelectionButton::AddNodeObserver()
{
if (this->m_SelectedNode.IsNotNull())
{
if (m_NodeObserved)
{
MITK_DEBUG << "Invalid observer state in QmitkNodeSelectionButton. There is already a registered observer. Internal logic is not correct. May be an old observer was not removed.";
}
auto modifiedCommand = itk::MemberCommand<QmitkNodeSelectionButton>::New();
modifiedCommand->SetCallbackFunction(this, &QmitkNodeSelectionButton::OnNodeModified);
// const cast because we need non const nodes and it seems to be the lesser of two evil.
// the changes to the node are only on the observer level. The other option would be to
// make the public interface require non const nodes, this we don't want to introduce.
auto nonconst_node = const_cast<mitk::DataNode*>(this->m_SelectedNode.GetPointer());
m_NodeModifiedObserverTag = nonconst_node->AddObserver(itk::ModifiedEvent(), modifiedCommand);
m_NodeObserved = true;
}
}
void QmitkNodeSelectionButton::RemoveNodeObserver()
{
if (this->m_SelectedNode.IsNotNull())
{
// const cast because we need non const nodes and it seems to be the lesser of two evil.
// the changes to the node are only on the observer level. The other option would be to
// make the public interface require non const nodes, this we don't want to introduce.
auto nonconst_node = const_cast<mitk::DataNode*>(this->m_SelectedNode.GetPointer());
nonconst_node->RemoveObserver(m_NodeModifiedObserverTag);
}
m_NodeObserved = false;
}
itk::ModifiedTimeType GetSelectedPropMTime(const mitk::DataNode* node)
{
itk::ModifiedTimeType propMTime = 0;
if (node)
{
auto prop = node->GetProperty("selected", nullptr, false);
if (prop)
{
propMTime = prop->GetMTime();
}
}
return propMTime;
}
void QmitkNodeSelectionButton::OnNodeModified(const itk::Object * /*caller*/, const itk::EventObject & event)
{
if (itk::ModifiedEvent().CheckEvent(&event))
{
auto propMTime = GetSelectedPropMTime(this->m_SelectedNode);
/*this check is introduced because of T27069. If the afformentioned issue is fixed,
this check can also be removed.*/
if (propMTime == this->m_SelectionPropMTime)
{
this->repaint();
}
this->m_SelectionPropMTime = propMTime;
}
}
const mitk::DataNode* QmitkNodeSelectionButton::GetSelectedNode() const
{
return m_SelectedNode;
}
void QmitkNodeSelectionButton::SetSelectedNode(const mitk::DataNode* node)
{
if (m_SelectedNode != node)
{
this->RemoveNodeObserver();
this->m_SelectedNode = node;
this->m_OutDatedThumpNail = true;
this->m_SelectionPropMTime = GetSelectedPropMTime(node);
this->AddNodeObserver();
}
this->update();
}
void QmitkNodeSelectionButton::SetNodeInfo(QString info)
{
this->m_Info = info;
this->update();
}
void QmitkNodeSelectionButton::paintEvent(QPaintEvent *p)
{
QString stylesheet;
ctkPluginContext* context = berry::WorkbenchPlugin::GetDefault()->GetPluginContext();
ctkServiceReference styleManagerRef = context->getServiceReference<berry::IQtStyleManager>();
if (styleManagerRef)
{
auto styleManager = context->getService<berry::IQtStyleManager>(styleManagerRef);
stylesheet = styleManager->GetStylesheet();
}
QPushButton::paintEvent(p);
QPainter painter(this);
QTextDocument td(this);
td.setDefaultStyleSheet(stylesheet);
auto widgetSize = this->size();
QPoint origin = QPoint(5, 5);
if (this->m_SelectedNode)
{
auto iconLength = widgetSize.height() - 10;
auto node = this->m_SelectedNode;
itk::ModifiedTimeType dataMTime = 0;
if (m_SelectedNode->GetData())
{
dataMTime = m_SelectedNode->GetData()->GetMTime();
}
if (dataMTime>m_DataMTime || this->m_OutDatedThumpNail)
{
this->m_ThumpNail = GetPixmapFromImageNode(node, iconLength);
this->m_OutDatedThumpNail = false;
m_DataMTime = dataMTime;
}
painter.drawPixmap(origin, m_ThumpNail);
origin.setX(origin.x() + iconLength + 5);
if (this->isEnabled())
{
td.setHtml(QString::fromStdString("<font class=\"normal\">" + node->GetName() + "</font>"));
}
else
{
td.setHtml(QString::fromStdString("<font class=\"disabled\">" + node->GetName() + "</font>"));
}
}
else
{
if (this->isEnabled())
{
if (this->m_IsOptional)
{
td.setHtml(QString("<font class=\"normal\">") + m_Info + QString("</font>"));
}
else
{
td.setHtml(QString("<font class=\"warning\">") + m_Info + QString("</font>"));
}
}
else
{
td.setHtml(QString("<font class=\"disabled\">") + m_Info + QString("</font>"));
}
}
auto textSize = td.size();
origin.setY( (widgetSize.height() - textSize.height()) / 2.);
painter.translate(origin);
td.drawContents(&painter);
}
void QmitkNodeSelectionButton::changeEvent(QEvent *event)
{
if (event->type() == QEvent::EnabledChange)
{
this->repaint();
}
}
bool QmitkNodeSelectionButton::GetSelectionIsOptional() const
{
return m_IsOptional;
}
void QmitkNodeSelectionButton::SetSelectionIsOptional(bool isOptional)
{
m_IsOptional = isOptional;
this->repaint();
}
<commit_msg>Fixed gcc compiler errors<commit_after>/*============================================================================
The Medical Imaging Interaction Toolkit (MITK)
Copyright (c) German Cancer Research Center (DKFZ)
All rights reserved.
Use of this source code is governed by a 3-clause BSD license that can be
found in the LICENSE file.
============================================================================*/
#include "QmitkNodeSelectionButton.h"
// berry includes
#include <berryWorkbenchPlugin.h>
#include <berryQtStyleManager.h>
#include "QPainter"
#include "QTextDocument"
#include "QEvent"
#include <mitkDataNode.h>
#include <QmitkNodeDescriptorManager.h>
// mitk core
#include <mitkBaseRenderer.h>
#include <mitkDataNode.h>
#include <mitkExtractSliceFilter.h>
#include <vtkMitkLevelWindowFilter.h>
#include <mitkPlanarFigure.h>
#include <mitkPropertyNameHelper.h>
// vtk
#include <vtkLookupTable.h>
QPixmap GetPixmapFromImageNode(const mitk::DataNode* dataNode, int height)
{
if (nullptr == dataNode)
{
return QPixmap();
}
const mitk::Image* image = dynamic_cast<const mitk::Image*>(dataNode->GetData());
if ((nullptr == image || !image->IsInitialized()) || // -> must be an image
(image->GetPixelType().GetNumberOfComponents() != 1)) // -> for now only single component are allowed
{
auto descManager = QmitkNodeDescriptorManager::GetInstance();
auto desc = descManager->GetDescriptor(dataNode);
auto icon = desc->GetIcon(dataNode);
auto fallBackMap = icon.pixmap(height, height);
return fallBackMap;
}
mitk::PlaneGeometry::Pointer planeGeometry = mitk::PlaneGeometry::New();
int sliceNumber = image->GetDimension(2) / 2;
planeGeometry->InitializeStandardPlane(image->GetGeometry(), mitk::PlaneGeometry::Axial, sliceNumber);
mitk::ExtractSliceFilter::Pointer extractSliceFilter = mitk::ExtractSliceFilter::New();
extractSliceFilter->SetInput(image);
extractSliceFilter->SetInterpolationMode(mitk::ExtractSliceFilter::RESLICE_CUBIC);
extractSliceFilter->SetResliceTransformByGeometry(image->GetGeometry());
extractSliceFilter->SetWorldGeometry(planeGeometry);
extractSliceFilter->SetOutputDimensionality(2);
extractSliceFilter->SetVtkOutputRequest(true);
extractSliceFilter->Update();
vtkImageData* imageData = extractSliceFilter->GetVtkOutput();
mitk::LevelWindow levelWindow;
dataNode->GetLevelWindow(levelWindow);
vtkSmartPointer<vtkLookupTable> lookupTable = vtkSmartPointer<vtkLookupTable>::New();
lookupTable->SetRange(levelWindow.GetLowerWindowBound(), levelWindow.GetUpperWindowBound());
lookupTable->SetSaturationRange(0.0, 0.0);
lookupTable->SetValueRange(0.0, 1.0);
lookupTable->SetHueRange(0.0, 0.0);
lookupTable->SetRampToLinear();
vtkSmartPointer<vtkMitkLevelWindowFilter> levelWindowFilter = vtkSmartPointer<vtkMitkLevelWindowFilter>::New();
levelWindowFilter->SetLookupTable(lookupTable);
levelWindowFilter->SetInputData(imageData);
levelWindowFilter->SetMinOpacity(0.0);
levelWindowFilter->SetMaxOpacity(1.0);
int dims[3];
imageData->GetDimensions(dims);
double clippingBounds[] = { 0.0, static_cast<double>(dims[0]), 0.0, static_cast<double>(dims[1]) };
levelWindowFilter->SetClippingBounds(clippingBounds);
levelWindowFilter->Update();
imageData = levelWindowFilter->GetOutput();
QImage thumbnailImage(reinterpret_cast<const unsigned char*>(imageData->GetScalarPointer()), dims[0], dims[1], QImage::Format_ARGB32);
thumbnailImage = thumbnailImage.scaledToHeight(height,Qt::SmoothTransformation).rgbSwapped();
return QPixmap::fromImage(thumbnailImage);
}
QmitkNodeSelectionButton::QmitkNodeSelectionButton(QWidget *parent)
: QPushButton(parent), m_OutDatedThumpNail(true), m_DataMTime(0), m_SelectionPropMTime(0), m_IsOptional(true), m_NodeModifiedObserverTag(0), m_NodeObserved(false)
{ }
QmitkNodeSelectionButton::~QmitkNodeSelectionButton()
{
this->RemoveNodeObserver();
this->m_SelectedNode = nullptr;
}
void QmitkNodeSelectionButton::AddNodeObserver()
{
if (this->m_SelectedNode.IsNotNull())
{
if (m_NodeObserved)
{
MITK_DEBUG << "Invalid observer state in QmitkNodeSelectionButton. There is already a registered observer. Internal logic is not correct. May be an old observer was not removed.";
}
auto modifiedCommand = itk::MemberCommand<QmitkNodeSelectionButton>::New();
modifiedCommand->SetCallbackFunction(this, &QmitkNodeSelectionButton::OnNodeModified);
// const cast because we need non const nodes and it seems to be the lesser of two evil.
// the changes to the node are only on the observer level. The other option would be to
// make the public interface require non const nodes, this we don't want to introduce.
auto nonconst_node = const_cast<mitk::DataNode*>(this->m_SelectedNode.GetPointer());
m_NodeModifiedObserverTag = nonconst_node->AddObserver(itk::ModifiedEvent(), modifiedCommand);
m_NodeObserved = true;
}
}
void QmitkNodeSelectionButton::RemoveNodeObserver()
{
if (this->m_SelectedNode.IsNotNull())
{
// const cast because we need non const nodes and it seems to be the lesser of two evil.
// the changes to the node are only on the observer level. The other option would be to
// make the public interface require non const nodes, this we don't want to introduce.
auto nonconst_node = const_cast<mitk::DataNode*>(this->m_SelectedNode.GetPointer());
nonconst_node->RemoveObserver(m_NodeModifiedObserverTag);
}
m_NodeObserved = false;
}
itk::ModifiedTimeType GetSelectedPropMTime(const mitk::DataNode* node)
{
itk::ModifiedTimeType propMTime = 0;
if (node)
{
auto prop = node->GetProperty("selected", nullptr, false);
if (prop)
{
propMTime = prop->GetMTime();
}
}
return propMTime;
}
void QmitkNodeSelectionButton::OnNodeModified(const itk::Object * /*caller*/, const itk::EventObject & event)
{
if (itk::ModifiedEvent().CheckEvent(&event))
{
auto propMTime = GetSelectedPropMTime(this->m_SelectedNode);
/*this check is introduced because of T27069. If the afformentioned issue is fixed,
this check can also be removed.*/
if (propMTime == this->m_SelectionPropMTime)
{
this->repaint();
}
this->m_SelectionPropMTime = propMTime;
}
}
const mitk::DataNode* QmitkNodeSelectionButton::GetSelectedNode() const
{
return m_SelectedNode;
}
void QmitkNodeSelectionButton::SetSelectedNode(const mitk::DataNode* node)
{
if (m_SelectedNode != node)
{
this->RemoveNodeObserver();
this->m_SelectedNode = node;
this->m_OutDatedThumpNail = true;
this->m_SelectionPropMTime = GetSelectedPropMTime(node);
this->AddNodeObserver();
}
this->update();
}
void QmitkNodeSelectionButton::SetNodeInfo(QString info)
{
this->m_Info = info;
this->update();
}
void QmitkNodeSelectionButton::paintEvent(QPaintEvent *p)
{
QString stylesheet;
ctkPluginContext* context = berry::WorkbenchPlugin::GetDefault()->GetPluginContext();
ctkServiceReference styleManagerRef = context->getServiceReference<berry::IQtStyleManager>();
if (styleManagerRef)
{
auto styleManager = context->getService<berry::IQtStyleManager>(styleManagerRef);
stylesheet = styleManager->GetStylesheet();
}
QPushButton::paintEvent(p);
QPainter painter(this);
QTextDocument td(this);
td.setDefaultStyleSheet(stylesheet);
auto widgetSize = this->size();
QPoint origin = QPoint(5, 5);
if (this->m_SelectedNode)
{
auto iconLength = widgetSize.height() - 10;
auto node = this->m_SelectedNode;
itk::ModifiedTimeType dataMTime = 0;
if (m_SelectedNode->GetData())
{
dataMTime = m_SelectedNode->GetData()->GetMTime();
}
if (dataMTime>m_DataMTime || this->m_OutDatedThumpNail)
{
this->m_ThumpNail = GetPixmapFromImageNode(node, iconLength);
this->m_OutDatedThumpNail = false;
m_DataMTime = dataMTime;
}
painter.drawPixmap(origin, m_ThumpNail);
origin.setX(origin.x() + iconLength + 5);
if (this->isEnabled())
{
td.setHtml(QString::fromStdString("<font class=\"normal\">" + node->GetName() + "</font>"));
}
else
{
td.setHtml(QString::fromStdString("<font class=\"disabled\">" + node->GetName() + "</font>"));
}
}
else
{
if (this->isEnabled())
{
if (this->m_IsOptional)
{
td.setHtml(QString("<font class=\"normal\">") + m_Info + QString("</font>"));
}
else
{
td.setHtml(QString("<font class=\"warning\">") + m_Info + QString("</font>"));
}
}
else
{
td.setHtml(QString("<font class=\"disabled\">") + m_Info + QString("</font>"));
}
}
auto textSize = td.size();
origin.setY( (widgetSize.height() - textSize.height()) / 2.);
painter.translate(origin);
td.drawContents(&painter);
}
void QmitkNodeSelectionButton::changeEvent(QEvent *event)
{
if (event->type() == QEvent::EnabledChange)
{
this->repaint();
}
}
bool QmitkNodeSelectionButton::GetSelectionIsOptional() const
{
return m_IsOptional;
}
void QmitkNodeSelectionButton::SetSelectionIsOptional(bool isOptional)
{
m_IsOptional = isOptional;
this->repaint();
}
<|endoftext|>
|
<commit_before>// Copyright 2008, Google Inc.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#include <string>
#include <memory>
#include "base/scoped_handle.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "sandbox/src/sandbox.h"
#include "sandbox/src/sandbox_policy.h"
#include "sandbox/src/sandbox_factory.h"
#include "sandbox/tests/common/controller.h"
namespace {
// The next 2 functions are copied from base\string_util.h and have been
// slighty modified because we don't want to depend on ICU.
template <class char_type>
inline char_type* WriteInto(
std::basic_string<char_type, std::char_traits<char_type>,
std::allocator<char_type> >* str,
size_t length_including_null) {
str->reserve(length_including_null);
str->resize(length_including_null - 1);
return &((*str)[0]);
}
std::string WideToMultiByte(const std::wstring& wide) {
if (wide.length() == 0)
return std::string();
// compute the length of the buffer we'll need
int charcount = WideCharToMultiByte(CP_UTF8, 0, wide.c_str(), -1,
NULL, 0, NULL, NULL);
if (charcount == 0)
return std::string();
std::string mb;
WideCharToMultiByte(CP_UTF8, 0, wide.c_str(), -1,
WriteInto(&mb, charcount), charcount, NULL, NULL);
return mb;
}
// While the shell API provides better calls than this home brew function
// we use GetSystemWindowsDirectoryW which does not query the registry so
// it is safe to use after revert.
std::wstring MakeFullPathToSystem32(const wchar_t* name) {
wchar_t windows_path[MAX_PATH] = {0};
::GetSystemWindowsDirectoryW(windows_path, MAX_PATH);
std::wstring full_path(windows_path);
if (full_path.empty()) {
return full_path;
}
full_path += L"\\system32\\";
full_path += name;
return full_path;
}
// Creates a process with the |exe| and |command| parameter using the
// unicode and ascii version of the api.
sandbox::SboxTestResult CreateProcessHelper(const std::wstring &exe,
const std::wstring &command) {
PROCESS_INFORMATION pi;
STARTUPINFOW si = {sizeof(si)};
wchar_t *exe_name = NULL;
if (!exe.empty())
exe_name = const_cast<wchar_t*>(exe.c_str());
wchar_t *cmd_line = NULL;
if (!command.empty())
cmd_line = const_cast<wchar_t*>(command.c_str());
// Create the process with the unicode version of the API.
sandbox::SboxTestResult ret1 = sandbox::SBOX_TEST_FAILED;
if (!::CreateProcessW(exe_name, cmd_line, NULL, NULL, FALSE, 0, NULL,
NULL, &si, &pi)) {
DWORD last_error = GetLastError();
if ((ERROR_NOT_ENOUGH_QUOTA == last_error) ||
(ERROR_ACCESS_DENIED == last_error) ||
(ERROR_FILE_NOT_FOUND == last_error)) {
ret1 = sandbox::SBOX_TEST_DENIED;
} else {
ret1 = sandbox::SBOX_TEST_FAILED;
}
} else {
ret1 = sandbox::SBOX_TEST_SUCCEEDED;
}
// Do the same with the ansi version of the api
STARTUPINFOA sia = {sizeof(sia)};
sandbox::SboxTestResult ret2 = sandbox::SBOX_TEST_FAILED;
if (!::CreateProcessA(
exe_name ? WideToMultiByte(exe_name).c_str() : NULL,
cmd_line ? const_cast<char*>(WideToMultiByte(cmd_line).c_str()) : NULL,
NULL, NULL, FALSE, 0, NULL, NULL, &sia, &pi)) {
DWORD last_error = GetLastError();
if ((ERROR_NOT_ENOUGH_QUOTA == last_error) ||
(ERROR_ACCESS_DENIED == last_error) ||
(ERROR_FILE_NOT_FOUND == last_error)) {
ret2 = sandbox::SBOX_TEST_DENIED;
} else {
ret2 = sandbox::SBOX_TEST_FAILED;
}
} else {
ret2 = sandbox::SBOX_TEST_SUCCEEDED;
}
if (ret1 == ret2)
return ret1;
return sandbox::SBOX_TEST_FAILED;
}
} // namespace
namespace sandbox {
// Tries to create the process in argv[0] using 7 different ways.
// Since we also try the Ansi and Unicode version of the CreateProcess API,
// The process referenced by argv[0] will be spawned 14 times.
SBOX_TESTS_COMMAND int Process_RunApp(int argc, wchar_t **argv) {
if (argc != 1) {
return SBOX_TEST_FAILED_TO_EXECUTE_COMMAND;
}
if ((NULL != argv) && (NULL == argv[0])) {
return SBOX_TEST_FAILED_TO_EXECUTE_COMMAND;
}
std::wstring path = MakeFullPathToSystem32(argv[0]);
// TEST 1: Try with the path in the app_name.
int result1 = CreateProcessHelper(path, std::wstring());
// TEST 2: Try with the path in the cmd_line.
std::wstring cmd_line = L"\"";
cmd_line += path;
cmd_line += L"\"";
int result2 = CreateProcessHelper(std::wstring(), cmd_line);
// TEST 3: Try file name in the cmd_line.
int result3 = CreateProcessHelper(std::wstring(), argv[0]);
// TEST 4: Try file name in the app_name and current directory sets correctly.
std::wstring system32 = MakeFullPathToSystem32(L"");
wchar_t current_directory[MAX_PATH + 1];
int result4;
bool test_succeeded = false;
DWORD ret = ::GetCurrentDirectory(MAX_PATH, current_directory);
if (0 != ret && ret < MAX_PATH) {
current_directory[ret] = L'\\';
current_directory[ret+1] = L'\0';
if (::SetCurrentDirectory(system32.c_str())) {
result4 = CreateProcessHelper(argv[0], std::wstring());
if (::SetCurrentDirectory(current_directory)) {
test_succeeded = true;
}
}
}
if (!test_succeeded)
result4 = SBOX_TEST_FAILED;
// TEST 5: Try with the path in the cmd_line and arguments.
cmd_line = L"\"";
cmd_line += path;
cmd_line += L"\" /INSERT";
int result5 = CreateProcessHelper(std::wstring(), cmd_line);
// TEST 6: Try with the file_name in the cmd_line and arguments.
cmd_line = argv[0];
cmd_line += L" /INSERT";
int result6 = CreateProcessHelper(std::wstring(), cmd_line);
// TEST 7: Try with the path without the drive.
cmd_line = path.substr(path.find(L'\\'));
int result7 = CreateProcessHelper(std::wstring(), cmd_line);
// Check if they all returned the same thing.
if ((result1 == result2) && (result2 == result3) && (result3 == result4) &&
(result4 == result5) && (result5 == result6) && (result6 == result7))
return result1;
return SBOX_TEST_FAILED;
}
// Creates a process and checks if it's possible to get a handle to it's token.
SBOX_TESTS_COMMAND int Process_GetChildProcessToken(int argc, wchar_t **argv) {
if (argc != 1)
return SBOX_TEST_FAILED_TO_EXECUTE_COMMAND;
if ((NULL != argv) && (NULL == argv[0]))
return SBOX_TEST_FAILED_TO_EXECUTE_COMMAND;
std::wstring path = MakeFullPathToSystem32(argv[0]);
PROCESS_INFORMATION pi = {0};
STARTUPINFOW si = {sizeof(si)};
if (!::CreateProcessW(path.c_str(), NULL, NULL, NULL, FALSE, CREATE_SUSPENDED,
NULL, NULL, &si, &pi)) {
return SBOX_TEST_FAILED;
}
ScopedHandle process(pi.hProcess);
ScopedHandle thread(pi.hThread);
HANDLE token = NULL;
BOOL result = ::OpenProcessToken(process.Get(), TOKEN_IMPERSONATE, &token);
DWORD error = ::GetLastError();
ScopedHandle token_handle(token);
if (!::TerminateProcess(process.Get(), 0))
return SBOX_TEST_FAILED;
if (result && token)
return SBOX_TEST_SUCCEEDED;
if (ERROR_ACCESS_DENIED == error)
return SBOX_TEST_DENIED;
return SBOX_TEST_FAILED;
}
SBOX_TESTS_COMMAND int Process_OpenToken(int argc, wchar_t **argv) {
HANDLE token;
if (!::OpenProcessToken(::GetCurrentProcess(), TOKEN_ALL_ACCESS, &token)) {
if (ERROR_ACCESS_DENIED == ::GetLastError()) {
return SBOX_TEST_DENIED;
}
} else {
::CloseHandle(token);
return SBOX_TEST_SUCCEEDED;
}
return SBOX_TEST_FAILED;
}
TEST(ProcessPolicyTest, TestAllAccess) {
// Check if the "all access" rule fails to be added when the token is too
// powerful.
TestRunner runner;
// Check the failing case.
runner.GetPolicy()->SetTokenLevel(USER_INTERACTIVE, USER_LOCKDOWN);
EXPECT_EQ(SBOX_ERROR_UNSUPPORTED,
runner.GetPolicy()->AddRule(TargetPolicy::SUBSYS_PROCESS,
TargetPolicy::PROCESS_ALL_EXEC,
L"this is not important"));
// Check the working case.
runner.GetPolicy()->SetTokenLevel(USER_INTERACTIVE, USER_INTERACTIVE);
EXPECT_EQ(SBOX_ALL_OK,
runner.GetPolicy()->AddRule(TargetPolicy::SUBSYS_PROCESS,
TargetPolicy::PROCESS_ALL_EXEC,
L"this is not important"));
}
TEST(ProcessPolicyTest, RunFindstrExe) {
TestRunner runner;
std::wstring exe_path = MakeFullPathToSystem32(L"findstr.exe");
std::wstring system32 = MakeFullPathToSystem32(L"");
ASSERT_TRUE(!exe_path.empty());
EXPECT_TRUE(runner.AddRule(TargetPolicy::SUBSYS_PROCESS,
TargetPolicy::PROCESS_MIN_EXEC,
exe_path.c_str()));
// Need to add directory rules for the directories that we use in
// SetCurrentDirectory.
EXPECT_TRUE(runner.AddFsRule(TargetPolicy::FILES_ALLOW_DIR_ANY,
system32.c_str()));
wchar_t current_directory[MAX_PATH];
DWORD ret = ::GetCurrentDirectory(MAX_PATH, current_directory);
ASSERT_TRUE(0 != ret && ret < MAX_PATH);
wcscat_s(current_directory, MAX_PATH, L"\\");
EXPECT_TRUE(runner.AddFsRule(TargetPolicy::FILES_ALLOW_DIR_ANY,
current_directory));
EXPECT_EQ(SBOX_TEST_SUCCEEDED, runner.RunTest(L"Process_RunApp findstr.exe"));
EXPECT_EQ(SBOX_TEST_DENIED, runner.RunTest(L"Process_RunApp calc.exe"));
}
TEST(ProcessPolicyTest, OpenToken) {
TestRunner runner;
EXPECT_EQ(SBOX_TEST_SUCCEEDED, runner.RunTest(L"Process_OpenToken"));
}
TEST(ProcessPolicyTest, TestGetProcessTokenMinAccess) {
TestRunner runner;
std::wstring exe_path = MakeFullPathToSystem32(L"findstr.exe");
ASSERT_TRUE(!exe_path.empty());
EXPECT_TRUE(runner.AddRule(TargetPolicy::SUBSYS_PROCESS,
TargetPolicy::PROCESS_MIN_EXEC,
exe_path.c_str()));
EXPECT_EQ(SBOX_TEST_DENIED,
runner.RunTest(L"Process_GetChildProcessToken findstr.exe"));
}
TEST(ProcessPolicyTest, TestGetProcessTokenMaxAccess) {
TestRunner runner(JOB_UNPROTECTED, USER_INTERACTIVE, USER_INTERACTIVE);
std::wstring exe_path = MakeFullPathToSystem32(L"findstr.exe");
ASSERT_TRUE(!exe_path.empty());
EXPECT_TRUE(runner.AddRule(TargetPolicy::SUBSYS_PROCESS,
TargetPolicy::PROCESS_ALL_EXEC,
exe_path.c_str()));
EXPECT_EQ(SBOX_TEST_SUCCEEDED,
runner.RunTest(L"Process_GetChildProcessToken findstr.exe"));
}
} // namespace sandbox
<commit_msg>Disable ProcessPolicyTest.RunFindstrExe until it can be made to work on any Windows drive. B=1305476 R=nsylvain<commit_after>// Copyright 2008, Google Inc.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#include <string>
#include <memory>
#include "base/scoped_handle.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "sandbox/src/sandbox.h"
#include "sandbox/src/sandbox_policy.h"
#include "sandbox/src/sandbox_factory.h"
#include "sandbox/tests/common/controller.h"
namespace {
// The next 2 functions are copied from base\string_util.h and have been
// slighty modified because we don't want to depend on ICU.
template <class char_type>
inline char_type* WriteInto(
std::basic_string<char_type, std::char_traits<char_type>,
std::allocator<char_type> >* str,
size_t length_including_null) {
str->reserve(length_including_null);
str->resize(length_including_null - 1);
return &((*str)[0]);
}
std::string WideToMultiByte(const std::wstring& wide) {
if (wide.length() == 0)
return std::string();
// compute the length of the buffer we'll need
int charcount = WideCharToMultiByte(CP_UTF8, 0, wide.c_str(), -1,
NULL, 0, NULL, NULL);
if (charcount == 0)
return std::string();
std::string mb;
WideCharToMultiByte(CP_UTF8, 0, wide.c_str(), -1,
WriteInto(&mb, charcount), charcount, NULL, NULL);
return mb;
}
// While the shell API provides better calls than this home brew function
// we use GetSystemWindowsDirectoryW which does not query the registry so
// it is safe to use after revert.
std::wstring MakeFullPathToSystem32(const wchar_t* name) {
wchar_t windows_path[MAX_PATH] = {0};
::GetSystemWindowsDirectoryW(windows_path, MAX_PATH);
std::wstring full_path(windows_path);
if (full_path.empty()) {
return full_path;
}
full_path += L"\\system32\\";
full_path += name;
return full_path;
}
// Creates a process with the |exe| and |command| parameter using the
// unicode and ascii version of the api.
sandbox::SboxTestResult CreateProcessHelper(const std::wstring &exe,
const std::wstring &command) {
PROCESS_INFORMATION pi;
STARTUPINFOW si = {sizeof(si)};
wchar_t *exe_name = NULL;
if (!exe.empty())
exe_name = const_cast<wchar_t*>(exe.c_str());
wchar_t *cmd_line = NULL;
if (!command.empty())
cmd_line = const_cast<wchar_t*>(command.c_str());
// Create the process with the unicode version of the API.
sandbox::SboxTestResult ret1 = sandbox::SBOX_TEST_FAILED;
if (!::CreateProcessW(exe_name, cmd_line, NULL, NULL, FALSE, 0, NULL,
NULL, &si, &pi)) {
DWORD last_error = GetLastError();
if ((ERROR_NOT_ENOUGH_QUOTA == last_error) ||
(ERROR_ACCESS_DENIED == last_error) ||
(ERROR_FILE_NOT_FOUND == last_error)) {
ret1 = sandbox::SBOX_TEST_DENIED;
} else {
ret1 = sandbox::SBOX_TEST_FAILED;
}
} else {
ret1 = sandbox::SBOX_TEST_SUCCEEDED;
}
// Do the same with the ansi version of the api
STARTUPINFOA sia = {sizeof(sia)};
sandbox::SboxTestResult ret2 = sandbox::SBOX_TEST_FAILED;
if (!::CreateProcessA(
exe_name ? WideToMultiByte(exe_name).c_str() : NULL,
cmd_line ? const_cast<char*>(WideToMultiByte(cmd_line).c_str()) : NULL,
NULL, NULL, FALSE, 0, NULL, NULL, &sia, &pi)) {
DWORD last_error = GetLastError();
if ((ERROR_NOT_ENOUGH_QUOTA == last_error) ||
(ERROR_ACCESS_DENIED == last_error) ||
(ERROR_FILE_NOT_FOUND == last_error)) {
ret2 = sandbox::SBOX_TEST_DENIED;
} else {
ret2 = sandbox::SBOX_TEST_FAILED;
}
} else {
ret2 = sandbox::SBOX_TEST_SUCCEEDED;
}
if (ret1 == ret2)
return ret1;
return sandbox::SBOX_TEST_FAILED;
}
} // namespace
namespace sandbox {
// Tries to create the process in argv[0] using 7 different ways.
// Since we also try the Ansi and Unicode version of the CreateProcess API,
// The process referenced by argv[0] will be spawned 14 times.
SBOX_TESTS_COMMAND int Process_RunApp(int argc, wchar_t **argv) {
if (argc != 1) {
return SBOX_TEST_FAILED_TO_EXECUTE_COMMAND;
}
if ((NULL != argv) && (NULL == argv[0])) {
return SBOX_TEST_FAILED_TO_EXECUTE_COMMAND;
}
std::wstring path = MakeFullPathToSystem32(argv[0]);
// TEST 1: Try with the path in the app_name.
int result1 = CreateProcessHelper(path, std::wstring());
// TEST 2: Try with the path in the cmd_line.
std::wstring cmd_line = L"\"";
cmd_line += path;
cmd_line += L"\"";
int result2 = CreateProcessHelper(std::wstring(), cmd_line);
// TEST 3: Try file name in the cmd_line.
int result3 = CreateProcessHelper(std::wstring(), argv[0]);
// TEST 4: Try file name in the app_name and current directory sets correctly.
std::wstring system32 = MakeFullPathToSystem32(L"");
wchar_t current_directory[MAX_PATH + 1];
int result4;
bool test_succeeded = false;
DWORD ret = ::GetCurrentDirectory(MAX_PATH, current_directory);
if (0 != ret && ret < MAX_PATH) {
current_directory[ret] = L'\\';
current_directory[ret+1] = L'\0';
if (::SetCurrentDirectory(system32.c_str())) {
result4 = CreateProcessHelper(argv[0], std::wstring());
if (::SetCurrentDirectory(current_directory)) {
test_succeeded = true;
}
}
}
if (!test_succeeded)
result4 = SBOX_TEST_FAILED;
// TEST 5: Try with the path in the cmd_line and arguments.
cmd_line = L"\"";
cmd_line += path;
cmd_line += L"\" /INSERT";
int result5 = CreateProcessHelper(std::wstring(), cmd_line);
// TEST 6: Try with the file_name in the cmd_line and arguments.
cmd_line = argv[0];
cmd_line += L" /INSERT";
int result6 = CreateProcessHelper(std::wstring(), cmd_line);
// TEST 7: Try with the path without the drive.
cmd_line = path.substr(path.find(L'\\'));
int result7 = CreateProcessHelper(std::wstring(), cmd_line);
// Check if they all returned the same thing.
if ((result1 == result2) && (result2 == result3) && (result3 == result4) &&
(result4 == result5) && (result5 == result6) && (result6 == result7))
return result1;
return SBOX_TEST_FAILED;
}
// Creates a process and checks if it's possible to get a handle to it's token.
SBOX_TESTS_COMMAND int Process_GetChildProcessToken(int argc, wchar_t **argv) {
if (argc != 1)
return SBOX_TEST_FAILED_TO_EXECUTE_COMMAND;
if ((NULL != argv) && (NULL == argv[0]))
return SBOX_TEST_FAILED_TO_EXECUTE_COMMAND;
std::wstring path = MakeFullPathToSystem32(argv[0]);
PROCESS_INFORMATION pi = {0};
STARTUPINFOW si = {sizeof(si)};
if (!::CreateProcessW(path.c_str(), NULL, NULL, NULL, FALSE, CREATE_SUSPENDED,
NULL, NULL, &si, &pi)) {
return SBOX_TEST_FAILED;
}
ScopedHandle process(pi.hProcess);
ScopedHandle thread(pi.hThread);
HANDLE token = NULL;
BOOL result = ::OpenProcessToken(process.Get(), TOKEN_IMPERSONATE, &token);
DWORD error = ::GetLastError();
ScopedHandle token_handle(token);
if (!::TerminateProcess(process.Get(), 0))
return SBOX_TEST_FAILED;
if (result && token)
return SBOX_TEST_SUCCEEDED;
if (ERROR_ACCESS_DENIED == error)
return SBOX_TEST_DENIED;
return SBOX_TEST_FAILED;
}
SBOX_TESTS_COMMAND int Process_OpenToken(int argc, wchar_t **argv) {
HANDLE token;
if (!::OpenProcessToken(::GetCurrentProcess(), TOKEN_ALL_ACCESS, &token)) {
if (ERROR_ACCESS_DENIED == ::GetLastError()) {
return SBOX_TEST_DENIED;
}
} else {
::CloseHandle(token);
return SBOX_TEST_SUCCEEDED;
}
return SBOX_TEST_FAILED;
}
TEST(ProcessPolicyTest, TestAllAccess) {
// Check if the "all access" rule fails to be added when the token is too
// powerful.
TestRunner runner;
// Check the failing case.
runner.GetPolicy()->SetTokenLevel(USER_INTERACTIVE, USER_LOCKDOWN);
EXPECT_EQ(SBOX_ERROR_UNSUPPORTED,
runner.GetPolicy()->AddRule(TargetPolicy::SUBSYS_PROCESS,
TargetPolicy::PROCESS_ALL_EXEC,
L"this is not important"));
// Check the working case.
runner.GetPolicy()->SetTokenLevel(USER_INTERACTIVE, USER_INTERACTIVE);
EXPECT_EQ(SBOX_ALL_OK,
runner.GetPolicy()->AddRule(TargetPolicy::SUBSYS_PROCESS,
TargetPolicy::PROCESS_ALL_EXEC,
L"this is not important"));
}
// This test is disabled. See bug 1305476.
TEST(ProcessPolicyTest, DISABLED_RunFindstrExe) {
TestRunner runner;
std::wstring exe_path = MakeFullPathToSystem32(L"findstr.exe");
std::wstring system32 = MakeFullPathToSystem32(L"");
ASSERT_TRUE(!exe_path.empty());
EXPECT_TRUE(runner.AddRule(TargetPolicy::SUBSYS_PROCESS,
TargetPolicy::PROCESS_MIN_EXEC,
exe_path.c_str()));
// Need to add directory rules for the directories that we use in
// SetCurrentDirectory.
EXPECT_TRUE(runner.AddFsRule(TargetPolicy::FILES_ALLOW_DIR_ANY,
system32.c_str()));
wchar_t current_directory[MAX_PATH];
DWORD ret = ::GetCurrentDirectory(MAX_PATH, current_directory);
ASSERT_TRUE(0 != ret && ret < MAX_PATH);
wcscat_s(current_directory, MAX_PATH, L"\\");
EXPECT_TRUE(runner.AddFsRule(TargetPolicy::FILES_ALLOW_DIR_ANY,
current_directory));
EXPECT_EQ(SBOX_TEST_SUCCEEDED, runner.RunTest(L"Process_RunApp findstr.exe"));
EXPECT_EQ(SBOX_TEST_DENIED, runner.RunTest(L"Process_RunApp calc.exe"));
}
TEST(ProcessPolicyTest, OpenToken) {
TestRunner runner;
EXPECT_EQ(SBOX_TEST_SUCCEEDED, runner.RunTest(L"Process_OpenToken"));
}
TEST(ProcessPolicyTest, TestGetProcessTokenMinAccess) {
TestRunner runner;
std::wstring exe_path = MakeFullPathToSystem32(L"findstr.exe");
ASSERT_TRUE(!exe_path.empty());
EXPECT_TRUE(runner.AddRule(TargetPolicy::SUBSYS_PROCESS,
TargetPolicy::PROCESS_MIN_EXEC,
exe_path.c_str()));
EXPECT_EQ(SBOX_TEST_DENIED,
runner.RunTest(L"Process_GetChildProcessToken findstr.exe"));
}
TEST(ProcessPolicyTest, TestGetProcessTokenMaxAccess) {
TestRunner runner(JOB_UNPROTECTED, USER_INTERACTIVE, USER_INTERACTIVE);
std::wstring exe_path = MakeFullPathToSystem32(L"findstr.exe");
ASSERT_TRUE(!exe_path.empty());
EXPECT_TRUE(runner.AddRule(TargetPolicy::SUBSYS_PROCESS,
TargetPolicy::PROCESS_ALL_EXEC,
exe_path.c_str()));
EXPECT_EQ(SBOX_TEST_SUCCEEDED,
runner.RunTest(L"Process_GetChildProcessToken findstr.exe"));
}
} // namespace sandbox
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright 2008 by Sun Microsystems, Inc.
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: SlsPageObjectViewContact.cxx,v $
* $Revision: 1.9 $
*
* This file is part of OpenOffice.org.
*
* OpenOffice.org is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* only, as published by the Free Software Foundation.
*
* OpenOffice.org is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License version 3 for more details
* (a copy is included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with OpenOffice.org. If not, see
* <http://www.openoffice.org/license.html>
* for a copy of the LGPLv3 License.
*
************************************************************************/
#include "precompiled_sd.hxx"
#include "view/SlsPageObjectViewContact.hxx"
#include "model/SlsPageDescriptor.hxx"
#include "controller/SlsPageObjectFactory.hxx"
#include <svx/svdopage.hxx>
#include <tools/debug.hxx>
using namespace ::sdr::contact;
namespace sd { namespace slidesorter { namespace view {
PageObjectViewContact::PageObjectViewContact (
SdrPageObj& rPageObj,
const model::SharedPageDescriptor& rpDescriptor)
: ViewContactOfPageObj (rPageObj),
mbIsValid(true),
mpDescriptor(rpDescriptor)
{
}
PageObjectViewContact::~PageObjectViewContact (void)
{
}
ViewObjectContact&
PageObjectViewContact::CreateObjectSpecificViewObjectContact(
ObjectContact& rObjectContact)
{
OSL_ASSERT(mpDescriptor.get()!=NULL);
ViewObjectContact* pResult
= mpDescriptor->GetPageObjectFactory().CreateViewObjectContact (
rObjectContact,
*this);
DBG_ASSERT (pResult!=NULL,
"PageObjectViewContact::CreateObjectSpecificViewObjectContact() was not able to create object.");
return *pResult;
}
const SdrPage* PageObjectViewContact::GetPage (void) const
{
if (mbIsValid)
return GetReferencedPage();
else
return NULL;
}
void PageObjectViewContact::CalcPaintRectangle (void)
{
ViewContactOfPageObj::CalcPaintRectangle();
if (mbIsValid)
{
OSL_ASSERT(mpDescriptor.get()!=NULL);
maPageObjectBoundingBox = maPaintRectangle;
SvBorder aBorder (mpDescriptor->GetModelBorder());
maPaintRectangle.Left() -= aBorder.Left();
maPaintRectangle.Right() += aBorder.Right();
maPaintRectangle.Top() -= aBorder.Top();
maPaintRectangle.Bottom() += aBorder.Bottom();
}
}
Rectangle PageObjectViewContact::GetPageRectangle (void)
{
return GetPageObj().GetCurrentBoundRect();
}
void PageObjectViewContact::ActionChanged (void)
{
ViewContactOfPageObj::ActionChanged();
}
Rectangle PageObjectViewContact::GetPageObjectBoundingBox (void) const
{
return maPageObjectBoundingBox;
}
SdrPageObj& PageObjectViewContact::GetPageObject (void) const
{
return ViewContactOfPageObj::GetPageObj();
}
void PageObjectViewContact::PrepareDelete (void)
{
mbIsValid = false;
}
} } } // end of namespace ::sd::slidesorter::view
<commit_msg>INTEGRATION: CWS aw033 (1.7.46); FILE MERGED 2008/07/10 12:56:27 aw 1.7.46.7: #i39532# XOutputDevice removed, PrepareDelete removed 2008/06/24 15:34:31 aw 1.7.46.6: #i39532# corrections 2008/05/27 15:18:03 aw 1.7.46.5: #i39532# changes DEV300 m12 resync corrections 2008/05/16 13:06:05 aw 1.7.46.4: adaptions after resync 2008/05/14 14:51:19 aw 1.7.46.3: RESYNC: (1.7-1.9); FILE MERGED 2008/01/29 10:34:21 aw 1.7.46.2: updated refresh for ActionChanged(), diverse removals 2008/01/22 12:16:42 aw 1.7.46.1: adaptions and 1st stripping<commit_after>/*************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright 2008 by Sun Microsystems, Inc.
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: SlsPageObjectViewContact.cxx,v $
* $Revision: 1.10 $
*
* This file is part of OpenOffice.org.
*
* OpenOffice.org is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* only, as published by the Free Software Foundation.
*
* OpenOffice.org is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License version 3 for more details
* (a copy is included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with OpenOffice.org. If not, see
* <http://www.openoffice.org/license.html>
* for a copy of the LGPLv3 License.
*
************************************************************************/
#include "precompiled_sd.hxx"
#include "view/SlsPageObjectViewContact.hxx"
#include "model/SlsPageDescriptor.hxx"
#include "controller/SlsPageObjectFactory.hxx"
#include <svx/svdopage.hxx>
#include <tools/debug.hxx>
#include <basegfx/polygon/b2dpolygontools.hxx>
#include <drawinglayer/primitive2d/polygonprimitive2d.hxx>
using namespace ::sdr::contact;
namespace sd { namespace slidesorter { namespace view {
PageObjectViewContact::PageObjectViewContact (
SdrPageObj& rPageObj,
const model::SharedPageDescriptor& rpDescriptor)
: ViewContactOfPageObj (rPageObj),
mbInDestructor(false),
mpDescriptor(rpDescriptor)
{
}
PageObjectViewContact::~PageObjectViewContact (void)
{
// remember that this instance is in destruction
mbInDestructor = true;
}
ViewObjectContact&
PageObjectViewContact::CreateObjectSpecificViewObjectContact(
ObjectContact& rObjectContact)
{
OSL_ASSERT(mpDescriptor.get()!=NULL);
ViewObjectContact* pResult
= mpDescriptor->GetPageObjectFactory().CreateViewObjectContact (
rObjectContact,
*this);
DBG_ASSERT (pResult!=NULL,
"PageObjectViewContact::CreateObjectSpecificViewObjectContact() was not able to create object.");
return *pResult;
}
const SdrPage* PageObjectViewContact::GetPage (void) const
{
// when this instance itself is in destruction, do no longer
// provide the referenced page to VOC childs of this OC. This
// happens e.g. in destructor which destroys all child-VOCs which
// may in their implementation still reference their VC from
// their own destructor
if (!mbInDestructor)
return GetReferencedPage();
else
return NULL;
}
void PageObjectViewContact::ActionChanged (void)
{
ViewContactOfPageObj::ActionChanged();
}
Rectangle PageObjectViewContact::GetPageObjectBoundingBox (void) const
{
// use model data directly here
OSL_ASSERT(mpDescriptor.get()!=NULL);
Rectangle aRetval(GetPageObject().GetLastBoundRect());
const SvBorder aPageDescriptorBorder(mpDescriptor->GetModelBorder());
aRetval.Left() -= aPageDescriptorBorder.Left();
aRetval.Top() -= aPageDescriptorBorder.Top();
aRetval.Right() += aPageDescriptorBorder.Right();
aRetval.Bottom() += aPageDescriptorBorder.Bottom();
return aRetval;
}
SdrPageObj& PageObjectViewContact::GetPageObject (void) const
{
return ViewContactOfPageObj::GetPageObj();
}
drawinglayer::primitive2d::Primitive2DSequence PageObjectViewContact::createViewIndependentPrimitive2DSequence() const
{
// ceate graphical visualisation data. Since this is the view-independent version which should not be used,
// create a replacement graphic visualisation here. Use GetLastBoundRect to access the model data directly
// which is aOutRect for SdrPageObj.
OSL_ASSERT(mpDescriptor.get()!=NULL);
Rectangle aModelRectangle(GetPageObj().GetLastBoundRect());
const SvBorder aBorder(mpDescriptor->GetModelBorder());
aModelRectangle.Left() -= aBorder.Left();
aModelRectangle.Right() += aBorder.Right();
aModelRectangle.Top() -= aBorder.Top();
aModelRectangle.Bottom() += aBorder.Bottom();
const basegfx::B2DRange aModelRange(aModelRectangle.Left(), aModelRectangle.Top(), aModelRectangle.Right(), aModelRectangle.Bottom());
const basegfx::B2DPolygon aOutline(basegfx::tools::createPolygonFromRect(aModelRange));
const basegfx::BColor aYellow(1.0, 1.0, 0.0);
const drawinglayer::primitive2d::Primitive2DReference xReference(new drawinglayer::primitive2d::PolygonHairlinePrimitive2D(aOutline, aYellow));
return drawinglayer::primitive2d::Primitive2DSequence(&xReference, 1);
}
} } } // end of namespace ::sd::slidesorter::view
// eof
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright 2000, 2010 Oracle and/or its affiliates.
*
* OpenOffice.org - a multi-platform office productivity suite
*
* This file is part of OpenOffice.org.
*
* OpenOffice.org is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* only, as published by the Free Software Foundation.
*
* OpenOffice.org is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License version 3 for more details
* (a copy is included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with OpenOffice.org. If not, see
* <http://www.openoffice.org/license.html>
* for a copy of the LGPLv3 License.
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_sc.hxx"
#undef SC_DLLIMPLEMENTATION
//------------------------------------------------------------------
#include <vcl/msgbox.hxx>
#include "shtabdlg.hxx"
#include "scresid.hxx"
#include "miscdlgs.hrc"
//==================================================================
ScShowTabDlg::ScShowTabDlg( Window* pParent ) :
ModalDialog ( pParent, ScResId( RID_SCDLG_SHOW_TAB ) ),
aLb ( this, ScResId( LB_ENTRYLIST ) ),
aBtnOk ( this, ScResId( BTN_OK ) ),
aBtnCancel ( this, ScResId( BTN_CANCEL ) ),
aBtnHelp ( this, ScResId( BTN_HELP ) ),
aFtLbTitle ( this, ScResId( FT_LABEL ) )
{
aLb.Clear();
aLb.SetDoubleClickHdl( LINK( this, ScShowTabDlg, DblClkHdl ) );
//-------------
FreeResource();
}
//------------------------------------------------------------------------
void ScShowTabDlg::SetDescription(
const String& rTitle, const String& rFixedText,
ULONG nDlgHelpId, ULONG nLbHelpId )
{
SetText( rTitle );
aFtLbTitle.SetText( rFixedText );
// FIXME: HELPID
SetHelpId( ""/*nDlgHelpId*/ );
// FIXME: HELPID
aLb.SetHelpId( ""/*nLbHelpId*/ );
}
void ScShowTabDlg::Insert( const String& rString, BOOL bSelected )
{
aLb.InsertEntry( rString );
if( bSelected )
aLb.SelectEntryPos( aLb.GetEntryCount() - 1 );
}
//------------------------------------------------------------------------
USHORT ScShowTabDlg::GetSelectEntryCount() const
{
return aLb.GetSelectEntryCount();
}
String ScShowTabDlg::GetSelectEntry(USHORT nPos) const
{
return aLb.GetSelectEntry(nPos);
}
USHORT ScShowTabDlg::GetSelectEntryPos(USHORT nPos) const
{
return aLb.GetSelectEntryPos(nPos);
}
//------------------------------------------------------------------------
IMPL_LINK_INLINE_START( ScShowTabDlg, DblClkHdl, void *, EMPTYARG )
{
EndDialog( RET_OK );
return 0;
}
IMPL_LINK_INLINE_END( ScShowTabDlg, DblClkHdl, void *, EMPTYARG )
__EXPORT ScShowTabDlg::~ScShowTabDlg()
{
}
<commit_msg>fix warnings<commit_after>/*************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright 2000, 2010 Oracle and/or its affiliates.
*
* OpenOffice.org - a multi-platform office productivity suite
*
* This file is part of OpenOffice.org.
*
* OpenOffice.org is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* only, as published by the Free Software Foundation.
*
* OpenOffice.org is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License version 3 for more details
* (a copy is included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with OpenOffice.org. If not, see
* <http://www.openoffice.org/license.html>
* for a copy of the LGPLv3 License.
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_sc.hxx"
#undef SC_DLLIMPLEMENTATION
//------------------------------------------------------------------
#include <vcl/msgbox.hxx>
#include "shtabdlg.hxx"
#include "scresid.hxx"
#include "miscdlgs.hrc"
//==================================================================
ScShowTabDlg::ScShowTabDlg( Window* pParent ) :
ModalDialog ( pParent, ScResId( RID_SCDLG_SHOW_TAB ) ),
aLb ( this, ScResId( LB_ENTRYLIST ) ),
aBtnOk ( this, ScResId( BTN_OK ) ),
aBtnCancel ( this, ScResId( BTN_CANCEL ) ),
aBtnHelp ( this, ScResId( BTN_HELP ) ),
aFtLbTitle ( this, ScResId( FT_LABEL ) )
{
aLb.Clear();
aLb.SetDoubleClickHdl( LINK( this, ScShowTabDlg, DblClkHdl ) );
//-------------
FreeResource();
}
//------------------------------------------------------------------------
void ScShowTabDlg::SetDescription(
const String& rTitle, const String& rFixedText,
ULONG nDlgHelpId, ULONG nLbHelpId )
{
SetText( rTitle );
aFtLbTitle.SetText( rFixedText );
// FIXME: HELPID
SetHelpId( ""/*nDlgHelpId*/ );
(void)nDlgHelpId;
// FIXME: HELPID
aLb.SetHelpId( ""/*nLbHelpId*/ );
(void)nLbHelpId;
}
void ScShowTabDlg::Insert( const String& rString, BOOL bSelected )
{
aLb.InsertEntry( rString );
if( bSelected )
aLb.SelectEntryPos( aLb.GetEntryCount() - 1 );
}
//------------------------------------------------------------------------
USHORT ScShowTabDlg::GetSelectEntryCount() const
{
return aLb.GetSelectEntryCount();
}
String ScShowTabDlg::GetSelectEntry(USHORT nPos) const
{
return aLb.GetSelectEntry(nPos);
}
USHORT ScShowTabDlg::GetSelectEntryPos(USHORT nPos) const
{
return aLb.GetSelectEntryPos(nPos);
}
//------------------------------------------------------------------------
IMPL_LINK_INLINE_START( ScShowTabDlg, DblClkHdl, void *, EMPTYARG )
{
EndDialog( RET_OK );
return 0;
}
IMPL_LINK_INLINE_END( ScShowTabDlg, DblClkHdl, void *, EMPTYARG )
__EXPORT ScShowTabDlg::~ScShowTabDlg()
{
}
<|endoftext|>
|
<commit_before>/*===================================================================
The Medical Imaging Interaction Toolkit (MITK)
Copyright (c) German Cancer Research Center,
Division of Medical and Biological Informatics.
All rights reserved.
This software is distributed WITHOUT ANY WARRANTY; without
even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE.
See LICENSE.txt or http://www.mitk.org for details.
===================================================================*/
#include "mitkTestDICOMLoading.h"
#include "mitkTestingMacros.h"
bool CheckAllPropertiesAreInOtherList(const mitk::PropertyList* list, const mitk::PropertyList* otherList)
{
MITK_TEST_CONDITION_REQUIRED(list and otherList, "Comparison is passed two non-empty property lists")
const mitk::PropertyList::PropertyMap* listM = list->GetMap();
const mitk::PropertyList::PropertyMap* otherListM = otherList->GetMap();
bool equal = true;
for ( mitk::PropertyList::PropertyMap::const_iterator iter = listM->begin();
iter != listM->end();
++iter )
{
std::string key = iter->first;
mitk::BaseProperty* property = iter->second;
mitk::PropertyList::PropertyMap::const_iterator otherEntry = otherListM->find( key );
MITK_TEST_CONDITION( otherEntry != otherListM->end(), " Property '" << key << "' is contained in other list" )
mitk::BaseProperty* otherProperty = otherEntry->second;
MITK_TEST_CONDITION( equal &= (*property == *otherProperty), " Property '" << key << "' is equal in both list" )
}
return equal;
}
bool VerifyPropertyListsEquality(const mitk::PropertyList* testList, const mitk::PropertyList* referenceList)
{
bool allTestPropsInReference = CheckAllPropertiesAreInOtherList(testList, referenceList);
MITK_TEST_CONDITION(allTestPropsInReference, "All test properties found in reference properties")
bool allReferencePropsInTest = CheckAllPropertiesAreInOtherList(referenceList, testList);
MITK_TEST_CONDITION(allReferencePropsInTest, "All reference properties found in test properties")
return allTestPropsInReference && allReferencePropsInTest;
}
int mitkDICOMPreloadedVolumeTest(int argc, char** const argv)
{
MITK_TEST_BEGIN("DICOMPreloadedVolume")
mitk::TestDICOMLoading loader;
mitk::TestDICOMLoading::StringContainer files;
// adapt expectations depending on configuration
std::string configuration = mitk::DicomSeriesReader::GetConfigurationString();
MITK_TEST_OUTPUT(<< "Configuration: " << configuration)
// load files from commandline
for (int arg = 1; arg < argc; ++arg)
{
MITK_TEST_OUTPUT(<< "Test file " << argv[arg])
files.push_back( argv[arg] );
}
// verify all files are DICOM
for (mitk::TestDICOMLoading::StringContainer::const_iterator fileIter = files.begin();
fileIter != files.end();
++fileIter)
{
MITK_TEST_CONDITION_REQUIRED( mitk::DicomSeriesReader::IsDicom(*fileIter) , *fileIter << " is recognized as loadable DICOM object" )
}
// load for a first time
mitk::TestDICOMLoading::ImageList images = loader.LoadFiles(files);
MITK_TEST_OUTPUT(<< "Loaded " << images.size() << " images. Remembering properties of the first one for later comparison.")
mitk::Image::Pointer firstImage = images.front();
mitk::PropertyList::Pointer originalProperties = firstImage->GetPropertyList(); // save the original
firstImage->SetPropertyList( mitk::PropertyList::New() ); // clear image properties
// what about DEFAULT properties? currently ONLY nodes get default properties
// load for a second time, this time provide the image volume as a pointer
// expectation is that the reader will provide the same properties to this image (without actually loading a new mitk::Image)
mitk::TestDICOMLoading::ImageList reloadedImages = loader.LoadFiles(files, firstImage);
MITK_TEST_OUTPUT(<< "Again loaded " << reloadedImages.size() << " images. Comparing to previously loaded version.")
mitk::Image::Pointer reloadedImage = reloadedImages.front();
mitk::PropertyList::Pointer regeneratedProperties = reloadedImage->GetPropertyList(); // get the version of the second load attempt
bool listsAreEqual = VerifyPropertyListsEquality(regeneratedProperties, originalProperties);
MITK_TEST_CONDITION(listsAreEqual, "LoadDicomSeries generates a valid property list when provided a pre-loaded image");
MITK_TEST_END()
}
<commit_msg>COMP: use "&&" instead of "and"<commit_after>/*===================================================================
The Medical Imaging Interaction Toolkit (MITK)
Copyright (c) German Cancer Research Center,
Division of Medical and Biological Informatics.
All rights reserved.
This software is distributed WITHOUT ANY WARRANTY; without
even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE.
See LICENSE.txt or http://www.mitk.org for details.
===================================================================*/
#include "mitkTestDICOMLoading.h"
#include "mitkTestingMacros.h"
bool CheckAllPropertiesAreInOtherList(const mitk::PropertyList* list, const mitk::PropertyList* otherList)
{
MITK_TEST_CONDITION_REQUIRED(list && otherList, "Comparison is passed two non-empty property lists")
const mitk::PropertyList::PropertyMap* listM = list->GetMap();
const mitk::PropertyList::PropertyMap* otherListM = otherList->GetMap();
bool equal = true;
for ( mitk::PropertyList::PropertyMap::const_iterator iter = listM->begin();
iter != listM->end();
++iter )
{
std::string key = iter->first;
mitk::BaseProperty* property = iter->second;
mitk::PropertyList::PropertyMap::const_iterator otherEntry = otherListM->find( key );
MITK_TEST_CONDITION( otherEntry != otherListM->end(), " Property '" << key << "' is contained in other list" )
mitk::BaseProperty* otherProperty = otherEntry->second;
MITK_TEST_CONDITION( equal &= (*property == *otherProperty), " Property '" << key << "' is equal in both list" )
}
return equal;
}
bool VerifyPropertyListsEquality(const mitk::PropertyList* testList, const mitk::PropertyList* referenceList)
{
bool allTestPropsInReference = CheckAllPropertiesAreInOtherList(testList, referenceList);
MITK_TEST_CONDITION(allTestPropsInReference, "All test properties found in reference properties")
bool allReferencePropsInTest = CheckAllPropertiesAreInOtherList(referenceList, testList);
MITK_TEST_CONDITION(allReferencePropsInTest, "All reference properties found in test properties")
return allTestPropsInReference && allReferencePropsInTest;
}
int mitkDICOMPreloadedVolumeTest(int argc, char** const argv)
{
MITK_TEST_BEGIN("DICOMPreloadedVolume")
mitk::TestDICOMLoading loader;
mitk::TestDICOMLoading::StringContainer files;
// adapt expectations depending on configuration
std::string configuration = mitk::DicomSeriesReader::GetConfigurationString();
MITK_TEST_OUTPUT(<< "Configuration: " << configuration)
// load files from commandline
for (int arg = 1; arg < argc; ++arg)
{
MITK_TEST_OUTPUT(<< "Test file " << argv[arg])
files.push_back( argv[arg] );
}
// verify all files are DICOM
for (mitk::TestDICOMLoading::StringContainer::const_iterator fileIter = files.begin();
fileIter != files.end();
++fileIter)
{
MITK_TEST_CONDITION_REQUIRED( mitk::DicomSeriesReader::IsDicom(*fileIter) , *fileIter << " is recognized as loadable DICOM object" )
}
// load for a first time
mitk::TestDICOMLoading::ImageList images = loader.LoadFiles(files);
MITK_TEST_OUTPUT(<< "Loaded " << images.size() << " images. Remembering properties of the first one for later comparison.")
mitk::Image::Pointer firstImage = images.front();
mitk::PropertyList::Pointer originalProperties = firstImage->GetPropertyList(); // save the original
firstImage->SetPropertyList( mitk::PropertyList::New() ); // clear image properties
// what about DEFAULT properties? currently ONLY nodes get default properties
// load for a second time, this time provide the image volume as a pointer
// expectation is that the reader will provide the same properties to this image (without actually loading a new mitk::Image)
mitk::TestDICOMLoading::ImageList reloadedImages = loader.LoadFiles(files, firstImage);
MITK_TEST_OUTPUT(<< "Again loaded " << reloadedImages.size() << " images. Comparing to previously loaded version.")
mitk::Image::Pointer reloadedImage = reloadedImages.front();
mitk::PropertyList::Pointer regeneratedProperties = reloadedImage->GetPropertyList(); // get the version of the second load attempt
bool listsAreEqual = VerifyPropertyListsEquality(regeneratedProperties, originalProperties);
MITK_TEST_CONDITION(listsAreEqual, "LoadDicomSeries generates a valid property list when provided a pre-loaded image");
MITK_TEST_END()
}
<|endoftext|>
|
<commit_before>/*
* Copyright (c) 2016, Ford Motor Company
* 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 Ford Motor Company nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#include <stdint.h>
#include <string>
#include "application_manager/commands/mobile/add_sub_menu_request.h"
#include "gtest/gtest.h"
#include "application_manager/commands/commands_test.h"
#include "application_manager/commands/command_request_test.h"
#include "application_manager/mock_application_manager.h"
#include "application_manager/mock_application.h"
#include "application_manager/mock_message_helper.h"
#include "application_manager/event_engine/event.h"
#include "application_manager/mock_hmi_interface.h"
namespace test {
namespace components {
namespace commands_test {
namespace mobile_commands_test {
namespace add_sub_menu_request {
namespace am = ::application_manager;
using am::commands::AddSubMenuRequest;
using am::commands::MessageSharedPtr;
using am::event_engine::Event;
using ::testing::_;
using ::testing::Return;
typedef SharedPtr<AddSubMenuRequest> AddSubMenuPtr;
namespace {
const uint32_t kConnectionKey = 2u;
} // namespace
class AddSubMenuRequestTest
: public CommandRequestTest<CommandsTestMocks::kIsNice> {};
TEST_F(AddSubMenuRequestTest, OnEvent_UI_UNSUPPORTED_RESOURCE) {
const uint32_t menu_id = 10u;
MessageSharedPtr msg = CreateMessage(smart_objects::SmartType_Map);
(*msg)[am::strings::params][am::strings::connection_key] = kConnectionKey;
(*msg)[am::strings::msg_params][am::strings::menu_id] = menu_id;
utils::SharedPtr<AddSubMenuRequest> command =
CreateCommand<AddSubMenuRequest>(msg);
MockAppPtr mock_app = CreateMockApp();
ON_CALL(app_mngr_, application(kConnectionKey))
.WillByDefault(Return(mock_app));
ON_CALL(*mock_app, app_id()).WillByDefault(Return(kConnectionKey));
EXPECT_CALL(*mock_app, AddSubMenu(menu_id, _));
EXPECT_CALL(*mock_app, UpdateHash());
MessageSharedPtr ev_msg = CreateMessage(smart_objects::SmartType_Map);
(*ev_msg)[am::strings::params][am::hmi_response::code] =
hmi_apis::Common_Result::UNSUPPORTED_RESOURCE;
(*ev_msg)[am::strings::msg_params][am::strings::info] = "info";
Event event(hmi_apis::FunctionID::UI_AddSubMenu);
event.set_smart_object(*ev_msg);
MessageSharedPtr ui_command_result;
EXPECT_CALL(
app_mngr_,
ManageMobileCommand(_, am::commands::Command::CommandOrigin::ORIGIN_SDL))
.WillOnce(DoAll(SaveArg<0>(&ui_command_result), Return(true)));
command->Init();
command->on_event(event);
EXPECT_EQ((*ui_command_result)[am::strings::msg_params][am::strings::success]
.asBool(),
true);
EXPECT_EQ(
(*ui_command_result)[am::strings::msg_params][am::strings::result_code]
.asInt(),
static_cast<int32_t>(hmi_apis::Common_Result::UNSUPPORTED_RESOURCE));
if ((*ui_command_result)[am::strings::msg_params].keyExists(
am::strings::info)) {
EXPECT_FALSE(
(*ui_command_result)[am::strings::msg_params][am::strings::info]
.asString()
.empty());
}
}
} // namespace add_sub_menu_request
} // namespace mobile_commands_test
} // namespace commands_test
} // namespace components
} // namespace test
<commit_msg>updates for unit test<commit_after>/*
* Copyright (c) 2016, Ford Motor Company
* 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 Ford Motor Company nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#include <stdint.h>
#include <string>
#include "application_manager/commands/mobile/add_sub_menu_request.h"
#include "gtest/gtest.h"
#include "application_manager/commands/commands_test.h"
#include "application_manager/commands/command_request_test.h"
#include "application_manager/mock_application_manager.h"
#include "application_manager/mock_application.h"
#include "application_manager/mock_message_helper.h"
#include "application_manager/event_engine/event.h"
#include "application_manager/mock_hmi_interface.h"
namespace test {
namespace components {
namespace commands_test {
namespace mobile_commands_test {
namespace add_sub_menu_request {
namespace am = ::application_manager;
using am::commands::AddSubMenuRequest;
using am::commands::MessageSharedPtr;
using am::event_engine::Event;
using ::testing::_;
using ::testing::Return;
typedef SharedPtr<AddSubMenuRequest> AddSubMenuPtr;
namespace {
const uint32_t kConnectionKey = 2u;
const uint32_t kAppId = 1u;
} // namespace
class AddSubMenuRequestTest
: public CommandRequestTest<CommandsTestMocks::kIsNice> {
public:
AddSubMenuRequestTest()
: mock_app(CreateMockApp()) {
EXPECT_CALL(app_mngr_, application(kConnectionKey))
.WillRepeatedly(Return(mock_app));
}
MockAppPtr mock_app;
MessageSharedPtr CreateMsgParams() {
MessageSharedPtr msg = CreateMessage();
(*msg)[am::strings::params][am::strings::connection_key] = kConnectionKey;
(*msg)[am::strings::msg_params][am::strings::app_id] = kAppId;
return msg;
}
};
TEST_F(AddSubMenuRequestTest, Run_ImageVerificationFailed_EXPECT_INVALID_DATA) {
const uint32_t menu_id = 10u;
MessageSharedPtr msg = CreateMsgParams();
SmartObject& msg_params = (*msg)[am::strings::msg_params];
msg_params[am::strings::menu_icon] = 1;
msg_params[am::strings::menu_icon][am::strings::value] = "10";
msg_params[am::strings::menu_id] = menu_id;
msg_params[am::strings::menu_name] = "test";
SmartObject& image = msg_params[am::strings::menu_icon];
EXPECT_CALL(mock_message_helper_, VerifyImage(image, _, _))
.WillOnce(Return(mobile_apis::Result::INVALID_DATA));
EXPECT_CALL(app_mngr_,
ManageMobileCommand(MobileResultCodeIs(mobile_apis::Result::INVALID_DATA), _));
utils::SharedPtr<AddSubMenuRequest> request_ptr =
CreateCommand<AddSubMenuRequest>(msg);
request_ptr->Run();
}
TEST_F(AddSubMenuRequestTest, OnEvent_UI_UNSUPPORTED_RESOURCE) {
const uint32_t menu_id = 10u;
MessageSharedPtr msg = CreateMessage(smart_objects::SmartType_Map);
(*msg)[am::strings::params][am::strings::connection_key] = kConnectionKey;
(*msg)[am::strings::msg_params][am::strings::menu_id] = menu_id;
utils::SharedPtr<AddSubMenuRequest> command =
CreateCommand<AddSubMenuRequest>(msg);
ON_CALL(app_mngr_, application(kConnectionKey))
.WillByDefault(Return(mock_app));
ON_CALL(*mock_app, app_id()).WillByDefault(Return(kConnectionKey));
EXPECT_CALL(*mock_app, AddSubMenu(menu_id, _));
EXPECT_CALL(*mock_app, UpdateHash());
MessageSharedPtr ev_msg = CreateMessage(smart_objects::SmartType_Map);
(*ev_msg)[am::strings::params][am::hmi_response::code] =
hmi_apis::Common_Result::UNSUPPORTED_RESOURCE;
(*ev_msg)[am::strings::msg_params][am::strings::info] = "info";
Event event(hmi_apis::FunctionID::UI_AddSubMenu);
event.set_smart_object(*ev_msg);
MessageSharedPtr ui_command_result;
EXPECT_CALL(
app_mngr_,
ManageMobileCommand(_, am::commands::Command::CommandOrigin::ORIGIN_SDL))
.WillOnce(DoAll(SaveArg<0>(&ui_command_result), Return(true)));
command->Init();
command->on_event(event);
EXPECT_EQ((*ui_command_result)[am::strings::msg_params][am::strings::success]
.asBool(),
true);
EXPECT_EQ(
(*ui_command_result)[am::strings::msg_params][am::strings::result_code]
.asInt(),
static_cast<int32_t>(hmi_apis::Common_Result::UNSUPPORTED_RESOURCE));
if ((*ui_command_result)[am::strings::msg_params].keyExists(
am::strings::info)) {
EXPECT_FALSE(
(*ui_command_result)[am::strings::msg_params][am::strings::info]
.asString()
.empty());
}
}
} // namespace add_sub_menu_request
} // namespace mobile_commands_test
} // namespace commands_test
} // namespace components
} // namespace test
<|endoftext|>
|
<commit_before>/*
Copyright (c) 2014, Project OSRM, Felix Guendling
All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
Redistributions of source code must retain the above copyright notice, this list
of conditions and the following disclaimer.
Redistributions in binary form must reproduce the above copyright notice, this
list of conditions and the following disclaimer in the documentation and/or
other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef MULTI_TARGET_ROUTING_H
#define MULTI_TARGET_ROUTING_H
#include "routing_base.hpp"
#include "../data_structures/search_engine_data.hpp"
#include "../typedefs.h"
#include <boost/assert.hpp>
#include <memory>
#include <vector>
template <class DataFacadeT, bool forward>
class MultiTargetRouting final : public BasicRoutingInterface<DataFacadeT, MultiTargetRouting<DataFacadeT, forward>>
{
typedef BasicRoutingInterface<DataFacadeT, MultiTargetRouting<DataFacadeT, forward>> super;
typedef SearchEngineData::QueryHeap QueryHeap;
SearchEngineData &engine_working_data;
public:
MultiTargetRouting(DataFacadeT *facade, SearchEngineData &engine_working_data)
: super(facade), engine_working_data(engine_working_data)
{
}
~MultiTargetRouting() {}
std::shared_ptr<std::vector<std::pair<EdgeWeight, double>>>
operator()(const PhantomNodeArray &phantom_nodes_array) const
{
BOOST_ASSERT(phantom_nodes_array.size() >= 2);
// Prepare results table:
// Each target (phantom_nodes_array[1], ..., phantom_nodes_array[n]) has its own index.
auto results = std::make_shared<std::vector<std::pair<EdgeWeight, double>>>();
results->reserve(phantom_nodes_array.size() - 1);
// For readability: some reference variables making it clear,
// which one is the source and which are the targets.
const auto &source = phantom_nodes_array[0];
std::vector<std::reference_wrapper<const std::vector<PhantomNode>>> targets(
std::next(begin(phantom_nodes_array)), end(phantom_nodes_array));
engine_working_data.InitializeOrClearFirstThreadLocalStorage(
super::facade->GetNumberOfNodes());
// The forward heap keeps the distances from the source.
// Therefore it will be reused for each target backward search.
QueryHeap &forward_heap = *(engine_working_data.forward_heap_1);
// The reverse heap will be cleared after each search from
// one of the targets to the source.
QueryHeap &reverse_heap = *(engine_working_data.reverse_heap_1);
// Fill forward heap with the source location phantom node(s).
// The source location is located at index 0.
// The target locations are located at index [1, ..., n].
EdgeWeight min_edge_offset = 0;
for (const PhantomNode &phantom_node : source)
{
if (SPECIAL_NODEID != phantom_node.forward_node_id)
{
EdgeWeight offset = (forward ? -1 : 1) * phantom_node.GetForwardWeightPlusOffset();
forward_heap.Insert(phantom_node.forward_node_id, offset,
phantom_node.forward_node_id);
min_edge_offset = std::min(min_edge_offset, offset);
}
if (SPECIAL_NODEID != phantom_node.reverse_node_id)
{
EdgeWeight offset = (forward ? -1 : 1) * phantom_node.GetReverseWeightPlusOffset();
forward_heap.Insert(phantom_node.reverse_node_id,
(forward ? -1 : 1) * phantom_node.GetReverseWeightPlusOffset(),
phantom_node.reverse_node_id);
min_edge_offset = std::min(min_edge_offset, offset);
}
}
for (auto const &target : targets)
{
const std::vector<PhantomNode> &phantom_node_vector = target;
auto result = FindShortestPath(source, phantom_node_vector, forward_heap, reverse_heap,
min_edge_offset);
results->emplace_back(std::move(result));
}
forward_heap.Clear();
reverse_heap.Clear();
return results;
}
std::pair<EdgeWeight, double> FindShortestPath(const std::vector<PhantomNode> &source,
const std::vector<PhantomNode> &target,
QueryHeap &forward_heap,
QueryHeap &backward_heap,
EdgeWeight min_edge_offset) const
{
NodeID middle = UINT_MAX;
int local_upper_bound = INT_MAX;
// Clear backward heap from the entries produced by the search to the last target
// and initialize heap for this target.
backward_heap.Clear();
for (const PhantomNode &phantom_node : target)
{
if (SPECIAL_NODEID != phantom_node.forward_node_id)
{
EdgeWeight offset = (forward ? 1 : -1) * phantom_node.GetForwardWeightPlusOffset();
backward_heap.Insert(phantom_node.forward_node_id, offset,
phantom_node.forward_node_id);
min_edge_offset = std::min(min_edge_offset, offset);
}
if (SPECIAL_NODEID != phantom_node.reverse_node_id)
{
EdgeWeight offset = (forward ? 1 : -1) * phantom_node.GetReverseWeightPlusOffset();
backward_heap.Insert(phantom_node.reverse_node_id, offset,
phantom_node.reverse_node_id);
min_edge_offset = std::min(min_edge_offset, offset);
}
}
// Execute bidirectional Dijkstra shortest path search.
while (0 < backward_heap.Size() || 0 < forward_heap.Size())
{
if (0 < forward_heap.Size())
{
super::RoutingStep(forward_heap, backward_heap, &middle, &local_upper_bound,
min_edge_offset, forward, false);
}
if (0 < backward_heap.Size())
{
super::RoutingStep(backward_heap, forward_heap, &middle, &local_upper_bound,
min_edge_offset, !forward);
}
}
// Check if no path could be found (-> early exit).
if (INVALID_EDGE_WEIGHT == local_upper_bound)
{
return std::make_pair(INVALID_EDGE_WEIGHT, 0);
}
// Calculate exact distance in km.
std::vector<NodeID> packed_path;
super::RetrievePackedPathFromHeap(forward_heap, backward_heap, middle, packed_path);
if (!forward)
{
std::reverse(begin(packed_path), end(packed_path));
}
auto source_phantom_it =
std::find_if(begin(source), end(source), [&packed_path](PhantomNode const &node)
{
return node.forward_node_id == packed_path[forward ? 0 : packed_path.size() - 1] ||
node.reverse_node_id == packed_path[forward ? 0 : packed_path.size() - 1];
});
auto target_phantom_it =
std::find_if(begin(target), end(target), [&packed_path](PhantomNode const &node)
{
return node.forward_node_id == packed_path[forward ? packed_path.size() - 1 : 0] ||
node.reverse_node_id == packed_path[forward ? packed_path.size() - 1 : 0];
});
BOOST_ASSERT(source_phantom_it != end(source));
BOOST_ASSERT(target_phantom_it != end(target));
std::vector<PathData> unpacked_path;
if (forward)
{
super::UnpackPath(packed_path, {*source_phantom_it, *target_phantom_it}, unpacked_path);
}
else
{
super::UnpackPath(packed_path, {*target_phantom_it, *source_phantom_it}, unpacked_path);
}
std::vector<FixedPointCoordinate> coordinates;
coordinates.reserve(unpacked_path.size() + 2);
coordinates.emplace_back(forward ? source_phantom_it->location
: target_phantom_it->location);
for (const auto &path_data : unpacked_path)
{
coordinates.emplace_back(super::facade->GetCoordinateOfNode(path_data.node));
}
coordinates.emplace_back(forward ? target_phantom_it->location
: source_phantom_it->location);
double distance = 0.0;
for (int i = 1; i < coordinates.size(); ++i)
{
distance += coordinate_calculation::euclidean_distance(coordinates[i - 1],
coordinates[i]);
}
return std::make_pair(round(local_upper_bound / 10.), distance);
}
};
#endif
<commit_msg>fix compiler warning<commit_after>/*
Copyright (c) 2014, Project OSRM, Felix Guendling
All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
Redistributions of source code must retain the above copyright notice, this list
of conditions and the following disclaimer.
Redistributions in binary form must reproduce the above copyright notice, this
list of conditions and the following disclaimer in the documentation and/or
other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef MULTI_TARGET_ROUTING_H
#define MULTI_TARGET_ROUTING_H
#include "routing_base.hpp"
#include "../data_structures/search_engine_data.hpp"
#include "../typedefs.h"
#include <boost/assert.hpp>
#include <memory>
#include <vector>
template <class DataFacadeT, bool forward>
class MultiTargetRouting final : public BasicRoutingInterface<DataFacadeT, MultiTargetRouting<DataFacadeT, forward>>
{
typedef BasicRoutingInterface<DataFacadeT, MultiTargetRouting<DataFacadeT, forward>> super;
typedef SearchEngineData::QueryHeap QueryHeap;
SearchEngineData &engine_working_data;
public:
MultiTargetRouting(DataFacadeT *facade, SearchEngineData &engine_working_data)
: super(facade), engine_working_data(engine_working_data)
{
}
~MultiTargetRouting() {}
std::shared_ptr<std::vector<std::pair<EdgeWeight, double>>>
operator()(const PhantomNodeArray &phantom_nodes_array) const
{
BOOST_ASSERT(phantom_nodes_array.size() >= 2);
// Prepare results table:
// Each target (phantom_nodes_array[1], ..., phantom_nodes_array[n]) has its own index.
auto results = std::make_shared<std::vector<std::pair<EdgeWeight, double>>>();
results->reserve(phantom_nodes_array.size() - 1);
// For readability: some reference variables making it clear,
// which one is the source and which are the targets.
const auto &source = phantom_nodes_array[0];
std::vector<std::reference_wrapper<const std::vector<PhantomNode>>> targets(
std::next(begin(phantom_nodes_array)), end(phantom_nodes_array));
engine_working_data.InitializeOrClearFirstThreadLocalStorage(
super::facade->GetNumberOfNodes());
// The forward heap keeps the distances from the source.
// Therefore it will be reused for each target backward search.
QueryHeap &forward_heap = *(engine_working_data.forward_heap_1);
// The reverse heap will be cleared after each search from
// one of the targets to the source.
QueryHeap &reverse_heap = *(engine_working_data.reverse_heap_1);
// Fill forward heap with the source location phantom node(s).
// The source location is located at index 0.
// The target locations are located at index [1, ..., n].
EdgeWeight min_edge_offset = 0;
for (const PhantomNode &phantom_node : source)
{
if (SPECIAL_NODEID != phantom_node.forward_node_id)
{
EdgeWeight offset = (forward ? -1 : 1) * phantom_node.GetForwardWeightPlusOffset();
forward_heap.Insert(phantom_node.forward_node_id, offset,
phantom_node.forward_node_id);
min_edge_offset = std::min(min_edge_offset, offset);
}
if (SPECIAL_NODEID != phantom_node.reverse_node_id)
{
EdgeWeight offset = (forward ? -1 : 1) * phantom_node.GetReverseWeightPlusOffset();
forward_heap.Insert(phantom_node.reverse_node_id,
(forward ? -1 : 1) * phantom_node.GetReverseWeightPlusOffset(),
phantom_node.reverse_node_id);
min_edge_offset = std::min(min_edge_offset, offset);
}
}
for (auto const &target : targets)
{
const std::vector<PhantomNode> &phantom_node_vector = target;
auto result = FindShortestPath(source, phantom_node_vector, forward_heap, reverse_heap,
min_edge_offset);
results->emplace_back(std::move(result));
}
forward_heap.Clear();
reverse_heap.Clear();
return results;
}
std::pair<EdgeWeight, double> FindShortestPath(const std::vector<PhantomNode> &source,
const std::vector<PhantomNode> &target,
QueryHeap &forward_heap,
QueryHeap &backward_heap,
EdgeWeight min_edge_offset) const
{
NodeID middle = UINT_MAX;
int local_upper_bound = INT_MAX;
// Clear backward heap from the entries produced by the search to the last target
// and initialize heap for this target.
backward_heap.Clear();
for (const PhantomNode &phantom_node : target)
{
if (SPECIAL_NODEID != phantom_node.forward_node_id)
{
EdgeWeight offset = (forward ? 1 : -1) * phantom_node.GetForwardWeightPlusOffset();
backward_heap.Insert(phantom_node.forward_node_id, offset,
phantom_node.forward_node_id);
min_edge_offset = std::min(min_edge_offset, offset);
}
if (SPECIAL_NODEID != phantom_node.reverse_node_id)
{
EdgeWeight offset = (forward ? 1 : -1) * phantom_node.GetReverseWeightPlusOffset();
backward_heap.Insert(phantom_node.reverse_node_id, offset,
phantom_node.reverse_node_id);
min_edge_offset = std::min(min_edge_offset, offset);
}
}
// Execute bidirectional Dijkstra shortest path search.
while (0 < backward_heap.Size() || 0 < forward_heap.Size())
{
if (0 < forward_heap.Size())
{
super::RoutingStep(forward_heap, backward_heap, &middle, &local_upper_bound,
min_edge_offset, forward, false);
}
if (0 < backward_heap.Size())
{
super::RoutingStep(backward_heap, forward_heap, &middle, &local_upper_bound,
min_edge_offset, !forward);
}
}
// Check if no path could be found (-> early exit).
if (INVALID_EDGE_WEIGHT == local_upper_bound)
{
return std::make_pair(INVALID_EDGE_WEIGHT, 0);
}
// Calculate exact distance in km.
std::vector<NodeID> packed_path;
super::RetrievePackedPathFromHeap(forward_heap, backward_heap, middle, packed_path);
if (!forward)
{
std::reverse(begin(packed_path), end(packed_path));
}
auto source_phantom_it =
std::find_if(begin(source), end(source), [&packed_path](PhantomNode const &node)
{
return node.forward_node_id == packed_path[forward ? 0 : packed_path.size() - 1] ||
node.reverse_node_id == packed_path[forward ? 0 : packed_path.size() - 1];
});
auto target_phantom_it =
std::find_if(begin(target), end(target), [&packed_path](PhantomNode const &node)
{
return node.forward_node_id == packed_path[forward ? packed_path.size() - 1 : 0] ||
node.reverse_node_id == packed_path[forward ? packed_path.size() - 1 : 0];
});
BOOST_ASSERT(source_phantom_it != end(source));
BOOST_ASSERT(target_phantom_it != end(target));
std::vector<PathData> unpacked_path;
if (forward)
{
super::UnpackPath(packed_path, {*source_phantom_it, *target_phantom_it}, unpacked_path);
}
else
{
super::UnpackPath(packed_path, {*target_phantom_it, *source_phantom_it}, unpacked_path);
}
std::vector<FixedPointCoordinate> coordinates;
coordinates.reserve(unpacked_path.size() + 2);
coordinates.emplace_back(forward ? source_phantom_it->location
: target_phantom_it->location);
for (const auto &path_data : unpacked_path)
{
coordinates.emplace_back(super::facade->GetCoordinateOfNode(path_data.node));
}
coordinates.emplace_back(forward ? target_phantom_it->location
: source_phantom_it->location);
double distance = 0.0;
for (size_t i = 1; i < coordinates.size(); ++i)
{
distance += coordinate_calculation::euclidean_distance(coordinates[i - 1],
coordinates[i]);
}
return std::make_pair(round(local_upper_bound / 10.), distance);
}
};
#endif
<|endoftext|>
|
<commit_before>#include "mopViewer.h"
mopViewer::mopViewer() {
}
mopViewer::~mopViewer() {
}
void mopViewer::showStats() {
mopfile = new MopFile();
mopfile->setFilename("Testing_Project.mop");
mopfile->openMopfileReader();
mopstate = new MopState();
mopstate = mopfile->readCyclingState();
mopstate = mopfile->readCyclingState();
std::cout << "Item Count: " << mopstate->getItemCount() << std::endl;
for (int i = 0; i < mopstate->getItemCount(); i++) {
std::cout << "Particle "<< i << " X value: " << mopstate->getMopItem(i).x << std::endl;
std::cout << "Particle "<< i << " Y value: " << mopstate->getMopItem(i).y << std::endl;
std::cout << "Particle "<< i << " Z value: " << mopstate->getMopItem(i).z << std::endl;
}
int x, y, x2, y2, x3, y3;
nCurses nCurse;
// nCurse.start(true, true, true, false);sd
initscr();
raw();
nCurse.startColour();
getmaxyx(stdscr, x, y);
init_pair(1, COLOR_WHITE, COLOR_BLACK);
init_pair(2, COLOR_BLACK, COLOR_WHITE);
wbkgd(stdscr, COLOR_PAIR(1));
wattron(stdscr, COLOR_PAIR(1));
nCurse.drawBox(stdscr, ACS_VLINE, ACS_HLINE);
WINDOW *window1 = newwin(x-4, (y/2)-5, 2, 2);
wbkgd(window1, COLOR_PAIR(2));
nCurse.drawBox(window1, ACS_VLINE, ACS_HLINE);
WINDOW *window2 = newwin(x-4, (y/2)-5, 2, (y/2)+2);
wbkgd(window2, COLOR_PAIR(2));
nCurse.drawBox(window2, ACS_VLINE, ACS_HLINE);
wattron(stdscr, A_BOLD);
mvwprintw(stdscr, 1, (y/2)-10, "Welcome to Mopviewer");
getmaxyx(window1, x2, y2);
getmaxyx(window2, x3, y3);
//Get the output for sizes of windows, helps me
std::cout << "Max X: " << x << std::endl;
std::cout << "Max Y: " << y << std::endl;
std::cout << "Max X1: " << x2 << std::endl;
std::cout << "Max Y1: " << y2 << std::endl;
std::cout << "Max X2: " << x3 << std::endl;
std::cout << "Max Y2: " << y3 << std::endl;
//Display the information to screen
int currentRow = 1;
int currentRow2 = 1;
for (int i = 0; i < mopstate->getItemCount(); i++) {
if(currentRow >= (x2-1)){
mvwprintw(window2, currentRow2,1, "Particle Number: %d", i);
currentRow2++;
mvwprintw(window2, currentRow2,1, "Particle X %f", mopstate->getMopItem(i).x);
currentRow2++;
mvwprintw(window2, currentRow2,1, "Particle Y: %f", mopstate->getMopItem(i).y);
currentRow2++;
mvwprintw(window2, currentRow2,1, "Particle Z %f", mopstate->getMopItem(i).z);
currentRow2++;
mvwprintw(window2, currentRow2,1, "Particle Red: %d", mopstate->getMopItem(i).red);
currentRow2++;
mvwprintw(window2, currentRow2,1, "Particle Green %d", mopstate->getMopItem(i).green);
currentRow2++;
mvwprintw(window2, currentRow2,1, "Particle Blue: %d", mopstate->getMopItem(i).blue);
currentRow2+=2;
}
else{
mvwprintw(window1, currentRow,1, "Particle Number: %d", i);
currentRow++;
mvwprintw(window1, currentRow,1, "Particle X %f", mopstate->getMopItem(i).x);
currentRow++;
mvwprintw(window1, currentRow,1, "Particle Y: %f", mopstate->getMopItem(i).y);
currentRow++;
mvwprintw(window1, currentRow,1, "Particle Z %f", mopstate->getMopItem(i).z);
currentRow++;
mvwprintw(window1, currentRow,1, "Particle Red: %d", mopstate->getMopItem(i).red);
currentRow++;
mvwprintw(window1, currentRow,1, "Particle Green %d", mopstate->getMopItem(i).green);
currentRow++;
mvwprintw(window1, currentRow,1, "Particle Blue: %d", mopstate->getMopItem(i).blue);
currentRow+=2;
}
}
refresh();
wrefresh(window1);
wrefresh(window2);
std::cout << "Amount per column: " << std::endl;
getch();
endwin();
}
void mopViewer::selectGame() {
int mx = 0, my = 0, mx2 = 0, my2 = 0;
char welcome[] = "Enter 1 to View Stats and 2 to Open MopViewer: ";
char exitMessage[] = "Enter anything else to exit";
// Create inital screen. Better to replace
// with the single start function from moody
WINDOW *myWindow = initscr();
raw();
cbreak();
keypad(myWindow, TRUE);
// noecho();
// Enable use of colour on screen
start_color();
// Create two colour pairs for the different screens
init_pair(1, COLOR_BLACK, COLOR_CYAN);
init_pair(2, COLOR_BLACK, COLOR_RED);
init_pair(3, COLOR_WHITE, COLOR_BLACK);
// Set the colour scheme of window 1 to pair 1
wattron(myWindow, COLOR_PAIR(1));
// Set background of main window to colour scheme 1
wbkgd(myWindow, COLOR_PAIR(1));
// Create a border for the main console screen
box(myWindow, ACS_BULLET, ACS_BULLET);
// Make a new window that is a sub window of
// main window and add a border to it
getmaxyx(myWindow, mx, my);
WINDOW *myWindow2 = subwin(myWindow, mx-5, my-5, 3, 3);
box(myWindow2, ACS_VLINE, ACS_HLINE);
// Get the max size of both windows for use later on
getmaxyx(myWindow, mx, my);
getmaxyx(myWindow2, mx2, my2);
// Set background and colour shceme of child window
wattron(myWindow2, COLOR_PAIR(2));
wbkgd(myWindow2, COLOR_PAIR(2));
// Add the title string to the main window
mvaddstr(1, (my2/2)-10, "Welcome to MopViewer!");
// Print string to second window at the x,y co-ordinates specificed
mvwprintw(myWindow2, mx2/2, ((my2-std::strlen(welcome))/2), "%s", welcome);
mvwprintw(myWindow2, (mx2/2)+10, ((my2-std::strlen(exitMessage))/2), "%s", exitMessage);
wmove(myWindow, (mx2/2)+5, ((my2/2)+std::strlen(welcome)));
// Refresh main window otherwise background colour won't show for some reason
wrefresh(myWindow);
char inputString[1];
// Get the input into inputString
wgetstr(myWindow2, inputString);
mopViewer mopViewers;
testWindow newWindow;
if (inputString[0] == '1') {
clear();
refresh();
endwin();
mopViewers.showStats();
} else if (inputString[0] == '2') {
clear();
refresh();
endwin();
newWindow.init();
mopViewers.selectGame();
}
endwin();
}
<commit_msg>Add option to cycle through particles using right arrow<commit_after>#include "mopViewer.h"
mopViewer::mopViewer() {
}
mopViewer::~mopViewer() {
}
void mopViewer::showStats() {
mopfile = new MopFile();
mopfile->setFilename("Testing_Project.mop");
mopfile->openMopfileReader();
mopstate = new MopState();
mopstate = mopfile->readCyclingState();
mopstate = mopfile->readCyclingState();
std::cout << "Item Count: " << mopstate->getItemCount() << std::endl;
for (int i = 0; i < mopstate->getItemCount(); i++) {
std::cout << "Particle "<< i << " X value: " << mopstate->getMopItem(i).x << std::endl;
std::cout << "Particle "<< i << " Y value: " << mopstate->getMopItem(i).y << std::endl;
std::cout << "Particle "<< i << " Z value: " << mopstate->getMopItem(i).z << std::endl;
}
int x, y, x2, y2, x3, y3;
nCurses nCurse;
// nCurse.start(true, true, true, false);sd
initscr();
raw();
nCurse.startColour();
getmaxyx(stdscr, x, y);
init_pair(1, COLOR_WHITE, COLOR_BLACK);
init_pair(2, COLOR_BLACK, COLOR_WHITE);
wbkgd(stdscr, COLOR_PAIR(1));
wattron(stdscr, COLOR_PAIR(1));
nCurse.drawBox(stdscr, ACS_VLINE, ACS_HLINE);
WINDOW *window1 = newwin(x-4, (y/2)-5, 2, 2);
wbkgd(window1, COLOR_PAIR(2));
nCurse.drawBox(window1, ACS_VLINE, ACS_HLINE);
WINDOW *window2 = newwin(x-4, (y/2)-5, 2, (y/2)+2);
wbkgd(window2, COLOR_PAIR(2));
nCurse.drawBox(window2, ACS_VLINE, ACS_HLINE);
wattron(stdscr, A_BOLD);
mvwprintw(stdscr, 1, (y/2)-10, "Welcome to Mopviewer");
getmaxyx(window1, x2, y2);
getmaxyx(window2, x3, y3);
//Get the output for sizes of windows, helps me
std::cout << "Max X: " << x << std::endl;
std::cout << "Max Y: " << y << std::endl;
std::cout << "Max X1: " << x2 << std::endl;
std::cout << "Max Y1: " << y2 << std::endl;
std::cout << "Max X2: " << x3 << std::endl;
std::cout << "Max Y2: " << y3 << std::endl;
float maxitems = (x2-2)/8;
float maxremainder = ((x2-2)%8);
std::cout << "Max amount of items per column: " << maxitems << std::endl;
std::cout << "Max amount of remainders per column: " << maxremainder << std::endl;
//Display the information to screen
int currentRow = 1;
int currentRow2 = 1;
int currentitem = 0;
for (int i = 0; i < (2*maxitems); i++) {
if((currentRow >= (8*maxitems))){
mvwprintw(window2, currentRow2,1, "Particle Number: %d", currentitem);
currentRow2++;
mvwprintw(window2, currentRow2,1, "Particle X %f", mopstate->getMopItem(currentitem).x);
currentRow2++;
mvwprintw(window2, currentRow2,1, "Particle Y: %f", mopstate->getMopItem(currentitem).y);
currentRow2++;
mvwprintw(window2, currentRow2,1, "Particle Z %f", mopstate->getMopItem(currentitem).z);
currentRow2++;
mvwprintw(window2, currentRow2,1, "Particle Red: %d", mopstate->getMopItem(currentitem).red);
currentRow2++;
mvwprintw(window2, currentRow2,1, "Particle Green %d", mopstate->getMopItem(currentitem).green);
currentRow2++;
mvwprintw(window2, currentRow2,1, "Particle Blue: %d", mopstate->getMopItem(currentitem).blue);
currentRow2+=2;
currentitem++;
}
else{
mvwprintw(window1, currentRow,1, "Particle Number: %d", currentitem);
currentRow++;
mvwprintw(window1, currentRow,1, "Particle X %f", mopstate->getMopItem(currentitem).x);
currentRow++;
mvwprintw(window1, currentRow,1, "Particle Y: %f", mopstate->getMopItem(currentitem).y);
currentRow++;
mvwprintw(window1, currentRow,1, "Particle Z %f", mopstate->getMopItem(currentitem).z);
currentRow++;
mvwprintw(window1, currentRow,1, "Particle Red: %d", mopstate->getMopItem(currentitem).red);
currentRow++;
mvwprintw(window1, currentRow,1, "Particle Green %d", mopstate->getMopItem(currentitem).green);
currentRow++;
mvwprintw(window1, currentRow,1, "Particle Blue: %d", mopstate->getMopItem(currentitem).blue);
currentRow+=2;
currentitem++;
}
}
refresh();
wrefresh(window1);
wrefresh(window2);
int ch;
while((ch = getch()) != GLFW_KEY_2)
{ switch(ch) {
case KEY_RIGHT:
currentRow = 1;
currentRow2 = 1;
for (int i = 0; i < (2*maxitems); i++) {
if((currentRow >= (8*maxitems)) && (currentitem <= mopstate->getItemCount())){
mvwprintw(window2, currentRow2,1, "Particle Number: %d", currentitem);
currentRow2++;
mvwprintw(window2, currentRow2,1, "Particle X %f", mopstate->getMopItem(currentitem).x);
currentRow2++;
mvwprintw(window2, currentRow2,1, "Particle Y: %f", mopstate->getMopItem(currentitem).y);
currentRow2++;
mvwprintw(window2, currentRow2,1, "Particle Z %f", mopstate->getMopItem(currentitem).z);
currentRow2++;
mvwprintw(window2, currentRow2,1, "Particle Red: %d", mopstate->getMopItem(currentitem).red);
currentRow2++;
mvwprintw(window2, currentRow2,1, "Particle Green %d", mopstate->getMopItem(currentitem).green);
currentRow2++;
mvwprintw(window2, currentRow2,1, "Particle Blue: %d", mopstate->getMopItem(currentitem).blue);
currentRow2+=2;
currentitem++;
}
else if (currentitem <= mopstate->getItemCount()){
mvwprintw(window1, currentRow,1, "Particle Number: %d", currentitem);
currentRow++;
mvwprintw(window1, currentRow,1, "Particle X %f", mopstate->getMopItem(currentitem).x);
currentRow++;
mvwprintw(window1, currentRow,1, "Particle Y: %f", mopstate->getMopItem(currentitem).y);
currentRow++;
mvwprintw(window1, currentRow,1, "Particle Z %f", mopstate->getMopItem(currentitem).z);
currentRow++;
mvwprintw(window1, currentRow,1, "Particle Red: %d", mopstate->getMopItem(currentitem).red);
currentRow++;
mvwprintw(window1, currentRow,1, "Particle Green %d", mopstate->getMopItem(currentitem).green);
currentRow++;
mvwprintw(window1, currentRow,1, "Particle Blue: %d", mopstate->getMopItem(currentitem).blue);
currentRow+=2;
currentitem++;
}
}
refresh();
wrefresh(window1);
wrefresh(window2);
break;
}
}
refresh();
wrefresh(window1);
wrefresh(window2);
//getch();
endwin();
}
void mopViewer::selectGame() {
int mx = 0, my = 0, mx2 = 0, my2 = 0;
char welcome[] = "Enter 1 to View Stats and 2 to Open MopViewer: ";
char exitMessage[] = "Enter anything else to exit";
// Create inital screen. Better to replace
// with the single start function from moody
WINDOW *myWindow = initscr();
raw();
cbreak();
keypad(myWindow, TRUE);
// noecho();
// Enable use of colour on screen
start_color();
// Create two colour pairs for the different screens
init_pair(1, COLOR_BLACK, COLOR_CYAN);
init_pair(2, COLOR_BLACK, COLOR_RED);
init_pair(3, COLOR_WHITE, COLOR_BLACK);
// Set the colour scheme of window 1 to pair 1
wattron(myWindow, COLOR_PAIR(1));
// Set background of main window to colour scheme 1
wbkgd(myWindow, COLOR_PAIR(1));
// Create a border for the main console screen
box(myWindow, ACS_BULLET, ACS_BULLET);
// Make a new window that is a sub window of
// main window and add a border to it
getmaxyx(myWindow, mx, my);
WINDOW *myWindow2 = subwin(myWindow, mx-5, my-5, 3, 3);
box(myWindow2, ACS_VLINE, ACS_HLINE);
// Get the max size of both windows for use later on
getmaxyx(myWindow, mx, my);
getmaxyx(myWindow2, mx2, my2);
// Set background and colour shceme of child window
wattron(myWindow2, COLOR_PAIR(2));
wbkgd(myWindow2, COLOR_PAIR(2));
// Add the title string to the main window
mvaddstr(1, (my2/2)-10, "Welcome to MopViewer!");
// Print string to second window at the x,y co-ordinates specificed
mvwprintw(myWindow2, mx2/2, ((my2-std::strlen(welcome))/2), "%s", welcome);
mvwprintw(myWindow2, (mx2/2)+10, ((my2-std::strlen(exitMessage))/2), "%s", exitMessage);
wmove(myWindow, (mx2/2)+5, ((my2/2)+std::strlen(welcome)));
// Refresh main window otherwise background colour won't show for some reason
wrefresh(myWindow);
char inputString[1];
// Get the input into inputString
wgetstr(myWindow2, inputString);
mopViewer mopViewers;
testWindow newWindow;
if (inputString[0] == '1') {
clear();
refresh();
endwin();
mopViewers.showStats();
} else if (inputString[0] == '2') {
clear();
refresh();
endwin();
newWindow.init();
mopViewers.selectGame();
}
endwin();
}
<|endoftext|>
|
<commit_before>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE-CHROMIUM file.
#include "browser/browser_main_parts.h"
#include "browser/browser_context.h"
#include "browser/devtools_manager_delegate.h"
#include "browser/web_ui_controller_factory.h"
#include "common/main_delegate.h"
#include "base/command_line.h"
#include "base/feature_list.h"
#include "base/strings/string_number_conversions.h"
#include "base/strings/utf_string_conversions.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/common/content_switches.h"
#include "media/base/localized_strings.h"
#include "net/proxy/proxy_resolver_v8.h"
#include "ui/base/l10n/l10n_util.h"
#include "ui/base/material_design/material_design_controller.h"
#if defined(USE_AURA)
#include "ui/display/display.h"
#include "ui/display/screen.h"
#include "ui/views/widget/desktop_aura/desktop_screen.h"
#include "ui/wm/core/wm_state.h"
#endif
#if defined(TOOLKIT_VIEWS)
#include "browser/views/views_delegate.h"
#endif
#if defined(USE_X11)
#include "base/environment.h"
#include "base/path_service.h"
#include "base/nix/xdg_util.h"
#include "base/threading/thread_task_runner_handle.h"
#include "browser/brightray_paths.h"
#include "chrome/browser/ui/libgtkui/gtk_ui.h"
#include "ui/base/x/x11_util.h"
#include "ui/base/x/x11_util_internal.h"
#include "ui/views/linux_ui/linux_ui.h"
#endif
#if defined(OS_WIN)
#include "ui/base/cursor/cursor_loader_win.h"
#include "ui/base/l10n/l10n_util_win.h"
#include "ui/gfx/platform_font_win.h"
#endif
#if defined(OS_LINUX)
#include "device/bluetooth/bluetooth_adapter_factory.h"
#include "device/bluetooth/dbus/dbus_bluez_manager_wrapper_linux.h"
#endif
namespace brightray {
namespace {
#if defined(OS_WIN)
// gfx::Font callbacks
void AdjustUIFont(LOGFONT* logfont) {
l10n_util::AdjustUIFont(logfont);
}
int GetMinimumFontSize() {
return 10;
}
#endif
#if defined(USE_X11)
// Indicates that we're currently responding to an IO error (by shutting down).
bool g_in_x11_io_error_handler = false;
// Number of seconds to wait for UI thread to get an IO error if we get it on
// the background thread.
const int kWaitForUIThreadSeconds = 10;
void OverrideLinuxAppDataPath() {
base::FilePath path;
if (PathService::Get(DIR_APP_DATA, &path))
return;
std::unique_ptr<base::Environment> env(base::Environment::Create());
path = base::nix::GetXDGDirectory(env.get(),
base::nix::kXdgConfigHomeEnvVar,
base::nix::kDotConfigDir);
PathService::Override(DIR_APP_DATA, path);
}
int BrowserX11ErrorHandler(Display* d, XErrorEvent* error) {
if (!g_in_x11_io_error_handler) {
base::ThreadTaskRunnerHandle::Get()->PostTask(
FROM_HERE, base::Bind(&ui::LogErrorEventDescription, d, *error));
}
return 0;
}
// This function is used to help us diagnose crash dumps that happen
// during the shutdown process.
NOINLINE void WaitingForUIThreadToHandleIOError() {
// Ensure function isn't optimized away.
asm("");
sleep(kWaitForUIThreadSeconds);
}
int BrowserX11IOErrorHandler(Display* d) {
if (!content::BrowserThread::CurrentlyOn(content::BrowserThread::UI)) {
// Wait for the UI thread (which has a different connection to the X server)
// to get the error. We can't call shutdown from this thread without
// tripping an error. Doing it through a function so that we'll be able
// to see it in any crash dumps.
WaitingForUIThreadToHandleIOError();
return 0;
}
// If there's an IO error it likely means the X server has gone away.
// If this CHECK fails, then that means SessionEnding() below triggered some
// code that tried to talk to the X server, resulting in yet another error.
CHECK(!g_in_x11_io_error_handler);
g_in_x11_io_error_handler = true;
LOG(ERROR) << "X IO error received (X server probably went away)";
base::ThreadTaskRunnerHandle::Get()->PostTask(
FROM_HERE, base::MessageLoop::QuitWhenIdleClosure());
return 0;
}
int X11EmptyErrorHandler(Display* d, XErrorEvent* error) {
return 0;
}
int X11EmptyIOErrorHandler(Display* d) {
return 0;
}
#endif
base::string16 MediaStringProvider(media::MessageId id) {
switch (id) {
case media::DEFAULT_AUDIO_DEVICE_NAME:
return base::ASCIIToUTF16("Default");
#if defined(OS_WIN)
case media::COMMUNICATIONS_AUDIO_DEVICE_NAME:
return base::ASCIIToUTF16("Communications");
#endif
default:
return base::string16();
}
}
} // namespace
BrowserMainParts::BrowserMainParts() {
}
BrowserMainParts::~BrowserMainParts() {
}
void BrowserMainParts::PreEarlyInitialization() {
std::unique_ptr<base::FeatureList> feature_list(new base::FeatureList);
feature_list->InitializeFromCommandLine("", "");
base::FeatureList::SetInstance(std::move(feature_list));
#if defined(USE_X11)
views::LinuxUI::SetInstance(BuildGtk2UI());
OverrideLinuxAppDataPath();
// Installs the X11 error handlers for the browser process used during
// startup. They simply print error messages and exit because
// we can't shutdown properly while creating and initializing services.
ui::SetX11ErrorHandlers(nullptr, nullptr);
#endif
}
void BrowserMainParts::ToolkitInitialized() {
ui::MaterialDesignController::Initialize();
#if defined(USE_AURA) && defined(USE_X11)
views::LinuxUI::instance()->Initialize();
#endif
#if defined(USE_AURA)
wm_state_.reset(new wm::WMState);
#endif
#if defined(TOOLKIT_VIEWS)
views_delegate_.reset(new ViewsDelegate);
#endif
#if defined(OS_WIN)
gfx::PlatformFontWin::adjust_font_callback = &AdjustUIFont;
gfx::PlatformFontWin::get_minimum_font_size_callback = &GetMinimumFontSize;
wchar_t module_name[MAX_PATH] = { 0 };
if (GetModuleFileName(NULL, module_name, MAX_PATH))
ui::CursorLoaderWin::SetCursorResourceModule(module_name);
#endif
}
void BrowserMainParts::PreMainMessageLoopStart() {
#if defined(OS_MACOSX)
l10n_util::OverrideLocaleWithCocoaLocale();
#endif
InitializeResourceBundle("");
#if defined(OS_MACOSX)
InitializeMainNib();
#endif
media::SetLocalizedStringProvider(MediaStringProvider);
}
void BrowserMainParts::PreMainMessageLoopRun() {
content::WebUIControllerFactory::RegisterFactory(
WebUIControllerFactory::GetInstance());
// --remote-debugging-port
auto command_line = base::CommandLine::ForCurrentProcess();
if (command_line->HasSwitch(switches::kRemoteDebuggingPort))
DevToolsManagerDelegate::StartHttpHandler();
}
void BrowserMainParts::PostMainMessageLoopStart() {
#if defined(USE_X11)
// Installs the X11 error handlers for the browser process after the
// main message loop has started. This will allow us to exit cleanly
// if X exits before us.
ui::SetX11ErrorHandlers(BrowserX11ErrorHandler, BrowserX11IOErrorHandler);
#endif
#if defined(OS_LINUX)
bluez::DBusBluezManagerWrapperLinux::Initialize();
#endif
}
void BrowserMainParts::PostMainMessageLoopRun() {
#if defined(USE_X11)
// Unset the X11 error handlers. The X11 error handlers log the errors using a
// |PostTask()| on the message-loop. But since the message-loop is in the
// process of terminating, this can cause errors.
ui::SetX11ErrorHandlers(X11EmptyErrorHandler, X11EmptyIOErrorHandler);
#endif
}
int BrowserMainParts::PreCreateThreads() {
#if defined(USE_AURA)
display::Screen* screen = views::CreateDesktopScreen();
display::Screen::SetScreenInstance(screen);
#if defined(USE_X11)
views::LinuxUI::instance()->UpdateDeviceScaleFactor();
#endif
#endif
return 0;
}
void BrowserMainParts::PostDestroyThreads() {
#if defined(OS_LINUX)
device::BluetoothAdapterFactory::Shutdown();
bluez::DBusBluezManagerWrapperLinux::Shutdown();
#endif
}
} // namespace brightray
<commit_msg>Fix building on Linux<commit_after>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE-CHROMIUM file.
#include "browser/browser_main_parts.h"
#include "browser/browser_context.h"
#include "browser/devtools_manager_delegate.h"
#include "browser/web_ui_controller_factory.h"
#include "common/main_delegate.h"
#include "base/command_line.h"
#include "base/feature_list.h"
#include "base/strings/string_number_conversions.h"
#include "base/strings/utf_string_conversions.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/common/content_switches.h"
#include "media/base/localized_strings.h"
#include "net/proxy/proxy_resolver_v8.h"
#include "ui/base/l10n/l10n_util.h"
#include "ui/base/material_design/material_design_controller.h"
#if defined(USE_AURA)
#include "ui/display/display.h"
#include "ui/display/screen.h"
#include "ui/views/widget/desktop_aura/desktop_screen.h"
#include "ui/wm/core/wm_state.h"
#endif
#if defined(TOOLKIT_VIEWS)
#include "browser/views/views_delegate.h"
#endif
#if defined(USE_X11)
#include "base/environment.h"
#include "base/path_service.h"
#include "base/nix/xdg_util.h"
#include "base/threading/thread_task_runner_handle.h"
#include "browser/brightray_paths.h"
#include "chrome/browser/ui/libgtkui/gtk_ui.h"
#include "ui/base/x/x11_util.h"
#include "ui/base/x/x11_util_internal.h"
#include "ui/views/linux_ui/linux_ui.h"
#endif
#if defined(OS_WIN)
#include "ui/base/cursor/cursor_loader_win.h"
#include "ui/base/l10n/l10n_util_win.h"
#include "ui/gfx/platform_font_win.h"
#endif
#if defined(OS_LINUX)
#include "device/bluetooth/bluetooth_adapter_factory.h"
#include "device/bluetooth/dbus/dbus_bluez_manager_wrapper_linux.h"
#endif
namespace brightray {
namespace {
#if defined(OS_WIN)
// gfx::Font callbacks
void AdjustUIFont(LOGFONT* logfont) {
l10n_util::AdjustUIFont(logfont);
}
int GetMinimumFontSize() {
return 10;
}
#endif
#if defined(USE_X11)
// Indicates that we're currently responding to an IO error (by shutting down).
bool g_in_x11_io_error_handler = false;
// Number of seconds to wait for UI thread to get an IO error if we get it on
// the background thread.
const int kWaitForUIThreadSeconds = 10;
void OverrideLinuxAppDataPath() {
base::FilePath path;
if (PathService::Get(DIR_APP_DATA, &path))
return;
std::unique_ptr<base::Environment> env(base::Environment::Create());
path = base::nix::GetXDGDirectory(env.get(),
base::nix::kXdgConfigHomeEnvVar,
base::nix::kDotConfigDir);
PathService::Override(DIR_APP_DATA, path);
}
int BrowserX11ErrorHandler(Display* d, XErrorEvent* error) {
if (!g_in_x11_io_error_handler) {
base::ThreadTaskRunnerHandle::Get()->PostTask(
FROM_HERE, base::Bind(&ui::LogErrorEventDescription, d, *error));
}
return 0;
}
// This function is used to help us diagnose crash dumps that happen
// during the shutdown process.
NOINLINE void WaitingForUIThreadToHandleIOError() {
// Ensure function isn't optimized away.
asm("");
sleep(kWaitForUIThreadSeconds);
}
int BrowserX11IOErrorHandler(Display* d) {
if (!content::BrowserThread::CurrentlyOn(content::BrowserThread::UI)) {
// Wait for the UI thread (which has a different connection to the X server)
// to get the error. We can't call shutdown from this thread without
// tripping an error. Doing it through a function so that we'll be able
// to see it in any crash dumps.
WaitingForUIThreadToHandleIOError();
return 0;
}
// If there's an IO error it likely means the X server has gone away.
// If this CHECK fails, then that means SessionEnding() below triggered some
// code that tried to talk to the X server, resulting in yet another error.
CHECK(!g_in_x11_io_error_handler);
g_in_x11_io_error_handler = true;
LOG(ERROR) << "X IO error received (X server probably went away)";
base::ThreadTaskRunnerHandle::Get()->PostTask(
FROM_HERE, base::MessageLoop::QuitWhenIdleClosure());
return 0;
}
int X11EmptyErrorHandler(Display* d, XErrorEvent* error) {
return 0;
}
int X11EmptyIOErrorHandler(Display* d) {
return 0;
}
#endif
base::string16 MediaStringProvider(media::MessageId id) {
switch (id) {
case media::DEFAULT_AUDIO_DEVICE_NAME:
return base::ASCIIToUTF16("Default");
#if defined(OS_WIN)
case media::COMMUNICATIONS_AUDIO_DEVICE_NAME:
return base::ASCIIToUTF16("Communications");
#endif
default:
return base::string16();
}
}
} // namespace
BrowserMainParts::BrowserMainParts() {
}
BrowserMainParts::~BrowserMainParts() {
}
void BrowserMainParts::PreEarlyInitialization() {
std::unique_ptr<base::FeatureList> feature_list(new base::FeatureList);
feature_list->InitializeFromCommandLine("", "");
base::FeatureList::SetInstance(std::move(feature_list));
#if defined(USE_X11)
views::LinuxUI::SetInstance(BuildGtkUi());
OverrideLinuxAppDataPath();
// Installs the X11 error handlers for the browser process used during
// startup. They simply print error messages and exit because
// we can't shutdown properly while creating and initializing services.
ui::SetX11ErrorHandlers(nullptr, nullptr);
#endif
}
void BrowserMainParts::ToolkitInitialized() {
ui::MaterialDesignController::Initialize();
#if defined(USE_AURA) && defined(USE_X11)
views::LinuxUI::instance()->Initialize();
#endif
#if defined(USE_AURA)
wm_state_.reset(new wm::WMState);
#endif
#if defined(TOOLKIT_VIEWS)
views_delegate_.reset(new ViewsDelegate);
#endif
#if defined(OS_WIN)
gfx::PlatformFontWin::adjust_font_callback = &AdjustUIFont;
gfx::PlatformFontWin::get_minimum_font_size_callback = &GetMinimumFontSize;
wchar_t module_name[MAX_PATH] = { 0 };
if (GetModuleFileName(NULL, module_name, MAX_PATH))
ui::CursorLoaderWin::SetCursorResourceModule(module_name);
#endif
}
void BrowserMainParts::PreMainMessageLoopStart() {
#if defined(OS_MACOSX)
l10n_util::OverrideLocaleWithCocoaLocale();
#endif
InitializeResourceBundle("");
#if defined(OS_MACOSX)
InitializeMainNib();
#endif
media::SetLocalizedStringProvider(MediaStringProvider);
}
void BrowserMainParts::PreMainMessageLoopRun() {
content::WebUIControllerFactory::RegisterFactory(
WebUIControllerFactory::GetInstance());
// --remote-debugging-port
auto command_line = base::CommandLine::ForCurrentProcess();
if (command_line->HasSwitch(switches::kRemoteDebuggingPort))
DevToolsManagerDelegate::StartHttpHandler();
}
void BrowserMainParts::PostMainMessageLoopStart() {
#if defined(USE_X11)
// Installs the X11 error handlers for the browser process after the
// main message loop has started. This will allow us to exit cleanly
// if X exits before us.
ui::SetX11ErrorHandlers(BrowserX11ErrorHandler, BrowserX11IOErrorHandler);
#endif
#if defined(OS_LINUX)
bluez::DBusBluezManagerWrapperLinux::Initialize();
#endif
}
void BrowserMainParts::PostMainMessageLoopRun() {
#if defined(USE_X11)
// Unset the X11 error handlers. The X11 error handlers log the errors using a
// |PostTask()| on the message-loop. But since the message-loop is in the
// process of terminating, this can cause errors.
ui::SetX11ErrorHandlers(X11EmptyErrorHandler, X11EmptyIOErrorHandler);
#endif
}
int BrowserMainParts::PreCreateThreads() {
#if defined(USE_AURA)
display::Screen* screen = views::CreateDesktopScreen();
display::Screen::SetScreenInstance(screen);
#if defined(USE_X11)
views::LinuxUI::instance()->UpdateDeviceScaleFactor();
#endif
#endif
return 0;
}
void BrowserMainParts::PostDestroyThreads() {
#if defined(OS_LINUX)
device::BluetoothAdapterFactory::Shutdown();
bluez::DBusBluezManagerWrapperLinux::Shutdown();
#endif
}
} // namespace brightray
<|endoftext|>
|
<commit_before>#include "specifyGenerationRulesDialog.h"
#include "ui_specifyGenerationRulesDialog.h"
using namespace qReal;
using namespace gui;
SpecifyGenerationRulesDialog::SpecifyGenerationRulesDialog(MainWindow &mainWindow
, EditorManagerInterface &interpreterEditorManager
, Id const &id) :
QDialog(&mainWindow)
, mUi(new Ui::SpecifyGenerationRulesDialog)
, mInterpreterEditorManager(interpreterEditorManager)
, mId(id)
{
mUi->setupUi(this);
addPropertiesList();
connect(mUi->propertiesView, &QListWidget::itemDoubleClicked, this
&SpecifyGenerationRulesDialog::insertPropertyIntoCode);
}
SpecifyGenerationRulesDialog::~SpecifyGenerationRulesDialog()
{
delete mUi;
}
void SpecifyGenerationRulesDialog::insertPropertyIntoCode(QListWidgetItem* property)
{
QString const propertyName = property->text();
mUi->codeArea->insertPlainText(propertyName);
}
void SpecifyGenerationRulesDialog::addPropertiesList()
{
mPropertiesNames = mInterpreterEditorManager.propertyNames(mId);
QStringList const propertiesDisplayedNames = propertiesDisplayedNamesList(mPropertiesNames);
mUi->propertiesView->clear();
mUi->propertiesView->addItems(propertiesDisplayedNames);
}
QStringList SpecifyGenerationRulesDialog::propertiesDisplayedNamesList(QStringList const &propertiesNames)
{
QStringList propertiesDisplayedNames;
for (QString const &propertyName : propertiesNames) {
propertiesDisplayedNames << mInterpreterEditorManager.propertyDisplayedName(mId, propertyName);
}
return propertiesDisplayedNames;
}
<commit_msg>added comma<commit_after>#include "specifyGenerationRulesDialog.h"
#include "ui_specifyGenerationRulesDialog.h"
using namespace qReal;
using namespace gui;
SpecifyGenerationRulesDialog::SpecifyGenerationRulesDialog(MainWindow &mainWindow
, EditorManagerInterface &interpreterEditorManager
, Id const &id) :
QDialog(&mainWindow)
, mUi(new Ui::SpecifyGenerationRulesDialog)
, mInterpreterEditorManager(interpreterEditorManager)
, mId(id)
{
mUi->setupUi(this);
addPropertiesList();
connect(mUi->propertiesView, &QListWidget::itemDoubleClicked, this
, &SpecifyGenerationRulesDialog::insertPropertyIntoCode);
}
SpecifyGenerationRulesDialog::~SpecifyGenerationRulesDialog()
{
delete mUi;
}
void SpecifyGenerationRulesDialog::insertPropertyIntoCode(QListWidgetItem* property)
{
QString const propertyName = property->text();
mUi->codeArea->insertPlainText(propertyName);
}
void SpecifyGenerationRulesDialog::addPropertiesList()
{
mPropertiesNames = mInterpreterEditorManager.propertyNames(mId);
QStringList const propertiesDisplayedNames = propertiesDisplayedNamesList(mPropertiesNames);
mUi->propertiesView->clear();
mUi->propertiesView->addItems(propertiesDisplayedNames);
}
QStringList SpecifyGenerationRulesDialog::propertiesDisplayedNamesList(QStringList const &propertiesNames)
{
QStringList propertiesDisplayedNames;
for (QString const &propertyName : propertiesNames) {
propertiesDisplayedNames << mInterpreterEditorManager.propertyDisplayedName(mId, propertyName);
}
return propertiesDisplayedNames;
}
<|endoftext|>
|
<commit_before>/*
* Copyright (c) <2002-2006> <Jean-Philippe Barrette-LaPierre>
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files
* (cURLpp), 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 CURLPP_INFO_HPP
#define CURLPP_INFO_HPP
#include "dllfct.h"
#include "Easy.hpp"
namespace cURLpp
{
/**
* This class is responsible of retreiving the Info from
* a handle. This is the class you use when you want to do
* so.
*/
template< CURLINFO info, typename T >
struct Info
{
static void get(cURLpp::Easy &handle, T &value);
static T get(cURLpp::Easy &handle);
};
/**
* This class is used when an info is not available for the
* current libcURL version.
*/
template< CURLINFO info, typename T >
struct NotAvailableInfo : Info< info, T >
{
static void get(cURLpp::Easy &handle, T &value);
static T get(cURLpp::Easy &handle);
};
/**
* This is the class you need to specialize if you use
* a special type that libcURL is not aware of. This class
* need to call cURLpp::InfoGetter::get function. See
* cURLpp::InfoGetter for more information.
*/
template< typename T >
struct InfoTypeConverter
{
static void get(cURLpp::Easy &handle, CURLINFO info, T &value);
};
template< >
void InfoTypeConverter< std::string >::get(cURLpp::Easy &handle,
CURLINFO info,
std::string &value);
template< >
void InfoTypeConverter< std::list< std::string > >::get(cURLpp::Easy & handle,
CURLINFO info,
std::list< std::string > &value);
template< >
void InfoTypeConverter< long >::get(cURLpp::Easy &handle,
CURLINFO info,
long &value);
template< >
void InfoTypeConverter< double >::get(cURLpp::Easy &handle,
CURLINFO info,
double &value);
/**
* This is the only class that is authorized to retreive
* info from a cURLpp::Easy class. So, this is the class
* you need to use when you specialize the class
* cURLpp::InfoTypeConverter. This class is in fact used
* as a proxy, just to be sure that nobody access cURLpp::Easy's
* private data.
*/
struct InfoGetter
{
template< typename T >
static void get(cURLpp::Easy &handle, CURLINFO info, T &value);
};
}
#include "Info.inl"
#endif
<commit_msg>Allowed curlpp to be built in a dynamic library (Win32: VC8 & VC9)<commit_after>/*
* Copyright (c) <2002-2006> <Jean-Philippe Barrette-LaPierre>
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files
* (cURLpp), 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 CURLPP_INFO_HPP
#define CURLPP_INFO_HPP
#include "dllfct.h"
#include "Easy.hpp"
namespace cURLpp
{
/**
* This class is responsible of retreiving the Info from
* a handle. This is the class you use when you want to do
* so.
*/
template< CURLINFO info, typename T >
struct Info
{
static void get(cURLpp::Easy &handle, T &value);
static T get(cURLpp::Easy &handle);
};
/**
* This class is used when an info is not available for the
* current libcURL version.
*/
template< CURLINFO info, typename T >
struct NotAvailableInfo : Info< info, T >
{
static void get(cURLpp::Easy &handle, T &value);
static T get(cURLpp::Easy &handle);
};
/**
* This is the class you need to specialize if you use
* a special type that libcURL is not aware of. This class
* need to call cURLpp::InfoGetter::get function. See
* cURLpp::InfoGetter for more information.
*/
template< typename T >
struct InfoTypeConverter
{
static void get(cURLpp::Easy &handle, CURLINFO info, T &value);
};
template< >
void CURLPPAPI InfoTypeConverter< std::string >::get(cURLpp::Easy &handle,
CURLINFO info,
std::string &value);
template< >
void CURLPPAPI InfoTypeConverter< std::list< std::string > >::get(cURLpp::Easy & handle,
CURLINFO info,
std::list< std::string > &value);
template< >
void CURLPPAPI InfoTypeConverter< long >::get(cURLpp::Easy &handle,
CURLINFO info,
long &value);
template< >
void CURLPPAPI InfoTypeConverter< double >::get(cURLpp::Easy &handle,
CURLINFO info,
double &value);
/**
* This is the only class that is authorized to retreive
* info from a cURLpp::Easy class. So, this is the class
* you need to use when you specialize the class
* cURLpp::InfoTypeConverter. This class is in fact used
* as a proxy, just to be sure that nobody access cURLpp::Easy's
* private data.
*/
struct InfoGetter
{
template< typename T >
static void get(cURLpp::Easy &handle, CURLINFO info, T &value);
};
}
#include "Info.inl"
#endif
<|endoftext|>
|
<commit_before>/* Copyright 2007-2015 QReal Research Group
*
* 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 "miscellaniousPage.h"
#include "ui_miscellaniousPage.h"
#include <qrkernel/settingsManager.h>
#include <qrutils/widgets/qRealFileDialog.h>
using namespace qReal;
PreferencesMiscellaniousPage::PreferencesMiscellaniousPage(QWidget *parent)
: PreferencesPage(parent)
, mUi(new Ui::PreferencesMiscellaniousPage)
{
mUi->setupUi(this);
setObjectName("preferencesMiscellaniousPage");
setWindowIcon(QIcon(":/preferencesDialog/images/miscellaneous.png"));
connect(mUi->imagesPathBrowseButton, SIGNAL(clicked()), this, SLOT(browseImagesPath()));
connect(mUi->toolbarSizeSlider, &QSlider::valueChanged
, [=](int value ) { SettingsManager::setValue("toolbarSize", value); });
restoreSettings();
}
PreferencesMiscellaniousPage::~PreferencesMiscellaniousPage()
{
delete mUi;
}
void PreferencesMiscellaniousPage::changeEvent(QEvent *e)
{
switch (e->type()) {
case QEvent::LanguageChange:
mUi->retranslateUi(this);
break;
default:
break;
}
}
void PreferencesMiscellaniousPage::browseImagesPath()
{
const QString path = utils::QRealFileDialog::getExistingDirectory("OpenImagesOnMiscellaniousPage"
, this, tr("Open Directory")).replace("\\", "/");
if (!path.isEmpty()) {
mUi->imagesPathEdit->setText(path);
}
}
void PreferencesMiscellaniousPage::save()
{
SettingsManager::setValue("Splashscreen", mUi->splashScreenCheckBox->isChecked());
SettingsManager::setValue("Antialiasing", mUi->antialiasingCheckBox->isChecked());
SettingsManager::setValue("pathToImages", mUi->imagesPathEdit->text());
SettingsManager::setValue("recentProjectsLimit", mUi->recentProjectsLimitSpinBox->value());
SettingsManager::setValue("toolbarSize", mUi->toolbarSizeSlider->value());
}
void PreferencesMiscellaniousPage::restoreSettings()
{
mUi->antialiasingCheckBox->setChecked(SettingsManager::value("Antialiasing").toBool());
mUi->splashScreenCheckBox->setChecked(SettingsManager::value("Splashscreen").toBool());
mUi->toolbarSizeSlider->setValue(SettingsManager::value("toolbarSize").toInt());
mUi->imagesPathEdit->setText(SettingsManager::value("pathToImages").toString());
}
<commit_msg>fix missed save step in miscellanious page<commit_after>/* Copyright 2007-2015 QReal Research Group
*
* 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 "miscellaniousPage.h"
#include "ui_miscellaniousPage.h"
#include <qrkernel/settingsManager.h>
#include <qrutils/widgets/qRealFileDialog.h>
using namespace qReal;
PreferencesMiscellaniousPage::PreferencesMiscellaniousPage(QWidget *parent)
: PreferencesPage(parent)
, mUi(new Ui::PreferencesMiscellaniousPage)
{
mUi->setupUi(this);
setObjectName("preferencesMiscellaniousPage");
setWindowIcon(QIcon(":/preferencesDialog/images/miscellaneous.png"));
connect(mUi->imagesPathBrowseButton, SIGNAL(clicked()), this, SLOT(browseImagesPath()));
connect(mUi->toolbarSizeSlider, &QSlider::valueChanged
, [=](int value ) { SettingsManager::setValue("toolbarSize", value); });
restoreSettings();
}
PreferencesMiscellaniousPage::~PreferencesMiscellaniousPage()
{
delete mUi;
}
void PreferencesMiscellaniousPage::changeEvent(QEvent *e)
{
switch (e->type()) {
case QEvent::LanguageChange:
mUi->retranslateUi(this);
break;
default:
break;
}
}
void PreferencesMiscellaniousPage::browseImagesPath()
{
const QString path = utils::QRealFileDialog::getExistingDirectory("OpenImagesOnMiscellaniousPage"
, this, tr("Open Directory")).replace("\\", "/");
if (!path.isEmpty()) {
mUi->imagesPathEdit->setText(path);
}
}
void PreferencesMiscellaniousPage::save()
{
SettingsManager::setValue("Splashscreen", mUi->splashScreenCheckBox->isChecked());
SettingsManager::setValue("Antialiasing", mUi->antialiasingCheckBox->isChecked());
SettingsManager::setValue("pathToImages", mUi->imagesPathEdit->text());
SettingsManager::setValue("recentProjectsLimit", mUi->recentProjectsLimitSpinBox->value());
SettingsManager::setValue("toolbarSize", mUi->toolbarSizeSlider->value());
}
void PreferencesMiscellaniousPage::restoreSettings()
{
mUi->antialiasingCheckBox->setChecked(SettingsManager::value("Antialiasing").toBool());
mUi->splashScreenCheckBox->setChecked(SettingsManager::value("Splashscreen").toBool());
mUi->recentProjectsLimitSpinBox->setValue(SettingsManager::value("recentProjectsLimit").toInt());
mUi->toolbarSizeSlider->setValue(SettingsManager::value("toolbarSize").toInt());
mUi->imagesPathEdit->setText(SettingsManager::value("pathToImages").toString());
}
<|endoftext|>
|
<commit_before>#include "i2c_interface.h"
I2CInterface::I2CInterface(const std::string& deviceFile, uint8_t slaveAddress)
: m_deviceFile(deviceFile),
m_slaveAddress(slaveAddress),
m_fileDescriptor(0)
{
}
I2CInterface::~I2CInterface()
{
closeFileDescriptor();
}
I2CInterface::RET_CODE I2CInterface::init()
{
return openFileDescriptor();
}
I2CInterface::RET_CODE I2CInterface::openFileDescriptor()
{
if(m_fileDescriptor)
{
closeFileDescriptor();
}
//Try to open the file descriptor
m_fileDescriptor = open(m_deviceFile.c_str(), O_RDWR);
if(m_fileDescriptor < 0)
{
std::cout << "i2c error: " << std::strerror(errno) << std::endl;
return RET_CODE::FAILED_OPEN_FILE_DESCRIPTOR;
}
//Init input output control
if(ioctl(m_fileDescriptor, I2C_SLAVE, m_slaveAddress) < 0)
{
std::cout << "i2c error: " << std::strerror(errno) << std::endl;
return RET_CODE::FAILED_INIT_INPUT_OUTPUT_CONTROL;
}
return RET_CODE::SUCCESS;
}
void I2CInterface::closeFileDescriptor()
{
if(m_fileDescriptor)
{
close(m_fileDescriptor);
m_fileDescriptor = 0;
}
}
I2CInterface::RET_CODE I2CInterface::setSlaveAddress(const uint8_t slaveAddress)
{
m_slaveAddress = slaveAddress;
return openFileDescriptor();
}
uint8_t I2CInterface::getSlaveAddress() const
{
return m_slaveAddress;
}
I2CInterface::RET_CODE I2CInterface::send(uint8_t registerAddress, uint8_t* txBuffer, int length)
{
//check for a null buffer pointer
if(txBuffer == nullptr)
{
std::cout << "i2c error: received null transmit buffer." << std::endl;
return RET_CODE::NULL_TRANSMIT_BUFFER;
}
//Check for an invalid length
if(length < 1)
{
std::cout << "i2c error: invalid send buffer length" << std::endl;
return RET_CODE::INVALID_TRANSMIT_BUFFER_LENGTH;
}
//Create the buffer
//Payload length plus zeroth element for register
uint8_t buffer[length + 1];
buffer[0] = registerAddress;
//Pack the buffer
for(size_t i = 0; i < length; ++i)
{
buffer[i+1] = txBuffer[i];
}
//Write the data
if(write(m_fileDescriptor, buffer, length) != length)
{
std::cout << "i2c error: " << std::strerror(errno) << std::endl;
return RET_CODE::FAILED_I2C_WRITE;
}
return RET_CODE::SUCCESS;
}
I2CInterface::RET_CODE I2CInterface::sendByte(uint8_t registerAddress, uint8_t data)
{
uint8_t buffer[2];
buffer[0] = registerAddress;
buffer[1] = data;
//Write the data
if(write(m_fileDescriptor, buffer, 2) != 2)
{
std::cout << "i2c error: " << std::strerror(errno) << std::endl;
return RET_CODE::FAILED_I2C_WRITE;
}
return RET_CODE::SUCCESS;
}
I2CInterface::RET_CODE I2CInterface::readFromRegister(uint8_t registerAddress, uint8_t* rxBuffer, int length)
{
if(write(m_fileDescriptor, registerAddress, 1) != 1)
{
std::cout << "i2c error: " << std::strerror(errno) << std::endl;
return RET_CODE::FAILED_I2C_WRITE;
}
if(read(m_fileDescriptor, rxBuffer, length) != length)
{
std::cout << "i2c error: " << std::strerror(errno) << std::endl;
return RET_CODE::FAILED_I2C_READ;
}
return RET_CODE::SUCCESS;
}<commit_msg>Added updated read<commit_after>#include "i2c_interface.h"
I2CInterface::I2CInterface(const std::string& deviceFile, uint8_t slaveAddress)
: m_deviceFile(deviceFile),
m_slaveAddress(slaveAddress),
m_fileDescriptor(0)
{
}
I2CInterface::~I2CInterface()
{
closeFileDescriptor();
}
I2CInterface::RET_CODE I2CInterface::init()
{
return openFileDescriptor();
}
I2CInterface::RET_CODE I2CInterface::openFileDescriptor()
{
if(m_fileDescriptor)
{
closeFileDescriptor();
}
//Try to open the file descriptor
m_fileDescriptor = open(m_deviceFile.c_str(), O_RDWR);
if(m_fileDescriptor < 0)
{
std::cout << "i2c error: " << std::strerror(errno) << std::endl;
return RET_CODE::FAILED_OPEN_FILE_DESCRIPTOR;
}
//Init input output control
if(ioctl(m_fileDescriptor, I2C_SLAVE, m_slaveAddress) < 0)
{
std::cout << "i2c error: " << std::strerror(errno) << std::endl;
return RET_CODE::FAILED_INIT_INPUT_OUTPUT_CONTROL;
}
return RET_CODE::SUCCESS;
}
void I2CInterface::closeFileDescriptor()
{
if(m_fileDescriptor)
{
close(m_fileDescriptor);
m_fileDescriptor = 0;
}
}
I2CInterface::RET_CODE I2CInterface::setSlaveAddress(const uint8_t slaveAddress)
{
m_slaveAddress = slaveAddress;
return openFileDescriptor();
}
uint8_t I2CInterface::getSlaveAddress() const
{
return m_slaveAddress;
}
I2CInterface::RET_CODE I2CInterface::send(uint8_t registerAddress, uint8_t* txBuffer, int length)
{
//check for a null buffer pointer
if(txBuffer == nullptr)
{
std::cout << "i2c error: received null transmit buffer." << std::endl;
return RET_CODE::NULL_TRANSMIT_BUFFER;
}
//Check for an invalid length
if(length < 1)
{
std::cout << "i2c error: invalid send buffer length" << std::endl;
return RET_CODE::INVALID_TRANSMIT_BUFFER_LENGTH;
}
//Create the buffer
//Payload length plus zeroth element for register
uint8_t buffer[length + 1];
buffer[0] = registerAddress;
//Pack the buffer
for(size_t i = 0; i < length; ++i)
{
buffer[i+1] = txBuffer[i];
}
//Write the data
if(write(m_fileDescriptor, buffer, length) != length)
{
std::cout << "i2c error: " << std::strerror(errno) << std::endl;
return RET_CODE::FAILED_I2C_WRITE;
}
return RET_CODE::SUCCESS;
}
I2CInterface::RET_CODE I2CInterface::sendByte(uint8_t registerAddress, uint8_t data)
{
uint8_t buffer[2];
buffer[0] = registerAddress;
buffer[1] = data;
//Write the data
if(write(m_fileDescriptor, buffer, 2) != 2)
{
std::cout << "i2c error: " << std::strerror(errno) << std::endl;
return RET_CODE::FAILED_I2C_WRITE;
}
return RET_CODE::SUCCESS;
}
I2CInterface::RET_CODE I2CInterface::readFromRegister(uint8_t registerAddress, uint8_t* rxBuffer, int length)
{
uint8_t buffer[1];
buffer[0] = registerAddress;
if(write(m_fileDescriptor, buffer, 1) != 1)
{
std::cout << "i2c error: " << std::strerror(errno) << std::endl;
return RET_CODE::FAILED_I2C_WRITE;
}
if(read(m_fileDescriptor, rxBuffer, length) != length)
{
std::cout << "i2c error: " << std::strerror(errno) << std::endl;
return RET_CODE::FAILED_I2C_READ;
}
return RET_CODE::SUCCESS;
}<|endoftext|>
|
<commit_before>#include <clang-c/Index.h>
#include <cstdio>
#include <array>
#include <iostream>
#include <vector>
namespace {
const unsigned int indent_spaces = 4;
const std::string indentation(indent_spaces, ' ');
}
CXCursor tu_cursor;
struct client_data
{
CXTranslationUnit tu;
std::vector<CXCursor> current_namespaces;
CXCursor current_struct;
// function signature, forwarding call arguments, optional return
// keyword, and function name
std::vector<std::array<std::string, 4>> member_functions;
bool printed_headers;
const char* filename;
};
std::pair<CXToken*, unsigned int>
get_tokens (CXTranslationUnit tu, CXCursor cursor)
{
CXSourceRange range = clang_getCursorExtent(cursor);
CXSourceLocation start = clang_getRangeStart(range);
CXSourceLocation end = clang_getRangeEnd(range);
unsigned int start_offset, end_offset;
std::pair<CXToken*, unsigned int> retval(0, 0);
clang_tokenize(tu, range, &retval.first, &retval.second);
return retval;
}
void
free_tokens (CXTranslationUnit tu, std::pair<CXToken*, unsigned int> tokens)
{ clang_disposeTokens(tu, tokens.first, tokens.second); }
void print_tokens (CXTranslationUnit tu, CXCursor cursor)
{
std::pair<CXToken*, unsigned int> tokens = get_tokens(tu, cursor);
for (unsigned int i = 0; i < tokens.second; ++i) {
if (i)
std::cout << " ";
CXString spelling = clang_getTokenSpelling(tu, tokens.first[i]);
std::cout << clang_getCString(spelling);
}
std::cout << "\n";
free_tokens(tu, tokens);
}
bool struct_kind (CXCursorKind kind)
{
switch (kind) {
case CXCursor_ClassDecl:
case CXCursor_StructDecl:
case CXCursor_ClassTemplate:
case CXCursor_ClassTemplatePartialSpecialization:
return true;
}
return false;
}
std::string indent (const client_data & data)
{
std::size_t size = data.current_namespaces.size();
return std::string(size * indent_spaces, ' ');
}
void print_lines (const client_data & data,
const char** lines,
std::size_t num_lines)
{
for (unsigned int i = 0; i < num_lines; ++i) {
if (lines[i])
std::cout << indent(data) << indentation << lines[i] << "\n";
else
std::cout << "\n";
}
}
void print_headers (client_data & data)
{
if (data.printed_headers)
return;
std::cout << "#include <algorithm>\n"
<< "#include <functional>\n"
<< "#include <memory>\n"
<< "#include <type_traits>\n"
<< "#include <utility>\n"
<< "\n";
data.printed_headers = true;
}
void open_struct (const client_data & data, CXCursor struct_cursor)
{
std::pair<CXToken*, unsigned int> tokens =
get_tokens(data.tu, struct_cursor);
std::cout << "\n" << indent(data);
const std::string open_brace = "{";
const std::string struct_ = "struct";
const std::string class_ = "class";
for (unsigned int i = 0; i < tokens.second; ++i) {
CXString spelling = clang_getTokenSpelling(data.tu, tokens.first[i]);
const char* c_str = clang_getCString(spelling);
if (c_str == open_brace)
break;
if (c_str == struct_ || c_str == class_) {
std::cout << "\n" << indent(data);
} else if (i) {
std::cout << " ";
}
std::cout << c_str;
}
free_tokens(data.tu, tokens);
std::cout << "\n"
<< indent(data) << "{\n"
<< indent(data) << "public:\n";
const char* public_interface[] = {
0,
"any_printable () = default;",
0,
"template <typename T_T__>",
"any_printable (T_T__ value) :",
" handle_ (",
" std::make_shared<",
" handle<typename std::remove_reference<T_T__>::type>",
" >(std::forward<T_T__>(value))",
" )",
"{}",
0,
"any_printable (any_printable && rhs) noexcept = default;",
0,
"template <typename T_T__>",
"any_printable & operator= (T_T__ value)",
"{",
" if (handle_.unique())",
" *handle_ = std::forward<T_T__>(value);",
" else if (!handle_)",
" handle_ = std::make_shared<T_T__>(std::forward<T_T__>(value));",
" return *this;",
"}",
0,
"any_printable & operator= (any_printable && rhs) noexcept = default;"
};
print_lines(data,
public_interface,
sizeof(public_interface) / sizeof(const char*));
}
void close_struct (const client_data & data)
{
std::cout << "\n"
<< indent(data) << "private:\n";
const char* handle_base_preamble[] = {
0,
"struct handle_base",
"{",
" virtual ~handle_base () {}",
" virtual std::shared_ptr<handle_base> close () const = 0;",
0
};
print_lines(data,
handle_base_preamble,
sizeof(handle_base_preamble) / sizeof(const char*));
for (auto & member : data.member_functions) {
std::cout << indent(data) << indentation << indentation
<< "virtual " << member[0] << " = 0;\n";
}
const char* handle_preamble[] = {
0,
"};",
0,
"template <typename T_T__>",
"struct handle :",
" handle_base",
"{",
" template <typename T_T__>",
" handle (T_T__ value,",
" typename std::enable_if<",
" std::is_reference<U_U__>::value",
" >::type* = 0) :",
" value_ (value)",
" {}",
0,
" template <typename U_U__ = T_T__>",
" handle (T_T__ value,",
" typename std::enable_if<",
" !std::is_reference<U_U__>::value,",
" int",
" >::type* = 0) noexcept :",
" value_ (std::move(value))",
" {}",
0,
" virtual std::shared_ptr<handle_base> clone () const",
" { return std::make_shared<handle>(value_); }"
};
print_lines(data,
handle_preamble,
sizeof(handle_preamble) / sizeof(const char*));
for (auto & member : data.member_functions) {
std::cout << "\n"
<< indent(data) << indentation << indentation
<< "virtual " << member[0] << "\n"
<< indent(data) << indentation << indentation
<< "{ " << member[2] << "value_." << member[3]
<< "( " << member[1] << " ); }\n";
}
const char* handle_postamble[] = {
0,
" T_T__ value_;",
"};",
0,
"template <typename T_T__>",
"struct handle<std::reference_wrapper<T_T__>> :",
" handle<T_T__ &>",
"{",
" handle (std::reference_wrapper<T_T__> ref) :",
" handle<T_T__ &> (ref.get())",
" {}",
"};",
0,
"const handle_base & read () const",
"{ return *handle_; }",
0,
"handle_base & write ()",
"{",
" if (!handle_.unique())",
" handle_ = handle_->clone();",
" return *handle_;",
"}",
0,
"std::shared_ptr<handle_base> handle_;"
};
print_lines(data,
handle_postamble,
sizeof(handle_postamble) / sizeof(const char*));
std::cout << "\n"
<< indent(data) << "};\n";
}
void print_member_function (const client_data & data, CXCursor cursor)
{
std::cout << "\n"
<< std::string(indent_spaces, ' ') << indent(data)
<< data.member_functions.back()[0];
std::cout << "\n" << std::string(indent_spaces, ' ') << indent(data)
<< "{ assert(handle_); " << data.member_functions.back()[2]
<< "handle_->"
<< clang_getCString(clang_getCursorSpelling(cursor))
<< "( " << data.member_functions.back()[1] << " ); }\n";
}
void open_namespace (const client_data & data, CXCursor namespace_)
{
std::cout
<< "\n"
<< indent(data)
<< "namespace "
<< clang_getCString(clang_getCursorSpelling(namespace_))
<< " {";
}
void close_namespace (const client_data & data)
{ std::cout << "\n" << indent(data) << "}\n"; }
CXChildVisitResult
visitor (CXCursor cursor, CXCursor parent, CXClientData data_)
{
client_data & data = *static_cast<client_data*>(data_);
CXCursor null_cursor = clang_getNullCursor();
// close open namespaces we have left
CXCursor enclosing_namespace = parent;
while (!clang_equalCursors(enclosing_namespace, tu_cursor) &&
clang_getCursorKind(enclosing_namespace) != CXCursor_Namespace) {
enclosing_namespace =
clang_getCursorSemanticParent(enclosing_namespace);
}
if (!clang_equalCursors(enclosing_namespace, tu_cursor) &&
clang_getCursorKind(enclosing_namespace) == CXCursor_Namespace) {
while (!data.current_namespaces.empty() &&
!clang_equalCursors(enclosing_namespace,
data.current_namespaces.back())) {
data.current_namespaces.pop_back();
close_namespace(data);
}
}
// close open struct if we have left it
CXCursor enclosing_struct = parent;
while (!clang_equalCursors(enclosing_struct, tu_cursor) &&
!struct_kind(clang_getCursorKind(enclosing_struct))) {
enclosing_struct = clang_getCursorSemanticParent(enclosing_struct);
}
if (!clang_Cursor_isNull(data.current_struct) &&
!clang_equalCursors(enclosing_struct, data.current_struct)) {
data.current_struct = null_cursor;
close_struct(data);
data.member_functions.clear();
}
CXCursorKind kind = clang_getCursorKind(cursor);
if (kind == CXCursor_Namespace) {
CXSourceLocation location = clang_getCursorLocation(cursor);
const bool from_main_file = clang_Location_isFromMainFile(location);
if (from_main_file) {
print_headers(data);
open_namespace(data, cursor);
data.current_namespaces.push_back(cursor);
}
return CXChildVisit_Recurse;
} else if (struct_kind(kind)) {
if (clang_Cursor_isNull(data.current_struct)) {
print_headers(data);
data.current_struct = cursor;
open_struct(data, cursor);
return CXChildVisit_Recurse;
}
} else if (kind == CXCursor_CXXMethod) {
std::pair<CXToken*, unsigned int> tokens = get_tokens(data.tu, cursor);
const std::string open_brace = "{";
const std::string semicolon = ";";
std::string str;
for (unsigned int i = 0; i < tokens.second; ++i) {
CXString spelling =
clang_getTokenSpelling(data.tu, tokens.first[i]);
const char* c_str = clang_getCString(spelling);
if (c_str == open_brace || c_str == semicolon)
break;
if (i)
str += " ";
str += c_str;
}
std::string args;
const int num_args = clang_Cursor_getNumArguments(cursor);
for (int i = 0; i < num_args; ++i) {
if (i)
args += ", ";
CXCursor arg_cursor = clang_Cursor_getArgument(cursor, i);
args += clang_getCString(clang_getCursorSpelling(arg_cursor));
}
const char* return_str =
clang_getCursorResultType(cursor).kind == CXType_Void ?
"" :
"return ";
const char* function_name =
clang_getCString(clang_getCursorSpelling(cursor));
free_tokens(data.tu, tokens);
data.member_functions.push_back({str, args, return_str, function_name});
print_member_function(data, cursor);
}
return CXChildVisit_Continue;
}
int main (int argc, char* argv[])
{
CXIndex index = clang_createIndex(0, 1);
CXTranslationUnit tu = clang_parseTranslationUnit(
index,
0,
argv,
argc,
0,
0,
CXTranslationUnit_DetailedPreprocessingRecord
);
const char* filename =
clang_getCString(clang_getTranslationUnitSpelling(tu));
client_data data = {tu, {}, clang_getNullCursor(), {}, false, filename};
tu_cursor = clang_getTranslationUnitCursor(tu);
clang_visitChildren(tu_cursor, visitor, &data);
if (!clang_Cursor_isNull(data.current_struct))
close_struct(data);
while (!data.current_namespaces.empty()) {
data.current_namespaces.pop_back();
close_namespace(data);
}
clang_disposeTranslationUnit(tu);
clang_disposeIndex(index);
return 0;
}
<commit_msg>Only process structs that originate in the TU's main file.<commit_after>#include <clang-c/Index.h>
#include <cstdio>
#include <array>
#include <iostream>
#include <vector>
namespace {
const unsigned int indent_spaces = 4;
const std::string indentation(indent_spaces, ' ');
}
CXCursor tu_cursor;
struct client_data
{
CXTranslationUnit tu;
std::vector<CXCursor> current_namespaces;
CXCursor current_struct;
// function signature, forwarding call arguments, optional return
// keyword, and function name
std::vector<std::array<std::string, 4>> member_functions;
bool printed_headers;
const char* filename;
};
std::pair<CXToken*, unsigned int>
get_tokens (CXTranslationUnit tu, CXCursor cursor)
{
CXSourceRange range = clang_getCursorExtent(cursor);
CXSourceLocation start = clang_getRangeStart(range);
CXSourceLocation end = clang_getRangeEnd(range);
unsigned int start_offset, end_offset;
std::pair<CXToken*, unsigned int> retval(0, 0);
clang_tokenize(tu, range, &retval.first, &retval.second);
return retval;
}
void
free_tokens (CXTranslationUnit tu, std::pair<CXToken*, unsigned int> tokens)
{ clang_disposeTokens(tu, tokens.first, tokens.second); }
void print_tokens (CXTranslationUnit tu, CXCursor cursor)
{
std::pair<CXToken*, unsigned int> tokens = get_tokens(tu, cursor);
for (unsigned int i = 0; i < tokens.second; ++i) {
if (i)
std::cout << " ";
CXString spelling = clang_getTokenSpelling(tu, tokens.first[i]);
std::cout << clang_getCString(spelling);
}
std::cout << "\n";
free_tokens(tu, tokens);
}
bool struct_kind (CXCursorKind kind)
{
switch (kind) {
case CXCursor_ClassDecl:
case CXCursor_StructDecl:
case CXCursor_ClassTemplate:
case CXCursor_ClassTemplatePartialSpecialization:
return true;
}
return false;
}
std::string indent (const client_data & data)
{
std::size_t size = data.current_namespaces.size();
return std::string(size * indent_spaces, ' ');
}
void print_lines (const client_data & data,
const char** lines,
std::size_t num_lines)
{
for (unsigned int i = 0; i < num_lines; ++i) {
if (lines[i])
std::cout << indent(data) << indentation << lines[i] << "\n";
else
std::cout << "\n";
}
}
void print_headers (client_data & data)
{
if (data.printed_headers)
return;
std::cout << "#include <algorithm>\n"
<< "#include <functional>\n"
<< "#include <memory>\n"
<< "#include <type_traits>\n"
<< "#include <utility>\n"
<< "\n";
data.printed_headers = true;
}
void open_struct (const client_data & data, CXCursor struct_cursor)
{
std::pair<CXToken*, unsigned int> tokens =
get_tokens(data.tu, struct_cursor);
std::cout << "\n" << indent(data);
const std::string open_brace = "{";
const std::string struct_ = "struct";
const std::string class_ = "class";
for (unsigned int i = 0; i < tokens.second; ++i) {
CXString spelling = clang_getTokenSpelling(data.tu, tokens.first[i]);
const char* c_str = clang_getCString(spelling);
if (c_str == open_brace)
break;
if (c_str == struct_ || c_str == class_) {
std::cout << "\n" << indent(data);
} else if (i) {
std::cout << " ";
}
std::cout << c_str;
}
free_tokens(data.tu, tokens);
std::cout << "\n"
<< indent(data) << "{\n"
<< indent(data) << "public:\n";
const char* public_interface[] = {
0,
"any_printable () = default;",
0,
"template <typename T_T__>",
"any_printable (T_T__ value) :",
" handle_ (",
" std::make_shared<",
" handle<typename std::remove_reference<T_T__>::type>",
" >(std::forward<T_T__>(value))",
" )",
"{}",
0,
"any_printable (any_printable && rhs) noexcept = default;",
0,
"template <typename T_T__>",
"any_printable & operator= (T_T__ value)",
"{",
" if (handle_.unique())",
" *handle_ = std::forward<T_T__>(value);",
" else if (!handle_)",
" handle_ = std::make_shared<T_T__>(std::forward<T_T__>(value));",
" return *this;",
"}",
0,
"any_printable & operator= (any_printable && rhs) noexcept = default;"
};
print_lines(data,
public_interface,
sizeof(public_interface) / sizeof(const char*));
}
void close_struct (const client_data & data)
{
std::cout << "\n"
<< indent(data) << "private:\n";
const char* handle_base_preamble[] = {
0,
"struct handle_base",
"{",
" virtual ~handle_base () {}",
" virtual std::shared_ptr<handle_base> close () const = 0;",
0
};
print_lines(data,
handle_base_preamble,
sizeof(handle_base_preamble) / sizeof(const char*));
for (auto & member : data.member_functions) {
std::cout << indent(data) << indentation << indentation
<< "virtual " << member[0] << " = 0;\n";
}
const char* handle_preamble[] = {
0,
"};",
0,
"template <typename T_T__>",
"struct handle :",
" handle_base",
"{",
" template <typename T_T__>",
" handle (T_T__ value,",
" typename std::enable_if<",
" std::is_reference<U_U__>::value",
" >::type* = 0) :",
" value_ (value)",
" {}",
0,
" template <typename U_U__ = T_T__>",
" handle (T_T__ value,",
" typename std::enable_if<",
" !std::is_reference<U_U__>::value,",
" int",
" >::type* = 0) noexcept :",
" value_ (std::move(value))",
" {}",
0,
" virtual std::shared_ptr<handle_base> clone () const",
" { return std::make_shared<handle>(value_); }"
};
print_lines(data,
handle_preamble,
sizeof(handle_preamble) / sizeof(const char*));
for (auto & member : data.member_functions) {
std::cout << "\n"
<< indent(data) << indentation << indentation
<< "virtual " << member[0] << "\n"
<< indent(data) << indentation << indentation
<< "{ " << member[2] << "value_." << member[3]
<< "( " << member[1] << " ); }\n";
}
const char* handle_postamble[] = {
0,
" T_T__ value_;",
"};",
0,
"template <typename T_T__>",
"struct handle<std::reference_wrapper<T_T__>> :",
" handle<T_T__ &>",
"{",
" handle (std::reference_wrapper<T_T__> ref) :",
" handle<T_T__ &> (ref.get())",
" {}",
"};",
0,
"const handle_base & read () const",
"{ return *handle_; }",
0,
"handle_base & write ()",
"{",
" if (!handle_.unique())",
" handle_ = handle_->clone();",
" return *handle_;",
"}",
0,
"std::shared_ptr<handle_base> handle_;"
};
print_lines(data,
handle_postamble,
sizeof(handle_postamble) / sizeof(const char*));
std::cout << "\n"
<< indent(data) << "};\n";
}
void print_member_function (const client_data & data, CXCursor cursor)
{
std::cout << "\n"
<< std::string(indent_spaces, ' ') << indent(data)
<< data.member_functions.back()[0];
std::cout << "\n" << std::string(indent_spaces, ' ') << indent(data)
<< "{ assert(handle_); " << data.member_functions.back()[2]
<< "handle_->"
<< clang_getCString(clang_getCursorSpelling(cursor))
<< "( " << data.member_functions.back()[1] << " ); }\n";
}
void open_namespace (const client_data & data, CXCursor namespace_)
{
std::cout
<< "\n"
<< indent(data)
<< "namespace "
<< clang_getCString(clang_getCursorSpelling(namespace_))
<< " {";
}
void close_namespace (const client_data & data)
{ std::cout << "\n" << indent(data) << "}\n"; }
CXChildVisitResult
visitor (CXCursor cursor, CXCursor parent, CXClientData data_)
{
client_data & data = *static_cast<client_data*>(data_);
CXCursor null_cursor = clang_getNullCursor();
// close open namespaces we have left
CXCursor enclosing_namespace = parent;
while (!clang_equalCursors(enclosing_namespace, tu_cursor) &&
clang_getCursorKind(enclosing_namespace) != CXCursor_Namespace) {
enclosing_namespace =
clang_getCursorSemanticParent(enclosing_namespace);
}
if (!clang_equalCursors(enclosing_namespace, tu_cursor) &&
clang_getCursorKind(enclosing_namespace) == CXCursor_Namespace) {
while (!data.current_namespaces.empty() &&
!clang_equalCursors(enclosing_namespace,
data.current_namespaces.back())) {
data.current_namespaces.pop_back();
close_namespace(data);
}
}
// close open struct if we have left it
CXCursor enclosing_struct = parent;
while (!clang_equalCursors(enclosing_struct, tu_cursor) &&
!struct_kind(clang_getCursorKind(enclosing_struct))) {
enclosing_struct = clang_getCursorSemanticParent(enclosing_struct);
}
if (!clang_Cursor_isNull(data.current_struct) &&
!clang_equalCursors(enclosing_struct, data.current_struct)) {
data.current_struct = null_cursor;
close_struct(data);
data.member_functions.clear();
}
CXSourceLocation location = clang_getCursorLocation(cursor);
const bool from_main_file = clang_Location_isFromMainFile(location);
CXCursorKind kind = clang_getCursorKind(cursor);
if (kind == CXCursor_Namespace) {
if (from_main_file) {
print_headers(data);
open_namespace(data, cursor);
data.current_namespaces.push_back(cursor);
}
return CXChildVisit_Recurse;
} else if (!from_main_file) {
return CXChildVisit_Continue;
} else if (struct_kind(kind)) {
if (clang_Cursor_isNull(data.current_struct)) {
print_headers(data);
data.current_struct = cursor;
open_struct(data, cursor);
return CXChildVisit_Recurse;
}
} else if (kind == CXCursor_CXXMethod) {
std::pair<CXToken*, unsigned int> tokens = get_tokens(data.tu, cursor);
const std::string open_brace = "{";
const std::string semicolon = ";";
std::string str;
for (unsigned int i = 0; i < tokens.second; ++i) {
CXString spelling =
clang_getTokenSpelling(data.tu, tokens.first[i]);
const char* c_str = clang_getCString(spelling);
if (c_str == open_brace || c_str == semicolon)
break;
if (i)
str += " ";
str += c_str;
}
std::string args;
const int num_args = clang_Cursor_getNumArguments(cursor);
for (int i = 0; i < num_args; ++i) {
if (i)
args += ", ";
CXCursor arg_cursor = clang_Cursor_getArgument(cursor, i);
args += clang_getCString(clang_getCursorSpelling(arg_cursor));
}
const char* return_str =
clang_getCursorResultType(cursor).kind == CXType_Void ?
"" :
"return ";
const char* function_name =
clang_getCString(clang_getCursorSpelling(cursor));
free_tokens(data.tu, tokens);
data.member_functions.push_back({str, args, return_str, function_name});
print_member_function(data, cursor);
}
return CXChildVisit_Continue;
}
int main (int argc, char* argv[])
{
CXIndex index = clang_createIndex(0, 1);
CXTranslationUnit tu = clang_parseTranslationUnit(
index,
0,
argv,
argc,
0,
0,
CXTranslationUnit_DetailedPreprocessingRecord
);
const char* filename =
clang_getCString(clang_getTranslationUnitSpelling(tu));
client_data data = {tu, {}, clang_getNullCursor(), {}, false, filename};
tu_cursor = clang_getTranslationUnitCursor(tu);
clang_visitChildren(tu_cursor, visitor, &data);
if (!clang_Cursor_isNull(data.current_struct))
close_struct(data);
while (!data.current_namespaces.empty()) {
data.current_namespaces.pop_back();
close_namespace(data);
}
clang_disposeTranslationUnit(tu);
clang_disposeIndex(index);
return 0;
}
<|endoftext|>
|
<commit_before>/*
Highly Optimized Object-oriented Many-particle Dynamics -- Blue Edition
(HOOMD-blue) Open Source Software License Copyright 2009-2014 The Regents of
the University of Michigan All rights reserved.
HOOMD-blue may contain modifications ("Contributions") provided, and to which
copyright is held, by various Contributors who have granted The Regents of the
University of Michigan the right to modify and/or distribute such Contributions.
You may redistribute, use, and create derivate works of HOOMD-blue, in source
and binary forms, provided you abide by the following conditions:
* Redistributions of source code must retain the above copyright notice, this
list of conditions, and the following disclaimer both in the code and
prominently in any materials provided with the distribution.
* 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.
* All publications and presentations based on HOOMD-blue, including any reports
or published results obtained, in whole or in part, with HOOMD-blue, will
acknowledge its use according to the terms posted at the time of submission on:
http://codeblue.umich.edu/hoomd-blue/citations.html
* Any electronic documents citing HOOMD-Blue will link to the HOOMD-Blue website:
http://codeblue.umich.edu/hoomd-blue/
* Apart from the above required attributions, neither the name of the copyright
holder nor the names of HOOMD-blue's contributors may be used to endorse or
promote products derived from this software without specific prior written
permission.
Disclaimer
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER AND CONTRIBUTORS ``AS IS'' AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, AND/OR ANY
WARRANTIES THAT THIS SOFTWARE IS FREE OF INFRINGEMENT 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.
*/
// Maintainer: jglaser
#ifdef WIN32
#pragma warning( push )
#pragma warning( disable : 4244 )
#endif
#include <boost/python.hpp>
using namespace boost::python;
#include <boost/bind.hpp>
using namespace boost;
#include "TwoStepNVTMTKGPU.h"
#include "TwoStepNVTMTKGPU.cuh"
#include "TwoStepNPTMTKGPU.cuh"
#ifdef ENABLE_MPI
#include "Communicator.h"
#include "HOOMDMPI.h"
#endif
/*! \file TwoStepNVTMTKGPU.h
\brief Contains code for the TwoStepNVTMTKGPU class
*/
/*! \param sysdef SystemDefinition this method will act on. Must not be NULL.
\param group The group of particles this integration method is to work on
\param thermo compute for thermodynamic quantities
\param tau NVT period
\param T Temperature set point
\param suffix Suffix to attach to the end of log quantity names
*/
TwoStepNVTMTKGPU::TwoStepNVTMTKGPU(boost::shared_ptr<SystemDefinition> sysdef,
boost::shared_ptr<ParticleGroup> group,
boost::shared_ptr<ComputeThermo> thermo,
Scalar tau,
boost::shared_ptr<Variant> T,
const std::string& suffix)
: TwoStepNVTMTK(sysdef, group, thermo, tau, T, suffix)
{
// only one GPU is supported
if (!exec_conf->isCUDAEnabled())
{
m_exec_conf->msg->error() << "Creating a TwoStepNVTMTKPU when CUDA is disabled" << endl;
throw std::runtime_error("Error initializing TwoStepNVTMTKGPU");
}
// initialize autotuner
std::vector<unsigned int> valid_params;
for (unsigned int block_size = 32; block_size <= 1024; block_size += 32)
valid_params.push_back(block_size);
m_tuner_one.reset(new Autotuner(valid_params, 5, 100000, "nvt_mtk_step_one", this->m_exec_conf));
m_tuner_two.reset(new Autotuner(valid_params, 5, 100000, "nvt_mtk_step_two", this->m_exec_conf));
m_reduction_block_size = 512;
// this breaks memory scaling (calculate memory requirements from global group size)
// unless we reallocate memory with every change of the maximum particle number
m_num_blocks = m_group->getNumMembersGlobal() / m_reduction_block_size + 1;
GPUArray< Scalar > scratch(m_num_blocks, exec_conf);
m_scratch.swap(scratch);
GPUArray< Scalar> temperature(1, exec_conf);
m_temperature.swap(temperature);
}
/*! \param timestep Current time step
\post Particle positions are moved forward to timestep+1 and velocities to timestep+1/2 per the Nose-Hoover method
*/
void TwoStepNVTMTKGPU::integrateStepOne(unsigned int timestep)
{
unsigned int group_size = m_group->getNumMembers();
if (group_size == 0)
return;
// profile this step
if (m_prof)
m_prof->push(exec_conf, "NVT MTK step 1");
// compute the current thermodynamic properties
m_thermo->compute(timestep);
// compute temperature for the next half time step
m_curr_T = m_thermo->getTemperature();
// advance thermostat
advanceThermostat(timestep, false);
// access all the needed data
ArrayHandle<Scalar4> d_pos(m_pdata->getPositions(), access_location::device, access_mode::readwrite);
ArrayHandle<Scalar4> d_vel(m_pdata->getVelocities(), access_location::device, access_mode::readwrite);
ArrayHandle<Scalar3> d_accel(m_pdata->getAccelerations(), access_location::device, access_mode::read);
ArrayHandle<int3> d_image(m_pdata->getImages(), access_location::device, access_mode::readwrite);
BoxDim box = m_pdata->getBox();
ArrayHandle< unsigned int > d_index_array(m_group->getIndexArray(), access_location::device, access_mode::read);
// perform the update on the GPU
m_tuner_one->begin();
gpu_nvt_mtk_step_one(d_pos.data,
d_vel.data,
d_accel.data,
d_image.data,
d_index_array.data,
group_size,
box,
m_tuner_one->getParam(),
m_exp_thermo_fac,
m_deltaT);
if (exec_conf->isCUDAErrorCheckingEnabled())
CHECK_CUDA_ERROR();
m_tuner_one->end();
// done profiling
if (m_prof)
m_prof->pop(exec_conf);
}
/*! \param timestep Current time step
\post particle velocities are moved forward to timestep+1 on the GPU
*/
void TwoStepNVTMTKGPU::integrateStepTwo(unsigned int timestep)
{
unsigned int group_size = m_group->getNumMembers();
const GPUArray< Scalar4 >& net_force = m_pdata->getNetForce();
// profile this step
if (m_prof)
m_prof->push(exec_conf, "NVT MTK step 2");
ArrayHandle<Scalar4> d_vel(m_pdata->getVelocities(), access_location::device, access_mode::readwrite);
ArrayHandle<Scalar3> d_accel(m_pdata->getAccelerations(), access_location::device, access_mode::readwrite);
ArrayHandle<Scalar4> d_net_force(net_force, access_location::device, access_mode::read);
ArrayHandle< unsigned int > d_index_array(m_group->getIndexArray(), access_location::device, access_mode::read);
// perform the update on the GPU
m_tuner_two->begin();
gpu_nvt_mtk_step_two(d_vel.data,
d_accel.data,
d_index_array.data,
group_size,
d_net_force.data,
m_tuner_two->getParam(),
m_deltaT);
if (exec_conf->isCUDAErrorCheckingEnabled())
CHECK_CUDA_ERROR();
m_tuner_two->end();
{
// recalulate temperature
ArrayHandle<Scalar> d_temperature(m_temperature, access_location::device, access_mode::overwrite);
ArrayHandle<Scalar> d_scratch(m_scratch, access_location::device, access_mode::overwrite);
// update number of blocks to current group size
m_num_blocks = m_group->getNumMembers() / m_reduction_block_size + 1;
gpu_npt_mtk_temperature(d_temperature.data,
d_vel.data,
d_scratch.data,
m_num_blocks,
m_reduction_block_size,
d_index_array.data,
group_size,
m_thermo->getNDOF());
if (m_exec_conf->isCUDAErrorCheckingEnabled())
CHECK_CUDA_ERROR();
}
// read back intermediate temperature from GPU
{
ArrayHandle<Scalar> h_temperature(m_temperature, access_location::host, access_mode::read);
m_curr_T= *h_temperature.data;
}
#ifdef ENABLE_MPI
if (m_comm)
{
MPI_Allreduce(MPI_IN_PLACE, &m_curr_T, 1, MPI_HOOMD_SCALAR, MPI_SUM, m_exec_conf->getMPICommunicator() );
}
#endif
// get temperature and advance thermostat
advanceThermostat(timestep+1,true);
// rescale velocities
gpu_npt_mtk_thermostat(d_vel.data,
d_index_array.data,
group_size,
m_exp_thermo_fac);
if (m_exec_conf->isCUDAErrorCheckingEnabled())
CHECK_CUDA_ERROR();
// done profiling
if (m_prof)
m_prof->pop(exec_conf);
}
void export_TwoStepNVTMTKGPU()
{
class_<TwoStepNVTMTKGPU, boost::shared_ptr<TwoStepNVTMTKGPU>, bases<TwoStepNVTMTK>, boost::noncopyable>
("TwoStepNVTMTKGPU", init< boost::shared_ptr<SystemDefinition>,
boost::shared_ptr<ParticleGroup>,
boost::shared_ptr<ComputeThermo>,
Scalar,
boost::shared_ptr<Variant>,
const std::string&
>())
;
}
#ifdef WIN32
#pragma warning( pop )
#endif
<commit_msg>Minor strong scaling optimization in NVT MTK<commit_after>/*
Highly Optimized Object-oriented Many-particle Dynamics -- Blue Edition
(HOOMD-blue) Open Source Software License Copyright 2009-2014 The Regents of
the University of Michigan All rights reserved.
HOOMD-blue may contain modifications ("Contributions") provided, and to which
copyright is held, by various Contributors who have granted The Regents of the
University of Michigan the right to modify and/or distribute such Contributions.
You may redistribute, use, and create derivate works of HOOMD-blue, in source
and binary forms, provided you abide by the following conditions:
* Redistributions of source code must retain the above copyright notice, this
list of conditions, and the following disclaimer both in the code and
prominently in any materials provided with the distribution.
* 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.
* All publications and presentations based on HOOMD-blue, including any reports
or published results obtained, in whole or in part, with HOOMD-blue, will
acknowledge its use according to the terms posted at the time of submission on:
http://codeblue.umich.edu/hoomd-blue/citations.html
* Any electronic documents citing HOOMD-Blue will link to the HOOMD-Blue website:
http://codeblue.umich.edu/hoomd-blue/
* Apart from the above required attributions, neither the name of the copyright
holder nor the names of HOOMD-blue's contributors may be used to endorse or
promote products derived from this software without specific prior written
permission.
Disclaimer
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER AND CONTRIBUTORS ``AS IS'' AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, AND/OR ANY
WARRANTIES THAT THIS SOFTWARE IS FREE OF INFRINGEMENT 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.
*/
// Maintainer: jglaser
#ifdef WIN32
#pragma warning( push )
#pragma warning( disable : 4244 )
#endif
#include <boost/python.hpp>
using namespace boost::python;
#include <boost/bind.hpp>
using namespace boost;
#include "TwoStepNVTMTKGPU.h"
#include "TwoStepNVTMTKGPU.cuh"
#include "TwoStepNPTMTKGPU.cuh"
#ifdef ENABLE_MPI
#include "Communicator.h"
#include "HOOMDMPI.h"
#endif
/*! \file TwoStepNVTMTKGPU.h
\brief Contains code for the TwoStepNVTMTKGPU class
*/
/*! \param sysdef SystemDefinition this method will act on. Must not be NULL.
\param group The group of particles this integration method is to work on
\param thermo compute for thermodynamic quantities
\param tau NVT period
\param T Temperature set point
\param suffix Suffix to attach to the end of log quantity names
*/
TwoStepNVTMTKGPU::TwoStepNVTMTKGPU(boost::shared_ptr<SystemDefinition> sysdef,
boost::shared_ptr<ParticleGroup> group,
boost::shared_ptr<ComputeThermo> thermo,
Scalar tau,
boost::shared_ptr<Variant> T,
const std::string& suffix)
: TwoStepNVTMTK(sysdef, group, thermo, tau, T, suffix)
{
// only one GPU is supported
if (!exec_conf->isCUDAEnabled())
{
m_exec_conf->msg->error() << "Creating a TwoStepNVTMTKPU when CUDA is disabled" << endl;
throw std::runtime_error("Error initializing TwoStepNVTMTKGPU");
}
// initialize autotuner
std::vector<unsigned int> valid_params;
for (unsigned int block_size = 32; block_size <= 1024; block_size += 32)
valid_params.push_back(block_size);
m_tuner_one.reset(new Autotuner(valid_params, 5, 100000, "nvt_mtk_step_one", this->m_exec_conf));
m_tuner_two.reset(new Autotuner(valid_params, 5, 100000, "nvt_mtk_step_two", this->m_exec_conf));
m_reduction_block_size = 512;
// this breaks memory scaling (calculate memory requirements from global group size)
// unless we reallocate memory with every change of the maximum particle number
m_num_blocks = m_group->getNumMembersGlobal() / m_reduction_block_size + 1;
GPUArray< Scalar > scratch(m_num_blocks, exec_conf);
m_scratch.swap(scratch);
GPUArray< Scalar> temperature(1, exec_conf, true);
m_temperature.swap(temperature);
}
/*! \param timestep Current time step
\post Particle positions are moved forward to timestep+1 and velocities to timestep+1/2 per the Nose-Hoover method
*/
void TwoStepNVTMTKGPU::integrateStepOne(unsigned int timestep)
{
unsigned int group_size = m_group->getNumMembers();
if (group_size == 0)
return;
// profile this step
if (m_prof)
m_prof->push(exec_conf, "NVT MTK step 1");
// compute the current thermodynamic properties
m_thermo->compute(timestep);
// compute temperature for the next half time step
m_curr_T = m_thermo->getTemperature();
// advance thermostat
advanceThermostat(timestep, false);
// access all the needed data
ArrayHandle<Scalar4> d_pos(m_pdata->getPositions(), access_location::device, access_mode::readwrite);
ArrayHandle<Scalar4> d_vel(m_pdata->getVelocities(), access_location::device, access_mode::readwrite);
ArrayHandle<Scalar3> d_accel(m_pdata->getAccelerations(), access_location::device, access_mode::read);
ArrayHandle<int3> d_image(m_pdata->getImages(), access_location::device, access_mode::readwrite);
BoxDim box = m_pdata->getBox();
ArrayHandle< unsigned int > d_index_array(m_group->getIndexArray(), access_location::device, access_mode::read);
// perform the update on the GPU
m_tuner_one->begin();
gpu_nvt_mtk_step_one(d_pos.data,
d_vel.data,
d_accel.data,
d_image.data,
d_index_array.data,
group_size,
box,
m_tuner_one->getParam(),
m_exp_thermo_fac,
m_deltaT);
if (exec_conf->isCUDAErrorCheckingEnabled())
CHECK_CUDA_ERROR();
m_tuner_one->end();
// done profiling
if (m_prof)
m_prof->pop(exec_conf);
}
/*! \param timestep Current time step
\post particle velocities are moved forward to timestep+1 on the GPU
*/
void TwoStepNVTMTKGPU::integrateStepTwo(unsigned int timestep)
{
unsigned int group_size = m_group->getNumMembers();
const GPUArray< Scalar4 >& net_force = m_pdata->getNetForce();
// profile this step
if (m_prof)
m_prof->push(exec_conf, "NVT MTK step 2");
ArrayHandle<Scalar4> d_vel(m_pdata->getVelocities(), access_location::device, access_mode::readwrite);
ArrayHandle<Scalar3> d_accel(m_pdata->getAccelerations(), access_location::device, access_mode::readwrite);
ArrayHandle<Scalar4> d_net_force(net_force, access_location::device, access_mode::read);
ArrayHandle< unsigned int > d_index_array(m_group->getIndexArray(), access_location::device, access_mode::read);
// perform the update on the GPU
m_tuner_two->begin();
gpu_nvt_mtk_step_two(d_vel.data,
d_accel.data,
d_index_array.data,
group_size,
d_net_force.data,
m_tuner_two->getParam(),
m_deltaT);
if (exec_conf->isCUDAErrorCheckingEnabled())
CHECK_CUDA_ERROR();
m_tuner_two->end();
{
// recalulate temperature
ArrayHandle<Scalar> d_temperature(m_temperature, access_location::device, access_mode::overwrite);
ArrayHandle<Scalar> d_scratch(m_scratch, access_location::device, access_mode::overwrite);
// update number of blocks to current group size
m_num_blocks = m_group->getNumMembers() / m_reduction_block_size + 1;
gpu_npt_mtk_temperature(d_temperature.data,
d_vel.data,
d_scratch.data,
m_num_blocks,
m_reduction_block_size,
d_index_array.data,
group_size,
m_thermo->getNDOF());
if (m_exec_conf->isCUDAErrorCheckingEnabled())
CHECK_CUDA_ERROR();
}
// read back intermediate temperature from GPU
{
ArrayHandle<Scalar> h_temperature(m_temperature, access_location::host, access_mode::read);
m_curr_T= *h_temperature.data;
}
#ifdef ENABLE_MPI
if (m_comm)
{
MPI_Allreduce(MPI_IN_PLACE, &m_curr_T, 1, MPI_HOOMD_SCALAR, MPI_SUM, m_exec_conf->getMPICommunicator() );
}
#endif
// get temperature and advance thermostat
advanceThermostat(timestep+1,true);
// rescale velocities
gpu_npt_mtk_thermostat(d_vel.data,
d_index_array.data,
group_size,
m_exp_thermo_fac);
if (m_exec_conf->isCUDAErrorCheckingEnabled())
CHECK_CUDA_ERROR();
// done profiling
if (m_prof)
m_prof->pop(exec_conf);
}
void export_TwoStepNVTMTKGPU()
{
class_<TwoStepNVTMTKGPU, boost::shared_ptr<TwoStepNVTMTKGPU>, bases<TwoStepNVTMTK>, boost::noncopyable>
("TwoStepNVTMTKGPU", init< boost::shared_ptr<SystemDefinition>,
boost::shared_ptr<ParticleGroup>,
boost::shared_ptr<ComputeThermo>,
Scalar,
boost::shared_ptr<Variant>,
const std::string&
>())
;
}
#ifdef WIN32
#pragma warning( pop )
#endif
<|endoftext|>
|
<commit_before>#include "utility/w5100.h"
#include "utility/socket.h"
extern "C" {
#include "string.h"
}
#include "Arduino.h"
#include "Ethernet.h"
#include "EthernetClient.h"
#include "EthernetServer.h"
#include "Dns.h"
uint16_t EthernetClient::_srcport = 49152; //Use IANA recommended ephemeral port range 49152-65535
EthernetClient::EthernetClient() : _sock(MAX_SOCK_NUM) {
}
EthernetClient::EthernetClient(uint8_t sock) : _sock(sock) {
}
int EthernetClient::connect(const char* host, uint16_t port) {
// Look up the host first
int ret = 0;
DNSClient dns;
IPAddress remote_addr;
dns.begin(Ethernet.dnsServerIP());
ret = dns.getHostByName(host, remote_addr);
if (ret == 1) {
return connect(remote_addr, port);
} else {
return ret;
}
}
int EthernetClient::connect(IPAddress ip, uint16_t port) {
if (_sock != MAX_SOCK_NUM)
return 0;
for (int i = 0; i < MAX_SOCK_NUM; i++) {
uint8_t s = socketStatus(i);
if (s == SnSR::CLOSED || s == SnSR::FIN_WAIT || s == SnSR::CLOSE_WAIT) {
_sock = i;
break;
}
}
if (_sock == MAX_SOCK_NUM)
return 0;
_srcport++;
if (_srcport == 0) _srcport = 49152; //Use IANA recommended ephemeral port range 49152-65535
socket(_sock, SnMR::TCP, _srcport, 0);
if (!::connect(_sock, rawIPAddress(ip), port)) {
_sock = MAX_SOCK_NUM;
return 0;
}
while (status() != SnSR::ESTABLISHED) {
delay(1);
if (status() == SnSR::CLOSED) {
_sock = MAX_SOCK_NUM;
return 0;
}
}
return 1;
}
size_t EthernetClient::write(uint8_t b) {
return write(&b, 1);
}
size_t EthernetClient::write(const uint8_t *buf, size_t size) {
if (_sock == MAX_SOCK_NUM) {
setWriteError();
return 0;
}
if (!send(_sock, buf, size)) {
setWriteError();
return 0;
}
return size;
}
int EthernetClient::available() {
if (_sock != MAX_SOCK_NUM)
return recvAvailable(_sock);
return 0;
}
int EthernetClient::read() {
uint8_t b;
if ( recv(_sock, &b, 1) > 0 )
{
// recv worked
return b;
}
else
{
// No data available
return -1;
}
}
int EthernetClient::read(uint8_t *buf, size_t size) {
return recv(_sock, buf, size);
}
int EthernetClient::peek() {
uint8_t b;
// Unlike recv, peek doesn't check to see if there's any data available, so we must
if (!available())
return -1;
::peek(_sock, &b);
return b;
}
void EthernetClient::flush() {
::flush(_sock);
}
void EthernetClient::stop() {
if (_sock == MAX_SOCK_NUM)
return;
// attempt to close the connection gracefully (send a FIN to other side)
disconnect(_sock);
unsigned long start = millis();
// wait up to a second for the connection to close
uint8_t s;
do {
s = status();
if (s == SnSR::CLOSED)
break; // exit the loop
delay(1);
} while (millis() - start < 1000);
// if it hasn't closed, close it forcefully
if (s != SnSR::CLOSED)
close(_sock);
EthernetClass::_server_port[_sock] = 0;
_sock = MAX_SOCK_NUM;
}
uint8_t EthernetClient::connected() {
if (_sock == MAX_SOCK_NUM) return 0;
uint8_t s = status();
return !(s == SnSR::LISTEN || s == SnSR::CLOSED || s == SnSR::FIN_WAIT ||
(s == SnSR::CLOSE_WAIT && !available()));
}
uint8_t EthernetClient::status() {
if (_sock == MAX_SOCK_NUM) return SnSR::CLOSED;
return socketStatus(_sock);
}
// the next function allows us to use the client returned by
// EthernetServer::available() as the condition in an if-statement.
EthernetClient::operator bool() {
return _sock != MAX_SOCK_NUM;
}
bool EthernetClient::operator==(const EthernetClient& rhs) {
return _sock == rhs._sock && _sock != MAX_SOCK_NUM && rhs._sock != MAX_SOCK_NUM;
}
+uint8_t EthernetClient::getSocketNumber () {
+ return _sock;
+}
<commit_msg>Removed typos in EthernetClient.cpp<commit_after>#include "utility/w5100.h"
#include "utility/socket.h"
extern "C" {
#include "string.h"
}
#include "Arduino.h"
#include "Ethernet.h"
#include "EthernetClient.h"
#include "EthernetServer.h"
#include "Dns.h"
uint16_t EthernetClient::_srcport = 49152; //Use IANA recommended ephemeral port range 49152-65535
EthernetClient::EthernetClient() : _sock(MAX_SOCK_NUM) {
}
EthernetClient::EthernetClient(uint8_t sock) : _sock(sock) {
}
int EthernetClient::connect(const char* host, uint16_t port) {
// Look up the host first
int ret = 0;
DNSClient dns;
IPAddress remote_addr;
dns.begin(Ethernet.dnsServerIP());
ret = dns.getHostByName(host, remote_addr);
if (ret == 1) {
return connect(remote_addr, port);
} else {
return ret;
}
}
int EthernetClient::connect(IPAddress ip, uint16_t port) {
if (_sock != MAX_SOCK_NUM)
return 0;
for (int i = 0; i < MAX_SOCK_NUM; i++) {
uint8_t s = socketStatus(i);
if (s == SnSR::CLOSED || s == SnSR::FIN_WAIT || s == SnSR::CLOSE_WAIT) {
_sock = i;
break;
}
}
if (_sock == MAX_SOCK_NUM)
return 0;
_srcport++;
if (_srcport == 0) _srcport = 49152; //Use IANA recommended ephemeral port range 49152-65535
socket(_sock, SnMR::TCP, _srcport, 0);
if (!::connect(_sock, rawIPAddress(ip), port)) {
_sock = MAX_SOCK_NUM;
return 0;
}
while (status() != SnSR::ESTABLISHED) {
delay(1);
if (status() == SnSR::CLOSED) {
_sock = MAX_SOCK_NUM;
return 0;
}
}
return 1;
}
size_t EthernetClient::write(uint8_t b) {
return write(&b, 1);
}
size_t EthernetClient::write(const uint8_t *buf, size_t size) {
if (_sock == MAX_SOCK_NUM) {
setWriteError();
return 0;
}
if (!send(_sock, buf, size)) {
setWriteError();
return 0;
}
return size;
}
int EthernetClient::available() {
if (_sock != MAX_SOCK_NUM)
return recvAvailable(_sock);
return 0;
}
int EthernetClient::read() {
uint8_t b;
if ( recv(_sock, &b, 1) > 0 )
{
// recv worked
return b;
}
else
{
// No data available
return -1;
}
}
int EthernetClient::read(uint8_t *buf, size_t size) {
return recv(_sock, buf, size);
}
int EthernetClient::peek() {
uint8_t b;
// Unlike recv, peek doesn't check to see if there's any data available, so we must
if (!available())
return -1;
::peek(_sock, &b);
return b;
}
void EthernetClient::flush() {
::flush(_sock);
}
void EthernetClient::stop() {
if (_sock == MAX_SOCK_NUM)
return;
// attempt to close the connection gracefully (send a FIN to other side)
disconnect(_sock);
unsigned long start = millis();
// wait up to a second for the connection to close
uint8_t s;
do {
s = status();
if (s == SnSR::CLOSED)
break; // exit the loop
delay(1);
} while (millis() - start < 1000);
// if it hasn't closed, close it forcefully
if (s != SnSR::CLOSED)
close(_sock);
EthernetClass::_server_port[_sock] = 0;
_sock = MAX_SOCK_NUM;
}
uint8_t EthernetClient::connected() {
if (_sock == MAX_SOCK_NUM) return 0;
uint8_t s = status();
return !(s == SnSR::LISTEN || s == SnSR::CLOSED || s == SnSR::FIN_WAIT ||
(s == SnSR::CLOSE_WAIT && !available()));
}
uint8_t EthernetClient::status() {
if (_sock == MAX_SOCK_NUM) return SnSR::CLOSED;
return socketStatus(_sock);
}
// the next function allows us to use the client returned by
// EthernetServer::available() as the condition in an if-statement.
EthernetClient::operator bool() {
return _sock != MAX_SOCK_NUM;
}
bool EthernetClient::operator==(const EthernetClient& rhs) {
return _sock == rhs._sock && _sock != MAX_SOCK_NUM && rhs._sock != MAX_SOCK_NUM;
}
uint8_t EthernetClient::getSocketNumber() {
return _sock;
}
<|endoftext|>
|
<commit_before>#include "movearray.hpp"
MoveArray::MoveArray() : count(0), num_attacks(0) {
//moveArray = new BitMove[100];
moveArray.resize(100);
}
MoveArray::~MoveArray() {}
void MoveArray::clear() {
count = 0;
num_attacks = 0;
}
void MoveArray::addMove(BitMove mv) {
moveArray[count] = mv;
++count;
}
<commit_msg>Размер массива в moveArray изменен на 109<commit_after>#include "movearray.hpp"
MoveArray::MoveArray() : count(0), num_attacks(0) {
//moveArray = new BitMove[100];
moveArray.resize(109);
}
MoveArray::~MoveArray() {}
void MoveArray::clear() {
count = 0;
num_attacks = 0;
}
void MoveArray::addMove(BitMove mv) {
moveArray[count] = mv;
++count;
}
<|endoftext|>
|
<commit_before>#include <cstdio>
#include <cstring>
#include <ctime>
#include <iostream>
#include <memory>
#include "block.hpp"
#include "hash.hpp"
#include "slice.hpp"
#include "threadpool.hpp"
#include "transforms.hpp"
int main (int argc, char** argv) {
time_t start, end;
time(&start);
std::unique_ptr<transform_t> delegate;
size_t memoryAlloc = 200 * 1024 * 1024;
size_t nThreads = 1;
// parse command line arguments
for (auto i = 1; i < argc; ++i) {
const auto arg = argv[i];
size_t transformIndex = 0;
if (sscanf(arg, "-t%lu", &transformIndex) == 1) {
assert(delegate == nullptr);
// raw
if (transformIndex == 0) delegate.reset(new dumpHeaders());
else if (transformIndex == 1) delegate.reset(new dumpScripts());
// indexd
else if (transformIndex == 2) delegate.reset(new dumpScriptIndex());
else if (transformIndex == 3) delegate.reset(new dumpSpentIndex());
else if (transformIndex == 4) delegate.reset(new dumpTxIndex());
else if (transformIndex == 5) delegate.reset(new dumpTxOutIndex());
else if (transformIndex == 8) delegate.reset(new dumpIndexdLevel());
// statistics
else if (transformIndex == 6) delegate.reset(new dumpStatistics());
else if (transformIndex == 7) delegate.reset(new dumpOutputValuesOverHeight());
continue;
}
if (sscanf(arg, "-j%lu", &nThreads) == 1) continue;
if (sscanf(arg, "-m%lu", &memoryAlloc) == 1) continue;
if (delegate && delegate->initialize(arg)) continue;
assert(false);
}
assert(delegate != nullptr);
// pre-allocate buffers
const auto halfMemoryAlloc = memoryAlloc / 2;
HeapSlice iobuffer(halfMemoryAlloc);
std::cerr << "Allocated IO buffer (" << halfMemoryAlloc << " bytes)" << std::endl;
HeapSlice buffer(halfMemoryAlloc);
std::cerr << "Allocated active buffer (" << halfMemoryAlloc << " bytes)" << std::endl;
ThreadPool<std::function<void(void)>> pool(nThreads);
std::cerr << "Initialized " << nThreads << " threads in the thread pool" << std::endl;
size_t count = 0;
size_t remainder = 0;
size_t accum = 0;
size_t invalid = 0;
while (true) {
const auto rbuf = iobuffer.drop(remainder);
const auto read = fread(rbuf.begin(), 1, rbuf.length(), stdin);
const auto eof = static_cast<size_t>(read) < rbuf.length();
accum += read;
// wait for all workers before overwrite
pool.wait();
// copy iobuffer to buffer, allows iobuffer to be modified independently after
memcpy(buffer.begin(), iobuffer.begin(), halfMemoryAlloc);
auto data = buffer.take(remainder + read);
if (invalid > 0) {
std::cerr << std::endl << "--- Skipped " << invalid << " bad bytes" << std::endl;
invalid = 0;
}
std::cerr << "-- Parsed " << count << " blocks (read " << read / 1024 << " KiB, " << accum / 1024 / 1024 << " MiB total)" << (eof ? " EOF" : "") << std::endl;
while (data.length() >= 88) {
// skip bad data (e.g bitcoind zero pre-allocations)
if (data.peek<uint32_t>() != 0xd9b4bef9) {
data.popFrontN(1);
continue;
}
// skip bad data cont.
const auto header = data.drop(8).take(80);
if (!Block(header).verify()) {
data.popFrontN(1);
std::cerr << '.';
++invalid;
continue;
}
if (invalid > 0) {
std::cerr << std::endl << "--- Skipped " << invalid << " bad bytes" << std::endl;
invalid = 0;
}
// do we have enough data?
const auto length = data.drop(4).peek<uint32_t>();
const auto total = 8 + length;
if (total > data.length()) break;
data.popFrontN(8);
// send the block data to the threadpool
const auto block = Block(header, data.drop(80));
pool.push([block, &delegate]() {
delegate->operator()(block);
});
count++;
data.popFrontN(length);
}
if (eof) break;
// assign remainder to front of iobuffer (rbuf is offset to avoid overwrite on rawRead)
remainder = data.length();
memcpy(iobuffer.begin(), data.begin(), remainder);
}
time(&end);
std::cerr << "Parsed " << count << " blocks in " << difftime(end, start) << " seconds" << std::endl;
return 0;
}
<commit_msg>parser: new line before final parsed message<commit_after>#include <cstdio>
#include <cstring>
#include <ctime>
#include <iostream>
#include <memory>
#include "block.hpp"
#include "hash.hpp"
#include "slice.hpp"
#include "threadpool.hpp"
#include "transforms.hpp"
int main (int argc, char** argv) {
time_t start, end;
time(&start);
std::unique_ptr<transform_t> delegate;
size_t memoryAlloc = 200 * 1024 * 1024;
size_t nThreads = 1;
// parse command line arguments
for (auto i = 1; i < argc; ++i) {
const auto arg = argv[i];
size_t transformIndex = 0;
if (sscanf(arg, "-t%lu", &transformIndex) == 1) {
assert(delegate == nullptr);
// raw
if (transformIndex == 0) delegate.reset(new dumpHeaders());
else if (transformIndex == 1) delegate.reset(new dumpScripts());
// indexd
else if (transformIndex == 2) delegate.reset(new dumpScriptIndex());
else if (transformIndex == 3) delegate.reset(new dumpSpentIndex());
else if (transformIndex == 4) delegate.reset(new dumpTxIndex());
else if (transformIndex == 5) delegate.reset(new dumpTxOutIndex());
else if (transformIndex == 8) delegate.reset(new dumpIndexdLevel());
// statistics
else if (transformIndex == 6) delegate.reset(new dumpStatistics());
else if (transformIndex == 7) delegate.reset(new dumpOutputValuesOverHeight());
continue;
}
if (sscanf(arg, "-j%lu", &nThreads) == 1) continue;
if (sscanf(arg, "-m%lu", &memoryAlloc) == 1) continue;
if (delegate && delegate->initialize(arg)) continue;
assert(false);
}
assert(delegate != nullptr);
// pre-allocate buffers
const auto halfMemoryAlloc = memoryAlloc / 2;
HeapSlice iobuffer(halfMemoryAlloc);
std::cerr << "Allocated IO buffer (" << halfMemoryAlloc << " bytes)" << std::endl;
HeapSlice buffer(halfMemoryAlloc);
std::cerr << "Allocated active buffer (" << halfMemoryAlloc << " bytes)" << std::endl;
ThreadPool<std::function<void(void)>> pool(nThreads);
std::cerr << "Initialized " << nThreads << " threads in the thread pool" << std::endl;
size_t count = 0;
size_t remainder = 0;
size_t accum = 0;
size_t invalid = 0;
while (true) {
const auto rbuf = iobuffer.drop(remainder);
const auto read = fread(rbuf.begin(), 1, rbuf.length(), stdin);
const auto eof = static_cast<size_t>(read) < rbuf.length();
accum += read;
// wait for all workers before overwrite
pool.wait();
// copy iobuffer to buffer, allows iobuffer to be modified independently after
memcpy(buffer.begin(), iobuffer.begin(), halfMemoryAlloc);
auto data = buffer.take(remainder + read);
if (invalid > 0) {
std::cerr << std::endl << "-- Skipped " << invalid << " bad bytes" << std::endl;
invalid = 0;
}
std::cerr << "-- Parsed " << count << " blocks (read " << read / 1024 << " KiB, " << accum / 1024 / 1024 << " MiB total)" << (eof ? " EOF" : "") << std::endl;
while (data.length() >= 88) {
// skip bad data (e.g bitcoind zero pre-allocations)
if (data.peek<uint32_t>() != 0xd9b4bef9) {
data.popFrontN(1);
continue;
}
// skip bad data cont.
const auto header = data.drop(8).take(80);
if (!Block(header).verify()) {
data.popFrontN(1);
std::cerr << '.';
++invalid;
continue;
}
if (invalid > 0) {
std::cerr << std::endl << "-- Skipped " << invalid << " bad bytes" << std::endl;
invalid = 0;
}
// do we have enough data?
const auto length = data.drop(4).peek<uint32_t>();
const auto total = 8 + length;
if (total > data.length()) break;
data.popFrontN(8);
// send the block data to the threadpool
const auto block = Block(header, data.drop(80));
pool.push([block, &delegate]() {
delegate->operator()(block);
});
count++;
data.popFrontN(length);
}
if (eof) break;
// assign remainder to front of iobuffer (rbuf is offset to avoid overwrite on rawRead)
remainder = data.length();
memcpy(iobuffer.begin(), data.begin(), remainder);
}
if (invalid > 0) {
std::cerr << std::endl << "-- Skipped " << invalid << " bad bytes" << std::endl;
invalid = 0;
}
time(&end);
std::cerr << "Parsed " << count << " blocks in " << difftime(end, start) << " seconds" << std::endl;
return 0;
}
<|endoftext|>
|
<commit_before>/* Copyright 2007-2015 QReal Research Group, Dmitry Mordvinov
*
* 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 "uiManager.h"
#include <QtCore/QTimer>
#include <QtWidgets/QAction>
#include <QtWidgets/QDialog>
#include <QtWidgets/QLineEdit>
#include <QtWidgets/QPushButton>
#include <QtWidgets/QStatusBar>
#include <QtWidgets/QToolBar>
#include <QtWidgets/QVBoxLayout>
#include <qrkernel/logging.h>
#include <qrkernel/settingsManager.h>
#include <qrutils/inFile.h>
#include <qrutils/smartDock.h>
#include <qrutils/widgets/consoleDock.h>
#include <kitBase/robotModel/robotModelUtils.h>
#include <kitBase/robotModel/robotParts/shell.h>
#include "src/ui/modeStripe.h"
using namespace interpreterCore;
static const QColor backgrondColor = QPalette().color(QPalette::Background);
static const QColor editModeColor = QPalette().color(QPalette::Background);
static const QColor debugModeColor = qRgb(152, 251, 152);
UiManager::UiManager(QAction &debugModeAction
, QAction &editModeAction
, qReal::gui::MainWindowDockInterface &mainWindow
, qReal::SystemEvents &systemEvents
, kitBase::EventsForKitPluginInterface &kitPluginEvents
, kitBase::robotModel::RobotModelManagerInterface &robotModelManager)
: mDebugModeAction(debugModeAction)
, mEditModeAction(editModeAction)
, mMainWindow(mainWindow)
, mRobotConsole(new qReal::ui::ConsoleDock(tr("Robot console"), mMainWindow.windowWidget()))
{
mMainWindow.graphicalModelDock()->setWindowTitle(QObject::tr("Blocks"));
connect(&systemEvents, &qReal::SystemEvents::activeTabChanged, this, &UiManager::onActiveTabChanged);
connect(&systemEvents, &qReal::SystemEvents::ensureDiagramVisible, this, &UiManager::ensureDiagramVisible);
connect(&kitPluginEvents, &kitBase::EventsForKitPluginInterface::interpretationStarted
, this, &UiManager::switchToDebuggerMode);
connect(&kitPluginEvents, &kitBase::EventsForKitPluginInterface::interpretationStarted
, mRobotConsole, &qReal::ui::ConsoleDock::clear);
connect(&kitPluginEvents, &kitBase::EventsForKitPluginInterface::robotModelChanged
, [=]() { QTimer::singleShot(0, this, SLOT(reloadDocksSavingToolbarsAndErrors())); });
connect(&robotModelManager, &kitBase::robotModel::RobotModelManagerInterface::robotModelChanged
, this, &UiManager::onRobotModelChanged);
connect(&debugModeAction, &QAction::triggered, this, &UiManager::switchToDebuggerMode);
connect(&editModeAction, &QAction::triggered, this, &UiManager::switchToEditorMode);
mRobotConsole->hide();
initTab();
mMainWindow.addDockWidget(Qt::BottomDockWidgetArea, mRobotConsole);
mMainWindow.tabifyDockWidget(mRobotConsole, mMainWindow.errorReporterDock());
mMainWindow.windowWidget()->addAction(mRobotConsole->toggleViewAction());
mRobotConsole->toggleViewAction()->setShortcut(Qt::ALT + Qt::Key_2);
mMainWindow.statusBar()->setAutoFillBackground(true);
mMainWindow.statusBar()->setStyleSheet("QStatusBar::item { border: 0px solid black; padding: 10px; }");
editModeAction.setProperty("modeName", tr("edit mode"));
debugModeAction.setProperty("modeName", tr("debug mode"));
produceModeButton(Mode::Editing, debugModeAction, mMainWindow.statusBar());
produceModeButton(Mode::Debugging, editModeAction, mMainWindow.statusBar());
switchToEditorMode();
onActiveTabChanged(qReal::TabInfo());
}
void UiManager::placeDevicesConfig(QWidget *devicesWidget)
{
QDockWidget * const devicesDock = produceDockWidget(QObject::tr("Configure devices"), devicesWidget);
devicesDock->setObjectName("devicesConfigurationDock");
mMainWindow.addDockWidget(Qt::LeftDockWidgetArea, devicesDock);
}
void UiManager::placeWatchPlugins(QDockWidget *watchWindow, QWidget *graphicsWatch)
{
mMainWindow.addDockWidget(Qt::LeftDockWidgetArea, watchWindow);
watchWindow->setObjectName("variablesDebuggerDock");
watchWindow->setFloating(false);
QDockWidget * const graphWatchDock = produceDockWidget(QObject::tr("Sensors state"), graphicsWatch);
graphWatchDock->setObjectName("graphicsWatcherDock");
mMainWindow.addDockWidget(Qt::LeftDockWidgetArea, graphWatchDock);
mMainWindow.tabifyDockWidget(watchWindow, graphWatchDock);
reloadDocks();
}
qReal::ui::ConsoleDock &UiManager::robotConsole()
{
return *mRobotConsole;
}
void UiManager::onActiveTabChanged(const qReal::TabInfo &tab)
{
if (tab.type() == mCurrentTab) {
return;
}
saveDocks();
mCurrentTab = tab.type();
reloadDocks();
toggleModeButtons();
}
void UiManager::onRobotModelChanged(kitBase::robotModel::RobotModelInterface &model)
{
auto subscribeShell = [this, &model]() {
if (kitBase::robotModel::robotParts::Shell * const shell = kitBase::robotModel::RobotModelUtils::findDevice
<kitBase::robotModel::robotParts::Shell>(model, "ShellPort"))
{
connect(shell, &kitBase::robotModel::robotParts::Shell::textPrinted
, mRobotConsole, &qReal::ui::ConsoleDock::print, Qt::UniqueConnection);
}
};
// Shell can be already configured or not. However, checking for it now or later, when everything is ready for use.
subscribeShell();
connect(&model, &kitBase::robotModel::RobotModelInterface::allDevicesConfigured, subscribeShell);
}
void UiManager::switchToEditorMode()
{
switchToMode(Mode::Editing);
}
void UiManager::switchToDebuggerMode()
{
switchToMode(Mode::Debugging);
}
void UiManager::switchToMode(UiManager::Mode mode)
{
if (mCurrentMode == mode) {
return;
}
saveDocks();
mCurrentMode = mode;
reloadDocksSavingToolbarsAndErrors();
toggleModeButtons();
}
void UiManager::toggleModeButtons()
{
mTabBar->setVisible(mCurrentTab != qReal::TabInfo::TabType::other);
mEditModeAction.setVisible(mCurrentTab != qReal::TabInfo::TabType::other);
mDebugModeAction.setVisible(mCurrentTab != qReal::TabInfo::TabType::other);
mEditModeAction.setChecked(mCurrentMode == Mode::Editing);
mDebugModeAction.setChecked(mCurrentMode == Mode::Debugging);
const QColor color = mCurrentTab == qReal::TabInfo::TabType::other
? backgrondColor
: mCurrentMode == Mode::Editing ? editModeColor : debugModeColor;
QPalette palette;
palette.setColor(QPalette::Background, color);
palette.setColor(QPalette::Base, color);
mMainWindow.statusBar()->setPalette(palette);
}
QDockWidget *UiManager::produceDockWidget(const QString &title, QWidget *content) const
{
QDockWidget * const dock = new QDockWidget(title);
dock->setWidget(content);
return dock;
}
void UiManager::produceModeButton(UiManager::Mode mode, QAction &action, QStatusBar *statusBar) const
{
QWidget *result = nullptr;
switch (mode) {
case Mode::Dummy:
return;
case Mode::Editing:
result = new ui::ModeStripe(action, tr("Edit mode"), statusBar);
break;
case Mode::Debugging:
result = new ui::ModeStripe(action, tr("Debug mode"), statusBar);
break;
}
if (!result) {
qWarning() << "Forgot to implement producing status bar button for mode" << static_cast<int>(mode);
return;
}
statusBar->addWidget(result, 10);
}
int UiManager::currentMode() const
{
return static_cast<int>(mCurrentTab) | static_cast<int>(mCurrentMode);
}
QString UiManager::currentSettingsKey() const
{
return "docksStateInMode" + QString::number(currentMode());
}
void UiManager::saveDocks() const
{
qReal::SettingsManager::setValue(currentSettingsKey(), mMainWindow.saveState(currentMode()));
}
void UiManager::reloadDocks() const
{
hack2dModelDock();
const QByteArray state = qReal::SettingsManager::value(currentSettingsKey()).toByteArray();
if (!mMainWindow.restoreState(state, currentMode())) {
QLOG_ERROR() << "Cannot apply docks state for mode" << currentMode() << ":" << state;
} else {
resetMainWindowCorners();
// Same trick as main window does with error reporter.
if (mRobotConsole->isEmpty()) {
mRobotConsole->hide();
}
}
}
void UiManager::reloadDocksSavingToolbarsAndErrors() const
{
// To this moment toolbars already updated their visibility. Calling just reloadDocks() here
// will loose some toolbars visibility and error reporter state, so memorizing it here...
const bool errorReporterWasVisible = mMainWindow.errorReporterDock()->isVisible();
const bool robotConsoleWasVisible = mRobotConsole->isVisible();
QMap<QToolBar *, bool> toolBarsVisiblity;
for (QToolBar * const toolBar : mMainWindow.toolBars()) {
toolBarsVisiblity[toolBar] = toolBar->isVisible();
}
// Now reloading docks, toolbars are in random visibility after this...
reloadDocks();
// And finally restoring old configuration.
mMainWindow.errorReporterDock()->setVisible(errorReporterWasVisible);
mRobotConsole->setVisible(robotConsoleWasVisible);
for (QToolBar * const toolBar : toolBarsVisiblity.keys()) {
toolBar->setVisible(toolBarsVisiblity[toolBar]);
}
}
void UiManager::resetMainWindowCorners() const
{
// Seems like on different platforms the default corner occupation is different, so fixing it here...
mMainWindow.setCorner(Qt::TopRightCorner, Qt::RightDockWidgetArea);
mMainWindow.setCorner(Qt::BottomRightCorner, Qt::BottomDockWidgetArea);
mMainWindow.setCorner(Qt::TopLeftCorner, Qt::LeftDockWidgetArea);
mMainWindow.setCorner(Qt::BottomLeftCorner, Qt::BottomDockWidgetArea);
}
void UiManager::ensureDiagramVisible()
{
if (mCurrentMode == Mode::Editing) {
return;
}
// 2D model is placed into smart dock that may hide central widget if docked into TopDockWidgetArea.
// If we met such case then switching to editor mode.
for (utils::SmartDock * const twoDModel : mMainWindow.windowWidget()->findChildren<utils::SmartDock *>()) {
if (twoDModel->isCentral()) {
switchToEditorMode();
return;
}
}
}
void UiManager::initTab()
{
mTabBar = new QToolBar(mMainWindow.windowWidget());
mTabBar->setObjectName("largeTabsBar");
mTabBar->setIconSize(QSize(32, 32));
mTabBar->setToolButtonStyle(Qt::ToolButtonTextUnderIcon);
mMainWindow.addToolBar(Qt::LeftToolBarArea, mTabBar);
mTabBar->addAction(&mEditModeAction);
mTabBar->addAction(&mDebugModeAction);
connect(&mEditModeAction, &QAction::triggered, this, &UiManager::switchToEditorMode);
connect(&mDebugModeAction, &QAction::triggered, this, &UiManager::switchToDebuggerMode);
}
void UiManager::hack2dModelDock() const
{
// 2D model is placed into smart dock: it may be embedded into instance of QDialog
// that is not influeced by mMainWindow::restoreState. So we must first switch to a docked form
// and then restore docks state.
if (utils::SmartDock * const twoDModel = mMainWindow.windowWidget()->findChild<utils::SmartDock *>()) {
twoDModel->switchToDocked();
}
}
void UiManager::enableDocksSnapshotter() const
{
// This method provides tools only for development.
// It must not be called in master branch code.
QWidget * const mainWindow = dynamic_cast<QWidget *>(&mMainWindow);
QDialog * const dialog = new QDialog(mainWindow);
QVBoxLayout * const layout = new QVBoxLayout;
dialog->setLayout(layout);
QPushButton * const button = new QPushButton("Snapshot docks", mainWindow);
QLineEdit * const lineEdit = new QLineEdit(mainWindow);
connect(button, &QPushButton::clicked, [=]() {
const QString tempSettingsFileName = "tempFileForStoringWindowState";
QSettings tempSettings(tempSettingsFileName, QSettings::IniFormat);
tempSettings.setValue(currentSettingsKey(), mMainWindow.saveState(currentMode()));
tempSettings.sync();
lineEdit->setText(utils::InFile::readAll(tempSettingsFileName).split("\n", QString::SkipEmptyParts).last());
QFile::remove(tempSettingsFileName);
});
layout->addWidget(button);
layout->addWidget(lineEdit);
dialog->show();
}
<commit_msg>Implemented mode tab sight customizing with screen resolution [ci skip]<commit_after>/* Copyright 2007-2015 QReal Research Group, Dmitry Mordvinov
*
* 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 "uiManager.h"
#include <QtCore/QTimer>
#include <QtWidgets/QAction>
#include <QtWidgets/QApplication>
#include <QtWidgets/QDesktopWidget>
#include <QtWidgets/QDialog>
#include <QtWidgets/QLineEdit>
#include <QtWidgets/QPushButton>
#include <QtWidgets/QStatusBar>
#include <QtWidgets/QToolBar>
#include <QtWidgets/QVBoxLayout>
#include <qrkernel/logging.h>
#include <qrkernel/settingsManager.h>
#include <qrutils/inFile.h>
#include <qrutils/smartDock.h>
#include <qrutils/widgets/consoleDock.h>
#include <kitBase/robotModel/robotModelUtils.h>
#include <kitBase/robotModel/robotParts/shell.h>
#include "src/ui/modeStripe.h"
const int lowerMediumResolutionBorder = 1024;
const int upperMediumResolutionBorder = 1280;
using namespace interpreterCore;
static const QColor backgrondColor = QPalette().color(QPalette::Background);
static const QColor editModeColor = QPalette().color(QPalette::Background);
static const QColor debugModeColor = qRgb(152, 251, 152);
UiManager::UiManager(QAction &debugModeAction
, QAction &editModeAction
, qReal::gui::MainWindowDockInterface &mainWindow
, qReal::SystemEvents &systemEvents
, kitBase::EventsForKitPluginInterface &kitPluginEvents
, kitBase::robotModel::RobotModelManagerInterface &robotModelManager)
: mDebugModeAction(debugModeAction)
, mEditModeAction(editModeAction)
, mMainWindow(mainWindow)
, mTabBar(nullptr)
, mRobotConsole(new qReal::ui::ConsoleDock(tr("Robot console"), mMainWindow.windowWidget()))
{
mMainWindow.graphicalModelDock()->setWindowTitle(QObject::tr("Blocks"));
connect(&systemEvents, &qReal::SystemEvents::activeTabChanged, this, &UiManager::onActiveTabChanged);
connect(&systemEvents, &qReal::SystemEvents::ensureDiagramVisible, this, &UiManager::ensureDiagramVisible);
connect(&kitPluginEvents, &kitBase::EventsForKitPluginInterface::interpretationStarted
, this, &UiManager::switchToDebuggerMode);
connect(&kitPluginEvents, &kitBase::EventsForKitPluginInterface::interpretationStarted
, mRobotConsole, &qReal::ui::ConsoleDock::clear);
connect(&kitPluginEvents, &kitBase::EventsForKitPluginInterface::robotModelChanged
, [=]() { QTimer::singleShot(0, this, SLOT(reloadDocksSavingToolbarsAndErrors())); });
connect(&robotModelManager, &kitBase::robotModel::RobotModelManagerInterface::robotModelChanged
, this, &UiManager::onRobotModelChanged);
connect(&debugModeAction, &QAction::triggered, this, &UiManager::switchToDebuggerMode);
connect(&editModeAction, &QAction::triggered, this, &UiManager::switchToEditorMode);
mRobotConsole->hide();
initTab();
mMainWindow.addDockWidget(Qt::BottomDockWidgetArea, mRobotConsole);
mMainWindow.tabifyDockWidget(mRobotConsole, mMainWindow.errorReporterDock());
mMainWindow.windowWidget()->addAction(mRobotConsole->toggleViewAction());
mRobotConsole->toggleViewAction()->setShortcut(Qt::ALT + Qt::Key_2);
mMainWindow.statusBar()->setAutoFillBackground(true);
mMainWindow.statusBar()->setStyleSheet("QStatusBar::item { border: 0px solid black; padding: 10px; }");
editModeAction.setProperty("modeName", tr("edit mode"));
debugModeAction.setProperty("modeName", tr("debug mode"));
produceModeButton(Mode::Editing, debugModeAction, mMainWindow.statusBar());
produceModeButton(Mode::Debugging, editModeAction, mMainWindow.statusBar());
switchToEditorMode();
onActiveTabChanged(qReal::TabInfo());
}
void UiManager::placeDevicesConfig(QWidget *devicesWidget)
{
QDockWidget * const devicesDock = produceDockWidget(QObject::tr("Configure devices"), devicesWidget);
devicesDock->setObjectName("devicesConfigurationDock");
mMainWindow.addDockWidget(Qt::LeftDockWidgetArea, devicesDock);
}
void UiManager::placeWatchPlugins(QDockWidget *watchWindow, QWidget *graphicsWatch)
{
mMainWindow.addDockWidget(Qt::LeftDockWidgetArea, watchWindow);
watchWindow->setObjectName("variablesDebuggerDock");
watchWindow->setFloating(false);
QDockWidget * const graphWatchDock = produceDockWidget(QObject::tr("Sensors state"), graphicsWatch);
graphWatchDock->setObjectName("graphicsWatcherDock");
mMainWindow.addDockWidget(Qt::LeftDockWidgetArea, graphWatchDock);
mMainWindow.tabifyDockWidget(watchWindow, graphWatchDock);
reloadDocks();
}
qReal::ui::ConsoleDock &UiManager::robotConsole()
{
return *mRobotConsole;
}
void UiManager::onActiveTabChanged(const qReal::TabInfo &tab)
{
if (tab.type() == mCurrentTab) {
return;
}
saveDocks();
mCurrentTab = tab.type();
reloadDocks();
toggleModeButtons();
}
void UiManager::onRobotModelChanged(kitBase::robotModel::RobotModelInterface &model)
{
auto subscribeShell = [this, &model]() {
if (kitBase::robotModel::robotParts::Shell * const shell = kitBase::robotModel::RobotModelUtils::findDevice
<kitBase::robotModel::robotParts::Shell>(model, "ShellPort"))
{
connect(shell, &kitBase::robotModel::robotParts::Shell::textPrinted
, mRobotConsole, &qReal::ui::ConsoleDock::print, Qt::UniqueConnection);
}
};
// Shell can be already configured or not. However, checking for it now or later, when everything is ready for use.
subscribeShell();
connect(&model, &kitBase::robotModel::RobotModelInterface::allDevicesConfigured, subscribeShell);
}
void UiManager::switchToEditorMode()
{
switchToMode(Mode::Editing);
}
void UiManager::switchToDebuggerMode()
{
switchToMode(Mode::Debugging);
}
void UiManager::switchToMode(UiManager::Mode mode)
{
if (mCurrentMode == mode) {
return;
}
saveDocks();
mCurrentMode = mode;
reloadDocksSavingToolbarsAndErrors();
toggleModeButtons();
}
void UiManager::toggleModeButtons()
{
mEditModeAction.setVisible(mCurrentTab != qReal::TabInfo::TabType::other);
mDebugModeAction.setVisible(mCurrentTab != qReal::TabInfo::TabType::other);
mEditModeAction.setChecked(mCurrentMode == Mode::Editing);
mDebugModeAction.setChecked(mCurrentMode == Mode::Debugging);
if (mTabBar) {
mTabBar->setVisible(mCurrentTab != qReal::TabInfo::TabType::other);
}
const QColor color = mCurrentTab == qReal::TabInfo::TabType::other
? backgrondColor
: mCurrentMode == Mode::Editing ? editModeColor : debugModeColor;
QPalette palette;
palette.setColor(QPalette::Background, color);
palette.setColor(QPalette::Base, color);
mMainWindow.statusBar()->setPalette(palette);
}
QDockWidget *UiManager::produceDockWidget(const QString &title, QWidget *content) const
{
QDockWidget * const dock = new QDockWidget(title);
dock->setWidget(content);
return dock;
}
void UiManager::produceModeButton(UiManager::Mode mode, QAction &action, QStatusBar *statusBar) const
{
QWidget *result = nullptr;
switch (mode) {
case Mode::Dummy:
return;
case Mode::Editing:
result = new ui::ModeStripe(action, tr("Edit mode"), statusBar);
break;
case Mode::Debugging:
result = new ui::ModeStripe(action, tr("Debug mode"), statusBar);
break;
}
if (!result) {
qWarning() << "Forgot to implement producing status bar button for mode" << static_cast<int>(mode);
return;
}
statusBar->addWidget(result, 10);
}
int UiManager::currentMode() const
{
return static_cast<int>(mCurrentTab) | static_cast<int>(mCurrentMode);
}
QString UiManager::currentSettingsKey() const
{
return "docksStateInMode" + QString::number(currentMode());
}
void UiManager::saveDocks() const
{
qReal::SettingsManager::setValue(currentSettingsKey(), mMainWindow.saveState(currentMode()));
}
void UiManager::reloadDocks() const
{
hack2dModelDock();
const QByteArray state = qReal::SettingsManager::value(currentSettingsKey()).toByteArray();
if (!mMainWindow.restoreState(state, currentMode())) {
QLOG_ERROR() << "Cannot apply docks state for mode" << currentMode() << ":" << state;
} else {
resetMainWindowCorners();
// Same trick as main window does with error reporter.
if (mRobotConsole->isEmpty()) {
mRobotConsole->hide();
}
}
}
void UiManager::reloadDocksSavingToolbarsAndErrors() const
{
// To this moment toolbars already updated their visibility. Calling just reloadDocks() here
// will loose some toolbars visibility and error reporter state, so memorizing it here...
const bool errorReporterWasVisible = mMainWindow.errorReporterDock()->isVisible();
const bool robotConsoleWasVisible = mRobotConsole->isVisible();
QMap<QToolBar *, bool> toolBarsVisiblity;
for (QToolBar * const toolBar : mMainWindow.toolBars()) {
toolBarsVisiblity[toolBar] = toolBar->isVisible();
}
// Now reloading docks, toolbars are in random visibility after this...
reloadDocks();
// And finally restoring old configuration.
mMainWindow.errorReporterDock()->setVisible(errorReporterWasVisible);
mRobotConsole->setVisible(robotConsoleWasVisible);
for (QToolBar * const toolBar : toolBarsVisiblity.keys()) {
toolBar->setVisible(toolBarsVisiblity[toolBar]);
}
}
void UiManager::resetMainWindowCorners() const
{
// Seems like on different platforms the default corner occupation is different, so fixing it here...
mMainWindow.setCorner(Qt::TopRightCorner, Qt::RightDockWidgetArea);
mMainWindow.setCorner(Qt::BottomRightCorner, Qt::BottomDockWidgetArea);
mMainWindow.setCorner(Qt::TopLeftCorner, Qt::LeftDockWidgetArea);
mMainWindow.setCorner(Qt::BottomLeftCorner, Qt::BottomDockWidgetArea);
}
void UiManager::ensureDiagramVisible()
{
if (mCurrentMode == Mode::Editing) {
return;
}
// 2D model is placed into smart dock that may hide central widget if docked into TopDockWidgetArea.
// If we met such case then switching to editor mode.
for (utils::SmartDock * const twoDModel : mMainWindow.windowWidget()->findChildren<utils::SmartDock *>()) {
if (twoDModel->isCentral()) {
switchToEditorMode();
return;
}
}
}
void UiManager::initTab()
{
connect(&mEditModeAction, &QAction::triggered, this, &UiManager::switchToEditorMode);
connect(&mDebugModeAction, &QAction::triggered, this, &UiManager::switchToDebuggerMode);
const QSize resolution = QApplication::desktop()->screenGeometry().size();
if (resolution.width() < lowerMediumResolutionBorder) {
// The screen is super-small, do not show tab bar at all
mMainWindow.statusBar()->addAction(&mEditModeAction);
mMainWindow.statusBar()->addAction(&mDebugModeAction);
return;
}
mTabBar = new QToolBar(mMainWindow.windowWidget());
mTabBar->setObjectName("largeTabsBar");
mTabBar->setIconSize(QSize(32, 32));
mTabBar->setToolButtonStyle(resolution.width() < upperMediumResolutionBorder
? Qt::ToolButtonIconOnly // On small resolutions in some locales text may be too wide.
: Qt::ToolButtonTextUnderIcon);
mMainWindow.addToolBar(Qt::LeftToolBarArea, mTabBar);
mTabBar->addAction(&mEditModeAction);
mTabBar->addAction(&mDebugModeAction);
}
void UiManager::hack2dModelDock() const
{
// 2D model is placed into smart dock: it may be embedded into instance of QDialog
// that is not influeced by mMainWindow::restoreState. So we must first switch to a docked form
// and then restore docks state.
if (utils::SmartDock * const twoDModel = mMainWindow.windowWidget()->findChild<utils::SmartDock *>()) {
twoDModel->switchToDocked();
}
}
void UiManager::enableDocksSnapshotter() const
{
// This method provides tools only for development.
// It must not be called in master branch code.
QWidget * const mainWindow = dynamic_cast<QWidget *>(&mMainWindow);
QDialog * const dialog = new QDialog(mainWindow);
QVBoxLayout * const layout = new QVBoxLayout;
dialog->setLayout(layout);
QPushButton * const button = new QPushButton("Snapshot docks", mainWindow);
QLineEdit * const lineEdit = new QLineEdit(mainWindow);
connect(button, &QPushButton::clicked, [=]() {
const QString tempSettingsFileName = "tempFileForStoringWindowState";
QSettings tempSettings(tempSettingsFileName, QSettings::IniFormat);
tempSettings.setValue(currentSettingsKey(), mMainWindow.saveState(currentMode()));
tempSettings.sync();
lineEdit->setText(utils::InFile::readAll(tempSettingsFileName).split("\n", QString::SkipEmptyParts).last());
QFile::remove(tempSettingsFileName);
});
layout->addWidget(button);
layout->addWidget(lineEdit);
dialog->show();
}
<|endoftext|>
|
<commit_before>// Copyright (c) 2013 The LevelDB Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file. See the AUTHORS file for names of contributors.
// Test for issue 178: a manual compaction causes deleted data to reappear.
#include <iostream>
#include <sstream>
#include <cstdlib>
#include "leveldb/db.h"
#include "leveldb/write_batch.h"
#include "util/testharness.h"
namespace {
const int kNumKeys = 1100000;
std::string Key1(int i) {
char buf[100];
snprintf(buf, sizeof(buf), "my_key_%d", i);
return buf;
}
std::string Key2(int i) {
return Key1(i) + "_xxx";
}
class Issue178 { };
TEST(Issue178, Test) {
// Get rid of any state from an old run.
std::string dbpath = leveldb::test::TmpDir() + "/leveldb_cbug_test";
DestroyDB(dbpath, leveldb::Options());
// Open database. Disable compression since it affects the creation
// of layers and the code below is trying to test against a very
// specific scenario.
leveldb::DB* db;
leveldb::Options db_options;
db_options.create_if_missing = true;
db_options.compression = leveldb::kNoCompression;
ASSERT_OK(leveldb::DB::Open(db_options, dbpath, &db));
// create first key range
leveldb::WriteBatch batch;
for (size_t i = 0; i < kNumKeys; i++) {
batch.Put(Key1(i), "value for range 1 key");
}
ASSERT_OK(db->Write(leveldb::WriteOptions(), &batch));
// create second key range
batch.Clear();
for (size_t i = 0; i < kNumKeys; i++) {
batch.Put(Key2(i), "value for range 2 key");
}
ASSERT_OK(db->Write(leveldb::WriteOptions(), &batch));
// delete second key range
batch.Clear();
for (size_t i = 0; i < kNumKeys; i++) {
batch.Delete(Key2(i));
}
ASSERT_OK(db->Write(leveldb::WriteOptions(), &batch));
// compact database
std::string start_key = Key1(0);
std::string end_key = Key1(kNumKeys - 1);
leveldb::Slice least(start_key.data(), start_key.size());
leveldb::Slice greatest(end_key.data(), end_key.size());
// commenting out the line below causes the example to work correctly
db->CompactRange(&least, &greatest);
// count the keys
leveldb::Iterator* iter = db->NewIterator(leveldb::ReadOptions());
size_t num_keys = 0;
for (iter->SeekToFirst(); iter->Valid(); iter->Next()) {
num_keys++;
}
delete iter;
ASSERT_EQ(kNumKeys, num_keys) << "Bad number of keys";
// close database
delete db;
DestroyDB(dbpath, leveldb::Options());
}
} // anonymous namespace
int main(int argc, char** argv) {
return leveldb::test::RunAllTests();
}
<commit_msg>testing<commit_after><|endoftext|>
|
<commit_before>/*******************************************************************************
* c7a/api/read_lines.hpp
*
* Part of Project c7a.
*
* Copyright (C) 2015 Alexander Noe <aleexnoe@gmail.com>
* Copyright (C) 2015 Timo Bingmann <tb@panthema.net>
*
* This file has no license. Only Chuck Norris can compile it.
******************************************************************************/
#pragma once
#ifndef C7A_API_READ_LINES_HEADER
#define C7A_API_READ_LINES_HEADER
#include <c7a/api/dia.hpp>
#include <c7a/api/dop_node.hpp>
#include <c7a/common/logger.hpp>
#include <c7a/net/buffer_builder.hpp>
// C7A_{/UN}LIKELY
#include <c7a/common/math.hpp>
#include <c7a/common/item_serialization_tools.hpp>
#include <fcntl.h>
#include <fstream>
#include <glob.h>
#include <string>
#include <sys/stat.h>
#include <sys/types.h>
namespace c7a {
namespace api {
//! \addtogroup api Interface
//! \{
/*!
* A DIANode which performs a line-based Read operation. Read reads a file from
* the file system and emits it as a DIA.
*/
class ReadLinesNode : public DOpNode<std::string>
{
public:
using Super = DOpNode<std::string>;
using Super::context_;
using Super::result_file_;
using FileSizePair = std::pair<std::string, size_t>;
/*!
* Constructor for a ReadLinesNode. Sets the Context
* and file path.
*
* \param ctx Reference to Context, which holds references to data and
* network.
*
* \param path Path of the input file(s)
*/
ReadLinesNode(Context& ctx,
const std::string& path,
StatsNode* stats_node)
: Super(ctx, { }, "Read", stats_node),
path_(path)
{
glob_t glob_result;
struct stat filestat;
glob(path_.c_str(), GLOB_TILDE, nullptr, &glob_result);
size_t directory_size = 0;
for (unsigned int i = 0; i < glob_result.gl_pathc; ++i) {
const char* filepath = glob_result.gl_pathv[i];
if (stat(filepath, &filestat)) {
throw std::runtime_error(
"ERROR: Invalid file " + std::string(filepath));
}
if (!S_ISREG(filestat.st_mode)) continue;
directory_size += filestat.st_size;
filesize_prefix.push_back(std::make_pair(filepath, directory_size));
}
globfree(&glob_result);
}
void Execute() final { }
void PushData() final {
InputLineIterator it = GetInputLineIterator(
filesize_prefix, context_.my_rank(), context_.num_workers());
// Hook Read
while (it.HasNext()) {
auto item = it.Next();
for (auto func : Super::callbacks_) {
func(item);
}
}
}
void Dispose() final { }
/*!
* Produces an 'empty' function stack, which only contains the identity
* emitter function.
*
* \return Empty function stack
*/
auto ProduceStack() {
return FunctionStack<std::string>();
}
std::string ToString() final {
return "[ReadLinesNode] Id: " + result_file_.ToString();
}
private:
//! Path of the input file.
std::string path_;
std::vector<std::pair<std::string, size_t> > filesize_prefix;
//! InputLineIterator gives you access to lines of a file
class InputLineIterator
{
public:
const size_t read_size = 2 * 1024 * 1024;
//! Creates an instance of iterator that reads file line based
InputLineIterator(
const std::vector<FileSizePair >& files,
size_t my_id,
size_t num_workers)
: files_(files),
my_id_(my_id),
num_workers_(num_workers) {
input_size_ = files[files.size() - 1].second;
// Go to start of 'local part'.
auto my_start_and_end = common::CalculateLocalRange(input_size_, num_workers_, my_id_);
size_t my_start = std::get<0>(my_start_and_end);
my_end_ = std::get<1>(my_start_and_end);
while (files_[current_file_].second <= my_start) {
current_file_++;
}
c_file_ = OpenFile(files_[current_file_].first);
// find offset in current file:
// offset = start - sum of previous file sizes
if (current_file_) {
offset_ = lseek(c_file_, my_start - files_[current_file_ - 1].second, SEEK_CUR);
current_size_ = files_[current_file_].second - files_[current_file_ - 1].second;
}
else {
offset_ = lseek(c_file_, my_start, SEEK_CUR);
current_size_ = files_[0].second;
}
if (offset_ != 0) {
offset_ = lseek(c_file_, -1, SEEK_CUR);
bb_.Reserve(read_size);
ssize_t buffer_size = read(c_file_, bb_.data(), read_size);
bb_.set_size(buffer_size);
current_ = 1;
//Move to next newline, if local part does not start at the beginning of a line.
if (bb_[0] != '\n') {
bool found_n = false;
// find next newline, discard all previous data as previous worker already covers it
while (!found_n) {
for (auto it = bb_.begin() + current_; it != bb_.end(); it++) {
if (C7A_UNLIKELY(*it == '\n')) {
current_ = it - bb_.begin() + 1;
found_n = true;
break;
}
}
// no newline found: read new data into buffer_builder
if (!found_n) {
current_ = 0;
offset_ += bb_.size();
buffer_size = read(c_file_, bb_.data(), read_size);
//EOF = newline per definition
if (!buffer_size) {
found_n = true;
}
bb_.set_size(buffer_size);
}
}
assert(bb_[current_ - 1] == '\n' || !buffer_size);
}
}
else {
bb_.Reserve(read_size);
ssize_t buffer_size = read(c_file_, bb_.data(), read_size);
bb_.set_size(buffer_size);
}
}
//! returns the next element if one exists
//!
//! does no checks whether a next element exists!
std::string Next() {
while (true) {
std::string ret;
for (auto it = bb_.begin() + current_; it != bb_.end(); it++) {
if (C7A_UNLIKELY(*it == '\n')) {
size_t strlen = it - bb_.begin() - current_;
current_ = it - bb_.begin() + 1;
return ret.append(bb_.PartialToString(current_ - strlen - 1, strlen));
}
}
ret.append(bb_.PartialToString(current_, bb_.size() - current_));
current_ = 0;
ssize_t buffer_size = read(c_file_, bb_.data(), read_size);
offset_ += bb_.size();
if (buffer_size) {
bb_.set_size(buffer_size);
}
else {
close(c_file_);
current_file_++;
offset_ = 0;
// REVIEW(an): you must extract all the open() commands
// (this and first) into a function OpenFile() if we are to
// add decompressors.
c_file_ = OpenFile(files_[current_file_].first);
ssize_t buffer_size = read(c_file_, bb_.data(), read_size);
bb_.set_size(buffer_size);
if (ret.length()) {
return ret;
}
}
}
}
//! returns true, if an element is available in local part
bool HasNext() {
if (current_file_) {
return (offset_ + current_ + files_[current_file_ - 1].second < my_end_);
}
else {
return offset_ + current_ < my_end_;
}
}
//! Open file and return file handle
//! \param path Path to open
int OpenFile(const std::string& path) {
return open(path.c_str(), O_RDONLY);
}
private:
//! Input files with inclusive size prefixsum.
std::vector<FileSizePair > files_;
//! Index of current file in files_
size_t current_file_ = 0;
//! Size of current file in bytes
size_t current_size_;
//! File handle to files_[current_file_]
int c_file_;
//! Offset of current block in c_file_.
size_t offset_;
//! Size of all files combined (in bytes)
size_t input_size_;
//! Worker ID
size_t my_id_;
//! total number of workers
size_t num_workers_;
//! (exclusive) end of local block
size_t my_end_;
//! Byte buffer to create line-std::strings
net::BufferBuilder bb_;
//! Start of next element in current buffer.
size_t current_ = 0;
};
//! Returns an InputLineIterator with a given input file stream.
//!
//! \param file Input file stream
//! \param my_id Id of this worker
//! \param num_work Number of workers
//!
//! \return An InputLineIterator for a given file stream
InputLineIterator GetInputLineIterator(
// REVIEW(an): please make some using typedefs!
std::vector<FileSizePair> files, size_t my_id, size_t num_work) {
return InputLineIterator(files, my_id, num_work);
}
};
DIARef<std::string> ReadLines(Context& ctx, std::string filepath) {
StatsNode* stats_node = ctx.stats_graph().AddNode("ReadLines", NodeType::DOP);
auto shared_node =
std::make_shared<ReadLinesNode>(
ctx, filepath, stats_node);
auto read_stack = shared_node->ProduceStack();
return DIARef<std::string, decltype(read_stack)>(
shared_node, read_stack, { stats_node });
}
//! \}
} // namespace api
} // namespace c7a
#endif // !C7A_API_READ_LINES_HEADER
/******************************************************************************/
<commit_msg>Move semantics!<commit_after>/*******************************************************************************
* c7a/api/read_lines.hpp
*
* Part of Project c7a.
*
* Copyright (C) 2015 Alexander Noe <aleexnoe@gmail.com>
* Copyright (C) 2015 Timo Bingmann <tb@panthema.net>
*
* This file has no license. Only Chuck Norris can compile it.
******************************************************************************/
#pragma once
#ifndef C7A_API_READ_LINES_HEADER
#define C7A_API_READ_LINES_HEADER
#include <c7a/api/dia.hpp>
#include <c7a/api/dop_node.hpp>
#include <c7a/common/logger.hpp>
#include <c7a/net/buffer_builder.hpp>
// C7A_{/UN}LIKELY
#include <c7a/common/math.hpp>
#include <c7a/common/item_serialization_tools.hpp>
#include <fcntl.h>
#include <fstream>
#include <glob.h>
#include <string>
#include <sys/stat.h>
#include <sys/types.h>
namespace c7a {
namespace api {
//! \addtogroup api Interface
//! \{
/*!
* A DIANode which performs a line-based Read operation. Read reads a file from
* the file system and emits it as a DIA.
*/
class ReadLinesNode : public DOpNode<std::string>
{
public:
using Super = DOpNode<std::string>;
using Super::context_;
using Super::result_file_;
using FileSizePair = std::pair<std::string, size_t>;
/*!
* Constructor for a ReadLinesNode. Sets the Context
* and file path.
*
* \param ctx Reference to Context, which holds references to data and
* network.
*
* \param path Path of the input file(s)
*/
ReadLinesNode(Context& ctx,
const std::string& path,
StatsNode* stats_node)
: Super(ctx, { }, "Read", stats_node),
path_(path)
{
glob_t glob_result;
struct stat filestat;
glob(path_.c_str(), GLOB_TILDE, nullptr, &glob_result);
size_t directory_size = 0;
for (unsigned int i = 0; i < glob_result.gl_pathc; ++i) {
const char* filepath = glob_result.gl_pathv[i];
if (stat(filepath, &filestat)) {
throw std::runtime_error(
"ERROR: Invalid file " + std::string(filepath));
}
if (!S_ISREG(filestat.st_mode)) continue;
directory_size += filestat.st_size;
filesize_prefix.emplace_back(std::move(filepath), directory_size);
}
globfree(&glob_result);
}
void Execute() final { }
void PushData() final {
InputLineIterator it = GetInputLineIterator(
filesize_prefix, context_.my_rank(), context_.num_workers());
// Hook Read
while (it.HasNext()) {
auto item = it.Next();
for (auto func : Super::callbacks_) {
func(item);
}
}
}
void Dispose() final { }
/*!
* Produces an 'empty' function stack, which only contains the identity
* emitter function.
*
* \return Empty function stack
*/
auto ProduceStack() {
return FunctionStack<std::string>();
}
std::string ToString() final {
return "[ReadLinesNode] Id: " + result_file_.ToString();
}
private:
//! Path of the input file.
std::string path_;
std::vector<std::pair<std::string, size_t> > filesize_prefix;
//! InputLineIterator gives you access to lines of a file
class InputLineIterator
{
public:
const size_t read_size = 2 * 1024 * 1024;
//! Creates an instance of iterator that reads file line based
InputLineIterator(
const std::vector<FileSizePair >& files,
size_t my_id,
size_t num_workers)
: files_(files),
my_id_(my_id),
num_workers_(num_workers) {
input_size_ = files[files.size() - 1].second;
// Go to start of 'local part'.
auto my_start_and_end = common::CalculateLocalRange(input_size_, num_workers_, my_id_);
size_t my_start = std::get<0>(my_start_and_end);
my_end_ = std::get<1>(my_start_and_end);
while (files_[current_file_].second <= my_start) {
current_file_++;
}
c_file_ = OpenFile(files_[current_file_].first);
// find offset in current file:
// offset = start - sum of previous file sizes
if (current_file_) {
offset_ = lseek(c_file_, my_start - files_[current_file_ - 1].second, SEEK_CUR);
current_size_ = files_[current_file_].second - files_[current_file_ - 1].second;
}
else {
offset_ = lseek(c_file_, my_start, SEEK_CUR);
current_size_ = files_[0].second;
}
if (offset_ != 0) {
offset_ = lseek(c_file_, -1, SEEK_CUR);
bb_.Reserve(read_size);
ssize_t buffer_size = read(c_file_, bb_.data(), read_size);
bb_.set_size(buffer_size);
current_ = 1;
//Move to next newline, if local part does not start at the beginning of a line.
if (bb_[0] != '\n') {
bool found_n = false;
// find next newline, discard all previous data as previous worker already covers it
while (!found_n) {
for (auto it = bb_.begin() + current_; it != bb_.end(); it++) {
if (C7A_UNLIKELY(*it == '\n')) {
current_ = it - bb_.begin() + 1;
found_n = true;
break;
}
}
// no newline found: read new data into buffer_builder
if (!found_n) {
current_ = 0;
offset_ += bb_.size();
buffer_size = read(c_file_, bb_.data(), read_size);
//EOF = newline per definition
if (!buffer_size) {
found_n = true;
}
bb_.set_size(buffer_size);
}
}
assert(bb_[current_ - 1] == '\n' || !buffer_size);
}
}
else {
bb_.Reserve(read_size);
ssize_t buffer_size = read(c_file_, bb_.data(), read_size);
bb_.set_size(buffer_size);
}
}
//! returns the next element if one exists
//!
//! does no checks whether a next element exists!
std::string Next() {
while (true) {
std::string ret;
for (auto it = bb_.begin() + current_; it != bb_.end(); it++) {
if (C7A_UNLIKELY(*it == '\n')) {
size_t strlen = it - bb_.begin() - current_;
current_ = it - bb_.begin() + 1;
return ret.append(bb_.PartialToString(current_ - strlen - 1, strlen));
}
}
ret.append(bb_.PartialToString(current_, bb_.size() - current_));
current_ = 0;
ssize_t buffer_size = read(c_file_, bb_.data(), read_size);
offset_ += bb_.size();
if (buffer_size) {
bb_.set_size(buffer_size);
}
else {
close(c_file_);
current_file_++;
offset_ = 0;
// REVIEW(an): you must extract all the open() commands
// (this and first) into a function OpenFile() if we are to
// add decompressors.
c_file_ = OpenFile(files_[current_file_].first);
ssize_t buffer_size = read(c_file_, bb_.data(), read_size);
bb_.set_size(buffer_size);
if (ret.length()) {
return ret;
}
}
}
}
//! returns true, if an element is available in local part
bool HasNext() {
if (current_file_) {
return (offset_ + current_ + files_[current_file_ - 1].second < my_end_);
}
else {
return offset_ + current_ < my_end_;
}
}
//! Open file and return file handle
//! \param path Path to open
int OpenFile(const std::string& path) {
return open(path.c_str(), O_RDONLY);
}
private:
//! Input files with inclusive size prefixsum.
std::vector<FileSizePair> files_;
//! Index of current file in files_
size_t current_file_ = 0;
//! Size of current file in bytes
size_t current_size_;
//! File handle to files_[current_file_]
int c_file_;
//! Offset of current block in c_file_.
size_t offset_;
//! Size of all files combined (in bytes)
size_t input_size_;
//! Worker ID
size_t my_id_;
//! total number of workers
size_t num_workers_;
//! (exclusive) end of local block
size_t my_end_;
//! Byte buffer to create line-std::strings
net::BufferBuilder bb_;
//! Start of next element in current buffer.
size_t current_ = 0;
};
//! Returns an InputLineIterator with a given input file stream.
//!
//! \param file Input file stream
//! \param my_id Id of this worker
//! \param num_work Number of workers
//!
//! \return An InputLineIterator for a given file stream
InputLineIterator GetInputLineIterator(
// REVIEW(an): please make some using typedefs!
std::vector<FileSizePair> files, size_t my_id, size_t num_work) {
return InputLineIterator(files, my_id, num_work);
}
};
DIARef<std::string> ReadLines(Context& ctx, std::string filepath) {
StatsNode* stats_node = ctx.stats_graph().AddNode("ReadLines", NodeType::DOP);
auto shared_node =
std::make_shared<ReadLinesNode>(
ctx, filepath, stats_node);
auto read_stack = shared_node->ProduceStack();
return DIARef<std::string, decltype(read_stack)>(
shared_node, read_stack, { stats_node });
}
//! \}
} // namespace api
} // namespace c7a
#endif // !C7A_API_READ_LINES_HEADER
/******************************************************************************/
<|endoftext|>
|
<commit_before>#include "LDLTResponse.h"
#include <sofa/core/ObjectFactory.h>
namespace sofa {
namespace component {
namespace linearsolver {
SOFA_DECL_CLASS(LDLTResponse)
int LDLTResponseClass = core::RegisterObject("A sparse Cholesky factorization of the response matrix.").add< LDLTResponse >();
LDLTResponse::LDLTResponse()
: regularize( initData(®ularize,
std::numeric_limits<real>::epsilon(),
"regularize",
"add identity*regularize to matrix H to make it definite.")),
constant( initData(&constant,
false,
"constant",
"reuse first factorization")),
factorized( false )
{}
void LDLTResponse::reinit()
{
Response::reinit();
factorized = false;
}
void LDLTResponse::factor(const mat& H, bool semidefinite ) {
if( constant.getValue() && factorized ) return;
factorized = true;
if( regularize.getValue() && semidefinite ) {
// add a tiny diagonal matrix to make H psd.
// TODO add epsilon only on the empty diagonal entries?
system_type::rmat identity(H.rows(),H.cols());
identity.setIdentity();
response.compute( ( H + identity * regularize.getValue() ).selfadjointView<Eigen::Upper>() );
}
else
{
// TODO make sure no temporary is used ?
response.compute( H.selfadjointView<Eigen::Upper>() );
}
if( response.info() != Eigen::Success ) {
serr << "non invertible response" << sendl;
}
assert( response.info() == Eigen::Success );
}
void LDLTResponse::solve(cmat& res, const cmat& M) const {
assert( response.rows() );
res = response.solve( M );
}
void LDLTResponse::solve(vec& res, const vec& x) const {
assert( response.rows() );
res = response.solve( x );
}
}
}
}
<commit_msg>Flexible_test: fixing crashes. But these tests are suspicious, because they are fixing all independent dofs (projective constraints).<commit_after>#include "LDLTResponse.h"
#include <sofa/core/ObjectFactory.h>
namespace sofa {
namespace component {
namespace linearsolver {
SOFA_DECL_CLASS(LDLTResponse)
int LDLTResponseClass = core::RegisterObject("A sparse Cholesky factorization of the response matrix.").add< LDLTResponse >();
LDLTResponse::LDLTResponse()
: regularize( initData(®ularize,
std::numeric_limits<real>::epsilon(),
"regularize",
"add identity*regularize to matrix H to make it definite.")),
constant( initData(&constant,
false,
"constant",
"reuse first factorization")),
factorized( false )
{}
void LDLTResponse::reinit()
{
Response::reinit();
factorized = false;
}
void LDLTResponse::factor(const mat& H, bool semidefinite ) {
#ifndef NDEBUG
if( !H.rows() ) serr<<"factor - null matrix"<<sendl;
#endif
if( constant.getValue() && factorized ) return;
factorized = true;
if( regularize.getValue() && semidefinite ) {
// add a tiny diagonal matrix to make H psd.
// TODO add epsilon only on the empty diagonal entries?
system_type::rmat identity(H.rows(),H.cols());
identity.setIdentity();
response.compute( ( H + identity * regularize.getValue() ).selfadjointView<Eigen::Upper>() );
}
else
{
// TODO make sure no temporary is used ?
response.compute( H.selfadjointView<Eigen::Upper>() );
}
if( response.info() != Eigen::Success ) {
serr << "non invertible response" << sendl;
}
assert( response.info() == Eigen::Success );
}
void LDLTResponse::solve(cmat& res, const cmat& M) const {
res = response.solve( M );
}
void LDLTResponse::solve(vec& res, const vec& x) const {
res = response.solve( x );
}
}
}
}
<|endoftext|>
|
<commit_before>#include "ninja.h"
#include <gtest/gtest.h>
struct NinjaTest : public testing::Test {
NinjaTest() {
rule_cat_ = state_.AddRule("cat", "cat @in > $out");
}
Rule* rule_cat_;
State state_;
};
TEST_F(NinjaTest, Basic) {
Edge* edge = state_.AddEdge(rule_cat_);
state_.AddInOut(edge, Edge::IN, "in1");
state_.AddInOut(edge, Edge::IN, "in2");
state_.AddInOut(edge, Edge::OUT, "out");
EXPECT_EQ("cat in1 in2 > out", edge->EvaluateCommand());
EXPECT_FALSE(state_.GetNode("in1")->dirty());
EXPECT_FALSE(state_.GetNode("in2")->dirty());
EXPECT_FALSE(state_.GetNode("out")->dirty());
state_.stat_cache()->GetFile("in1")->Touch(1);
EXPECT_TRUE(state_.GetNode("in1")->dirty());
EXPECT_FALSE(state_.GetNode("in2")->dirty());
EXPECT_TRUE(state_.GetNode("out")->dirty());
Plan plan(&state_);
plan.AddTarget("out");
ASSERT_TRUE(plan.FindWork());
ASSERT_FALSE(plan.FindWork());
}
struct TestEnv : public EvalString::Env {
virtual string Evaluate(const string& var) {
return vars[var];
}
map<string, string> vars;
};
TEST(EvalString, PlainText) {
EvalString str;
str.Parse("plain text");
ASSERT_EQ("plain text", str.Evaluate(NULL));
}
TEST(EvalString, OneVariable) {
EvalString str;
ASSERT_TRUE(str.Parse("hi $var"));
TestEnv env;
EXPECT_EQ("hi ", str.Evaluate(&env));
env.vars["$var"] = "there";
EXPECT_EQ("hi there", str.Evaluate(&env));
}
<commit_msg>more test<commit_after>#include "ninja.h"
#include <gtest/gtest.h>
struct NinjaTest : public testing::Test {
NinjaTest() {
rule_cat_ = state_.AddRule("cat", "cat @in > $out");
}
Rule* rule_cat_;
State state_;
};
TEST_F(NinjaTest, Basic) {
Edge* edge = state_.AddEdge(rule_cat_);
state_.AddInOut(edge, Edge::IN, "in1");
state_.AddInOut(edge, Edge::IN, "in2");
state_.AddInOut(edge, Edge::OUT, "out");
EXPECT_EQ("cat in1 in2 > out", edge->EvaluateCommand());
EXPECT_FALSE(state_.GetNode("in1")->dirty());
EXPECT_FALSE(state_.GetNode("in2")->dirty());
EXPECT_FALSE(state_.GetNode("out")->dirty());
state_.stat_cache()->GetFile("in1")->Touch(1);
EXPECT_TRUE(state_.GetNode("in1")->dirty());
EXPECT_FALSE(state_.GetNode("in2")->dirty());
EXPECT_TRUE(state_.GetNode("out")->dirty());
Plan plan(&state_);
plan.AddTarget("out");
edge = plan.FindWork();
ASSERT_TRUE(edge);
EXPECT_EQ("cat in1 in2 > out", edge->EvaluateCommand());
ASSERT_FALSE(plan.FindWork());
}
struct TestEnv : public EvalString::Env {
virtual string Evaluate(const string& var) {
return vars[var];
}
map<string, string> vars;
};
TEST(EvalString, PlainText) {
EvalString str;
str.Parse("plain text");
ASSERT_EQ("plain text", str.Evaluate(NULL));
}
TEST(EvalString, OneVariable) {
EvalString str;
ASSERT_TRUE(str.Parse("hi $var"));
TestEnv env;
EXPECT_EQ("hi ", str.Evaluate(&env));
env.vars["$var"] = "there";
EXPECT_EQ("hi there", str.Evaluate(&env));
}
<|endoftext|>
|
<commit_before>#include "interfaces/non_conservative/navier_stokes.h"
#include "pidomus.h"
#include "deal.II/base/numbers.h"
#include "Teuchos_CommandLineProcessor.hpp"
#include "Teuchos_GlobalMPISession.hpp"
#include "Teuchos_oblackholestream.hpp"
#include "Teuchos_StandardCatchMacros.hpp"
#include "Teuchos_Version.hpp"
#include "mpi.h"
#include <iostream>
#include <string>
void print_status( std::string name,
std::string prm_file,
int dim,
int spacedim,
const MPI_Comm &comm);
int main (int argc, char *argv[])
{
using namespace dealii;
using namespace deal2lkit;
Teuchos::CommandLineProcessor My_CLP;
My_CLP.setDocString(
".__________ _______ ______ .___ ___. __ __ _______. \n"
"|_ __ __| | \\ / __ \\ | \\/ | | | | | / | \n"
" | | | | ______| .--. | | | | | \\ / | | | | | | (----` \n"
" | | | | |______| | | | | | | | |\\/| | | | | | \\ \\ \n"
" | | | | | '--' | `--' | | | | | | `--' | .----) | \n"
" |_| |_| |_______/ \\______/ |__| |__| \\______/ |_______/ \n\n"
);
std::string pde_name="navier_stokes";
My_CLP.setOption("pde", &pde_name, "name of the PDE (heat, stokes, dynamic_stokes, or navier_stokes)");
int spacedim = 2;
My_CLP.setOption("spacedim", &spacedim, "dimensione of the whole space");
int dim = 2;
My_CLP.setOption("dim", &dim, "dimension of the problem");
int n_threads = 0;
My_CLP.setOption("n_threads", &n_threads, "number of threads");
std::string prm_file=pde_name+".prm";
My_CLP.setOption("prm", &prm_file, "name of the parameter file");
// My_CLP.recogniseAllOptions(true);
My_CLP.throwExceptions(false);
Teuchos::CommandLineProcessor::EParseCommandLineReturn
parseReturn= My_CLP.parse( argc, argv );
if ( parseReturn == Teuchos::CommandLineProcessor::PARSE_HELP_PRINTED )
{
return 0;
}
if ( parseReturn != Teuchos::CommandLineProcessor::PARSE_SUCCESSFUL )
{
return 1; // Error!
}
Utilities::MPI::MPI_InitFinalize mpi_initialization(argc, argv,
n_threads == 0 ? numbers::invalid_unsigned_int : n_threads);
const MPI_Comm &comm = MPI_COMM_WORLD;
Teuchos::oblackholestream blackhole;
std::ostream &out = ( Utilities::MPI::this_mpi_process(comm) == 0 ? std::cout : blackhole );
My_CLP.printHelpMessage(argv[0], out);
deallog.depth_console (0);
if (pde_name == "navier_stokes")
{
print_status( "Navier-Stokes Equation",
prm_file,
dim,
spacedim,
comm);
if (dim==2)
{
NavierStokes<2> energy;
piDoMUS<2,2,3> navier_stokes_equation (energy);
ParameterAcceptor::initialize(prm_file, pde_name+"_used.prm");
ParameterAcceptor::prm.log_parameters(deallog);
navier_stokes_equation.run ();
}
else
{
NavierStokes<3> energy;
piDoMUS<3,3,4> navier_stokes_equation (energy);
ParameterAcceptor::initialize(prm_file, pde_name+"_used.prm");
ParameterAcceptor::prm.log_parameters(deallog);
navier_stokes_equation.run ();
}
}
else
{
out << std::endl
<< "============================================================="
<< std::endl
<< " ERROR:"
<< std::endl
<< " " << pde_name << " needs to be implemented or it is bad name."
<< std::endl
<< "=============================================================";
}
out << std::endl;
return 0;
}
void print_status( std::string name,
std::string prm_file,
int dim,
int spacedim,
const MPI_Comm &comm)
{
int numprocs = Utilities::MPI::n_mpi_processes(comm);
int myid = Utilities::MPI::this_mpi_process(comm);
Teuchos::oblackholestream blackhole;
std::ostream &out = ( Utilities::MPI::this_mpi_process(comm) == 0 ? std::cout : blackhole );
if (myid == 0)
{
out << std::endl
<< "============================================================="
<< std::endl
<< " Name: " << name
// << std::endl
// << "-------------------------------------------------------------"
<< std::endl
<< " Prm file: " << prm_file
<< std::endl
<< " spacedim: " << spacedim
<< std::endl
<< " dim: " << dim
<< std::endl
<< " codim: " << spacedim-dim
<< std::endl
<< "-------------------------------------------------------------"
<< std::endl;
}
out << " Process " << getpid() << " is " << myid
<< " of " << numprocs << " processes" << std::endl;
if (myid == 0)
{
out << "-------------------------------------------------------------"
<< std::endl;
system("read -p \" Press [Enter] key to start...\"");
out << "============================================================="
<<std::endl<<std::endl;
}
}
<commit_msg>indent<commit_after>#include "interfaces/non_conservative/navier_stokes.h"
#include "pidomus.h"
#include "deal.II/base/numbers.h"
#include "Teuchos_CommandLineProcessor.hpp"
#include "Teuchos_GlobalMPISession.hpp"
#include "Teuchos_oblackholestream.hpp"
#include "Teuchos_StandardCatchMacros.hpp"
#include "Teuchos_Version.hpp"
#include "mpi.h"
#include <iostream>
#include <string>
void print_status( std::string name,
std::string prm_file,
int dim,
int spacedim,
const MPI_Comm &comm);
int main (int argc, char *argv[])
{
using namespace dealii;
using namespace deal2lkit;
Teuchos::CommandLineProcessor My_CLP;
My_CLP.setDocString(
".__________ _______ ______ .___ ___. __ __ _______. \n"
"|_ __ __| | \\ / __ \\ | \\/ | | | | | / | \n"
" | | | | ______| .--. | | | | | \\ / | | | | | | (----` \n"
" | | | | |______| | | | | | | | |\\/| | | | | | \\ \\ \n"
" | | | | | '--' | `--' | | | | | | `--' | .----) | \n"
" |_| |_| |_______/ \\______/ |__| |__| \\______/ |_______/ \n\n"
);
std::string pde_name="navier_stokes";
My_CLP.setOption("pde", &pde_name, "name of the PDE (heat, stokes, dynamic_stokes, or navier_stokes)");
int spacedim = 2;
My_CLP.setOption("spacedim", &spacedim, "dimensione of the whole space");
int dim = 2;
My_CLP.setOption("dim", &dim, "dimension of the problem");
int n_threads = 0;
My_CLP.setOption("n_threads", &n_threads, "number of threads");
std::string prm_file=pde_name+".prm";
My_CLP.setOption("prm", &prm_file, "name of the parameter file");
// My_CLP.recogniseAllOptions(true);
My_CLP.throwExceptions(false);
Teuchos::CommandLineProcessor::EParseCommandLineReturn
parseReturn= My_CLP.parse( argc, argv );
if ( parseReturn == Teuchos::CommandLineProcessor::PARSE_HELP_PRINTED )
{
return 0;
}
if ( parseReturn != Teuchos::CommandLineProcessor::PARSE_SUCCESSFUL )
{
return 1; // Error!
}
Utilities::MPI::MPI_InitFinalize mpi_initialization(argc, argv,
n_threads == 0 ? numbers::invalid_unsigned_int : n_threads);
const MPI_Comm &comm = MPI_COMM_WORLD;
Teuchos::oblackholestream blackhole;
std::ostream &out = ( Utilities::MPI::this_mpi_process(comm) == 0 ? std::cout : blackhole );
My_CLP.printHelpMessage(argv[0], out);
deallog.depth_console (0);
if (pde_name == "navier_stokes")
{
print_status( "Navier-Stokes Equation",
prm_file,
dim,
spacedim,
comm);
if (dim==2)
{
NavierStokes<2> energy;
piDoMUS<2,2,3> navier_stokes_equation (energy);
ParameterAcceptor::initialize(prm_file, pde_name+"_used.prm");
ParameterAcceptor::prm.log_parameters(deallog);
navier_stokes_equation.run ();
}
else
{
NavierStokes<3> energy;
piDoMUS<3,3,4> navier_stokes_equation (energy);
ParameterAcceptor::initialize(prm_file, pde_name+"_used.prm");
ParameterAcceptor::prm.log_parameters(deallog);
navier_stokes_equation.run ();
}
}
else
{
out << std::endl
<< "============================================================="
<< std::endl
<< " ERROR:"
<< std::endl
<< " " << pde_name << " needs to be implemented or it is bad name."
<< std::endl
<< "=============================================================";
}
out << std::endl;
return 0;
}
void print_status( std::string name,
std::string prm_file,
int dim,
int spacedim,
const MPI_Comm &comm)
{
int numprocs = Utilities::MPI::n_mpi_processes(comm);
int myid = Utilities::MPI::this_mpi_process(comm);
Teuchos::oblackholestream blackhole;
std::ostream &out = ( Utilities::MPI::this_mpi_process(comm) == 0 ? std::cout : blackhole );
if (myid == 0)
{
out << std::endl
<< "============================================================="
<< std::endl
<< " Name: " << name
// << std::endl
// << "-------------------------------------------------------------"
<< std::endl
<< " Prm file: " << prm_file
<< std::endl
<< " spacedim: " << spacedim
<< std::endl
<< " dim: " << dim
<< std::endl
<< " codim: " << spacedim-dim
<< std::endl
<< "-------------------------------------------------------------"
<< std::endl;
}
out << " Process " << getpid() << " is " << myid
<< " of " << numprocs << " processes" << std::endl;
if (myid == 0)
{
out << "-------------------------------------------------------------"
<< std::endl;
system("read -p \" Press [Enter] key to start...\"");
out << "============================================================="
<<std::endl<<std::endl;
}
}
<|endoftext|>
|
<commit_before>
//
// This source file is part of appleseed.
// Visit http://appleseedhq.net/ for additional information and resources.
//
// This software is released under the MIT license.
//
// Copyright (c) 2014-2015 Esteban Tovagliari, The appleseedhq Organization
//
// 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.
//
// appleseed.foundation headers.
#include "foundation/math/rng/serialmersennetwister.h"
#ifdef APPLESEED_USE_SSE
#include "foundation/math/rng/simdmersennetwister.h"
#endif
#include "foundation/utility/benchmark.h"
// Standard headers.
#include <cstddef>
using namespace foundation;
BENCHMARK_SUITE(Foundation_Math_Rng_SerialMersenneTwister)
{
BENCHMARK_CASE(RandUint32)
{
SerialMersenneTwister rng;
for (size_t i = 0; i < 1753117; ++i)
rng.rand_uint32();
}
}
#ifdef APPLESEED_USE_SSE
BENCHMARK_SUITE(Foundation_Math_Rng_SimdMersenneTwister)
{
BENCHMARK_CASE(RandUint32)
{
SimdMersenneTwister rng;
for (size_t i = 0; i < 1753117; ++i)
rng.rand_uint32();
}
}
#endif
<commit_msg>fixed and completed RNG benchmarks.<commit_after>
//
// This source file is part of appleseed.
// Visit http://appleseedhq.net/ for additional information and resources.
//
// This software is released under the MIT license.
//
// Copyright (c) 2014-2015 Esteban Tovagliari, The appleseedhq Organization
//
// 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.
//
// appleseed.foundation headers.
#include "foundation/math/rng/lcg.h"
#include "foundation/math/rng/pcg.h"
#include "foundation/math/rng/serialmersennetwister.h"
#ifdef APPLESEED_USE_SSE
#include "foundation/math/rng/simdmersennetwister.h"
#endif
#include "foundation/math/rng/xorshift.h"
#include "foundation/platform/types.h"
#include "foundation/utility/benchmark.h"
// Standard headers.
#include <cstddef>
using namespace foundation;
BENCHMARK_SUITE(Foundation_Math_RNG)
{
template <typename RNG>
struct Fixture
{
RNG m_rng;
uint32 m_dummy;
Fixture()
: m_dummy(0)
{
}
};
BENCHMARK_CASE_F(LCG_RandUint32, Fixture<LCG>)
{
for (size_t i = 0; i < 250000; ++i)
{
m_dummy ^= m_rng.rand_uint32();
m_dummy ^= m_rng.rand_uint32();
m_dummy ^= m_rng.rand_uint32();
m_dummy ^= m_rng.rand_uint32();
}
}
BENCHMARK_CASE_F(PCG_RandUint32, Fixture<PCG>)
{
for (size_t i = 0; i < 250000; ++i)
{
m_dummy ^= m_rng.rand_uint32();
m_dummy ^= m_rng.rand_uint32();
m_dummy ^= m_rng.rand_uint32();
m_dummy ^= m_rng.rand_uint32();
}
}
BENCHMARK_CASE_F(SerialMersenneTwister_RandUint32, Fixture<SerialMersenneTwister>)
{
for (size_t i = 0; i < 250000; ++i)
{
m_dummy ^= m_rng.rand_uint32();
m_dummy ^= m_rng.rand_uint32();
m_dummy ^= m_rng.rand_uint32();
m_dummy ^= m_rng.rand_uint32();
}
}
#ifdef APPLESEED_USE_SSE
BENCHMARK_CASE_F(SimdMersenneTwister_RandUint32, Fixture<SimdMersenneTwister>)
{
for (size_t i = 0; i < 250000; ++i)
{
m_dummy ^= m_rng.rand_uint32();
m_dummy ^= m_rng.rand_uint32();
m_dummy ^= m_rng.rand_uint32();
m_dummy ^= m_rng.rand_uint32();
}
}
#endif
BENCHMARK_CASE_F(Xorshift_RandUint32, Fixture<Xorshift>)
{
for (size_t i = 0; i < 250000; ++i)
{
m_dummy ^= m_rng.rand_uint32();
m_dummy ^= m_rng.rand_uint32();
m_dummy ^= m_rng.rand_uint32();
m_dummy ^= m_rng.rand_uint32();
}
}
}
<|endoftext|>
|
<commit_before>#pragma once
#include <cstddef>
#include <cstring>
#include <string>
#include <utility>
#include <iterator>
#include <iomanip>
namespace microbson
{
typedef unsigned char byte;
enum node_type {
double_node = 0x01,
string_node = 0x02,
document_node = 0x03,
binary_node = 0x05,
boolean_node = 0x08,
null_node = 0x0A,
int32_node = 0x10,
int64_node = 0x12,
unknown_node = 0xFF
};
class document;
template<typename T> struct type_converter { };
template<> struct type_converter<double>
{
enum { node_type_code = double_node };
};
template<> struct type_converter<std::string>
{
enum { node_type_code = string_node };
};
template<> struct type_converter<document>
{
enum { node_type_code = document_node };
};
template<> struct type_converter<void*>
{
enum { node_type_code = binary_node };
};
template<> struct type_converter<bool>
{
enum { node_type_code = boolean_node };
};
template<> struct type_converter<int>
{
enum { node_type_code = int32_node };
};
template<> struct type_converter<long long>
{
enum { node_type_code = int64_node };
};
struct node
{
byte* bytes;
node() : bytes(NULL) { }
node(byte* bytes) : bytes(bytes) { }
node_type get_type() const { return static_cast<node_type>(bytes[0]); }
const char* get_name() const
{
return reinterpret_cast<const char*>( bytes + 1 );
}
size_t get_size() const
{
size_t result = 1U + strlen(get_name()) + 1U;
switch (get_type())
{
case double_node:
result += sizeof(double);
break;
case document_node:
result += *reinterpret_cast<int*>(bytes + result);
break;
case string_node:
case binary_node:
result += (
sizeof(int)
+ *reinterpret_cast<int*>(bytes + result)
+ 1U
);
break;
case boolean_node:
result += 1U;
case null_node:
break;
case int32_node:
result += sizeof(int);
break;
case int64_node:
result += sizeof(long long);
break;
default:
result = 0U;
break;
}
return result;
}
void* get_data() const
{
return bytes + 1U + strlen(get_name()) + 1U;
}
bool valid(size_t size) const
{
return (size >= 2) && (get_size() <= size);
}
};
class document
{
private:
byte* bytes;
size_t size;
bool lookup(const char* name, node& result) const
{
byte* iterator = bytes + sizeof(int);
size_t left = size - sizeof(int);
bool found = false;
result = node(iterator);
while (result.valid(left))
{
if (strcmp(result.get_name(), name) == 0)
{
found = true;
break;
}
else
{
iterator += result.get_size();
left -= result.get_size();
result = node(iterator);
}
}
return found;
}
template<typename T, typename W>
T get(node _node) const
{
return static_cast<T>(
*reinterpret_cast<W*>(_node.get_data())
);
}
std::string get_string(const node& _node) const
{
return std::string(
reinterpret_cast<const char*>(_node.get_data())
+ sizeof(int),
*reinterpret_cast<int*>(_node.get_data())
);
}
template<typename T, typename W>
T get(const std::string& name, T _default) const
{
node _node;
return lookup(name.c_str(), _node)
? get<T, W>(_node)
: _default
;
}
void dump(const node& _node, std::ostream& _stream) const
{
switch(_node.get_type())
{
case double_node:
_stream << get<double, double>(_node);
break;
case string_node:
_stream << '"' << get_string(_node) << '"';
break;
case binary_node:
{
byte* bytes = reinterpret_cast<byte*>(
_node.get_data()
);
std::ios::fmtflags flags( _stream.flags() );
_stream
<< std::hex
<< std::setw(2)
<< std::setfill('0')
;
copy(
bytes + 5U,
bytes + 5U + *static_cast<int*>(
_node.get_data()
),
std::ostream_iterator<int>(_stream)
);
_stream.flags(flags);
break;
}
case boolean_node:
_stream << (get<bool, byte>(_node) ? "true" : "false");
break;
case null_node:
_stream << "(null)";
break;
case int32_node:
_stream << get<int, int>(_node);
break;
case int64_node:
_stream << get<long long, long long>(_node);
break;
default:
break;
}
}
public:
document() : bytes(NULL), size(0U) { }
document(void* bytes, size_t count)
: bytes(reinterpret_cast<byte*>(bytes)), size(count)
{
}
bool valid() const
{
return (size >= 7U) && (bytes[size -1] == 0);
}
double get(const std::string& name, double _default) const
{
return get<double, double>(name, _default);
}
std::string get(
const std::string& name,
const std::string& _default
) const
{
node _node;
bool found = lookup(name.c_str(), _node);
std::string result(_default);
if (found)
result = get_string(_node);
return result;
}
document get(
const std::string& name,
const document& _default
) const
{
node _node;
bool found = lookup(name.c_str(), _node);
document result(_default);
if (found)
result = document(_node.bytes, _node.get_size());
return result;
}
std::pair<void*, size_t> get(const std::string& name) const
{
node _node;
bool found = lookup(name.c_str(), _node);
std::pair<void*, size_t> result(NULL, 0U);
if (found) {
result.second = *reinterpret_cast<int*>(_node.get_data());
result.first = reinterpret_cast<byte*>(_node.get_data()) + 5U;
}
return result;
}
bool get(const std::string& name, bool _default) const
{
return get<bool, byte>(name, _default);
}
int get(const std::string& name, int _default) const
{
return get<int, int>(name, _default);
}
long long get(const std::string& name, long long _default) const
{
return get<long long, long long>(name, _default);
}
void dump(std::ostream& _stream) const
{
byte* iterator = bytes + sizeof(int);
size_t left = size - sizeof(int);
node _node(iterator);
_stream << "{ ";
while (_node.valid(left))
{
_stream << _node.get_name() << " : ";
if (_node.get_type() == document_node)
document(
_node.get_data(),
*static_cast<int*>(_node.get_data())
).dump(_stream);
else
dump(_node, _stream);
iterator += _node.get_size();
left -= _node.get_size();
_node = node(iterator);
if (_node.valid(left))
_stream << ", ";
}
_stream << " }";
}
bool contains(const std::string& name)
{
node _node;
return lookup(name.c_str(), _node);
}
template<typename T>
bool contains(const std::string& name)
{
node _node;
bool found = lookup(name.c_str(), _node);
return (
found
&& (_node.get_type() == type_converter<T>::node_type_code)
);
}
};
}
<commit_msg>Fix string size calculation in microbson.<commit_after>#pragma once
#include <cstddef>
#include <cstring>
#include <string>
#include <utility>
#include <iterator>
#include <iomanip>
namespace microbson
{
typedef unsigned char byte;
enum node_type {
double_node = 0x01,
string_node = 0x02,
document_node = 0x03,
binary_node = 0x05,
boolean_node = 0x08,
null_node = 0x0A,
int32_node = 0x10,
int64_node = 0x12,
unknown_node = 0xFF
};
class document;
template<typename T> struct type_converter { };
template<> struct type_converter<double>
{
enum { node_type_code = double_node };
};
template<> struct type_converter<std::string>
{
enum { node_type_code = string_node };
};
template<> struct type_converter<document>
{
enum { node_type_code = document_node };
};
template<> struct type_converter<void*>
{
enum { node_type_code = binary_node };
};
template<> struct type_converter<bool>
{
enum { node_type_code = boolean_node };
};
template<> struct type_converter<int>
{
enum { node_type_code = int32_node };
};
template<> struct type_converter<long long>
{
enum { node_type_code = int64_node };
};
struct node
{
byte* bytes;
node() : bytes(NULL) { }
node(byte* bytes) : bytes(bytes) { }
node_type get_type() const { return static_cast<node_type>(bytes[0]); }
const char* get_name() const
{
return reinterpret_cast<const char*>( bytes + 1 );
}
size_t get_size() const
{
size_t result = 1U + strlen(get_name()) + 1U;
switch (get_type())
{
case double_node:
result += sizeof(double);
break;
case document_node:
result += *reinterpret_cast<int*>(bytes + result);
break;
case string_node:
case binary_node:
result += (
sizeof(int)
+ *reinterpret_cast<int*>(bytes + result)
+ 1U
);
break;
case boolean_node:
result += 1U;
case null_node:
break;
case int32_node:
result += sizeof(int);
break;
case int64_node:
result += sizeof(long long);
break;
default:
result = 0U;
break;
}
return result;
}
void* get_data() const
{
return bytes + 1U + strlen(get_name()) + 1U;
}
bool valid(size_t size) const
{
return (size >= 2) && (get_size() <= size);
}
};
class document
{
private:
byte* bytes;
size_t size;
bool lookup(const char* name, node& result) const
{
byte* iterator = bytes + sizeof(int);
size_t left = size - sizeof(int);
bool found = false;
result = node(iterator);
while (result.valid(left))
{
if (strcmp(result.get_name(), name) == 0)
{
found = true;
break;
}
else
{
iterator += result.get_size();
left -= result.get_size();
result = node(iterator);
}
}
return found;
}
template<typename T, typename W>
T get(node _node) const
{
return static_cast<T>(
*reinterpret_cast<W*>(_node.get_data())
);
}
std::string get_string(const node& _node) const
{
return std::string(
reinterpret_cast<const char*>(_node.get_data())
+ sizeof(int),
*reinterpret_cast<int*>(_node.get_data()) - 1
);
}
template<typename T, typename W>
T get(const std::string& name, T _default) const
{
node _node;
return lookup(name.c_str(), _node)
? get<T, W>(_node)
: _default
;
}
void dump(const node& _node, std::ostream& _stream) const
{
switch(_node.get_type())
{
case double_node:
_stream << get<double, double>(_node);
break;
case string_node:
_stream << '"' << get_string(_node) << '"';
break;
case binary_node:
{
byte* bytes = reinterpret_cast<byte*>(
_node.get_data()
);
std::ios::fmtflags flags( _stream.flags() );
_stream
<< std::hex
<< std::setw(2)
<< std::setfill('0')
;
copy(
bytes + 5U,
bytes + 5U + *static_cast<int*>(
_node.get_data()
),
std::ostream_iterator<int>(_stream)
);
_stream.flags(flags);
break;
}
case boolean_node:
_stream << (get<bool, byte>(_node) ? "true" : "false");
break;
case null_node:
_stream << "(null)";
break;
case int32_node:
_stream << get<int, int>(_node);
break;
case int64_node:
_stream << get<long long, long long>(_node);
break;
default:
break;
}
}
public:
document() : bytes(NULL), size(0U) { }
document(void* bytes, size_t count)
: bytes(reinterpret_cast<byte*>(bytes)), size(count)
{
}
bool valid() const
{
return (size >= 7U) && (bytes[size -1] == 0);
}
double get(const std::string& name, double _default) const
{
return get<double, double>(name, _default);
}
std::string get(
const std::string& name,
const std::string& _default
) const
{
node _node;
bool found = lookup(name.c_str(), _node);
std::string result(_default);
if (found)
result = get_string(_node);
return result;
}
document get(
const std::string& name,
const document& _default
) const
{
node _node;
bool found = lookup(name.c_str(), _node);
document result(_default);
if (found)
result = document(_node.bytes, _node.get_size());
return result;
}
std::pair<void*, size_t> get(const std::string& name) const
{
node _node;
bool found = lookup(name.c_str(), _node);
std::pair<void*, size_t> result(NULL, 0U);
if (found) {
result.second = *reinterpret_cast<int*>(_node.get_data());
result.first = reinterpret_cast<byte*>(_node.get_data()) + 5U;
}
return result;
}
bool get(const std::string& name, bool _default) const
{
return get<bool, byte>(name, _default);
}
int get(const std::string& name, int _default) const
{
return get<int, int>(name, _default);
}
long long get(const std::string& name, long long _default) const
{
return get<long long, long long>(name, _default);
}
void dump(std::ostream& _stream) const
{
byte* iterator = bytes + sizeof(int);
size_t left = size - sizeof(int);
node _node(iterator);
_stream << "{ ";
while (_node.valid(left))
{
_stream << _node.get_name() << " : ";
if (_node.get_type() == document_node)
document(
_node.get_data(),
*static_cast<int*>(_node.get_data())
).dump(_stream);
else
dump(_node, _stream);
iterator += _node.get_size();
left -= _node.get_size();
_node = node(iterator);
if (_node.valid(left))
_stream << ", ";
}
_stream << " }";
}
bool contains(const std::string& name)
{
node _node;
return lookup(name.c_str(), _node);
}
template<typename T>
bool contains(const std::string& name)
{
node _node;
bool found = lookup(name.c_str(), _node);
return (
found
&& (_node.get_type() == type_converter<T>::node_type_code)
);
}
};
}
<|endoftext|>
|
<commit_before>#include <iostream>
#include <queue>
#include <utility>
using namespace std;
typedef pair<int,int> node;
int re[1000000];
int main(int argc, char const *argv[])
{
priority_queue<node> pq;
pq.push(make_pair(1,2));
node n;
while(1){
node n=pq.top();
pq.pop();
switch(n.second){
case 2:
pq.push(make_pair(n.first*2,3));
break;
case 3:
pq.push(make_pair(n.first*3,5));
break;
case 5:
pq.push(make_pair(n.first*5,0));
break;
}
}
return 0;
}<commit_msg>update 346588<commit_after>#include <iostream>
#include <queue>
#include <utility>
using namespace std;
typedef pair<int,int> node;
int re[1000000];
int main(int argc, char const *argv[])
{
priority_queue<node> pq;
pq.push(make_pair(1,2));
node n;
int i=0;
while(1){
node n=pq.top();
pq.pop();
switch(n.second){
case 2:
pq.push(make_pair(n.first*2,3));
break;
case 3:
pq.push(make_pair(n.first*3,5));
break;
case 5:
pq.push(make_pair(n.first*5,0));
break;
}
re[i++]=n.first;
}
return 0;
}<|endoftext|>
|
<commit_before>/*
* EnvironmentMonitor.cpp
*
* Copyright (C) 2009-12 by RStudio, Inc.
*
* Unless you have received this program directly from RStudio pursuant
* to the terms of a commercial license agreement with RStudio, then
* this program is licensed to you under the terms of version 3 of the
* GNU Affero General Public License. This program is distributed WITHOUT
* ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT,
* MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the
* AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details.
*
*/
#include "EnvironmentMonitor.hpp"
#include <r/RSexp.hpp>
#include <r/RInterface.hpp>
#include <session/SessionModuleContext.hpp>
#include "EnvironmentUtils.hpp"
using namespace core;
namespace session {
namespace modules {
namespace environment {
namespace {
bool compareVarName(const r::sexp::Variable& var1,
const r::sexp::Variable& var2)
{
return var1.first < var2.first;
}
void enqueRefreshEvent()
{
ClientEvent refreshEvent(client_events::kEnvironmentRefresh);
module_context::enqueClientEvent(refreshEvent);
}
// if the given variable is an unevaluated promise, add it to the given
// list of variables
void addUnevaledPromise(std::vector<r::sexp::Variable>* pEnv,
const r::sexp::Variable& var)
{
if (isUnevaluatedPromise(var.second))
{
pEnv->push_back(var);
}
}
// if the given variable exists in the given list, remove it
void removeVarFromList(std::vector<r::sexp::Variable>* pEnv,
const r::sexp::Variable& var)
{
std::vector<r::sexp::Variable>::iterator iter =
std::find(pEnv->begin(), pEnv->end(), var);
if (iter != pEnv->end())
{
pEnv->erase(iter);
}
}
} // anonymous namespace
EnvironmentMonitor::EnvironmentMonitor() :
initialized_(false)
{}
void EnvironmentMonitor::enqueRemovedEvent(const r::sexp::Variable& variable)
{
ClientEvent removedEvent(client_events::kEnvironmentRemoved, variable.first);
module_context::enqueClientEvent(removedEvent);
}
void EnvironmentMonitor::enqueAssignedEvent(const r::sexp::Variable& variable)
{
// get object info
json::Value objInfo = varToJson(getMonitoredEnvironment(), variable);
// enque event
ClientEvent assignedEvent(client_events::kEnvironmentAssigned, objInfo);
module_context::enqueClientEvent(assignedEvent);
}
void EnvironmentMonitor::setMonitoredEnvironment(SEXP pEnvironment)
{
environment_.set(pEnvironment);
// init the environment by doing an initial check for changes
initialized_ = false;
checkForChanges();
}
SEXP EnvironmentMonitor::getMonitoredEnvironment()
{
return environment_.get();
}
void EnvironmentMonitor::listEnv(std::vector<r::sexp::Variable>* pEnv)
{
r::sexp::Protect rProtect;
r::sexp::listEnvironment(getMonitoredEnvironment(), false, &rProtect, pEnv);
}
void EnvironmentMonitor::checkForChanges()
{
// information about the current environment
std::vector<r::sexp::Variable> currentEnv ;
std::vector<r::sexp::Variable> currentPromises;
// list of assigns/removes (includes both value changes and promise
// evaluations)
std::vector<r::sexp::Variable> addedVars;
std::vector<r::sexp::Variable> removedVars;
// get the set of variables and promises in the current environment
listEnv(¤tEnv);
// R returns an environment list sorted in dictionary order. Since the
// set difference algorithms below use simple string comparisons to
// establish order, we need to re-sort the list into canonical order
// to avoid the algorithms detecting superfluous insertions.
std::sort(currentEnv.begin(), currentEnv.end(), compareVarName);
std::for_each(currentEnv.begin(), currentEnv.end(),
boost::bind(addUnevaledPromise, ¤tPromises, _1));
bool refreshEnqueued = false;
if (!initialized_)
{
if (getMonitoredEnvironment() == R_GlobalEnv)
{
enqueRefreshEvent();
refreshEnqueued = true;
}
initialized_ = true;
}
else
{
if (currentEnv != lastEnv_)
{
// optimize for empty currentEnv (user reset workspace) or empty
// lastEnv_ (startup) by just sending a single refresh event
// only do this for the global environment--while debugging local
// environments, the environment object list is sent down as part of
// the context depth event.
if ((currentEnv.empty() || lastEnv_.empty())
&& getMonitoredEnvironment() == R_GlobalEnv)
{
enqueRefreshEvent();
refreshEnqueued = true;
}
else
{
std::set_difference(lastEnv_.begin(), lastEnv_.end(),
currentEnv.begin(), currentEnv.end(),
std::back_inserter(removedVars),
compareVarName);
// fire removed event for deletes
std::for_each(removedVars.begin(),
removedVars.end(),
boost::bind(&EnvironmentMonitor::enqueRemovedEvent,
this, _1));
// remove deleted objects from the list of uneval'ed promises
// so we'll stop monitoring them for evaluation
std::for_each(removedVars.begin(),
removedVars.end(),
boost::bind(removeVarFromList, &unevaledPromises_, _1));
// find adds & assigns (all variable name/value combinations in the
// current environment but NOT in the previous environment)
std::set_difference(currentEnv.begin(), currentEnv.end(),
lastEnv_.begin(), lastEnv_.end(),
std::back_inserter(addedVars));
}
}
// if a refresh is scheduled there's no need to emit add events one by one
if (!refreshEnqueued)
{
// have any promises been evaluated since we last checked?
if (currentPromises != unevaledPromises_)
{
// for each promise that is in the set of promises we are monitoring
// for evaluation but not in the set of currently tracked promises,
// we assume this to be an eval--process as an assign
std::set_difference(unevaledPromises_.begin(), unevaledPromises_.end(),
currentPromises.begin(), currentPromises.end(),
std::back_inserter(addedVars));
}
// fire assigned event for adds, assigns, and promise evaluations
std::for_each(addedVars.begin(),
addedVars.end(),
boost::bind(&EnvironmentMonitor::enqueAssignedEvent,
this, _1));
}
}
unevaledPromises_ = currentPromises;
lastEnv_ = currentEnv;
}
} // namespace environment
} // namespace modules
} // namespace session
<commit_msg>fix promise evaluation display when promise SEXP is simultaneously eval'ed and assigned<commit_after>/*
* EnvironmentMonitor.cpp
*
* Copyright (C) 2009-12 by RStudio, Inc.
*
* Unless you have received this program directly from RStudio pursuant
* to the terms of a commercial license agreement with RStudio, then
* this program is licensed to you under the terms of version 3 of the
* GNU Affero General Public License. This program is distributed WITHOUT
* ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT,
* MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the
* AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details.
*
*/
#include "EnvironmentMonitor.hpp"
#include <r/RSexp.hpp>
#include <r/RInterface.hpp>
#include <session/SessionModuleContext.hpp>
#include "EnvironmentUtils.hpp"
using namespace core;
namespace session {
namespace modules {
namespace environment {
namespace {
bool compareVarName(const r::sexp::Variable& var1,
const r::sexp::Variable& var2)
{
return var1.first < var2.first;
}
void enqueRefreshEvent()
{
ClientEvent refreshEvent(client_events::kEnvironmentRefresh);
module_context::enqueClientEvent(refreshEvent);
}
// if the given variable is an unevaluated promise, add it to the given
// list of variables
void addUnevaledPromise(std::vector<r::sexp::Variable>* pEnv,
const r::sexp::Variable& var)
{
if (isUnevaluatedPromise(var.second))
{
pEnv->push_back(var);
}
}
// If the given variable exists in the given list, remove it. Compares on name
// only.
void removeVarFromList(std::vector<r::sexp::Variable>* pEnv,
const r::sexp::Variable& var)
{
for (std::vector<r::sexp::Variable>::iterator iter = pEnv->begin();
iter != pEnv->end(); iter++)
{
if (iter->first == var.first)
{
pEnv->erase(iter);
break;
}
}
}
} // anonymous namespace
EnvironmentMonitor::EnvironmentMonitor() :
initialized_(false)
{}
void EnvironmentMonitor::enqueRemovedEvent(const r::sexp::Variable& variable)
{
ClientEvent removedEvent(client_events::kEnvironmentRemoved, variable.first);
module_context::enqueClientEvent(removedEvent);
}
void EnvironmentMonitor::enqueAssignedEvent(const r::sexp::Variable& variable)
{
// get object info
json::Value objInfo = varToJson(getMonitoredEnvironment(), variable);
// enque event
ClientEvent assignedEvent(client_events::kEnvironmentAssigned, objInfo);
module_context::enqueClientEvent(assignedEvent);
}
void EnvironmentMonitor::setMonitoredEnvironment(SEXP pEnvironment)
{
environment_.set(pEnvironment);
// init the environment by doing an initial check for changes
initialized_ = false;
checkForChanges();
}
SEXP EnvironmentMonitor::getMonitoredEnvironment()
{
return environment_.get();
}
void EnvironmentMonitor::listEnv(std::vector<r::sexp::Variable>* pEnv)
{
r::sexp::Protect rProtect;
r::sexp::listEnvironment(getMonitoredEnvironment(), false, &rProtect, pEnv);
}
void EnvironmentMonitor::checkForChanges()
{
// information about the current environment
std::vector<r::sexp::Variable> currentEnv ;
std::vector<r::sexp::Variable> currentPromises;
// list of assigns/removes (includes both value changes and promise
// evaluations)
std::vector<r::sexp::Variable> addedVars;
std::vector<r::sexp::Variable> removedVars;
// get the set of variables and promises in the current environment
listEnv(¤tEnv);
// R returns an environment list sorted in dictionary order. Since the
// set difference algorithms below use simple string comparisons to
// establish order, we need to re-sort the list into canonical order
// to avoid the algorithms detecting superfluous insertions.
std::sort(currentEnv.begin(), currentEnv.end(), compareVarName);
std::for_each(currentEnv.begin(), currentEnv.end(),
boost::bind(addUnevaledPromise, ¤tPromises, _1));
bool refreshEnqueued = false;
if (!initialized_)
{
if (getMonitoredEnvironment() == R_GlobalEnv)
{
enqueRefreshEvent();
refreshEnqueued = true;
}
initialized_ = true;
}
else
{
if (currentEnv != lastEnv_)
{
// optimize for empty currentEnv (user reset workspace) or empty
// lastEnv_ (startup) by just sending a single refresh event
// only do this for the global environment--while debugging local
// environments, the environment object list is sent down as part of
// the context depth event.
if ((currentEnv.empty() || lastEnv_.empty())
&& getMonitoredEnvironment() == R_GlobalEnv)
{
enqueRefreshEvent();
refreshEnqueued = true;
}
else
{
std::set_difference(lastEnv_.begin(), lastEnv_.end(),
currentEnv.begin(), currentEnv.end(),
std::back_inserter(removedVars),
compareVarName);
// fire removed event for deletes
std::for_each(removedVars.begin(),
removedVars.end(),
boost::bind(&EnvironmentMonitor::enqueRemovedEvent,
this, _1));
// remove deleted objects from the list of uneval'ed promises
// so we'll stop monitoring them for evaluation
std::for_each(removedVars.begin(),
removedVars.end(),
boost::bind(removeVarFromList, &unevaledPromises_, _1));
// find adds & assigns (all variable name/value combinations in the
// current environment but NOT in the previous environment)
std::set_difference(currentEnv.begin(), currentEnv.end(),
lastEnv_.begin(), lastEnv_.end(),
std::back_inserter(addedVars));
// remove assigned objects from the list of uneval'ed promises
// (otherwise, we double-assign in the case where a promise SEXP
// is simultaneously forced/evaluated and assigned a new value)
std::for_each(addedVars.begin(),
addedVars.end(),
boost::bind(removeVarFromList, &unevaledPromises_, _1));
}
}
// if a refresh is scheduled there's no need to emit add events one by one
if (!refreshEnqueued)
{
// have any promises been evaluated since we last checked?
if (currentPromises != unevaledPromises_)
{
// for each promise that is in the set of promises we are monitoring
// for evaluation but not in the set of currently tracked promises,
// we assume this to be an eval--process as an assign
std::set_difference(unevaledPromises_.begin(), unevaledPromises_.end(),
currentPromises.begin(), currentPromises.end(),
std::back_inserter(addedVars));
}
// fire assigned event for adds, assigns, and promise evaluations
std::for_each(addedVars.begin(),
addedVars.end(),
boost::bind(&EnvironmentMonitor::enqueAssignedEvent,
this, _1));
}
}
unevaledPromises_ = currentPromises;
lastEnv_ = currentEnv;
}
} // namespace environment
} // namespace modules
} // namespace session
<|endoftext|>
|
<commit_before>//
// application_context.cpp
// usbtest
//
// Created by Kristoffer Andersen on 13/07/15.
// Copyright (c) 2015 Monolit ApS. All rights reserved.
//
#include "application_context.h"
#include "application_controller_interface.h"
#include <display_painter.h>
#include "consoles.h"
#include <mbed_interface.h>
extern "C" {
#include <project.h>
}
void faultExceptionHandler()
{
mbed_die();
}
using namespace mono;
ApplicationContext ApplicationContext::singleton;
IApplicationContext *IApplicationContext::Instance = NULL; //&(ApplicationContext::singleton);
ApplicationContext::ApplicationContext() : IApplicationContext(&pwrMgmt, &runLoop, &dispController), dispController()
{
PWM_Start();
PWM_WriteCompare1(0);
PWM_WriteCompare2(0);
}
int ApplicationContext::exec()
{
runLoop.exec();
return 0;
}
void ApplicationContext::setMonoApplication(mono::IApplication *monoApp)
{
this->application = monoApp;
//CyIntSetSysVector(CY_INT_NMI_IRQN, &faultExceptionHandler);
CyIntSetSysVector(CY_INT_HARD_FAULT_IRQN, &faultExceptionHandler);
//CyIntSetSysVector(CY_INT_MEM_MANAGE_IRQN, &faultExceptionHandler);
//CyIntSetSysVector(CY_INT_BUS_FAULT_IRQN, &faultExceptionHandler);
//CyIntSetSysVector(CY_INT_USAGE_FAULT_IRQN, &faultExceptionHandler);
//PowerSystem->onSystemPowerOnReset();
//pwrMgmt.processResetAwarenessQueue();
//defaultSerial.printf("Display init deactivated\n\t");
mono::IApplicationContext::Instance->DisplayController->init();
monoApp->monoWakeFromReset();
}
void ApplicationContext::sleepForMs(uint32_t ms)
{
uint8_t ticks = 1;
while ((1u << ticks) < ms) {
ticks++;
}
defaultSerial.printf("Setting CTW to: %i for ms: %i\n\r",ticks, ms);
*((reg8*)CYREG_PM_TW_CFG1) = 0x0F & ticks;
PM_TW_CFG2 = PM_TW_CFG2 | 0x0C; // CTW enable and CTW interrupts
defaultSerial.printf("CTW CFG Reg: 0x%x\n\r",PM_TW_CFG2);
enterSleepMode();
}
void ApplicationContext::enterSleepMode()
{
this->application->monoWillGotoSleep();
PowerManager->EnterSleep();
this->application->monoWakeFromSleep();
}
void ApplicationContext::_softwareReset()
{
Bootloadable_SET_RUN_TYPE(Bootloadable_START_APP);
CySoftwareReset();
while(1); // silence compiler warning
}
void ApplicationContext::_softwareResetToBootloader()
{
Bootloadable_SET_RUN_TYPE(Bootloadable_START_BTLDR);
CySoftwareReset();
while(1); // silence compiler warning
}
void ApplicationContext::resetOnUserButton()
{
debug("Mono will reset on user button!\n\r");
this->runLoop.setResetOnUserButton(true);
}
<commit_msg>fault handler call mbed directly<commit_after>//
// application_context.cpp
// usbtest
//
// Created by Kristoffer Andersen on 13/07/15.
// Copyright (c) 2015 Monolit ApS. All rights reserved.
//
#include "application_context.h"
#include "application_controller_interface.h"
#include <display_painter.h>
#include "consoles.h"
#include <mbed_interface.h>
extern "C" {
#include <project.h>
}
using namespace mono;
ApplicationContext ApplicationContext::singleton;
IApplicationContext *IApplicationContext::Instance = NULL; //&(ApplicationContext::singleton);
ApplicationContext::ApplicationContext() : IApplicationContext(&pwrMgmt, &runLoop, &dispController), dispController()
{
PWM_Start();
PWM_WriteCompare1(0);
PWM_WriteCompare2(0);
}
int ApplicationContext::exec()
{
runLoop.exec();
return 0;
}
void ApplicationContext::setMonoApplication(mono::IApplication *monoApp)
{
this->application = monoApp;
//CyIntSetSysVector(CY_INT_NMI_IRQN, &faultExceptionHandler);
CyIntSetSysVector(CY_INT_HARD_FAULT_IRQN, &mbed_die);
//CyIntSetSysVector(CY_INT_MEM_MANAGE_IRQN, &faultExceptionHandler);
//CyIntSetSysVector(CY_INT_BUS_FAULT_IRQN, &faultExceptionHandler);
//CyIntSetSysVector(CY_INT_USAGE_FAULT_IRQN, &faultExceptionHandler);
//PowerSystem->onSystemPowerOnReset();
pwrMgmt.processResetAwarenessQueue();
//defaultSerial.printf("Display init deactivated\n\t");
mono::IApplicationContext::Instance->DisplayController->init();
monoApp->monoWakeFromReset();
}
void ApplicationContext::sleepForMs(uint32_t ms)
{
uint8_t ticks = 1;
while ((1u << ticks) < ms) {
ticks++;
}
defaultSerial.printf("Setting CTW to: %i for ms: %i\n\r",ticks, ms);
*((reg8*)CYREG_PM_TW_CFG1) = 0x0F & ticks;
PM_TW_CFG2 = PM_TW_CFG2 | 0x0C; // CTW enable and CTW interrupts
defaultSerial.printf("CTW CFG Reg: 0x%x\n\r",PM_TW_CFG2);
enterSleepMode();
}
void ApplicationContext::enterSleepMode()
{
this->application->monoWillGotoSleep();
PowerManager->EnterSleep();
this->application->monoWakeFromSleep();
}
void ApplicationContext::_softwareReset()
{
Bootloadable_SET_RUN_TYPE(Bootloadable_START_APP);
CySoftwareReset();
while(1); // silence compiler warning
}
void ApplicationContext::_softwareResetToBootloader()
{
Bootloadable_SET_RUN_TYPE(Bootloadable_START_BTLDR);
CySoftwareReset();
while(1); // silence compiler warning
}
void ApplicationContext::resetOnUserButton()
{
debug("Mono will reset on user button!\n\r");
this->runLoop.setResetOnUserButton(true);
}
<|endoftext|>
|
<commit_before>/* IBM_PROLOG_BEGIN_TAG */
/* This is an automatically generated prolog. */
/* */
/* $Source: src/import/chips/p9/procedures/hwp/initfiles/p9_psi_scom.C $ */
/* */
/* OpenPOWER HostBoot Project */
/* */
/* Contributors Listed Below - COPYRIGHT 2016 */
/* [+] International Business Machines Corp. */
/* */
/* */
/* 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. */
/* */
/* IBM_PROLOG_END_TAG */
#include "p9_psi_scom.H"
#include <stdint.h>
#include <stddef.h>
#include <fapi2.H>
using namespace fapi2;
constexpr uint64_t literal_0xFE00000000000000 = 0xFE00000000000000;
constexpr uint64_t literal_0x0000000000000000 = 0x0000000000000000;
constexpr uint64_t literal_0b00111001000000101111111111111 = 0b00111001000000101111111111111;
constexpr uint64_t literal_0b00000000000000000000000000000 = 0b00000000000000000000000000000;
constexpr uint64_t literal_0b11000110001010010000000000000 = 0b11000110001010010000000000000;
constexpr uint64_t literal_0x000 = 0x000;
constexpr uint64_t literal_0b00000 = 0b00000;
fapi2::ReturnCode p9_psi_scom(const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& TGT0)
{
{
fapi2::ATTR_EC_Type l_chip_ec;
fapi2::ATTR_NAME_Type l_chip_id;
FAPI_TRY(FAPI_ATTR_GET_PRIVILEGED(fapi2::ATTR_NAME, TGT0, l_chip_id));
FAPI_TRY(FAPI_ATTR_GET_PRIVILEGED(fapi2::ATTR_EC, TGT0, l_chip_ec));
fapi2::buffer<uint64_t> l_scom_buffer;
{
FAPI_TRY(fapi2::getScom( TGT0, 0x4011803ull, l_scom_buffer ));
l_scom_buffer.insert<0, 7, 0, uint64_t>(literal_0xFE00000000000000 );
FAPI_TRY(fapi2::putScom(TGT0, 0x4011803ull, l_scom_buffer));
}
{
FAPI_TRY(fapi2::getScom( TGT0, 0x4011806ull, l_scom_buffer ));
l_scom_buffer.insert<0, 7, 0, uint64_t>(literal_0x0000000000000000 );
FAPI_TRY(fapi2::putScom(TGT0, 0x4011806ull, l_scom_buffer));
}
{
FAPI_TRY(fapi2::getScom( TGT0, 0x4011807ull, l_scom_buffer ));
l_scom_buffer.insert<0, 7, 0, uint64_t>(literal_0x0000000000000000 );
FAPI_TRY(fapi2::putScom(TGT0, 0x4011807ull, l_scom_buffer));
}
{
FAPI_TRY(fapi2::getScom( TGT0, 0x5012903ull, l_scom_buffer ));
l_scom_buffer.insert<0, 29, 35, uint64_t>(literal_0b00111001000000101111111111111 );
FAPI_TRY(fapi2::putScom(TGT0, 0x5012903ull, l_scom_buffer));
}
{
FAPI_TRY(fapi2::getScom( TGT0, 0x5012906ull, l_scom_buffer ));
l_scom_buffer.insert<0, 29, 35, uint64_t>(literal_0b00000000000000000000000000000 );
FAPI_TRY(fapi2::putScom(TGT0, 0x5012906ull, l_scom_buffer));
}
{
FAPI_TRY(fapi2::getScom( TGT0, 0x5012907ull, l_scom_buffer ));
l_scom_buffer.insert<0, 29, 35, uint64_t>(literal_0b11000110001010010000000000000 );
FAPI_TRY(fapi2::putScom(TGT0, 0x5012907ull, l_scom_buffer));
}
{
FAPI_TRY(fapi2::getScom( TGT0, 0x501290full, l_scom_buffer ));
l_scom_buffer.insert<16, 12, 52, uint64_t>(literal_0x000 );
l_scom_buffer.insert<48, 5, 59, uint64_t>(literal_0b00000 );
FAPI_TRY(fapi2::putScom(TGT0, 0x501290full, l_scom_buffer));
}
};
fapi_try_exit:
return fapi2::current_err;
}
<commit_msg>PSI FIR updates<commit_after>/* IBM_PROLOG_BEGIN_TAG */
/* This is an automatically generated prolog. */
/* */
/* $Source: src/import/chips/p9/procedures/hwp/initfiles/p9_psi_scom.C $ */
/* */
/* OpenPOWER HostBoot Project */
/* */
/* Contributors Listed Below - COPYRIGHT 2016,2017 */
/* [+] International Business Machines Corp. */
/* */
/* */
/* 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. */
/* */
/* IBM_PROLOG_END_TAG */
#include "p9_psi_scom.H"
#include <stdint.h>
#include <stddef.h>
#include <fapi2.H>
using namespace fapi2;
constexpr uint64_t literal_0xFE00000000000000 = 0xFE00000000000000;
constexpr uint64_t literal_0x0000000000000000 = 0x0000000000000000;
constexpr uint64_t literal_0b00111111000000100000011011111 = 0b00111111000000100000011011111;
constexpr uint64_t literal_0b00000000000000000000000000000 = 0b00000000000000000000000000000;
constexpr uint64_t literal_0b11000000001010011111100100000 = 0b11000000001010011111100100000;
constexpr uint64_t literal_0x000 = 0x000;
constexpr uint64_t literal_0b00000 = 0b00000;
fapi2::ReturnCode p9_psi_scom(const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& TGT0)
{
{
fapi2::ATTR_EC_Type l_chip_ec;
fapi2::ATTR_NAME_Type l_chip_id;
FAPI_TRY(FAPI_ATTR_GET_PRIVILEGED(fapi2::ATTR_NAME, TGT0, l_chip_id));
FAPI_TRY(FAPI_ATTR_GET_PRIVILEGED(fapi2::ATTR_EC, TGT0, l_chip_ec));
fapi2::buffer<uint64_t> l_scom_buffer;
{
FAPI_TRY(fapi2::getScom( TGT0, 0x4011803ull, l_scom_buffer ));
l_scom_buffer.insert<0, 7, 0, uint64_t>(literal_0xFE00000000000000 );
FAPI_TRY(fapi2::putScom(TGT0, 0x4011803ull, l_scom_buffer));
}
{
FAPI_TRY(fapi2::getScom( TGT0, 0x4011806ull, l_scom_buffer ));
l_scom_buffer.insert<0, 7, 0, uint64_t>(literal_0x0000000000000000 );
FAPI_TRY(fapi2::putScom(TGT0, 0x4011806ull, l_scom_buffer));
}
{
FAPI_TRY(fapi2::getScom( TGT0, 0x4011807ull, l_scom_buffer ));
l_scom_buffer.insert<0, 7, 0, uint64_t>(literal_0x0000000000000000 );
FAPI_TRY(fapi2::putScom(TGT0, 0x4011807ull, l_scom_buffer));
}
{
FAPI_TRY(fapi2::getScom( TGT0, 0x5012903ull, l_scom_buffer ));
l_scom_buffer.insert<0, 29, 35, uint64_t>(literal_0b00111111000000100000011011111 );
FAPI_TRY(fapi2::putScom(TGT0, 0x5012903ull, l_scom_buffer));
}
{
FAPI_TRY(fapi2::getScom( TGT0, 0x5012906ull, l_scom_buffer ));
l_scom_buffer.insert<0, 29, 35, uint64_t>(literal_0b00000000000000000000000000000 );
FAPI_TRY(fapi2::putScom(TGT0, 0x5012906ull, l_scom_buffer));
}
{
FAPI_TRY(fapi2::getScom( TGT0, 0x5012907ull, l_scom_buffer ));
l_scom_buffer.insert<0, 29, 35, uint64_t>(literal_0b11000000001010011111100100000 );
FAPI_TRY(fapi2::putScom(TGT0, 0x5012907ull, l_scom_buffer));
}
{
FAPI_TRY(fapi2::getScom( TGT0, 0x501290full, l_scom_buffer ));
l_scom_buffer.insert<16, 12, 52, uint64_t>(literal_0x000 );
l_scom_buffer.insert<48, 5, 59, uint64_t>(literal_0b00000 );
FAPI_TRY(fapi2::putScom(TGT0, 0x501290full, l_scom_buffer));
}
};
fapi_try_exit:
return fapi2::current_err;
}
<|endoftext|>
|
<commit_before>/*
* Bubble.cpp
* openc2e
*
* Created by Alyssa Milburn on Sat Apr 26 2008.
* Copyright (c) 2008 Alyssa Milburn. All rights reserved.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
*/
#include "Bubble.h"
#include "World.h"
#include "Engine.h"
#include "Backend.h"
#include "Camera.h"
#include "creaturesImage.h"
// class BubblePart *ourPart;
Bubble::Bubble(unsigned char family, unsigned char genus, unsigned short species, unsigned int plane,
std::string spritefile, unsigned int firstimage, unsigned int imagecount,
unsigned int tx, unsigned int ty, unsigned int twidth, unsigned int theight,
unsigned int bgcolour, unsigned int tcolour)
: CompoundAgent(family, genus, species, plane, spritefile, firstimage, imagecount) {
ourPart = new BubblePart(this, 1, tx, ty);
addPart(ourPart);
ourPart->textwidth = twidth;
ourPart->textheight = theight;
ourPart->backgroundcolour = bgcolour;
ourPart->textcolour = tcolour;
ourPart->editable = false;
}
void Bubble::setText(std::string s) {
ourPart->setText(s);
}
std::string Bubble::getText() {
return ourPart->text;
}
void Bubble::setEditing(bool e) {
ourPart->editable = e;
if (e)
world.setFocus(ourPart); // gain focus
else if (world.focusagent == AgentRef(this) && world.focuspart == ourPart->id)
world.setFocus(0); // lose focus
}
void Bubble::setTimeout(unsigned int t) {
timeout = t;
}
void Bubble::tick() {
CompoundAgent::tick();
if (!paused && timeout) {
timeout--;
if (timeout == 0) kill();
}
}
void Bubble::turnIntoSpeech() {
newBubble((Agent *)world.hand(), true, getText());
// TODO: announce via shou
// TODO: add to speech history
kill();
}
Bubble *Bubble::newBubble(Agent *parent, bool speech, std::string text) {
assert(engine.version < 3);
assert(parent);
bool leftside = false;
// TODO: cope with wrap
if (parent->x - world.camera->getX() < world.camera->getWidth() / 2) leftside = true;
int pose;
if (engine.version == 1) {
// C1 poses
if (speech)
pose = leftside ? 10 : 9;
else
pose = leftside ? 12 : 11;
} else {
// C2 poses
// pose adjusted on setText() if necessary
if (speech)
pose = leftside ? 21 : 18;
else
pose = leftside ? 27 : 24;
}
int plane;
if (engine.version == 1) {
plane = 9000;
} else {
// C2
if (parent == (Agent *)world.hand())
plane = 9999;
else
plane = 9995;
}
int xoffset = (engine.version == 1) ? 6 : 8;
int yoffset = (engine.version == 1) ? 3 : 8;
int twidth = (engine.version == 1) ? 144 : 95; // extended to fit text upon setText()
Bubble *ourBubble = new Bubble(2, 1, speech ? 2 : 1, plane, "syst", pose, engine.version == 1 ? 1 : 3, xoffset, yoffset, twidth, 12, 0, 0);
ourBubble->finishInit();
ourBubble->leftside = leftside;
ourBubble->attr = 32; // floating
ourBubble->floatTo(parent);
// TODO: fix positioning
if (leftside)
ourBubble->moveTo(parent->x + parent->getWidth() - 2, parent->y - ourBubble->getHeight());
else
ourBubble->moveTo(parent->x - ourBubble->getWidth() + 2, parent->y - ourBubble->getHeight());
ourBubble->setText(text);
if (speech)
ourBubble->setTimeout(2 * 10); // TODO: 2s is probably not right
else
ourBubble->setEditing(true);
return ourBubble;
}
/*
class BubblePart : public CompoundPart {
bool editable;
std::string text;
unsigned int textwidth, textheight;
unsigned int backgroundcolour, textcolour;
*/
BubblePart::BubblePart(Bubble *p, unsigned int _id, int x, int y) : CompoundPart(p, _id, x, y, 1) {
editable = false;
textwidth = 0;
textheight = 0;
textoffset = 0; // doesn't matter when text is empty
}
void BubblePart::partRender(class Surface *renderer, int xoffset, int yoffset) {
renderer->renderText(xoffset + x + textoffset, yoffset + y, text, textcolour, backgroundcolour);
}
void BubblePart::gainFocus() {
assert(editable);
}
void BubblePart::loseFocus() {
parent->kill();
}
void BubblePart::handleKey(char c) {
// TODO: reject invalid chars
setText(text + c);
}
void BubblePart::handleSpecialKey(char c) {
switch (c) {
case 8: // backspace
if (text.size() == 0) { loseFocus(); return; }
{ std::string s = text;
s.erase(s.begin() + (s.size() - 1));
setText(s); }
if (text.size() == 0) { loseFocus(); return; }
break;
case 13: // return
((Bubble *)parent)->turnIntoSpeech(); // TODO: omg hax
break;
}
}
unsigned int BubblePart::poseForWidth(unsigned int width) {
if (engine.version == 1) return 0;
SpritePart *s;
if (!(s = dynamic_cast<SpritePart *>(parent->part(0)))) return 0;
unsigned int sprite = s->getFirstImg();
while (sprite < s->getFirstImg()+2 && width > s->getSprite()->width(sprite) - 17)
sprite++;
return sprite - s->getFirstImg();
}
void BubblePart::setText(std::string str) {
unsigned int twidth = engine.backend->textWidth(str);
unsigned int pose = poseForWidth(twidth);
SpritePart *s;
if ((s = dynamic_cast<SpritePart *>(parent->part(0)))) {
if (pose != s->getPose()) {
s->setPose(pose);
textwidth = s->getWidth() - 17;
Bubble* p = (Bubble*)parent; // TODO: omg hax
if (!p->leftside)
p->moveTo(p->floatingagent->x - p->getWidth() + 2, p->floatingagent->y - p->getHeight());
}
}
if (twidth > textwidth) return;
text = str;
textoffset = (textwidth - twidth) / 2;
}
/* vim: set noet: */
<commit_msg>make BubblePart::setText only mess with poses/width in C2<commit_after>/*
* Bubble.cpp
* openc2e
*
* Created by Alyssa Milburn on Sat Apr 26 2008.
* Copyright (c) 2008 Alyssa Milburn. All rights reserved.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
*/
#include "Bubble.h"
#include "World.h"
#include "Engine.h"
#include "Backend.h"
#include "Camera.h"
#include "creaturesImage.h"
// class BubblePart *ourPart;
Bubble::Bubble(unsigned char family, unsigned char genus, unsigned short species, unsigned int plane,
std::string spritefile, unsigned int firstimage, unsigned int imagecount,
unsigned int tx, unsigned int ty, unsigned int twidth, unsigned int theight,
unsigned int bgcolour, unsigned int tcolour)
: CompoundAgent(family, genus, species, plane, spritefile, firstimage, imagecount) {
ourPart = new BubblePart(this, 1, tx, ty);
addPart(ourPart);
ourPart->textwidth = twidth;
ourPart->textheight = theight;
ourPart->backgroundcolour = bgcolour;
ourPart->textcolour = tcolour;
ourPart->editable = false;
}
void Bubble::setText(std::string s) {
ourPart->setText(s);
}
std::string Bubble::getText() {
return ourPart->text;
}
void Bubble::setEditing(bool e) {
ourPart->editable = e;
if (e)
world.setFocus(ourPart); // gain focus
else if (world.focusagent == AgentRef(this) && world.focuspart == ourPart->id)
world.setFocus(0); // lose focus
}
void Bubble::setTimeout(unsigned int t) {
timeout = t;
}
void Bubble::tick() {
CompoundAgent::tick();
if (!paused && timeout) {
timeout--;
if (timeout == 0) kill();
}
}
void Bubble::turnIntoSpeech() {
newBubble((Agent *)world.hand(), true, getText());
// TODO: announce via shou
// TODO: add to speech history
kill();
}
Bubble *Bubble::newBubble(Agent *parent, bool speech, std::string text) {
assert(engine.version < 3);
assert(parent);
bool leftside = false;
// TODO: cope with wrap
if (parent->x - world.camera->getX() < world.camera->getWidth() / 2) leftside = true;
int pose;
if (engine.version == 1) {
// C1 poses
if (speech)
pose = leftside ? 10 : 9;
else
pose = leftside ? 12 : 11;
} else {
// C2 poses
// pose adjusted on setText() if necessary
if (speech)
pose = leftside ? 21 : 18;
else
pose = leftside ? 27 : 24;
}
int plane;
if (engine.version == 1) {
plane = 9000;
} else {
// C2
if (parent == (Agent *)world.hand())
plane = 9999;
else
plane = 9995;
}
int xoffset = (engine.version == 1) ? 6 : 8;
int yoffset = (engine.version == 1) ? 3 : 8;
int twidth = (engine.version == 1) ? 144 : 95; // extended to fit text upon setText()
Bubble *ourBubble = new Bubble(2, 1, speech ? 2 : 1, plane, "syst", pose, engine.version == 1 ? 1 : 3, xoffset, yoffset, twidth, 12, 0, 0);
ourBubble->finishInit();
ourBubble->leftside = leftside;
ourBubble->attr = 32; // floating
ourBubble->floatTo(parent);
// TODO: fix positioning
if (leftside)
ourBubble->moveTo(parent->x + parent->getWidth() - 2, parent->y - ourBubble->getHeight());
else
ourBubble->moveTo(parent->x - ourBubble->getWidth() + 2, parent->y - ourBubble->getHeight());
ourBubble->setText(text);
if (speech)
ourBubble->setTimeout(2 * 10); // TODO: 2s is probably not right
else
ourBubble->setEditing(true);
return ourBubble;
}
/*
class BubblePart : public CompoundPart {
bool editable;
std::string text;
unsigned int textwidth, textheight;
unsigned int backgroundcolour, textcolour;
*/
BubblePart::BubblePart(Bubble *p, unsigned int _id, int x, int y) : CompoundPart(p, _id, x, y, 1) {
editable = false;
textwidth = 0;
textheight = 0;
textoffset = 0; // doesn't matter when text is empty
}
void BubblePart::partRender(class Surface *renderer, int xoffset, int yoffset) {
renderer->renderText(xoffset + x + textoffset, yoffset + y, text, textcolour, backgroundcolour);
}
void BubblePart::gainFocus() {
assert(editable);
}
void BubblePart::loseFocus() {
parent->kill();
}
void BubblePart::handleKey(char c) {
// TODO: reject invalid chars
setText(text + c);
}
void BubblePart::handleSpecialKey(char c) {
switch (c) {
case 8: // backspace
if (text.size() == 0) { loseFocus(); return; }
{ std::string s = text;
s.erase(s.begin() + (s.size() - 1));
setText(s); }
if (text.size() == 0) { loseFocus(); return; }
break;
case 13: // return
((Bubble *)parent)->turnIntoSpeech(); // TODO: omg hax
break;
}
}
unsigned int BubblePart::poseForWidth(unsigned int width) {
if (engine.version == 1) return 0;
SpritePart *s;
if (!(s = dynamic_cast<SpritePart *>(parent->part(0)))) return 0;
unsigned int sprite = s->getFirstImg();
while (sprite < s->getFirstImg()+2 && width > s->getSprite()->width(sprite) - 17)
sprite++;
return sprite - s->getFirstImg();
}
void BubblePart::setText(std::string str) {
unsigned int twidth = engine.backend->textWidth(str);
if (engine.version == 2) {
unsigned int pose = poseForWidth(twidth);
SpritePart *s;
if ((s = dynamic_cast<SpritePart *>(parent->part(0)))) {
if (pose != s->getPose()) {
s->setPose(pose);
textwidth = s->getWidth() - 17;
Bubble* p = (Bubble*)parent; // TODO: omg hax
if (!p->leftside)
p->moveTo(p->floatingagent->x - p->getWidth() + 2, p->floatingagent->y - p->getHeight());
}
}
}
if (twidth > textwidth) return;
text = str;
textoffset = (textwidth - twidth) / 2;
}
/* vim: set noet: */
<|endoftext|>
|
<commit_before>/* IBM_PROLOG_BEGIN_TAG */
/* This is an automatically generated prolog. */
/* */
/* $Source: src/import/chips/p9/procedures/hwp/memory/p9_mss_memdiag.C $ */
/* */
/* OpenPOWER HostBoot Project */
/* */
/* Contributors Listed Below - COPYRIGHT 2015,2019 */
/* [+] International Business Machines Corp. */
/* */
/* */
/* 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. */
/* */
/* IBM_PROLOG_END_TAG */
///
/// @file p9_mss_memdiag.C
/// @brief Mainstore pattern testing
///
// *HWP HWP Owner: Brian Silver <bsilver@us.ibm.com>
// *HWP HWP Backup: Andre Marin <aamarin@us.ibm.com>
// *HWP Team: Memory
// *HWP Level: 2
// *HWP Consumed by: FSP:HB
#include <fapi2.H>
#include <p9_mss_memdiag.H>
#include <lib/utils/poll.H>
#include <lib/utils/find.H>
#include <lib/utils/count_dimm.H>
#include <lib/mcbist/address.H>
#include <lib/mcbist/memdiags.H>
#include <lib/mcbist/mcbist.H>
#include <lib/mc/port.H>
#include <lib/ecc/ecc.H>
using fapi2::TARGET_TYPE_MCBIST;
using fapi2::TARGET_TYPE_SYSTEM;
using fapi2::TARGET_TYPE_MCA;
extern "C"
{
///
/// @brief Pattern test the DRAM
/// @param[in] i_target the McBIST of the ports of the dram you're training
/// @return FAPI2_RC_SUCCESS iff ok
///
fapi2::ReturnCode p9_mss_memdiag( const fapi2::Target<TARGET_TYPE_MCBIST>& i_target )
{
FAPI_INF("Start memdiag");
// If there are no DIMM we don't need to bother. In fact, we can't as we didn't setup
// attributes for the PHY, etc.
if (mss::count_dimm(i_target) == 0)
{
FAPI_INF("... skipping mem_diags %s - no DIMM ...", mss::c_str(i_target));
return fapi2::FAPI2_RC_SUCCESS;
}
uint8_t l_sim = false;
FAPI_TRY( mss::is_simulation( l_sim) );
// Read the bad_dq_bitmap attribute and place corresponding symbol and chip marks
for (const auto& l_mca : mss::find_targets<TARGET_TYPE_MCA>(i_target))
{
fapi2::buffer<uint8_t> l_repairs_applied;
fapi2::buffer<uint8_t> l_repairs_exceeded;
std::vector<uint64_t> l_ranks;
FAPI_TRY( mss::restore_repairs( l_mca, l_repairs_applied, l_repairs_exceeded) );
// assert if we have exceeded the allowed repairs
for (const auto& l_dimm : mss::find_targets<fapi2::TARGET_TYPE_DIMM>(l_mca))
{
FAPI_ASSERT( !(l_repairs_exceeded.getBit(mss::index(l_dimm))),
fapi2::MSS_MEMDIAGS_REPAIRS_EXCEEDED().set_TARGET(l_dimm),
"p9_mss_memdiag bad bit repairs exceeded %s", mss::c_str(l_dimm) );
}
#ifdef __HOSTBOOT_MODULE
// assert if both chip and symbol marks exist for any given rank
FAPI_TRY( mss::rank::ranks(l_mca, l_ranks) );
for (const auto l_rank : l_ranks)
{
if (l_repairs_applied.getBit(l_rank))
{
uint64_t l_galois = 0;
mss::states l_confirmed = mss::NO;
// check for chip mark in hardware mark store
FAPI_TRY( mss::ecc::get_hwms(l_mca, l_rank, l_galois, l_confirmed) );
if (l_confirmed)
{
auto l_type = mss::ecc::fwms::mark_type::CHIP;
auto l_region = mss::ecc::fwms::mark_region::DISABLED;
auto l_addr = mss::mcbist::address(0);
// check for symbol mark in firmware mark store
FAPI_TRY( mss::ecc::get_fwms(l_mca, l_rank, l_galois, l_type, l_region, l_addr) );
FAPI_ASSERT( l_region == mss::ecc::fwms::mark_region::DISABLED,
fapi2::MSS_MEMDIAGS_CHIPMARK_AND_SYMBOLMARK().set_TARGET(l_mca).set_RANK(l_rank),
"p9_mss_memdiag both chip mark and symbol mark on rank %d: %s", l_rank, mss::c_str(l_mca) );
}
}
}
#endif
}
// We start the sf_init (write 0's) and it'll tickle the MCBIST complete FIR. PRD will see that
// and start a background scrub.
FAPI_TRY( memdiags::sf_init(i_target, mss::mcbist::PATTERN_0) );
// If we're in the sim, we want to poll for the FIR bit. I don't think this ever really happens
// unless we're expressly testing this API.
if (l_sim)
{
// Poll for the fir bit. We expect this to be set ...
fapi2::buffer<uint64_t> l_status;
// A small vector of addresses to poll during the polling loop
const std::vector<mss::poll_probe<fapi2::TARGET_TYPE_MCBIST>> l_probes =
{
{i_target, "mcbist current address", MCBIST_MCBMCATQ},
};
mss::poll_parameters l_poll_parameters;
bool l_poll_results = mss::poll(i_target, MCBIST_MCBISTFIRQ, l_poll_parameters,
[&l_status](const size_t poll_remaining,
const fapi2::buffer<uint64_t>& stat_reg) -> bool
{
FAPI_DBG("mcbist firq 0x%llx, remaining: %d", stat_reg, poll_remaining);
l_status = stat_reg;
return l_status.getBit<MCBIST_MCBISTFIRQ_MCBIST_PROGRAM_COMPLETE>() == true;
},
l_probes);
FAPI_ASSERT( l_poll_results == true,
fapi2::MSS_MEMDIAGS_SUPERFAST_INIT_FAILED_TO_INIT().set_TARGET(i_target),
"p9_mss_memdiags timedout %s", mss::c_str(i_target) );
}
fapi_try_exit:
FAPI_INF("End memdiag");
return fapi2::current_err;
}
}
<commit_msg>Move find API to share among memory controllers<commit_after>/* IBM_PROLOG_BEGIN_TAG */
/* This is an automatically generated prolog. */
/* */
/* $Source: src/import/chips/p9/procedures/hwp/memory/p9_mss_memdiag.C $ */
/* */
/* OpenPOWER HostBoot Project */
/* */
/* Contributors Listed Below - COPYRIGHT 2015,2019 */
/* [+] International Business Machines Corp. */
/* */
/* */
/* 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. */
/* */
/* IBM_PROLOG_END_TAG */
///
/// @file p9_mss_memdiag.C
/// @brief Mainstore pattern testing
///
// *HWP HWP Owner: Brian Silver <bsilver@us.ibm.com>
// *HWP HWP Backup: Andre Marin <aamarin@us.ibm.com>
// *HWP Team: Memory
// *HWP Level: 2
// *HWP Consumed by: FSP:HB
#include <fapi2.H>
#include <p9_mss_memdiag.H>
#include <lib/utils/poll.H>
#include <generic/memory/lib/utils/find.H>
#include <lib/utils/count_dimm.H>
#include <lib/mcbist/address.H>
#include <lib/mcbist/memdiags.H>
#include <lib/mcbist/mcbist.H>
#include <lib/mc/port.H>
#include <lib/ecc/ecc.H>
using fapi2::TARGET_TYPE_MCBIST;
using fapi2::TARGET_TYPE_SYSTEM;
using fapi2::TARGET_TYPE_MCA;
extern "C"
{
///
/// @brief Pattern test the DRAM
/// @param[in] i_target the McBIST of the ports of the dram you're training
/// @return FAPI2_RC_SUCCESS iff ok
///
fapi2::ReturnCode p9_mss_memdiag( const fapi2::Target<TARGET_TYPE_MCBIST>& i_target )
{
FAPI_INF("Start memdiag");
// If there are no DIMM we don't need to bother. In fact, we can't as we didn't setup
// attributes for the PHY, etc.
if (mss::count_dimm(i_target) == 0)
{
FAPI_INF("... skipping mem_diags %s - no DIMM ...", mss::c_str(i_target));
return fapi2::FAPI2_RC_SUCCESS;
}
uint8_t l_sim = false;
FAPI_TRY( mss::is_simulation( l_sim) );
// Read the bad_dq_bitmap attribute and place corresponding symbol and chip marks
for (const auto& l_mca : mss::find_targets<TARGET_TYPE_MCA>(i_target))
{
fapi2::buffer<uint8_t> l_repairs_applied;
fapi2::buffer<uint8_t> l_repairs_exceeded;
std::vector<uint64_t> l_ranks;
FAPI_TRY( mss::restore_repairs( l_mca, l_repairs_applied, l_repairs_exceeded) );
// assert if we have exceeded the allowed repairs
for (const auto& l_dimm : mss::find_targets<fapi2::TARGET_TYPE_DIMM>(l_mca))
{
FAPI_ASSERT( !(l_repairs_exceeded.getBit(mss::index(l_dimm))),
fapi2::MSS_MEMDIAGS_REPAIRS_EXCEEDED().set_TARGET(l_dimm),
"p9_mss_memdiag bad bit repairs exceeded %s", mss::c_str(l_dimm) );
}
#ifdef __HOSTBOOT_MODULE
// assert if both chip and symbol marks exist for any given rank
FAPI_TRY( mss::rank::ranks(l_mca, l_ranks) );
for (const auto l_rank : l_ranks)
{
if (l_repairs_applied.getBit(l_rank))
{
uint64_t l_galois = 0;
mss::states l_confirmed = mss::NO;
// check for chip mark in hardware mark store
FAPI_TRY( mss::ecc::get_hwms(l_mca, l_rank, l_galois, l_confirmed) );
if (l_confirmed)
{
auto l_type = mss::ecc::fwms::mark_type::CHIP;
auto l_region = mss::ecc::fwms::mark_region::DISABLED;
auto l_addr = mss::mcbist::address(0);
// check for symbol mark in firmware mark store
FAPI_TRY( mss::ecc::get_fwms(l_mca, l_rank, l_galois, l_type, l_region, l_addr) );
FAPI_ASSERT( l_region == mss::ecc::fwms::mark_region::DISABLED,
fapi2::MSS_MEMDIAGS_CHIPMARK_AND_SYMBOLMARK().set_TARGET(l_mca).set_RANK(l_rank),
"p9_mss_memdiag both chip mark and symbol mark on rank %d: %s", l_rank, mss::c_str(l_mca) );
}
}
}
#endif
}
// We start the sf_init (write 0's) and it'll tickle the MCBIST complete FIR. PRD will see that
// and start a background scrub.
FAPI_TRY( memdiags::sf_init(i_target, mss::mcbist::PATTERN_0) );
// If we're in the sim, we want to poll for the FIR bit. I don't think this ever really happens
// unless we're expressly testing this API.
if (l_sim)
{
// Poll for the fir bit. We expect this to be set ...
fapi2::buffer<uint64_t> l_status;
// A small vector of addresses to poll during the polling loop
const std::vector<mss::poll_probe<fapi2::TARGET_TYPE_MCBIST>> l_probes =
{
{i_target, "mcbist current address", MCBIST_MCBMCATQ},
};
mss::poll_parameters l_poll_parameters;
bool l_poll_results = mss::poll(i_target, MCBIST_MCBISTFIRQ, l_poll_parameters,
[&l_status](const size_t poll_remaining,
const fapi2::buffer<uint64_t>& stat_reg) -> bool
{
FAPI_DBG("mcbist firq 0x%llx, remaining: %d", stat_reg, poll_remaining);
l_status = stat_reg;
return l_status.getBit<MCBIST_MCBISTFIRQ_MCBIST_PROGRAM_COMPLETE>() == true;
},
l_probes);
FAPI_ASSERT( l_poll_results == true,
fapi2::MSS_MEMDIAGS_SUPERFAST_INIT_FAILED_TO_INIT().set_TARGET(i_target),
"p9_mss_memdiags timedout %s", mss::c_str(i_target) );
}
fapi_try_exit:
FAPI_INF("End memdiag");
return fapi2::current_err;
}
}
<|endoftext|>
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.